<template>
<el-dialog 
  width="900px" 
  append-to-body 
  :title="isShow ? '查看数据标准' : isEdit ? '修改数据标准' : '新增数据标准'" 
  v-model="visible" 
  @close="handleClose"
>
  <el-form 
    :model="formData" 
    ref="formRef" 
    label-width="120px" 
    :rules="formRules"
  >
    <!-- 第一行：三列 -->
    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item label="标准归属" prop="dataStdVest">
          <el-select
            v-model="formData.dataStdVest"
            placeholder="请选择字典归属"
            maxlength="30"
            @change="changeCodeType"
          >
            <el-option
              v-for="dict in std_code_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="8" v-if="showSys">
        <el-form-item label="来源系统" prop="srcSys">
          <el-select
            v-model="formData.srcSys"
            :disabled="isShow"
            placeholder="请选择来源系统"
            @change="handleSystemChange"
          >
            <el-option
              v-for="dict in dbResourceOldList"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="8">
        <el-form-item label="公司级数据标准" prop="companyLevelDataStdNo">
          <el-select
            v-model="formData.companyLevelDataStdNo"
            placeholder="公司级数据标准"
            filterable
            clearable
            :filter-method="filterStdList"
          >
            <el-option
              v-for="dict in filteredStdList"
              :key="dict.onum"
              :label="dict.dataStdNo + '-' + dict.dataStdEngName + '-' + dict.dataStdCnName"
              :value="dict.dataStdNo"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 第二行：三列 -->
    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item label="标准编号" prop="dataStdNo">
          <el-input 
            v-model="formData.dataStdNo" 
            :disabled="isEdit || isShow" 
            placeholder="请输入标准编号" 
            clearable 
          />
        </el-form-item>
      </el-col>

      <el-col :span="8">
        <el-form-item label="标准中文名" prop="dataStdCnName">
          <el-input 
            v-model="formData.dataStdCnName" 
            :disabled="isShow" 
            placeholder="请输入标准中文名" 
            clearable 
          />
        </el-form-item>
      </el-col>

      <el-col :span="8">
        <el-form-item label="标准英文名" prop="dataStdEngName">
          <el-input 
            v-model="formData.dataStdEngName" 
            :disabled="isShow" 
            placeholder="请输入标准英文名" 
            clearable 
          />
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 第三行：标准业务定义独占一行 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-form-item label="标准业务定义" prop="dataStdBusiDefn">
          <el-input
            type="textarea"
            v-model="formData.dataStdBusiDefn"
            :disabled="isShow"
            placeholder="请输入标准业务定义"
            clearable
            rows="4"
          />
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 第四行：三列 -->
    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item label="标准类型" prop="dataStdType">
          <el-select 
            v-model="formData.dataStdType" 
            :disabled="isShow" 
            placeholder="请选择标准类型"
          >
            <el-option label="基础数据" value="0" />
            <el-option label="指标数据" value="1" />
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="8">
        <el-form-item label="标准来源" prop="dataStdSrc">
          <el-select 
            v-model="formData.dataStdSrc" 
            :disabled="isShow" 
            placeholder="请选择标准来源"
          >
            <el-option label="行业标准" value="行业标准" />
            <el-option label="自建标准" value="自建标准" />
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="8">
        <el-form-item label="数据类别" prop="dataClas">
          <el-select 
            v-model="formData.dataClas" 
            :disabled="isShow" 
            placeholder="请选择数据类别"
          >
            <el-option label="日期类" value="日期类" />
            <el-option label="文本类" value="文本类" />
            <el-option label="数值类" value="数值类" />
            <el-option label="金额类" value="金额类" />
            <el-option label="编码类" value="编码类" />
            <el-option label="标志类" value="标志类" />
            <el-option label="码值类" value="码值类" />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 其余字段也按三列布局排布即可 -->
    <el-row justify="center" style="margin-top: 20px;" v-if="!isShow">
      <el-col :span="4" style="padding-right: 10px;">
        <el-button @click="handleClose" style="width: 100%" plain>取消</el-button>
      </el-col>
      <el-col :span="4" style="padding-left: 10px;">
        <el-button type="primary" @click="handleSubmit" style="width: 100%">保存</el-button>
      </el-col>
    </el-row>
  </el-form>
</el-dialog>

</template>

