<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.monitorIdx" @change="handleChnChange">
              <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">
              <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"/>
            <el-tree v-if="switchItem === 1" :default-expanded-keys="defaultExpandedKeys" node-key="id"
                     :data="treeDataAll" :props="defaultProps" @node-click="handleNodeClick"/>
          </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 {getFormData, getTreeData, getCheckData} from "@/api/check/test";

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

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

const visible = ref(false)

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

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

// 不符合测试项、全部测试项切换
const switchItem = ref<number>(-1)
// 左侧树数据-不符合测试项
let treeDataUnQualified: CheckData.ScriptItem[] = []
// 左侧树数据-全部测试项
let treeDataAll: CheckData.ScriptItem[] = []
// 左侧树被选中的叶子节点id
const checkedScriptId = ref<string>('')


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

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

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

// 监控通道号下拉框
const handleChnChange = (data: any) => {

  console.log("通道号下拉框", data);

  // 后端请求，查询该通道号下的测试项（可以只查询不合格测试项，也可以全部测试项、不合格测试项都查询）
  // const result = await getTreeData({deviceId, formContent.monitorIdx, checkItemId})
  //  treeDataUnQualified=[]
  //  treeDataAll=[]


}
// watch(() => formContent.monitorIdx, (newVal, oldVal) => {
//   if (newVal) {
//     console.log("通道号下拉框", newVal, oldVal);
//
//     // 后端请求，查询该通道号下的测试项（可以只查询不合格测试项，也可以全部测试项、不合格测试项都查询）
//     // const result = await getTreeData({deviceId, formContent.monitorIdx, checkItemId})
//     //  treeDataUnQualified=[]
//     //  treeDataAll=[]
//
//   }
// })

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

watch(checkedScriptId, (newVal, oldVal) => {
  if (newVal) {
    console.log("左侧树被选中的叶子节点id", newVal);
    // 发起请求，查询该测试项的检测结果
    // const result = await getCheckData({deviceId, formContent.monitorIdx, checkItemId})
    Object.assign(checkResultTableData, [{
      chnNum: '1',
      standardValue: 57.74,
      L1: 57.73,
      L1_errValue: 0.01,
      L2: 57.73,
      L2_errValue: 0.01,
      L3: 57.73,
      L3_errValue: 0.01,
      maxErrVaule: 0.05774,
      result: '合格',
    }])
    Object.assign(rawTableData, [
      {
        updateTime: "2024-10-10 09:30:00",
        L1: 57.73,
        L2: 57.73,
        L3: 57.73,
      },
      {
        updateTime: "2024-10-10 09:30:03",
        L1: 57.73,
        L2: 57.73,
        L3: 57.73,
      },
      {
        updateTime: "2024-10-10 09:30:06",
        L1: 57.73,
        L2: 57.73,
        L3: 57.73,
      },
      {
        updateTime: "2024-10-10 09:30:09",
        L1: 57.73,
        L2: 57.73,
        L3: 57.73,
      },
      {
        updateTime: "2024-10-10 09:30:12",
        L1: 57.73,
        L2: 57.73,
        L3: 57.73,
      },
      {
        updateTime: "2024-10-10 09:30:15",
        L1: 57.73,
        L2: 57.73,
        L3: 57.73,
      },
      {
        updateTime: "2024-10-10 09:30:18",
        L1: 57.73,
        L2: 57.73,
        L3: 57.73,
      },
      {
        updateTime: "2024-10-10 09:30:21",
        L1: 57.73,
        L2: 57.73,
        L3: 57.73,
      },
      {
        updateTime: "2024-10-10 09:30:24",
        L1: 57.73,
        L2: 57.73,
        L3: 57.73,
      },
      {
        updateTime: "2024-10-10 09:30:27",
        L1: 57.73,
        L2: 57.73,
        L3: 57.73,
      },
      {
        updateTime: "2024-10-10 09:30:30",
        L1: 57.73,
        L2: 57.73,
        L3: 57.73,
      },
      {
        updateTime: "2024-10-10 09:30:33",
        L1: 57.73,
        L2: 57.73,
        L3: 57.73,
      },
      {
        updateTime: "2024-10-10 09:30:36",
        L1: 57.73,
        L2: 57.73,
        L3: 57.73,
      },
      {
        updateTime: "2024-10-10 09:30:39",
        L1: 57.73,
        L2: 57.73,
        L3: 57.73,
      },
      {
        updateTime: "2024-10-10 09:30:42",
        L1: 57.73,
        L2: 57.73,
        L3: 57.73,
      },
      {
        updateTime: "2024-10-10 09:30:45",
        L1: 57.73,
        L2: 57.73,
        L3: 57.73,
      },
      {
        updateTime: "2024-10-10 09:30:48",
        L1: 57.73,
        L2: 57.73,
        L3: 57.73,
      },
      {
        updateTime: "2024-10-10 09:30:51",
        L1: 57.73,
        L2: 57.73,
        L3: 57.73,
      },
      {
        updateTime: "2024-10-10 09:30:54",
        L1: 57.73,
        L2: 57.73,
        L3: 57.73,
      },
      {
        updateTime: "2024-10-10 09:30:57",
        L1: 57.73,
        L2: 57.73,
        L3: 57.73,
      }
    ])
  }
})

