<template>
  <div>
    <el-card :body-style="cardBodyStyle">
      <el-form :inline="true">
        <el-row :span="24">

          <el-col :span="5">
            <el-form-item label="类别名称" style="margin-bottom: 5px;width: 220px;" prop="name">
              <el-select v-model="query.type" placeholder="" clearable>
                <el-option v-for="item in typeList" :key="item.itemCd" :label="item.itemNm" :value="item.itemNm"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <ButtonBar area="button-right" @search="handleSearch" @add="handleAdd">
    </ButtonBar>
    <el-card :body-style="cardBodyStyle">
      <el-tabs v-model="activeNameTop" type="border-card">
        <el-tab-pane label="归属条件配置" name="master">
          <el-table :data="tableData" height="280px" border highlight-current-row
            @selection-change="handleSelectionChange">
            <el-table-column prop="name" label="类别名称" align="center" width="200">
            </el-table-column>
            <el-table-column prop="banben" label="版本" width="300px" header-align="center" align="center"
              show-overflow-tooltip></el-table-column>
            <el-table-column prop="remark" label="备注" width="200px" header-align="center" align="center"
              show-overflow-tooltip></el-table-column>
            <el-table-column prop="flag" label="状态" width="200px" header-align="center" align="center"
              show-overflow-tooltip></el-table-column>
            <el-table-column label="操作" header-align="center" align="center" width="300px">
              <template #default="{ row }">
                <el-button plain type="warning" @click="handleEdit(row)">编辑</el-button>
                <el-button plain type="danger" @click="handleDelete(row)">删除</el-button>
                <el-button plain type="primary" @click="handleCheck(row)">检测</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="pageSizes" :total="totalRows"
            background="background" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
            @current-change="handleCurrentChange">
          </el-pagination>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-card :body-style="cardBodyStyle">

    </el-card>
  </div>

  <div>
    <el-row>
      <el-col :span="12">
        <el-tabs v-model="activeNameBottom" type="border-card" @tab-change="handleTabChange">
          <el-tab-pane label="化学检测项目" name="first">
            <ButtonBar area="button-left" @add="handleAddCP" @remove="handleRemoveBatch"></ButtonBar>
            <el-table :data="detailData" row-key="id" border height="200px" highlight-current-row
              @selection-change="handleSelectionChange" @row-click="handleClick" ref="tableRef1">
              <el-table-column type="selection" fixed></el-table-column>
              <el-table-column v-if="true" prop="name" label="质检项目" width="150" header-align="center" align="center"
                show-overflow-tooltip></el-table-column>
              <el-table-column v-if="true" prop="sslb" label="所属类别" width="150" header-align="center" align="center"
                show-overflow-tooltip></el-table-column>
              <el-table-column v-if="true" prop="xiuyuegz" label="修约规则" width="150" header-align="center" align="center"
                show-overflow-tooltip></el-table-column>
              <el-table-column v-if="true" prop="xiaoshuwei" label="小数位数" width="150" header-align="center"
                align="center" show-overflow-tooltip></el-table-column>
              <el-table-column v-if="true" prop="sortindex" label="排序" width="150 " header-align="center" align="center"
                show-overflow-tooltip></el-table-column>
            </el-table>
          </el-tab-pane>

          <el-tab-pane label="物理检测项目" name="second">
            <ButtonBar area="button-left" @add="handleAddCP" @remove="handleRemoveBatch"></ButtonBar>
            <el-table :data="detailData" row-key="id" border height="200px" highlight-current-row
              @selection-change="handleSelectionChange" ref="tableRef2" @row-click="handleClick">
              <el-table-column type="selection" fixed></el-table-column>
              <el-table-column v-if="true" prop="name" label="质检项目" width="150" header-align="center" align="center"
                show-overflow-tooltip></el-table-column>
              <el-table-column v-if="true" prop="sslb" label="所属类别" width="150" header-align="center" align="center"
                show-overflow-tooltip></el-table-column>
              <el-table-column v-if="true" prop="xiuyuegz" label="修约规则" width="150" header-align="center" align="center"
                show-overflow-tooltip></el-table-column>
              <el-table-column v-if="true" prop="xiaoshuwei" label="小数位数" width="150" header-align="center"
                align="center" show-overflow-tooltip></el-table-column>
              <el-table-column v-if="true" prop="sortindex" label="排序" width="150" header-align="center" align="center"
                show-overflow-tooltip></el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-col>
      <el-col :span="12">
        <el-tabs v-model="activeNameTop" type="border-card">
          <el-tab-pane label="对应项目包含规则" name="master">

            <ButtonBar :disabled="isRowClicked" area="button-left" @remove="handleRemoveBatchGZ" @add="handleAddGZ">
            </ButtonBar>
            <el-table :data="planDetailData" border height="200px" highlight-current-row
              @selection-change="handleSelectionChange">
              <el-table-column type="selection" fixed></el-table-column>
              <el-table-column prop="leixing" label="类型" width="200" header-align="center" align="center"
                show-overflow-tooltip></el-table-column>
              <el-table-column prop="name" label="等级名称" width="200" header-align="center" align="center"
                show-overflow-tooltip></el-table-column>
              <el-table-column prop="yangshi" label="取值范围/条件文本" width="200" header-align="center" align="center"
                show-overflow-tooltip>
                <template #default="{ row }">
                  {{ row.xiaxian }} < {{ row.sjtype }} <={{ row.shangxian }} </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
    <!--归属条件配置新增界面-->
    <el-dialog :close-on-click-modal="false" draggable title="新增" v-model="dialogVisible" width="1200px" top="5vh"
      @open="openDialog">
      <el-form :model="form" label-width="120px" label-position="right" inline ref="ruleFormRef" :rules="rules">
        <el-form-item label="物料名称" prop="itemNm">
          <el-select v-model="form.itemNm" placeholder="请选择产品类别" clearable style="width: 200px">
            <el-option v-for="item in typeList" :key="item.itemCd" :label="item.itemNm" :value="item.itemNm"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" clearable style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="flag">
          <el-select v-model="form.flag" placeholder="请选择状态" clearable style="width: 200px;">
            <el-option label="已启用" value="已启用"></el-option>
            <el-option label="未启用" value="未启用"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="handleSave(ruleFormRef)">保存</el-button>
          <el-button type="danger" @click="handleCancelSave">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <!--  检测项目新增界面 -->
    <el-dialog :close-on-click-modal="false" draggable title="新增" v-model="dialogVisibleChe" width="1210px" top="5vh"
      @open="openDialog">
      <el-form :model="bootoomLForm" label-width="80px" label-position="left" inline ref="ruleFormRef" :rules="rules">

        <el-form-item label="质检项目" prop="name">
          <el-tree-select v-model="bootoomLForm.name" :data="treeData" :render-after-expand="false" style="width: 180px"
            @change="handleChange" clearable>
            <template #default="{ node }">
              <el-tooltip :content="node.label" placement="left" show-after="500">
                <span>{{ node.label }}</span>
              </el-tooltip>
            </template>
          </el-tree-select>
        </el-form-item>

        <el-form-item label="修约规则" prop="xiuyuegz">
          <el-select v-model="bootoomLForm.xiuyuegz" placeholder="请选择修约规则" clearable style="width: 180px;">
            <el-option label="无" value="无"></el-option>
            <el-option label="四舍五入" value="四舍五入"></el-option>
            <el-option label="四舍六入" value="四舍六入"></el-option>
            <el-option label="0.5单位修约" value="0.5单位修约"></el-option>
            <el-option label="5单位修约" value="5单位修约"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="小数位数" prop="xiaoshuwei">
          <el-input-number v-model="bootoomLForm.xiaoshuwei" min="0" placeholder="请输入小数位" clearable
            style="width: 180px"></el-input-number>
        </el-form-item>
        <el-form-item label="序号" prop="sortindex">
          <el-input-number v-model="bootoomLForm.sortindex" :min="0" placeholder="请输入序号" clearable
            style="width: 180px"></el-input-number>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="handleSaveChe(ruleFormRef)">保存</el-button>
          <el-button type="danger" @click="handleCancelSave">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!--  对应项目包含规则新增界面 -->
    <el-dialog :close-on-click-modal="false" draggable title="新增" v-model="dialogVisibleGZ" width="1270px" top="5vh"
      @open="openDialog">
      <el-form :model="bootoomRForm" label-width="80px" label-position="left" inline ref="ruleFormRef" :rules="rules">

        <el-form-item label="类型" prop="leixing">
          <el-select v-model="bootoomRForm.leixing" placeholder="请选择类型" clearable style="width: 200px;">
            <el-option label="判定" value="判定"></el-option>
            <el-option label="内控" value="内控"></el-option>
            <el-option label="参考" value="参考"></el-option>
            <el-option label="目标" value="目标"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="结果等级" prop="jgid">
          <el-tree-select v-model="bootoomRForm.jgid" :data="typeData" :render-after-expand="false" style="width: 180px"
            clearable />
        </el-form-item>
        <el-form-item label="下限" prop="xiaxian">
          <el-input-number v-model="bootoomRForm.xiaxian" :precision="4" min="0" placeholder="请输入下限" clearable
            style="width: 200px"></el-input-number>
        </el-form-item>
        <el-form-item label="上限" prop="shangxian">
          <el-input-number v-model="bootoomRForm.shangxian" :precision="4" :min="+bootoomRForm.xiaxian"
            placeholder="请输入上限" clearable style="width: 200px"></el-input-number>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="handleSaveJC(ruleFormRef)">保存</el-button>
          <el-button type="danger" @click="handleCancelSave">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { useRoute } from 'vue-router';
