<template> 
   <!-- 基础信息弹出框 -->
   <el-dialog :title="dialogTitle" v-model='dialogVisible' @close="close" v-bind="dialogBig">
  <div>
    <el-row :gutter="24">
      <el-col :span="12">
        <el-form :model="formContent" ref='dialogFormRef' :rules='rules'>
          <el-form-item label="名称" prop="name" :label-width="100">
            <el-input v-model="formContent.name" placeholder="请输入名称" autocomplete="off"/>
          </el-form-item>
          <el-form-item label='检测源' prop='sourceIds' :label-width='100'>
            <el-select v-model="formContent.sourceIds" :multiple="selectByMode" collapse-tags placeholder="请选择检测源">
              <el-option
                v-for="(option, index) in pqSourceArray"
                :key="index"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="数据源" prop="datasourceIds" :label-width="100">
            <el-select v-model="formContent.datasourceIds" :multiple="selectByMode" collapse-tags placeholder="请选择数据源" autocomplete="off">
              <el-option
                v-for="item in dictStore.getDictData(dataSourceType)"
                :key="item.id"
                :label="item.name"
                :value="item.value || ''"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="检测脚本" prop="scriptId" :label-width="100">
            <el-select v-model="formContent.scriptId" placeholder="请选择检测脚本" autocomplete="off" :disabled="isSelectDisabled ">
              <el-option
                v-for="(option, index) in pqScriptArray"
                :key="index"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="误差体系" prop="errorSysId" :label-width="100">
            <el-select v-model="formContent.errorSysId" placeholder="请选择误差体系" autocomplete="off" :disabled="isSelectDisabled">
              <el-option
                v-for="(option, index) in pqErrorArray"
                :key="index"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="守时检测" :label-width="100" prop='timeCheck'>
            <el-radio-group v-model="formContent.timeCheck">
              <el-radio :value="1">是</el-radio>
              <el-radio :value="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="12">
          <el-transfer
            v-model="value"
            filterable
            :filter-method="filterMethod"
            filter-placeholder="请输入内容搜索"
            :data="allData"
            :titles="['未绑定设备', '已绑定设备']">
            <template #default="{ option }">
              <el-tooltip :content="option.tips" placement="top" :show-after=1000>
                <span>{{ option.label }}</span>
              </el-tooltip>
            </template>
          </el-transfer>
      </el-col>
    </el-row>
  </div>
  <template #footer>
    <div class="dialog-footer">
      <el-button @click='close()'>取 消</el-button>
      <el-button type="primary" @click='save()'>确 定</el-button>
    </div>
  </template>
</el-dialog>
</template>

<script setup lang="ts">
  import{ElMessage, type FormInstance,type FormItemRule}from'element-plus'
  import { defineProps, defineEmits, reactive,watch,ref, type Ref, computed } from 'vue';
  import { dialogBig} from '@/utils/elementBind'
  import { type Plan } from '@/api/plan/interface';
  import { addPlan, updatePlan,getUnboundPqDevList,getBoundPqDevList,getPqErrSysList,getPqScriptList,getTestSourceList } from '@/api/plan/plan.ts'
  import { useDictStore } from '@/stores/modules/dict'
  import { type TestSource } from '@/api/device/interface/testSource';
  import { type TestScript } from '@/api/device/interface/testScript';
  import { type ErrorSystem } from '@/api/device/interface/error';
  import { type Device } from '@/api/device/interface/device';
import { Loading } from '@element-plus/icons-vue/dist/types';
import { truncate } from 'lodash';



  const dictStore = useDictStore()
  // 定义弹出组件元信息
  const dialogFormRef = ref()
  const mode = ref()
  const selectByMode = ref(true)
  const pqSourceList=ref<TestSource.ResTestSource[]>([])//获取指定模式下所有检测源 
  const pqScriptList=ref<TestScript.ResTestScript[]>([])//获取指定模式下所有检测源 
  const pqErrSysList=ref<ErrorSystem.ErrorSystemList[]>([])//获取指定模式下所有检测源 
  const pqDevList=ref<Device.ResPqDev[]>([])//获取指定模式下所有检测源 

  const pqSourceArray = ref<{ label: string; value: string; }[]>()
  const pqScriptArray = ref<{ label: string; value: string; }[]>()
  const pqErrorArray = ref<{ label: string; value: string; }[]>()
  const pqDevArray = ref<{ label: string; value: string; }[]>()



  const unboundPqDevList=ref<Device.ResPqDev[]>([])//指定模式下所有未绑定的设备
  const boundPqDevList=ref<Device.ResPqDev[]>([])//根据检测计划id查询出所有已绑定的设备 
  const value = ref<string[]>([])
  const allData = computed(() => generateData())
  const isSelectDisabled = ref(false)
