<template>
    <el-dialog  :title="dialogTitle" v-model='dialogVisible' @close="close" v-bind="dialogBig" width="1500px">
        <el-tabs type="border-card">
            <el-tab-pane label="基础信息">
                <div >
                    <el-form :model="formContent" ref='dialogFormRef' :rules='rules' label-width="auto" class="form-three">
                        <el-form-item  label="标准号" prop="standardName" >
                            <el-input  v-model='formContent.standardName'   placeholder="请填写标准号"/>
                        </el-form-item>
                        <el-form-item label="标准推行年份" prop="standardTime" >
                            <el-date-picker
                                v-model="formContent.standardTime"
                                type="year"
                                placeholder="请选择标准推行年份"
                                />
                        </el-form-item>
                        <el-form-item label="适用设备等级" prop="devLevel" >
                            <el-select v-model='formContent.devLevel' placeholder="请选择设备等级">
                                <el-option
                                        v-for="item in dictStore.getDictData('Dev_Level')"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id"/>       
                            </el-select>        
                        </el-form-item>
                        <el-form-item label="状态" prop="enable" >
                            <el-select v-model='formContent.enable' placeholder="请选择状态">
                                <el-option label="启用" :value="1"></el-option>
                                <el-option label="不启用" :value="0"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-form>
                </div>
            </el-tab-pane>
        </el-tabs>
  
         
        <ErrorSystemDetailTable :tableData="tableData" :errorOptions="errorOptions"  :scriptOptions="scriptOptions" @updateTableData="handleTableDataUpdate" />
        
        <template #footer>
            <div >
                <el-button @click='close()'>取 消</el-button>
                <el-button type="primary" @click='save()'>保存</el-button>
            </div>
        </template>
    </el-dialog>


