<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 搜索条件区域 -->
      <el-col :span="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" size="small">
          <el-form-item label="项目名">
            <el-input v-model="queryParams.searchKey" placeholder="国临编码/国临名称/医保编码/医保名称" clearable style="width: 280px" />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      
      <!-- 操作按钮区域 -->
      <el-col :span="24" class="mb20">
        <el-button type="primary" icon="Plus" @click="handleAdd">添加新项目</el-button>
        <el-button type="danger" icon="Stop" @click="handleDelete">删除</el-button>
        <el-button type="success" icon="Check">启用</el-button>
        <el-button type="info" icon="Download">导入</el-button>
      </el-col>
      
      <!-- 数据表格区域 -->
      <el-col :span="24">
        <el-table 
          v-loading="loading" 
          :data="dataList" 
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
        
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column prop="glNo" 
            label="国临版疾病编码" 
            key="glNo"
            :show-overflow-tooltip="true"
            align="center" 
            width="180" />
              
          <el-table-column prop="glName"
            label="国临版疾病名称" 
            key="glName"
            :show-overflow-tooltip="true"
            align="center" 
            min-width="200" />
            
          <el-table-column prop="icd10No" 
            label="医保版疾病编码" 
            key="icd10No"
            :show-overflow-tooltip="true"
            align="center" 
            width="180" />

          <el-table-column prop="icd10Name" 
            label="医保版疾病名称" 
            key="icd10Name"
            :show-overflow-tooltip="true"
            align="center" 
            min-width="200" />
          <el-table-column label="操作" width="120" align="center">
            <template #default="scope">
              <el-button type="primary" link size="small" @click="handleEdit(scope.row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页控件 -->
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-col>
    </el-row>
   
    <!-- 添加对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="添加国临编码"
      width="600px"
      :before-close="handleClose"
    >

      <el-form
        ref="addFormRef"
        :model="addFormData"
        :rules="rules"
        label-width="120px"
        size="small"
      >
        <el-form-item label="国临版疾病编码" prop="glNo">
          <el-input v-model="addFormData.glNo" placeholder="请输入国临版疾病编码" clearable />
        </el-form-item>
        <el-form-item label="国临版疾病名称" prop="glName">
          <el-input v-model="addFormData.glName" placeholder="请输入国临版疾病名称" clearable />
        </el-form-item>
        <el-form-item label="医保版疾病编码" prop="icd10No">
          <el-input v-model="addFormData.icd10No" placeholder="请输入医保版疾病编码" clearable />
        </el-form-item>
        <el-form-item label="医保版疾病名称" prop="icd10Name">
          <el-input v-model="addFormData.icd10Name" placeholder="请输入医保版疾病名称" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
      <!-- 编辑对话框 -->
  <el-dialog
    v-model="editDialogVisible"
    title="编辑国临编码"
    width="600px"
    :before-close="handleEditClose"
  >
    <el-form
      ref="editFormRef"
      :model="editFormData"
      :rules="rules"
      label-width="120px"
      size="small"
    >
      <el-form-item label="国临版疾病编码" prop="glNo">
        <el-input v-model="editFormData.glNo" placeholder="请输入国临版疾病编码" clearable />
      </el-form-item>
      <el-form-item label="国临版疾病名称" prop="glName">
        <el-input v-model="editFormData.glName" placeholder="请输入国临版疾病名称" clearable />
      </el-form-item>
      <el-form-item label="医保版疾病编码" prop="icd10No">
        <el-input v-model="editFormData.icd10No" placeholder="请输入医保版疾病编码" clearable />
      </el-form-item>
      <el-form-item label="医保版疾病名称" prop="icd10Name">
        <el-input v-model="editFormData.icd10Name" placeholder="请输入医保版疾病名称" clearable />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleEditClose">取消</el-button>
      <el-button type="primary" @click="handleEditSubmit">确定</el-button>
    </template>
  </el-dialog>

    
  </div>
</template>

<script setup name="NationalCode">
import { ref, reactive, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import request from '@/utils/request';
const router = useRouter();
const route = useRoute();

// 页面数据
const loading = ref(true);
const dataList = ref([]);
const total = ref(0);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);

// 对话框相关
const addDialogVisible = ref(false);
const editDialogVisible = ref(false); // 编辑对话框可见性
const addFormRef = ref(null);
const editFormRef = ref(null); // 编辑表单引用
const addFormData = reactive({
  glNo: '',
  glName: '',
  icd10No: '',
  icd10Name: ''
});
// 编辑表单数据
const editFormData = reactive({
  id: '',
  glNo: '',
  glName: '',
  icd10No: '',
  icd10Name: ''
});

// 表单验证规则
const rules = {
  glNo: [
    { required: true, message: '请输入国临版疾病编码', trigger: 'blur' }
  ],
  glName: [
    { required: true, message: '请输入国临版疾病名称', trigger: 'blur' }
  ],
  icd10No: [
    { required: true, message: '请输入医保版疾病编码', trigger: 'blur' }
  ],
  icd10Name: [
    { required: true, message: '请输入医保版疾病名称', trigger: 'blur' }
  ]
};

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  searchKey: undefined
});

// 查询
function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}

// 重置
function resetQuery() {
  Object.assign(queryParams, {
    searchKey: undefined,
    status: undefined,
    ybFlag: undefined,
    type: undefined
  });
  handleQuery();
}

// 分页变化
function handleSizeChange(size) {
  queryParams.pageSize = size;
  getList();
}