const generateData = () => {
  const unboundData = unboundPqDevList.value.map((i: Device.ResPqDev) => ({
    key: i.id,
    label: i.name,
    //tips: i.description
  }))
  const boundData = boundPqDevList.value.map((i: Device.ResPqDev) => ({
    key: i.id,
    label: i.name,
    //tips: i.description
    disabled:i.checkState != 0 ,
  }))
  return [...unboundData, ...boundData]
}

const filterMethod = (query: string, item: { label?: string }) => {
  return item.label?.toLowerCase().includes(query.toLowerCase()) ?? false
}


  function useMetaInfo() {
    const dialogVisible = ref(false)
    const titleType = ref('add')
    const formContent = reactive<Plan.ReqPlan>({
                        id:'',
                        planId:'',
                        name: '',
                        pattern: mode.value,
                        fatherPlanId: '',
                        dataSourceId: '',
                        scriptId: '',
                        errorSysId: '',
                        timeCheck:0,
                        testState: 0,
                        reportState: 0,
                        result: 2,
                        code:1,
                        state:1,
                        scriptName:'',
                        errorSysName:'',
                        sourceName:'',
                        devIds:[],
                        sourceIds:'',
                        datasourceIds:'',
                      })
    return { dialogVisible, titleType, formContent }
  }

  const { dialogVisible, titleType, formContent } = useMetaInfo()

  // 清空formContent
  const resetFormContent = () => {
    Object.assign(
      formContent,{
        id:'',
        planId:'',
        name: '',
        pattern: mode.value,
        fatherPlanId: '',
        dataSourceId: '',
        scriptId: '',
        errorSysId: '',
        timeCheck:0,
        testState: 0,
        reportState: 0,
        result: 2,
        code:1,
        state:1,
        scriptName:'',
        errorSysName:'',
        sourceName:'',
        devIds:[],
        sourceIds:'',
        datasourceIds:'',
      }
    )
    
  }

  let dialogTitle = computed(() => {
    return titleType.value === 'add' ? '新增检测计划' : '编辑检测计划'
  })

  
// 定义规则
const formRuleRef = ref<FormInstance>()
const rules: Ref<Record<string, Array<FormItemRule>>> = ref({
    name: [{ required: true, message: '检测计划名称必填！', trigger: 'blur' }],
    sourceIds: [{ required: true, message: '检测源必选！', trigger: 'blur' }],
    datasourceIds: [{ required: true, message: '数据源必选！', trigger: 'blur' }],
    scriptId: [{ required: true, message: '检测脚本必选！', trigger: 'blur' }],
    errorSysId: [{ required: true, message: '误差体系必选！', trigger: 'blur' }],
});

  // 关闭弹窗
  const close = () => {
    value.value = []
    dialogVisible.value = false
    // 清空dialogForm中的值
    resetFormContent()
    // 重置表单
    dialogFormRef.value?.resetFields()
   
  }


   // 保存数据
   const save = () => {
    try {      
        dialogFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
          formContent.devIds = value.value
           // 将 formContent.devIds 转换为 ReqPqDevParams 数组
          //  boundPqDevList.value = pqDevList.value
          //                       .filter(device => formContent.devIds.includes(device.id))
          //                       .map(device => ({
          //                         id: device.id,
          //                         name: device.name,
          //                         devType: device.devType,
          //                         createTime: device.createDate,
          //                         pattern: device.pattern,
          //                       }));

      
          if (formContent.id) {
                if( mode.value === '比对式'){
                  await updatePlan(formContent)
                }else{
                  await updatePlan({...formContent,'sourceIds':[formContent.sourceIds],'datasourceIds':[formContent.datasourceIds]});
                }
                ElMessage.success({ message: `${dialogTitle.value}成功！` })

            } else {  
              // 新增需要把设备模式转成字典ID
              const patternItem = dictStore.getDictData('Pattern').find(item => item.name === formContent.pattern);
              if (patternItem) {
                  formContent.pattern = patternItem.id;
              }
              if( mode.value === '比对式'){
                  await addPlan(formContent);
                }else{
                  await addPlan({...formContent,'sourceIds':[formContent.sourceIds],'datasourceIds':[formContent.datasourceIds]});
                }
              ElMessage.success({ message: `${dialogTitle.value}成功！` })
            }
          close()
          // 刷新表格
          await props.refreshTable!()

        }
    })
  } catch (err) {
    console.error('验证过程中出现错误', err)
  }
}