</template>
  
  <script lang="ts" setup name="ErrorSystemDialog">
  import{type CascaderOption, 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 { addPqErrSys,updatePqErrSys,getPqErrSysListById} from '@/api/device/error/index'
  import {CirclePlus, Delete, EditPen,FolderOpened,CopyDocument} from '@element-plus/icons-vue'
  import { useDictStore } from '@/stores/modules/dict'
  import { type ErrorSystem } from '@/api/device/interface/error';
  import ErrorSystemDetailTable from '@/views/machine/errorSystem/components/errorSystemDetailTable.vue';
  import {getDictTreeList} from '@/api/system/dictionary/dictTree'
  import { type Dict } from '@/api/system/dictionary/interface';
  // 定义弹出组件元信息
  const dialogFormRef = ref()
  const dictStore = useDictStore()
  const tableData = ref<ErrorSystem.ErrorSystemDetail[]>([]);
  const errorOptions: Ref<CascaderOption[]> = ref([]); // 修改这里
  const scriptOptions: Ref<CascaderOption[]> = ref([]); // 修改这里
   
const handleTableDataUpdate = (newTableData: ErrorSystem.ErrorSystemDetail[]) => {
        tableData.value = newTableData;
};

  function useMetaInfo() {
    const dialogVisible = ref(false)
    const titleType = ref('add')
    const formContent = ref<ErrorSystem.ErrorSystemList>({
        id: '',
        name: '',
        standardName: '',
        standardTime: '',
        devLevel: '',
        enable: 1,
        state:1,
        pqErrSysDtlsList:[]
    })
    return { dialogVisible, titleType, formContent }
  }
  
  const { dialogVisible, titleType, formContent } = useMetaInfo()
  // 清空formContent
  const resetFormContent = () => {
    formContent.value = {
        id: '',
        name: '',
        standardName: '',
        standardTime: '',
        devLevel: '',
        enable: 1,
        state:1,
        pqErrSysDtlsList:[]
    }
    tableData.value  =[]
  }
  
  let dialogTitle = computed(() => {
    return titleType.value === 'add' ? '新增误差体系' : '编辑误差体系'
  })

    // 定义规则
    const rules: Ref<Record<string, Array<FormItemRule>>> = ref({
    name: [{ required: true, message: '误差体系名称必填！', trigger: 'blur' }],
    standardName: [{ required: true, message: '参照标准名称必填！', trigger: 'blur' }],
    standardTime: [{ required: true, message: '标准推行年份必选！', trigger: 'blur' }],
    devLevel:[{ required: true, message: '请选择一项设备等级', trigger: 'change' },],
    enable:[{ required: true, message: '请选择一项状态', trigger: 'change '},]
});    


    // 关闭弹窗
    const close = () => {
        dialogVisible.value = false
        // 清空dialogForm中的值
        resetFormContent()
        // 重置表单
        dialogFormRef.value?.resetFields()
    }
  
    // 保存数据
    const save = () => {
        try {      
            dialogFormRef.value?.validate(async (valid: boolean) => {
            if (valid) {
                 // 确保 standardTime 是 Date 对象
                 if (formContent.value.standardTime) {
                    const date = new Date(formContent.value.standardTime);
                    formContent.value.standardTime = date.getFullYear().toString();
                }
            
                formContent.value.pqErrSysDtlsList = tableData.value
                if (formContent.value.id) {
                    await updatePqErrSys(formContent.value);
                    ElMessage.success({ message: `${dialogTitle.value}成功！` })
                } else {  
                    await addPqErrSys(formContent.value);
                    ElMessage.success({ message: `${dialogTitle.value}成功！` })    
                }            
                close()
                // 刷新表格
                await props.refreshTable!()       

            }
        })
    } catch (err) {
        console.error('验证过程中出现错误', err)
    }
    }
 // 封装提取第二层节点的逻辑
const loadSecondLevelOptions = async () => {
  const dictCode = '误差体系指标项'; // 替换为实际需要的字典代码
  const dictCode2 = '脚本-误差'; // 替换为实际需要的字典代码

  const resDictTree: Dict.ResDictTree = {
    name: dictCode,
    id: '',
    pid: '',
    pids: '',
    code: '',
    sort: 0
  };

  const resDictTree2: Dict.ResDictTree = {
    name: dictCode2,
    id: '',
    pid: '',
    pids: '',
    code: '',
    sort: 0
  };

  // 并行请求两个字典树列表
  const [result, result2] = await Promise.all([
    getDictTreeList(resDictTree),
    getDictTreeList(resDictTree2)
  ]);

  const allOptions = convertToOptions(result.data as Dict.ResDictTree[]);
  const allOptions2 = convertToOptions(result2.data as Dict.ResDictTree[]);

  // 提取第二层节点
  const secondLevelOptions: any[] = [];
  allOptions.forEach(option => {
    if (option.children && option.children.length > 0) {
      secondLevelOptions.push(...option.children);
    }
  });

  const secondLevelOptions2: any[] = [];
  allOptions2.forEach(option => {
    if (option.children && option.children.length > 0) {
      secondLevelOptions2.push(...option.children);
    }
  });

  // 将第二层节点赋值给 options.value
  errorOptions.value = secondLevelOptions;
  scriptOptions.value = secondLevelOptions2;
};

    // 转换函数
    const convertToOptions = (dictTree: Dict.ResDictTree[]): CascaderOption[] => {
    return dictTree.map(item => ({
        value: item.id,
        label: item.name,
        code: item.code,
        children: item.children ? convertToOptions(item.children) : undefined
    }));
    };

    
 // 打开弹窗，可能是新增，也可能是编辑
const open = async (sign: string, data: ErrorSystem.ErrorSystemList) => {
  titleType.value = sign;

  // 并行执行两个异步操作
  const loadOptionsPromise = loadSecondLevelOptions();
  const fetchDataPromise = data.id ? getPqErrSysListById(data) : Promise.resolve(null);

  const [_, result] = await Promise.all([loadOptionsPromise, fetchDataPromise]);

  if (result && result.data) {
    formContent.value = result.data as ErrorSystem.ErrorSystemList;
    tableData.value = formContent.value.pqErrSysDtlsList || [];
  } else {
    resetFormContent();
  }

  // 重置表单
  dialogFormRef.value?.resetFields();
  dialogVisible.value = true;
};


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

</style>
  
