<template>
  <div class="app-container">
    <el-table
      v-loading="loading"
      :data="adjustmentList"
      tooltip-effect="dark"
      :show-overflow-tooltip="true"
      style="width: 100%"
    >
      <el-table-column label="单据编号" align="center" prop="busNo" min-width="180" />
      <el-table-column
        label="调价类型"
        align="center"
        prop="categoryEnum_enumText"
        min-width="120"
      />
      <el-table-column label="审核状态" align="center" prop="statusEnum" min-width="100">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.statusEnum)">
            {{ scope.row.statusEnum_enumText || '-' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="制单人" align="center" prop="applicantId_dictText" min-width="120" />
      <el-table-column label="制单时间" align="center" prop="createTime" min-width="180">
        <template #default="scope">
          {{ parseTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="审核人" align="center" prop="approverId_dictText" min-width="120" />
      <el-table-column label="审核日期" align="center" prop="approvalTime" min-width="180">
        <template #default="scope">
          {{ scope.row.approvalTime ? parseTime(scope.row.approvalTime) : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="180">
        <template #default="scope">
          <el-button size="small" link @click="handleDetail(scope.row)">详情</el-button>
          <template v-if="scope.row.statusEnum === 1">
            <el-button
              size="small"
              link
              type="success"
              @click="handleSubmitApproval(scope.row)"
              style="margin-left: 5px"
              >提审</el-button
            >
            <el-button
              size="small"
              link
              type="danger"
              @click="handleCancelApproval(scope.row)"
              style="margin-left: 5px"
              >作废</el-button
            >
          </template>
          <template v-else>
            <el-button size="small" link disabled></el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <Pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="handlePagination"
    />
    <!-- 详情弹窗组件 -->
    <DetailDialog
      v-model:visible="detailDialogVisible"
      :detail-data="selectedRow"
      :category-type="categoryType"
      :create-name="createName"
      @close="handleDetailClose"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { parseTime } from '@/utils/openhis';
import Pagination from '@/components/Pagination';
import {
  getPriceAdjustmentPage,
  cancelSupplyRequestData,
  searchSupplyRequestByHealth,
  searchSupplyRequestByActivity,
  searchSupplyRequestByDevice,
  searchSupplyRequestByMed,
  submitApprovalForPriceAdjustment,
} from './components/api';

import DetailDialog from './components/detailDialog.vue';

// 表格数据
const adjustmentList = ref([]);
const loading = ref(false);
const total = ref(0);
const activeName = ref('1'); // 当前激活的标签页

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  chargeItemContext: '', // 用于区分不同类型的调价
});

// 详情弹窗相关
const detailDialogVisible = ref(false);
const selectedRow = ref({});
const categoryType = ref('');
const createName = ref('');
// 状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    1: 'warning', // 待审核
    2: 'success', // 已审核
    3: 'danger', // 已拒绝
  };
  return typeMap[status] || 'info';
};

// 处理分页事件
const handlePagination = (params) => {
  // 将分页组件的参数映射到查询参数
  queryParams.pageNum = params.page;
  queryParams.pageSize = params.limit;
  getList();
};

// 处理标签页切换
const handleClick = (tab) => {
  // 更新激活标签页状态
  activeName.value = tab.paneName;
  // 设置当前查询类型
  queryParams.chargeItemContext = tab.paneName;
  // 重置页码
  queryParams.pageNum = 1;

  // 重新获取对应类型的数据
  getList();
};

// 查询数据
const getList = async () => {
  loading.value = true;
  try {
    // 确保设置当前查询类型参数
    queryParams.chargeItemContext = activeName.value;

    // 调用后端API获取对应类型的调价数据
    const response = await getPriceAdjustmentPage(queryParams);
console.log('调价审核列表响应数据:', response);
    // 处理返回的数据
    if (response && response.code === 200) {
      // 直接从records字段获取数据
      adjustmentList.value = response.data?.records || [];
      total.value = response.data?.total || 0;
    } else {
      ElMessage.error(response?.msg || '获取调价审核列表失败');
      adjustmentList.value = [];
      total.value = 0;
    }
  } catch (error) {
    ElMessage.error('获取数据异常，请稍后重试');
    console.error('获取调价审核列表异常:', error);
    adjustmentList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 操作按钮处理函数
const handleDetail = async (row) => {
  // 保存当前行的调价类型
  categoryType.value = row.typeEnum_enumText || '';
  // 调用详情API获取数据
  try {
    // 显示加载状态
    loading.value = true;

    // 准备API参数
    const params = {
      busNo: row.busNo,
    };
    console.log('查询详情参数:', params);
    console.log('查询详情参数:', row);
    // 根据categoryEnum选择不同的API接口
    let response;
    if (row.itemCategoryEnum === 49) {
      // 挂号
      response = await searchSupplyRequestByHealth(params);
    } else if (row.itemCategoryEnum === 48) {
      // 诊疗
      response = await searchSupplyRequestByActivity(params);
    } else if (row.itemCategoryEnum === 47) {
      // 耗材
      response = await searchSupplyRequestByDevice(params);
    } else if (row.itemCategoryEnum === 46) {
      // 药品
      response = await searchSupplyRequestByMed(params);
    }

    if (response && response.code === 200) {
      // 日志记录原始返回数据

      // 准备显示数据
      createName.value = row.applicantId_dictText || '-';
      // 设置selectedRow
      selectedRow.value = response.data;
      // 显示弹窗
      detailDialogVisible.value = true;
    } else {
      ElMessage.error(response?.msg || '获取详情数据失败');
    }
  } catch (error) {
    ElMessage.error('获取详情数据失败');
    console.error('获取详情数据异常:', error);
  } finally {
    loading.value = false;
  }
};

// 关闭详情弹窗处理
const handleDetailClose = () => {
  // 重置选中的行数据和类型
  selectedRow.value = {};
  categoryType.value = '';
};

// 处理提审审核
const handleSubmitApproval = async (row) => {
  try {
    // 弹出确认对话框
    await ElMessageBox.confirm('确定要提审该价格调整记录吗？', '确认提审', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info',
    });

    // 调用后端提审接口
    const response = await submitApprovalForPriceAdjustment({ busNo: row.busNo });

    if (response && response.code === 200) {
      ElMessage.success('提审成功');
      // 重新加载列表数据
      getList();
    } else {
      ElMessage.error(response?.msg || '提审失败');
    }
  } catch (error) {
    // 用户取消操作不会触发错误提示
    if (error !== 'cancel') {
      ElMessage.error('提审失败');
      console.error('提审价格调整记录异常:', error);
    }
  }
};

// 处理作废审核
const handleCancelApproval = async (row) => {
  try {
    // 弹出确认对话框
    await ElMessageBox.confirm('确定要作废该价格调整记录吗？', '确认作废', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    // 调用后端作废接口
    const response = await cancelSupplyRequestData({ busNo: row.busNo });

    if (response && response.code === 200) {
      ElMessage.success('作废成功');
      // 重新加载列表数据
      getList();
    } else {
      ElMessage.error(response?.msg || '作废失败');
    }
  } catch (error) {
    // 用户取消操作不会触发错误提示
    if (error !== 'cancel') {
      ElMessage.error('作废失败');
      console.error('作废价格调整记录异常:', error);
    }
  }
};

// 生命周期 - 加载
onMounted(() => {
  // 设置初始查询类型为药品调价
  queryParams.chargeItemContext = activeName.value;
  getList();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

:deep(.el-tabs__content) {
  height: auto;
}

:deep(.demo-tabs > .el-tabs__content) {
  color: #6b778c;
  font-size: 14px;
}
</style>