import SearchBox from "@/components/SearchBox.vue";
import ButtonBar from '@/components/ButtonBar.vue'
import {
  ref,
  reactive,
  onMounted,
  getCurrentInstance,
  watch
} from 'vue'
import style from '@/tools/style'
import { ElMessage, ElMessageBox } from "element-plus";
import Templates from "@/views/system/templates.vue";

onMounted(() => {

  queryType()
  getDetail()
  handleSearch()
  getTypeData()
})

const { proxy } = getCurrentInstance()
const dialogVisible = ref(false)
const dialogVisibleChe = ref(false)
const isRowClicked = ref(false)
const dialogVisibleGZ = ref(false)
const ruleFormRef = ref()
const rules = reactive({
  itemNm: [{
    required: true,
    message: '请输入产品类别',
    trigger: 'change' | 'blur'
  }],
  id: [{
    required: true,
    message: '请输入产品类别',
    trigger: 'change' | 'blur'
  }],
  remark: [{
    required: true,
    message: '请输入备注',
    trigger: 'change' | 'blur'
  }],
  flag: [{
    required: true,
    message: '请选择',
    trigger: 'change' | 'blur'
  }],
  name: [{
    required: true,
    message: '请输入质检项目名称',
    trigger: 'change' | 'blur'
  }],
  xiuyuegz: [{
    required: true,
    message: '请选择修约规则',
    trigger: 'change' | 'blur'
  }],
  sortindex: [{
    required: true,
    message: '请输入序号',
    trigger: 'change' | 'blur'
  }],
  leixing: [{
    required: true,
    message: '请选择规则类型',
    trigger: 'change' | 'blur'
  }],
  jgid: [{
    required: true,
    message: '请选择结果等级',
    trigger: 'change' | 'blur'
  }],
  xiaxian: [{
    required: true,
    message: '请输入下限',

  }],
  shangxian: [{
    required: true,
    message: '请输入上限',
  }]
})
const cardBodyStyle = ref(style.card)
const searchBarRef = ref(null)
const PopupUserRef = ref(null)
const showPop = () => {
  PopupUserRef.value.open()
}

