<template>
  <el-dialog :append-to-body="appendToBody" class="dialog" title="数据查询" :model-value='visible' @close="close"
             v-bind="dialogBig" :draggable="false" style="margin-left: 20%;">
    <div class="data-check-dialog">
      <div class="data-check-head">
        <el-form :model='formContent' label-width="auto" class="form-three ">
          <el-form-item label="检测脚本">
            <el-input v-model='formContent.scriptName' :disabled="true"/>
          </el-form-item>
          <el-form-item label="误差体系">
            <el-input v-model='formContent.errorSysName' :disabled="true"/>
          </el-form-item>
          <el-form-item label="数据原则">
            <el-input v-model='formContent.dataRule' :disabled="true"/>
          </el-form-item>
          <el-form-item label="设备名称">
            <el-input v-model='formContent.deviceName' :disabled="true"/>
          </el-form-item>
          <el-form-item label='通道号'>
            <el-select v-model="formContent.chnNum">
              <el-option v-for="item in chnList" :key="item.value" :label="item.label"
                         :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-form>
      </div>

      <div class="data-check-body">
        <div class="content-left-tree">
          <div>
            <el-radio-group v-model="switchItem" @change="handleSwitchChange">
              <el-radio-button label="不符合测试项" :value="0"/>
              <el-radio-button label="全部测试项" :value="1"/>
            </el-radio-group>
          </div>
          <div class="content-tree">
            <el-tree v-if="switchItem === 0" :default-expanded-keys="defaultExpandedKeys" node-key="id"
                     :data="treeDataUnqualified" :props="defaultProps" @node-click="handleNodeClick"
                     class="custom-tree">
              <template #default="{ node, data }">
                <span class="custom-tree-node">{{ data.scriptName }}</span>
              </template>
            </el-tree>
            <el-tree v-if="switchItem === 1" :default-expanded-keys="defaultExpandedKeys" node-key="id"
                     :data="treeDataAll" :props="defaultProps" @node-click="handleNodeClick" class="custom-tree">
              <template #default="{ node, data }">
                <span class="custom-tree-node">{{ data.scriptName }}</span>
              </template>
            </el-tree>
          </div>
        </div>

        <div class="content-right">
          <div class="content-right-title">
            <el-divider>当前检测项目</el-divider>
            <span>{{ currentScriptDsc }}</span>
          </div>
          <div class="content-right-Tabs">
            <el-tabs type="border-card" v-model="activeTab">
              <el-tab-pane label="检测结果" name="resultTab">
                <DataCheckResultTable :tableData="checkResultTableData" ref="resultTableRef"/>
              </el-tab-pane>
              <el-tab-pane label="原始数据" name="rawDataTab">
                <DataCheckRawDataTable :tableData="rawTableData" ref="rawDataTableRef"/>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>

</template>
<script setup lang='ts'>
import {dialogBig} from '@/utils/elementBind'
import {reactive, ref} from 'vue'
import DataCheckResultTable from './dataCheckResultTable.vue'
import DataCheckRawDataTable from './dataCheckRawDataTable.vue'
import {CheckData} from "@/api/check/interface";
import {useDictStore} from "@/stores/modules/dict";
import {useCheckStore} from "@/stores/modules/check";

const {appendToBody} = withDefaults(defineProps<{
  appendToBody: boolean
}>(), {appendToBody: false})

const defaultProps = {
  label: "scriptName",
  children: "children",
};

const dictStore = useDictStore()
const checkStore = useCheckStore()

const visible = ref(false)

// 表单数据
const formContent = reactive<CheckData.DataCheck>({
  scriptName: '',
  errorSysName: '',
  dataRule: '',
  deviceName: '',
  chnNum: '',
})
let deviceId: string = ''
let scriptType: string | null = null

// 通道下拉列表
let chnList: any[] = []

// 不符合测试项、全部测试项切换
const switchItem = ref<number>(0)
// 左侧树数据
let treeDataUnqualified: CheckData.ScriptItem[] = []
let treeDataAll: CheckData.ScriptItem[] = []

// 左侧树被选中的叶子节点id
const checkedScriptId = ref<string>('')

const currentScriptDsc = ref('');
// 右侧Tab选中项
const activeTab = ref<string>('resultTab')
// 检测结果表格数据
let checkResultTableData: CheckData.CheckResult = []
// 原始数据表格数据
let rawTableData: CheckData.RawDataItem[] = []

const resultTableRef = ref()
const rawDataTableRef = ref()

// 左侧树默认展开节点id
let defaultExpandedKeys: string[] = []

// 点击左侧树节点触发事件
const handleNodeClick = async (data: any) => {
  if (!data.children) {
    checkedScriptId.value = data.id
    currentScriptDsc.value = data.scriptName

    if (checkedScriptId.value) {
      await updateTableData()
    }
  }
};

watch(() => formContent.chnNum, async (newVal, oldVal) => {
  console.log("通道号", newVal);

  switchItem.value = 0
  await handleSwitchChange(0)
})