function handleCurrentChange(current) {
  queryParams.pageNum = current;
  getList();
}
function handleDelete() {
  // 安全检查ids.value是否存在且为数组
  if (!ids.value || ids.value.length === 0) {
    ElMessage.warning('请先选择要删除的数据');
    return;
  }
  
  // 显示确认对话框
  ElMessageBox.confirm('确定要删除选中的数据吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    loading.value = true;
    
    // 修复：确保ids.value是数组并过滤掉无效值
    const validIds = Array.isArray(ids.value) ? ids.value.filter(id => id) : [];
    
    if (validIds.length === 0) {
      loading.value = false;
      ElMessage.warning('没有有效的数据可删除');
      return;
    }
    
    // 简化删除逻辑，改为单个请求，因为后端可能不支持批量删除
    // 先删除第一个，后续可以根据需要调整
    const firstId = validIds[0];
    
    request({
      url: '/base-data-manage/ICD10/delete-icd-Information',
      method: 'delete',
      params: { glNo: firstId } // 传递glNo参数
    }).then(res => {
      loading.value = false;
      if (res.code === 200) {
        ElMessage.success('删除成功');
        // 刷新列表
        getList();
        // 清空选中状态
        ids.value = [];
      } else {
        ElMessage.error(res.msg || '删除失败');
      }
    }).catch(error => {
      loading.value = false;
      console.error('删除数据失败:', error);
      ElMessage.error('删除失败，请稍后重试');
    });
  }).catch(() => {
    // 用户取消删除操作
  });
}

// 同时修复handleSelectionChange函数，确保正确设置ids
function handleSelectionChange(selection) {
  // 确保selection是数组
  if (Array.isArray(selection)) {
    ids.value = selection.map(item => {
      // 尝试使用glNo，如果没有则使用id，确保返回有效的值
      return item.glNo || item.id || '';
    }).filter(Boolean); // 过滤掉空值
    single.value = ids.value.length <= 1;
    multiple.value = !single.value;
  } else {
    // 如果selection不是数组，重置ids
    ids.value = [];
    single.value = true;
    multiple.value = false;
  }
}

// 打开添加对话框
function handleAdd() {
  // 重置表单
  addFormRef.value?.resetFields();
  Object.assign(addFormData, {
    glNo: '',
    glName: '',
    icd10No: '',
    icd10Name: ''
  });
  // 显示对话框
  addDialogVisible.value = true;
}

// 关闭对话框
function handleClose() {
  addDialogVisible.value = false;
}
function handleEdit(row) {
  // 填充编辑表单数据
  Object.assign(editFormData, {
    id: row.id || '',
    glNo: row.glNo || '',
    glName: row.glName || '',
    icd10No: row.icd10No || '',
    icd10Name: row.icd10Name || ''
  });
  // 显示编辑对话框
  editDialogVisible.value = true;
}

function handleEditClose() {
  editDialogVisible.value = false;
}

function handleEditSubmit() {
  editFormRef.value?.validate((valid) => {
    if (valid) {
      // 移除查重校验，直接进行编辑操作
      loading.value = true;
      // 调用后端编辑接口
      request({
        url: '/base-data-manage/ICD10/update-icd-Information',
        method: 'put',
        data: editFormData
      }).then(res => {
        loading.value = false;
        if (res.code === 200) {
          console.log('编辑国临编码成功');
          ElMessage.success('编辑成功');
          editDialogVisible.value = false;
          getList();
        } else {
          ElMessage.error(res.msg || '编辑失败');
        }
      }).catch(error => {
        loading.value = false;
        console.error('编辑国临编码失败:', error);
        ElMessage.error('编辑失败，请稍后重试');
      });
    }
  });
}
// 提交表单
function handleSubmit() {
  addFormRef.value?.validate((valid) => {
    if (valid) {
       
      // 先进行查重校验
      checkAddDuplicate().then(isDuplicate => {
        if (isDuplicate) {
          ElMessage.warning('该项目已存在，请检查国临编码或医保编码是否重复');
          return;
        }
        
        loading.value = true;
        // 调用后端添加接口
        request({
          url: '/base-data-manage/ICD10/add-icd-Information',
          method: 'post',
          data: addFormData // 直接提交表单数据
        }).then(res => {
          loading.value = false;
          if (res.code === 200) {
            // 成功提示
            ElMessage.success('添加成功');
            // 关闭对话框
            addDialogVisible.value = false;
            // 刷新列表
            getList();
          } else {
            // 失败提示
            ElMessage.error(res.msg || '添加失败');
          }
        }).catch(error => {
          loading.value = false;
          console.error('添加国临编码失败:', error);
          ElMessage.error('添加失败，请稍后重试');
        });
      }).catch(error => {
        console.error('查重校验失败:', error);
        ElMessage.error('校验失败，请稍后重试');
      });
    }
  });
}

// 查重校验函数
async function checkAddDuplicate() {
  try {
    // 查询现有数据列表
    const res = await request({
      url: '/base-data-manage/ICD10/information-page',
      method: 'get',
      params: {
        pageNum: 1,
        pageSize: 1000, // 查询足够多的数据进行校验
        searchKey: undefined
      }
    });
    
    if (res.code === 200 && res.data.records) {
      // 检查是否存在相同的国临编码或医保编码
      const isExist = res.data.records.some(item => 
        item.glNo === addFormData.glNo || item.icd10No === addFormData.icd10No
      );
      return isExist;
    }
    return false;
  } catch (error) {
    console.error('查重校验请求失败:', error);
    return false;
  }
}

// 获取列表数据
function getList() {
  loading.value = true;
  request({
    url: '/base-data-manage/ICD10/information-page',
    method: 'get',
    params: queryParams
  }).then(res => {
    loading.value = false;
    if (res.code === 200) {
      dataList.value = res.data.records || [];
      total.value = res.data.total || 0;
    }
  }).catch(error => {
    loading.value = false;
    console.error('获取国临编码数据失败:', error);
  });
}

// 页面初始化
onMounted(() => {
  getList();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.mb20 {
  margin-bottom: 20px;
}
</style>