const handleChange = (val) => {
  bootoomLForm.value.xmid = val

}

const getLeibieid = () => {
  typeList.value.forEach(x => {
    if (x.itemNm == form.value.itemNm) {
      console.log(x)
      form.value.leibieid = x.itemCd
    }
  })
  
}
const getLeibieName = (row) => {
  form.value.name = ''
  console.log(typeList.value)
  typeList.value.forEach(x => {
    if (x.itemCd == row.leibieid) {
      form.value.itemNm = x.itemNm
    }
  })
  console.log(form.value)
}


const query = ref({
  type: ''
})
// 上方数据
const tableData = ref([])
// 下方数据
const detailData = ref([])
const planDetailData = ref([])
const activeNameTop = ref('master')
const activeNameBottom = ref('first')
const totalRows = ref(0)

const route = useRoute();
// 使用 ref 创建 form 数据
const form = ref({
  name: '',
  leibieid: '',
  remark: '',
  flag: '',
  itemNm:''
});

// 取消
const handleCancelSave = () => {

  dialogVisible.value = false
  dialogVisibleChe.value = false
  dialogVisibleGZ.value = false
}


// 保存
const handleSave = (ruleFormRef) => {
  getLeibieid()
  console.log(form.value)
  ruleFormRef.validate((valid, fields) => {
    if (valid) {
      var url = 'syi/checkPlan/save'
      var param = {
        json: JSON.stringify(form.value),
      }
      proxy.$axios.post(url, param).then(response => {
        if (response.data.code == 0) {
          form.value = response.data.data
          ElMessage({
            message: '保存成功',
            type: 'success',
          })
          getTableData()

          rows = {}
          dialogVisible.value = false
          detailData.value = []
          planDetailData.value = []
          clickCheck.value = false
          flag.value = false
        } else {
          // ElMessage.error('操作失败！' + response.data.msg)
          ElMessage({
            message: '操作失败' + response.data.msg,
            type: 'error'
          })
        }
      })

    } else {
      console.log('error submit!', fields)
    }
  })
}
const ids = ref([])
/**
 * 检测项目保存
 */