// 切换不合格测试项、全部测试项 触发事件
watch(switchItem, (newVal, oldVal) => {
  let node = null
  if (newVal === 0) {
    node = getDefaultNode(treeDataUnQualified)
  }
  if (newVal === 1) {
    node = getDefaultNode(treeDataAll)
  }

  currentScriptDsc.value = node?.scriptName
  checkedScriptId.value = node?.id
  defaultExpandedKeys = [node?.id]
})

const open = async (_deviceId: string, chnNum: number, _checkItemId?: string) => {
  console.log(deviceId, chnNum, checkItemId);
  deviceId = _deviceId
  checkItemId = _checkItemId ?? ''
  switchItem.value = 0
  // 发起后端请求，查询详细信息 当chnNum为-1时，查询所有通道号
  //const result1 = await getFormData({deviceId, chnNum})

  // 数据处理
  chnList = [
    {value: 1, label: '1'},
    {value: 2, label: '2 （不合格）'},
    {value: 3, label: '3'},
    {value: 4, label: '4 （不合格）'}]
  Object.assign(formContent, {
    scriptName: 'Q/GDW 10650.4-2021 模拟式',
    errorSysName: 'Q/GDW 10650.2-2021',
    dataRule: '所有值',
    deviceName: '被检设备1',
    monitorIdx: chnList[0].value
  })

  // const result2 = await getTreeData({deviceId, formContent.monitorIdx, checkItemId})
  treeDataAll = [{
    "id": "1",
    "pid": "0",
    "scriptName": "频率准确度检测",
    "children": [
      {
        "id": "1-1",
        "pid": "1",
        "scriptName": "额定工作条件下的检测",
        "children": [
          {
            "id": "1-1-1",
            "pid": "1-1",
            "scriptName": "输入：频率 42.5Hz..."
          },
          {
            "id": "1-1-2",
            "pid": "1-1",
            "scriptName": "输入：频率 50.0Hz..."
          },
          {
            "id": "1-1-3",
            "pid": "1-1",
            "scriptName": "输入：频率 50.05Hz...."
          }
        ]
      },
      {
        "id": "1-2",
        "pid": "1",
        "scriptName": "电压对频率测量的影响",
        "children": [
          {
            "id": "1-2-1",
            "pid": "1-2",
            "scriptName": "输入：频率 50.05Hz Ua =10%Un..."
          },
          {
            "id": "1-2-1",
            "pid": "1-2",
            "scriptName": "输入：频率 51.05Hz Ua =10%Un..."
          },
          {
            "id": "1-2-2",
            "pid": "1-2",
            "scriptName": "输入：频率 52.05Hz Ua =10%Un..."
          }
        ]
      },
      {
        "id": "1-3",
        "pid": "1",
        "scriptName": "谐波对频率测量的影响",
        "children": [
          {
            "id": "1-3-1",
            "pid": "1-3",
            "scriptName": "输入：频率 50.05Hz Ua =100%Un..."
          }
        ]
      }
    ]
  }]
  treeDataUnQualified = [{
    "id": "1",
    "pid": "0",
    "scriptName": "频率准确度检测",
    "children": [
      {
        "id": "1-2",
        "pid": "1",
        "scriptName": "电压对频率测量的影响",
        "children": [
          {
            "id": "1-2-1",
            "pid": "1-2",
            "scriptName": "输入：频率 50.05Hz Ua =10%Un..."
          },
          {
            "id": "1-2-1",
            "pid": "1-2",
            "scriptName": "输入：频率 51.05Hz Ua =10%Un..."
          },
          {
            "id": "1-2-2",
            "pid": "1-2",
            "scriptName": "输入：频率 52.05Hz Ua =10%Un..."
          }
        ]
      }
    ]
  }]

  visible.value = true;
}

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

  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: auto;

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

      .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>