// 打开弹窗，可能是新增，也可能是编辑
const open = async (sign: string, 
              data: Plan.ReqPlan,
              currentMode: string,) => {
    unboundPqDevList.value = []
    boundPqDevList.value = []
     //处理异步调用
     const patternId   = dictStore.getDictData('Pattern').find(item=>item.name=== currentMode)?.id ?? ''
     data.pattern = patternId
     mode.value = currentMode
     titleType.value = sign
     isSelectDisabled.value = false
      if (data.id) {
          if(data.testState === 0){
            isSelectDisabled.value = false
          }else{
            isSelectDisabled.value = true
          }
          
          Object.assign(formContent,{ ...data })
      } else {
        resetFormContent()
      }
      // 重置表单
      dialogFormRef.value?.resetFields()

     if(sign == 'add')
      {
        const [pqSource_Result, PqScript_Result, PqErrSys_Result,pqDevList_Result] = await Promise.all([
            getTestSourceList(data),
            getPqScriptList(data),
            getPqErrSysList(),
            getUnboundPqDevList(data)
        ]);

        pqSourceList.value = pqSource_Result.data as TestSource.ResTestSource[];
        pqScriptList.value = PqScript_Result.data as TestScript.ResTestScript[];
        pqErrSysList.value = PqErrSys_Result.data as unknown as ErrorSystem.ErrorSystemList[];  
        pqDevList.value = pqDevList_Result.data as Device.ResPqDev[];
        // 初始化 boundPqDevList 为空数组
        unboundPqDevList.value = pqDevList.value 
        boundPqDevList.value = [];
      }else{//编辑时先给表单赋值（这会没接收被检设备），需要手动再给被检设备复制后整体表单赋值
        const [pqSource_Result, PqScript_Result, PqErrSys_Result,boundPqDevList_Result, unboundPqDevList_Result] = await Promise.all([
            getTestSourceList(data),
            getPqScriptList(data),
            getPqErrSysList(),    
            getBoundPqDevList({ 'planId': data.id }),
            getUnboundPqDevList(data)
        ]);
        
        pqSourceList.value = pqSource_Result.data as TestSource.ResTestSource[];
        pqScriptList.value = PqScript_Result.data as TestScript.ResTestScript[];
        pqErrSysList.value = PqErrSys_Result.data as unknown as ErrorSystem.ErrorSystemList[];  
        const boundData = Array.isArray(boundPqDevList_Result.data) ? boundPqDevList_Result.data : [];
        const unboundData = Array.isArray(unboundPqDevList_Result.data) ? unboundPqDevList_Result.data : [];

        pqDevList.value = [...boundData,...unboundData] as Device.ResPqDev[];
        formContent.devIds = boundData.map(i =>  i.id );// 已绑定设备id集合

        Object.assign(formContent,{ ...data })
        //设备绑定显示
        unboundPqDevList.value = unboundPqDevList_Result.data as Device.ResPqDev[];
        boundPqDevList.value = boundPqDevList_Result.data as Device.ResPqDev[];
      }

      pqToArray();//将对象转为数组

      if( mode.value != '比对式'){
          selectByMode.value = false
          // 将 formContent.sourceIds 从数组转换为字符串
          if (Array.isArray(formContent.sourceIds)) {
                      formContent.sourceIds = formContent.sourceIds.join(',');
                  }  
          // 将 formContent.sourceIds 从数组转换为字符串
          if (Array.isArray(formContent.datasourceIds)) {
              formContent.datasourceIds = formContent.datasourceIds.join(',');
          } 
      }

      value.value = boundPqDevList.value.map((i: { id: { toString: () => any } }) => i.id.toString());
       // 所有数据加载完成后显示对话框
       dialogVisible.value = true;
}


function pqToArray() {
  const sourceArray1 = Array.isArray(pqSourceList.value) ? pqSourceList.value : []
      // 将 pqSource_Result 转换成 { label, value } 数组
      pqSourceArray.value = sourceArray1.map(item => ({
        label: item.name  || '',
        value: item.id
      }));

      const sourceArray2 = Array.isArray(pqScriptList.value ) ? pqScriptList.value  : []
      pqScriptArray.value = sourceArray2.map(item => ({
        label: item.name  || '',
        value: item.id  || ''
      }));

      const sourceArray3 = Array.isArray(pqErrSysList.value) ? pqErrSysList.value : []
      pqErrorArray.value = sourceArray3.map(item => ({
        label: item.name,
        value: item.id
      }));

      const sourceArray4 = Array.isArray(pqDevList.value) ? pqDevList.value : []
      pqDevArray.value = sourceArray4.map(item => ({
        label: item.name,
        value: item.id
    }))
}

const dataSourceType = computed(() => {
      switch (mode.value) {
        case '模拟式':
          return 'Datasource_Simulate'
        case '数字式':
          return 'Datasource_Digital'
        default:
          return 'Datasource_Contrast'
      }
    })



// 对外映射
defineExpose({ open })
const props = defineProps<{
  refreshTable: (() => Promise<void>) | undefined;
}>()


</script>

<style scoped lang="scss">
// :deep(.dialog-small .el-dialog__body){
//   max-height: 330px !important;
// }
</style>