const handleSaveChe = (ruleFormRef) => {
  getLeibieid()
  ruleFormRef.validate((valid, fields) => {
    if (valid) {
      var url = 'syi/LeiBieTJPD/save'
      bootoomLForm.value.leibietjid = rows.id
      var param = {
        json: JSON.stringify(bootoomLForm.value),
      }
      proxy.$axios.post(url, param).then(response => {
        if (response.data.code == 0) {
          form.value = response.data.data
          ElMessage({
            message: '保存成功',
            type: 'success',
          })
          getDetailData(rows)
          getTreeData()
          dialogVisibleChe.value = false
        } else {
          // ElMessage.error('操作失败！' + response.data.msg)
          ElMessage({
            message: '操作失败' + response.data.msg,
            type: 'error'
          })
        }
      })

    } else {
      console.log('error submit!', fields)
    }
  })
};

/**
 * 项目规则结果界面保存
 */

const handleSaveJC = (ruleFormRef) => {
  if (bootoomRForm.value.xiaxian > bootoomRForm.value.shangxian) {
    ElMessage({
      message: '下限不能大于上限',
      type: 'error'
    })
    return false;
  }
  ruleFormRef.validate((valid, fields) => {
    if (valid) {
      bootoomRForm.value.pdid = Dedata.value.id
      var url = 'syi/LeiBieTJPDJB/save'
      var param = {
        json: JSON.stringify(bootoomRForm.value),
      }
      proxy.$axios.post(url, param).then(response => {
        if (response.data.code == 0) {
          form.value = response.data.data
          ElMessage({
            message: '保存成功',
            type: 'success',
          })
          getPlanDetailData()
          dialogVisibleGZ.value = false
        } else {
          ElMessage({
            message: '操作失败' + response.data.msg,
            type: 'error'
          })
        }
      })

    } else {
      console.log('error submit!', fields)
    }
  })
};

// 编辑
const handleEdit = (row) => {
  dialogVisible.value = true
  console.log(row)
  form.value = JSON.parse(JSON.stringify(row))
  console.log(form.value)
  getLeibieName(row)

}