<script setup>
import { ref, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { updateStdMain, addStdMain } from '@/api/datastd/std'
import { listUser, deptTreeSelect } from "@/api/system/user"
import codeComponents from '../../stdcode/codeComponents.vue'
const { proxy } = getCurrentInstance();
const { std_code_status,std_code_appr } = proxy.useDict("std_code_status","std_code_appr");
const emit = defineEmits(['update:visible', 'refresh'])

const props = defineProps({
  data: { type: Object, default: () => ({}) },
  isEdit: { type: Boolean, default: false },
  isShow: { type: Boolean, default: false },
  visible: { type: Boolean, required: true },
    stdList: {
    type: Object,
    required: false,
  },
  dbResourceOldList: { type: Array, default: () => [] }
})

// 表单数据（完整映射所有数据库字段）

const formData = ref({ ...props.data });
const filterStdList = (query) => {
  searchQuery.value = query; // 更新搜索词
};
// 初始化表单数据
watch(() => props.data, (newVal) => {
  if (newVal) {
    formData.value=props.data 
  if (formData.value.dataStdVest !== "company") {
      showSys.value = true
    } else {
      showSys.value = false
    }
  }
}, { immediate: true })
const searchQuery = ref(''); // 存储用户输入的搜索词

const filteredStdList = computed(() => {
  if (!searchQuery.value) return props.stdList; // 如果没有输入，返回全部
  const query = searchQuery.value.toLowerCase();
  return props.stdList.filter(dict => 
    dict.dataStdNo.toLowerCase().includes(query) ||
    dict.dataStdEngName.toLowerCase().includes(query) ||
    dict.dataStdCnName.toLowerCase().includes(query)
  );
});
// 表单验证规则
const formRules = ref({
  dataStdNo: [{ required: true, message: '请输入标准编号', trigger: 'blur' }],
  dataStdVest: [{ required: true, message: '请选择标准归属', trigger: 'change' }],
  dataStdCnName: [{ required: true, message: '请输入标准中文名', trigger: 'blur' }],
  dataStdType: [{ required: true, message: '请选择标准类型', trigger: 'change' }],
  dataStdSrc: [{ required: true, message: '请选择标准来源', trigger: 'change' }],
  dataClas: [{ required: true, message: '请选择数据类别', trigger: 'change' }],
  // dataStdBusiOwnershipDept: [{ required: true, message: '请选择业务认责部门', trigger: 'change' }],
  // dataStdItOwnershipDept: [{ required: true, message: '请选择技术认责部门', trigger: 'change' }]
})

// 组件状态
const visible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})
const codeVisible = ref(false)
const deptOptions = ref([])
const userList = ref([])

// 初始化部门树和用户列表
const initData = async () => {
  try {
    const [deptRes, userRes] = await Promise.all([
      deptTreeSelect(),
      listUser({ pageSize: 1000, pageNum: 1 })
    ])
    deptOptions.value = deptRes.data
    userList.value = userRes.rows
  } catch (error) {
    ElMessage.error('初始化数据失败')
    console.error(error)
  }
}
const showSys = ref(false);

function changeCodeType(data) {
  if (data != "company") {
    showSys.value = true;
    formData.value.sysName = "";
    formData.value.srcSys = undefined;
  } else {
    showSys.value = false;
    formData.value.sysName = "公司级";
    formData.value.srcSys = 10000;
  }
}
// 系统选择变化处理
const handleSystemChange = (id) => {
  const system = props.dbResourceOldList.find(item => item.id === id)
  if (system) {
    formData.value.sysName = system.name
  }
}

// 代码选择处理
const handleCodeSelect = () => {
  const selectedCodes = proxy.$refs.showCodeDialog?.selections || []
  if (selectedCodes.length !== 1) {
    ElMessage.warning('请选择一条代码')
    return
  }
  
  const code = selectedCodes[0]
  formData.value.cdId = code.onum
  formData.value.cdNo = code.cdNo || code.onum
  codeVisible.value = false
  ElMessage.success('代码选择成功')
}

// 表单提交
const handleSubmit = () => {
  proxy.$refs.formRef.validate(async (valid) => {
    if (!valid) return;
    
    try {
      // 直接使用驼峰命名的表单数据，不进行下划线转换
      const submitData = { ...formData.value };
      
      // 处理特殊字段类型转换
      submitData.srcSys = Number(submitData.srcSys) || null;
      submitData.beltDataStdContent = Number(submitData.beltDataStdContent) || null;
      
      // 确保必填字段有值（特别是技术认责人员和业务认责人员）
      submitData.dataStdItOwnershipPrsn = submitData.dataStdItOwnershipPrsn || '';
      submitData.dataStdBusiOwnershipPrsn = submitData.dataStdBusiOwnershipPrsn || '';
      
      // 根据模式调用API
      const api = props.isEdit ? updateStdMain : addStdMain;
      const res = await api(submitData);
      
      if (res.code === 200) {
        ElMessage.success(props.isEdit ? '已提交修改审核' : '已提交新增审核');
        emit('refresh');
        handleClose();
      } else {
        ElMessage.error(res.msg || '操作失败');
      }
    } catch (error) {
      console.error('提交失败:', error);
      
      // 特定错误处理（如数据库约束错误）
      if (error.message.includes('cannot be null')) {
        const column = error.message.match(/Column '(.*?)'/)[1];
        ElMessage.warning(`字段 ${column} 不能为空`);
      }
    }
  });
};

// 关闭弹窗
const handleClose = () => {
  proxy.$refs.formRef.resetFields()
  visible.value = false
}

// 初始化
initData()
</script>