const handleSwitchChange = async (data: any) => {
  console.log("切换不合格测试项、全部测试项", data);

  if (data === 0) {
    // 发起请求，查询该测试项的检测结果
    // const result = await getTreeData({checkStore.scriptId,deviceId, formContent.chnNum+'', scriptType,0})
    treeDataUnqualified = [{
      "id": "1",
      "scriptName": "频率准确度检测",
      "children": [
        {
          "id": "1-2",
          "scriptName": "电压对频率测量的影响",
          "children": [
            {
              "id": "1-2-1",
              "scriptName": "输入：频率 50.05Hz Ua =10%Un..."
            },
            {
              "id": "1-2-2",
              "scriptName": "输入：频率 51.05Hz Ua =10%Un..."
            },
            {
              "id": "1-2-3",
              "scriptName": "输入：频率 52.05Hz Ua =10%Un..."
            }
          ]
        },
        {
          "id": "1-3",
          "scriptName": "谐波对频率测量的影响",
          "children": [
            {
              "id": "1-3-1",
              "scriptName": "输入：频率 50.05Hz Ua =100%Un..."
            }
          ]
        }
      ]
    }]
  } else {
    // 发起请求，查询该测试项的检测结果
    // const result = await getTreeData({checkStore.scriptId,deviceId, formContent.chnNum+'', scriptType,1})
    treeDataAll = [
      {
        "id": "1",
        "scriptName": "频率准确度检测",
        "children": [
          {
            "id": "1-1",
            "scriptName": "额定工作条件下的检测",
            "children": [
              {
                "id": "1-1-1",
                "scriptName": "输入：频率 42.5Hz..."
              },
              {
                "id": "1-1-2",
                "scriptName": "输入：频率 50.0Hz..."
              },
              {
                "id": "1-1-3",
                "scriptName": "输入：频率 50.05Hz...."
              }
            ]
          },
          {
            "id": "1-2",
            "scriptName": "电压对频率测量的影响",
            "children": [
              {
                "id": "1-2-1",
                "scriptName": "输入：频率 50.05Hz Ua =10%Un..."
              },
              {
                "id": "1-2-2",
                "scriptName": "输入：频率 51.05Hz Ua =10%Un..."
              },
              {
                "id": "1-2-3",
                "scriptName": "输入：频率 52.05Hz Ua =10%Un..."
              }
            ]
          },
          {
            "id": "1-3",
            "scriptName": "谐波对频率测量的影响",
            "children": [
              {
                "id": "1-3-1",
                "scriptName": "输入：频率 50.05Hz Ua =100%Un..."
              }
            ]
          }
        ]
      },
    ]

  }

  defaultOperate()
  await updateTableData()
}

// 默认操作
const defaultOperate = () => {
  let node = null
  if (switchItem.value === 0) {
    node = getDefaultNode(treeDataUnqualified)
  } else {
    node = getDefaultNode(treeDataAll)
  }
  currentScriptDsc.value = node?.scriptName
  checkedScriptId.value = node?.id
  defaultExpandedKeys = [node?.id]
}

const updateTableData = async () => {
  console.log("左侧树被选中的叶子节点id", checkedScriptId.value);
  // 发起请求，查询该测试项的检测结果
  // const result = await getTableData({checkStore.scriptId,deviceId, formContent.chnNum, scriptType})

  checkResultTableData = [{
    chnNum: '1',
    standardValue: 57.74,
    A: 57.73,
    A_errValue: 0.01,
    B: 57.73,
    B_errValue: 0.01,
    C: 57.73,
    C_errValue: 0.01,
    maxErrVaule: 0.05774,
    result: '合格',
  }]

  rawTableData = [
    {
      updateTime: "2024-10-10 09:30:00",
      A: 57.73,
      B: 57.73,
      C: 57.73,
    },
    {
      updateTime: "2024-10-10 09:30:03",
      A: 57.73,
      B: 57.73,
      C: 57.73,
    },
    {
      updateTime: "2024-10-10 09:30:06",
      A: 57.73,
      B: 57.73,
      C: 57.73,
    },
    {
      updateTime: "2024-10-10 09:30:09",
      A: 57.73,
      B: 57.73,
      C: 57.73,
    },
    {
      updateTime: "2024-10-10 09:30:12",
      A: 57.73,
      B: 57.73,
      C: 57.73,
    },
    {
      updateTime: "2024-10-10 09:30:15",
      A: 57.73,
      B: 57.73,
      C: 57.73,
    },
    {
      updateTime: "2024-10-10 09:30:18",
      A: 57.73,
      B: 57.73,
      C: 57.73,
    },
    {
      updateTime: "2024-10-10 09:30:21",
      A: 57.73,
      B: 57.73,
      C: 57.73,
    },
    {
      updateTime: "2024-10-10 09:30:24",
      A: 57.73,
      B: 57.73,
      C: 57.73,
    },
    {
      updateTime: "2024-10-10 09:30:27",
      A: 57.73,
      B: 57.73,
      C: 57.73,
    },
    {
      updateTime: "2024-10-10 09:30:30",
      A: 57.73,
      B: 57.73,
      C: 57.73,
    },
    {
      updateTime: "2024-10-10 09:30:33",
      A: 57.73,
      B: 57.73,
      C: 57.73,
    },
    {
      updateTime: "2024-10-10 09:30:36",
      A: 57.73,
      B: 57.73,
      C: 57.73,
    },
    {
      updateTime: "2024-10-10 09:30:39",
      A: 57.73,
      B: 57.73,
      C: 57.73,
    },
    {
      updateTime: "2024-10-10 09:30:42",
      A: 57.73,
      B: 57.73,
      C: 57.73,
    },
    {
      updateTime: "2024-10-10 09:30:45",
      A: 57.73,
      B: 57.73,
      C: 57.73,
    },
    {
      updateTime: "2024-10-10 09:30:48",
      A: 57.73,
      B: 57.73,
      C: 57.73,
    },
    {
      updateTime: "2024-10-10 09:30:51",
      A: 57.73,
      B: 57.73,
      C: 57.73,
    },
    {
      updateTime: "2024-10-10 09:30:54",
      A: 57.73,
      B: 57.73,
      C: 57.73,
    },
    {
      updateTime: "2024-10-10 09:30:57",
      A: 57.73,
      B: 57.73,
      C: 57.73,
    }
  ]
}