const openDialog = () => {
  // nextTick(() => {
  //   if(ruleFormRef.value){
  //     ruleFormRef.value.clearValidate()
  //   }

  // })

}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定删除本条记录?',
    '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }
  )
    .then(() => {
      var url = 'syi/checkPlan/remove'
      var param = {
        id: row.id
      }
      proxy.$axios.post(url, param).then(response => {
        if (response.data.code == 0) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          getTableData()
        } else {
          ElMessage({
            type: 'error',
            message: '删除失败' + response.data.msg
          });
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })
};

// =============================== 按钮 =================================
// 检测项目批量删除
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}
const handleRemoveBatch = () => {
  if (multipleSelection.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请选择要删除的数据!'
    })
    return
  }
  ElMessageBox.confirm('此操作将删除该数据, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    var ids = []
    multipleSelection.value.forEach((item, index) => {
      ids.push(item.id)
    })
    var url = 'syi/LeiBieTJPD/removeBatch'
    var param = {
      ids: JSON.stringify(ids)
    }
    proxy.$axios.post(url, param).then(response => {
      if (response.data.code == '0') {
        ElMessage({
          type: 'success',
          message: '操作成功!',
        });
        getDetailData(rows)
        getTreeData()
        dialogVisible.value = false
      } else {
        ElMessage({
          type: 'error',
          message: '操作失败!' + response.data.msg
        });
      }
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}
//对应项目规则批量删除
const handleRemoveBatchGZ = () => {
  if (multipleSelection.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请选择要删除的数据!'
    })
    return
  }
  ElMessageBox.confirm('此操作将删除该数据, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    var ids = []
    multipleSelection.value.forEach((item, index) => {
      ids.push(item.id)
    })
    var url = 'syi/LeiBieTJPDJB/removeBatch'
    var param = {
      ids: JSON.stringify(ids)
    }
    proxy.$axios.post(url, param).then(response => {
      if (response.data.code == '0') {
        ElMessage({
          type: 'success',
          message: '操作成功!',
        });
        getPlanDetailData()
        dialogVisible.value = false
      } else {
        ElMessage({
          type: 'error',
          message: '操作失败!' + response.data.msg
        });
      }
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}
// 批量编辑
const handleEditBatch = () => {
  console.log('handleEditBatch')
  if (multipleSelection.value.length != 1) {
    ElMessage({
      type: 'warning',
      message: '请选择一条数据编辑!'
    })
    return
  }
  handleEdit(multipleSelection.value[0])
}

//新增
const handleAdd = () => {
  form.value = {
    name: '',
    leibieid: '',
    remark: '',
    flag: '',
  }
  console.log(form.value)

  dialogVisible.value = true
}
/**
 * 检测项目表单
 */
const bootoomLForm = ref({
  id: '',
  name: '',
  xiuyuegz: '',
  xiaoshuwei: '',
  sortindex: '',
  xmid: '',
  leibietjid: ''

})

/**
 * 项目规则表单
 */
const bootoomRForm = ref({
  id: '',
  pdid: '',
  jgid: '',
  name: '',
  leixing: '',
  shangxian: '',
  xiaxian: '',
  sjtype: '',
  yangshi: ''
})

/**
 * 新增检测项目
 */
const handleAddCP = () => {
  bootoomLForm.value = {
    id: '',
    name: '',
    xiuyuegz: '',
    xiaoshuwei: '',
    sortindex: '',
    xmid: '',
    leibietjid: ''
  }
  getTreeData()
  if (clickCheck.value) {
    if (data.value.flag == '未启用') {
      dialogVisibleChe.value = true
    } else {
      ElMessage.warning("当前为启用状态，请先关闭该状态")
    }
  } else {
    ElMessage.warning("请先选择产品类别")
  }


}


/**
 *新增项目规则
 */
const flag = ref(false)
const handleAddGZ = () => {
  bootoomRForm.value = {
    id: '',
    pdid: '',
    jgid: '',
    name: '',
    leixing: '',
    shangxian: '',
    xiaxian: '',
    sjtype: '',
    yangshi: ''
  }
  if (flag.value) {
    if (data.value.flag == '未启用') {
      dialogVisibleGZ.value = true
    } else {
      ElMessage.warning("当前为启用状态，请先关闭该状态")
    }
  } else {
    ElMessage.warning("请先选择项目")
  }
}
// 查询
const handleSearch = () => {
  currentPage.value = 1
  detailData.value = []
  planDetailData.value = []

  clickCheck.value = false
  flag.value = false
  getTableData()
  rows = {}

}
/**
 * 获取质检项目名称的树形数据
 */
const treeData = ref([]);

const getTreeData = () => {
  treeData.value = []
  var url = 'syi/LeiBieTJPD/queryJCName'
  var param = {
    params: JSON.stringify(data.value)
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      console.log(response.data.data,"22222222222222222")
      treeData.value = [];
      response.data.data.forEach(x => {
        const treeDataNode = processNode(x)
        treeData.value.push(treeDataNode.value)
        console.log(treeData.value)
      })
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}


const processNode = (node) => {
  const data = ref({
    label: '',
    value: '',
    children: []
  })
  data.value.label = node.name
  data.value.value = node.id

  if (node.children && node.children.length > 0) {
    node.children.forEach(childNode => {
      // 递归处理子节点
      const childData = processNode(childNode)
      data.value.children.push(childData.value)
    })
  }
  return data
}

// 自定义渲染节点内容，结合 el-tooltip 来显示完整文本
const renderNodeContent = (h, { node }) => {
  return h('el-tooltip', {
    content: node.label,  // 完整内容
    placement: 'top',     // 提示显示位置
    effect: "dark"        // 提示框的主题色
  }, [
    h('span', node.label)  // 在节点中显示的简略文本
  ]);
};



/**
 * 获取质检项目类型树形数据
 */
const typeData = ref([]);

const getTypeData = () => {
  typeData.value = []
  var url = 'syi/LeiBieTJPDJB/queryType'
  var param = {}
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      typeData.value = [];
      console.log(response.data.data, "1111111111111111111")
      response.data.data.forEach(x => {
        const treeDataNode = processNodeType(x)
        typeData.value.push(treeDataNode.value)
        console.log(typeData.value)
      })
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}


const processNodeType = (node) => {
  const data = ref({
    label: '',
    value: '',
    children: []
  })
  data.value.label = node.name
  data.value.value = node.id

  if (node.children && node.children.length > 0) {
    node.children.forEach(childNode => {
      // 递归处理子节点
      const childData = processNodeType(childNode)
      data.value.children.push(childData.value)
    })
  }
  return data
}
// 查询产品类型
const typeList = ref([])
const queryType = () => {
  var url = 'syi/wuliao/queryType'
  var param = {}
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      typeList.value = response.data.data
      console.log(response.data.data)
      console.log(typeList.value)
      totalRows.value = response.data.data.total
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}
/**
 * 分页
 */
const currentPage = ref(1)
const pageSizes = ref([5, 10, 20, 30, 40])
const pageSize = ref(5)
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  getTableData()
}
/**
 * 分页
 */

// 方法：根据路由参数获取数据
const param_page = ref()
const getDetail = () => {
  query.value.type = ''
  if (route.query.param) {
    param_page.value = JSON.parse(route.query.param);
    console.log(param_page.value)
    getTableData()
    queryType()
  }
};

// 上方数据查询
const getTableData = () => {

  // console.log(JSON.stringify(param_page.value.id))
  var url = 'syi/checkPlan/query'
  var param = {
    page: currentPage.value,
    rows: pageSize.value,
    params: JSON.stringify(query.value),
    itemCd: param_page.value.itemCd
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      tableData.value = response.data.data.records
      console.log(response.data.data.records[0])
      console.log(tableData.value)
      totalRows.value = response.data.data.total
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}
/**
 * 检测按钮
 */
const clickCheck = ref(false)
const data = ref([])
const handleCheck = async (row) => {
  clickCheck.value = true
  flag.value = false
  data.value = row
  planDetailData.value = []
  detailData.value = []

  // 等待 getDetailData 完成
  await getDetailData(row);

  // 再执行 getTreeData
  getTreeData();

};


/**
 * tab标签页改变,
 */
var u = 'syi/LeiBieTJPD/queryChemistry'
var rows = {}
// 处理标签切换的逻辑
const handleTabChange = (activeNameBottom) => {
  if (Object.keys(rows).length === 0) {
    return
  }
  detailData.value = []
  if (activeNameBottom === 'second') {
    u = 'syi/LeiBieTJPD/queryPhysics'
    getDetailData(rows)  // 确保传入 rows 数据
    getTreeData();
  } else if (activeNameBottom === 'first') {
    u = 'syi/LeiBieTJPD/queryChemistry'
    getDetailData(rows)  // 可以根据需要在切换回化学检测时也调用查询
    getTreeData()
  }
}

//左下方数据查询
const getDetailData = (row) => {

  rows = row
  var url = u
  var param = {
    json: JSON.stringify(row),
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      detailData.value = response.data.data
    } else {
      // ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}
//定义一个中间变量
const Dedata = ref([])
// 单击一行数据进行查询
const handleClick = (row) => {
  Dedata.value = row
  flag.value = true; // 一旦点击行，允许按钮点击
  console.log(Dedata.value, "2222222222222")
  getPlanDetailData()
};
// 右下方数据查询
const getPlanDetailData = () => {
  var url = 'syi/LeiBieTJPDJB/query'
  var param = {
    json: JSON.stringify(Dedata.value),
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      planDetailData.value = response.data.data
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}
// 使用 watch 监听路由参数的变化
watch(
  () => route.query.param,
  (newParam) => {
    if (newParam) {
      form.value = JSON.parse(newParam);
      getDetail();
      // 路由参数发生变化时重新获取数据
    }
  }
);

</script>

<style scoped></style>
