  <template>
  <!-- 病历文件基本信息弹窗 -->
  <el-dialog
    :title="title"
    v-model="dialogVisible"
    width="900px"
    destroy-on-close
    @open="handleOpen"
  >
    <!-- 使用el-form包裹表单 -->
    <el-form :model="formData" ref="formRef" :rules="rules" label-width="120px">
       <el-form-item label="一级菜单" prop="primaryMenuEnum">
        <el-select 
          v-model="formData.primaryMenuEnum" 
          placeholder="请选择一级菜单"
          value-key="value"
        >
          <el-option
            v-for="item in props.docTypes || []"
            :key="item.value"
            :label="item.info"
            :value="Number(item.value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="二级菜单" prop="subMenu">
        <el-input v-model="formData.subMenu" placeholder="二级菜单"></el-input>
      </el-form-item>
      <el-form-item label="版本" prop="version">
        <el-input v-model="formData.version" placeholder="请输入版本"></el-input>
      </el-form-item>
      
      <el-form-item label="名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入名称"></el-input>
      </el-form-item>
      <el-form-item label="文件" prop="vueRouter">
        <el-select v-model="formData.vueRouter" placeholder="请选择文件路径">
          <el-option
            v-for="item in components"
            :key="item.name"
            :label="item.name"
            :value="item.name"
          />
        </el-select>
        <!-- <el-input v-model="formData.vueRouter" placeholder="请输入文件路径"></el-input>s -->
      </el-form-item>
      <el-form-item label="显示顺序" prop="displayOrder">
       <el-input-number v-model="formData.displayOrder"  :min="1"  label="描述文字"></el-input-number>
      </el-form-item>
      <el-form-item label="使用范围" prop="useRangeEnum">
        <div class="radio-group">
          <el-radio 
            v-for="item in props.useRanges" 
            :key="item.value" 
            v-model="formData.useRangeEnum" 
            :label="item.value"
          >{{item.info}}</el-radio>

          {{ formData.organizationIds }}
        </div>
      </el-form-item>
      
      <!-- 科室选择框，仅当使用范围为科室使用时显示 -->
      <el-form-item v-if="formData.useRangeEnum === 2" label="科室选择" prop="organizationIds">
        <el-transfer
          v-model="formData.organizationIds"
          filterable
          :titles="['未分配科室', '已分配科室']"
          :button-texts="['移除', '添加']"
          :format="{
            noChecked: '${total}',
            hasChecked: '${checked}/${total}',
          }"
          :props="{key: 'id', label: 'name',}"
          :data="transferData"
        >
        </el-transfer>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer"></div>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </template>
  </el-dialog>
</template>
<script setup >
import { ref, onMounted } from 'vue'
import useUserStore from '@/store/modules/user';
import { add, update,getLocationTree } from '../api';
import { ElMessage } from 'element-plus';
import { components } from '@/template';
const emits = defineEmits(['submitOk'])
const props = defineProps({
  title: {
    type: String,
    default: '编辑病历文件信息'
  }, 
  formData: {
    type: Object,
    default: () => ({}) 
  },
  currentNodeData: {
    type: Object,
    default: () => ({})
  },
  docTypes: {
    type: Array,
    default: () => []
  },
  useRanges: {
    type: Array,
    default: () => []
  },
})
const userStore = useUserStore();
const formRef = ref(null)

const dialogVisible= defineModel( 'dialogVisible', {
  type: Boolean,
  default: false
})

// 表单数据
const formData = ref({
  primaryMenuEnum: undefined,
  subMenu: '',
  displayOrder: 1,
  version: '',
  name: '',
  vueRouter: '',
  useRangeEnum: 0, // 默认"暂不使用"（0：暂不使用，1：全院使用，2：科室使用）
  organizationIds: [], // 选中的科室ID列表（整数类型）
  environment: '0'
});
// 表单验证规则（响应式，支持动态验证）
const rules = reactive({
  primaryMenuEnum: [{ required: true, message: '请选择一级菜单', trigger: 'change' }],
  // subMenu: [{ required: true, message: '请输入二级菜单', trigger: 'blur' }],
  version: [{ required: true, message: '请输入版本', trigger: 'blur' }],
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  vueRouter: [{ required: true, message: '请输入文件路径', trigger: 'blur' }],
  displayOrder: [{ required: true, message: '请设置显示顺序', trigger: 'change' }],
  useRangeEnum: [{ required: true, message: '请选择使用范围', trigger: 'change' }],
  organizationIds: [
    { 
      required: () => formData.value.useRangeEnum === 2, // 仅当"科室使用"时必填
      message: '请选择科室', 
      trigger: ['change', 'blur'] 
    }
  ]
});
const transferData = ref([]);
/** 查询科室树数据（TreeSelect和Transfer共用） */
const getLocationInfo = () => {
  
   getLocationTree().then((response) => {
    transferData.value = response?.data || [];
 }).catch((error) => {
    ElMessage.error('获取科室树失败');
 });
}
/** 递归将所有ID转换为整数类型 */
const convertIdsToNumbers = (item) => {
  return {
    ...item,
    id: Number(item.id), // 确保ID为整数
    ...(item.children && item.children.length > 0 
      ? { children: item.children.map((child  ) => convertIdsToNumbers(child)) } 
      : {})
  };
};
const handleOpen = () => {
   
  
  if (props.formData) {
    console.log('props.formData', props.formData);
   formData.value= props.formData
  } else {
     resetForm();
     formRef.value.resetFields()
  }
}

// 提交表单
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 表单验证通过，执行保存操作
      saveForm();
    } else {
      // 表单验证失败
      ElMessage.error('请填写必填项');
      return false;
    }
  });
};
// 保存表单
const saveForm =async () => {
  const userStore = useUserStore()
  console.log('提交表单数据:', formData.value);
  let data = { ...formData.value, tenantId: userStore.tenantId }
   if (formData.value.useRangeEnum !== 2) {
      formData.value.organizationIds = [];
    }
  try {
    // 如果有当前节点数据，表示是编辑操作
    if (props.currentNodeData) {
      data.id = props.currentNodeData.id; // 添加ID
      data.busNo = props.currentNodeData.busNo;
      data.hospitalId = props.currentNodeData.hospitalId;
console.log('data',data)
      const res = await update(data);
      if (res.code == 200) {
        ElMessage.success('更新成功');
        emits('submitOk')
      }else {
        ElMessage.error('保存失败');
      }
    } else {
      // 新建操作
      const res = await add(data);
      if (res.code == 200) {
        ElMessage.success('保存成功');
        emits('submitOk')
      }else {
        ElMessage.error('保存失败',error);
      }
    }
  }
  catch (error) {
    console.log(error)
    // ElMessage.error('保存失败',error);
  }
}
// 重置表单
const resetForm = () => {
  formRef.value?.resetFields();
  formData.value.useRangeEnum = 0;
  formData.value.environment = '0';
  formData.value.organizationIds = [];
};

onMounted(()=>{
  getLocationInfo() 
})
</script>
<style lang="scss" scoped>
</style>