const open = (_deviceId: string, chnNum: string, _scriptType: string | null) => {
  console.log(checkStore.scriptId, _deviceId, chnNum, _scriptType);
  deviceId = _deviceId
  scriptType = _scriptType

  // 发起后端请求，查询详细信息 当chnNum为-1时，查询所有通道号
  //const resFormContent = await getFormData({checkStore.scriptId,deviceId, chnNum,scriptType})

  // 数据处理
  let resFormContent = {
    scriptName: 'Q/GDW 10650.4-2021 模拟式',
    errorSysName: 'Q/GDW 10650.2-2021',
    dataRule: '505f063f9f91ab108d895a9fe96b5dce',
    deviceName: '被检设备1',
    chnList: [
      {value: '1', label: '1'},
      {value: '2', label: '0'},
      {value: '3', label: '1'},
      {value: '4', label: '0'}],
  }
  chnList = resFormContent.chnList.map(item => ({
    value: item.value,
    label: item.label == '1' ? `${item.value}` : `${item.value}（不符合）`
  }))

  let dataRuleName = dictStore.getDictData('Data_Rule').find(item => item.id == resFormContent.dataRule)?.name

  Object.assign(formContent, {...resFormContent, dataRule: dataRuleName, chnNum: chnList[0].value})


  visible.value = true;
}

const close = () => {
  //数据清空
  Object.assign(formContent, {
    scriptName: '',
    errorSysName: '',
    dataRule: '',
    deviceName: '',
    chnNum: '',
  })
  treeDataUnqualified = []
  treeDataAll = []
  checkedScriptId.value = ''
  activeTab.value = 'rawDataTab'
  currentScriptDsc.value = ''
  switchItem.value = 0

  visible.value = false;
};

const findFirstLeafNode = (node: any): any => {
  if (!node.children || node.children.length === 0) {
    return node;
  }

  return findFirstLeafNode(node.children[0]);
}
const getDefaultNode = (data: any[]) => {
  if (!data || data.length === 0) {
    return null;
  }

  const firstElement = data[0];

  return findFirstLeafNode(firstElement);
}

defineExpose({
  open
})
</script>

<style lang="scss" scoped>

.dialog {
  display: flex;
  flex-direction: column;
  overflow-y: hidden;
  overflow-x: hidden;


  .data-check-dialog {
    display: flex;
    flex-direction: column;

    .data-check-head {
      display: flex;
      flex-direction: row;
      width: 100%;
    }

    .data-check-body {
      width: 100%;
      display: flex;
      flex-direction: row;

      .content-left-tree {
        width: 25%;
        display: flex;
        flex-direction: column;
        align-items: center;
        max-height: 473px;

        padding: 10px 0;
        border: 1px solid #ccc;
        overflow-y: auto;

        .content-tree {
          width: 100%;
          height: 100%;
          max-height: 100%;
          margin-top: 10px;

          .custom-tree-node {
            overflow-x: hidden !important; // 溢出部分隐藏
            white-space: nowrap !important; //禁止自动换行
            text-overflow: ellipsis !important; // 使溢出部分以省略号显示
          }
        }
      }

      .content-right {
        width: 75%;
        margin-left: 10px;
        flex: 1;

        .content-right-title {
          /*margin-bottom: 10px;*/
          div {
            font-size: 16px;
            font-weight: 600;
          }
        }

        .content-right-Tabs {
          box-sizing: border-box;
          margin-top: 20px;
          margin-bottom: 10px;
          max-height: 400px;
        }
      }
    }
  }
}

</style>