<template>
  <el-dialog v-model="dialogVisible" title="补费" width="90%" :close-on-click-modal="false">
    <!-- 弹窗内容 - 左右布局 -->
    <div style="display: flex; gap: 20px; height: 70vh">
      <!-- 左侧：收费组套列表 - 卡片式布局 -->
      <div
        style="
          width: 250px;
          border: 1px solid #e4e7ed;
          border-radius: 4px;
          display: flex;
          flex-direction: column;
        "
      >
        <!-- 搜索框 -->
        <div style="padding: 10px; border-bottom: 1px solid #e4e7ed">
          <el-input v-model="groupSearchText" placeholder="输入组套名称" clearable />
        </div>
        <!-- 收费组套列表 - 卡片式布局 -->
        <div style="flex: 1; overflow-y: auto; padding: 10px">
          <div
            v-for="group in chargeGroups"
            :key="group.id"
            class="group-card"
            @click="selectChargeGroup(group)"
          >
            <div class="group-status">
              <span class="status-dot"></span>
              {{ getGroupType(group.name) }}
            </div>
            <div class="group-name">{{ group.name }}</div>
            <div class="group-info">
              {{ getGroupInfo(group.id) }}
            </div>
          </div>
          <!-- 只显示暂无数据文本 -->
          <div
            v-if="chargeGroups.length === 0"
            style="text-align: center; color: #909399; padding: 20px"
          >
            暂无数据
          </div>
        </div>
      </div>

      <!-- 右侧：费用项目和信息 -->
      <div style="flex: 1; display: flex; flex-direction: column">
        <!-- 费用项目表格 -->
        <el-table :data="feeItemsList" border style="width: 100%; flex: 1">
          <el-table-column label="收费项目" prop="itemName" min-width="200">
            <template #default="scope">
              <el-input
                v-model="scope.row.itemName"
                placeholder="请输入收费项目"
                style="width: 100%"
              />
            </template>
          </el-table-column>
          <el-table-column label="单价" prop="unitPrice" width="100" align="center">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.unitPrice"
                :min="0"
                :step="0.01"
                precision="2"
                style="width: 100px"
                @change="calculateTotalAmount"
              />
            </template>
          </el-table-column>
          <el-table-column label="计费数量" prop="quantity" width="100" align="center">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.quantity"
                :min="1"
                :step="1"
                style="width: 100px"
                @change="calculateTotalAmount"
              />
            </template>
          </el-table-column>
          <el-table-column label="金额" prop="amount" width="100" align="center" />
          <el-table-column label="医保类型" prop="insuranceType" width="100" align="center">
            <template #default="scope">
              <el-input
                v-model="scope.row.insuranceType"
                placeholder="医保类型"
                style="width: 100px"
              />
            </template>
          </el-table-column>
          <el-table-column label="特限符合" prop="special" width="100" align="center">
            <template #default="scope">
              <el-switch v-model="scope.row.special" />
            </template>
          </el-table-column>
        </el-table>

        <!-- 添加项目按钮 - 移到右侧费用项目表格下方 -->
        <div
          style="
            margin-top: 10px;
            padding: 15px;
            border: 1px dashed #dcdfe6;
            border-radius: 4px;
            text-align: center;
            cursor: pointer;
            color: #409eff;
            transition: all 0.3s;
          "
          @click="addEmptyItem"
        >
          + 添加项目
        </div>

        <!-- 底部信息区域 -->
        <div style="margin-top: 20px; display: flex; flex-wrap: wrap; gap: 15px">
          <div style="display: flex; align-items: center">
            <span style="margin-right: 8px">执行时间：</span>
            <el-date-picker
              v-model="executeTime"
              type="datetime"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="选择日期时间"
              style="width: 200px"
            />
          </div>

          <div style="display: flex; align-items: center">
            <span style="margin-right: 8px">执行科室：</span>
            <el-select v-model="selectedDept" placeholder="选择科室" style="width: 150px">
              <el-option
                v-for="dept in departmentOptions"
                :key="dept.value"
                :label="dept.label"
                :value="dept.value"
              />
            </el-select>
          </div>

          <div style="display: flex; align-items: center">
            <span style="margin-right: 8px">开方医生：</span>
            <el-select v-model="selectedDoctor" placeholder="选择医生" style="width: 150px">
              <el-option label="内科医生" value="doctor1" />
              <el-option label="外科医生" value="doctor2" />
              <el-option label="儿科医生" value="doctor3" />
            </el-select>
          </div>

          <div style="display: flex; align-items: center">
            <span style="margin-right: 8px">执行人：</span>
            <el-select v-model="executor" placeholder="选择执行人" style="width: 150px">
              <el-option label="系统管理员" value="admin" />
              <el-option label="护士甲" value="nurse1" />
              <el-option label="护士乙" value="nurse2" />
            </el-select>
          </div>
        </div>

        <!-- 总金额和操作按钮 -->
        <div
          style="
            margin-top: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <div style="font-size: 14px; font-weight: bold; text-align: right">
            本次补费总金额：<span style="color: #ff4d4f">{{ totalAmount.toFixed(2) }}</span>
          </div>
          <div>
            <el-button @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="handleConfirm">确定</el-button>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { formatDateStr } from '@/utils/index';

// Props定义
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  initialData: {
    type: Array,
    default: () => [],
  },
  patientInfo: {
    type: String,
    default: '',
  },
});

// Emits定义
const emit = defineEmits(['update:visible', 'confirm', 'cancel']);

// 响应式数据
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value),
});
const searchItemText = ref('');
const selectedItemName = ref('');
const feeTabs = ref('chargeItems');
const feeItemsList = ref([]);
const executeTime = ref('');
const selectedDept = ref('');
const selectedDoctor = ref('');
const executor = ref('');
const departmentOptions = ref([]);
// 收费组套相关数据
const chargeGroups = ref([]);
const groupSearchText = ref('');

// 计算总金额
const totalAmount = computed(() => {
  return feeItemsList.value.reduce((sum, item) => {
    return sum + (item.unitPrice || 0) * (item.quantity || 0);
  }, 0);
});

// 初始化
onMounted(() => {
  // 加载科室选项
  loadDepartmentOptions();
  // 加载收费组套数据
  loadChargeGroups();
});

// 监听初始数据变化
watch(
  () => props.initialData,
  (newData) => {
    if (newData && newData.length > 0) {
      initFeeDialogData(newData);
    }
  },
  { deep: true }
);

// 监听弹窗显示状态
watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      // 设置默认执行时间为当前时间
      executeTime.value = formatDateStr(new Date(), 'YYYY-MM-DD HH:mm:ss');
    } else {
      // 弹窗关闭时重置数据
      resetData();
    }
  }
);

// 加载科室选项
function loadDepartmentOptions() {
  // 模拟科室数据
  departmentOptions.value = [
    { label: '内科', value: 'internal' },
    { label: '外科', value: 'surgery' },
    { label: '儿科', value: 'pediatrics' },
    { label: '妇产科', value: 'obstetrics' },
    { label: '其他科室', value: 'others' },
  ];
}

// 加载收费组套数据
function loadChargeGroups() {
  // 模拟收费组套数据
  chargeGroups.value = [
    { id: '1', name: '血常规检查组套' },
    { id: '2', name: '生化检查组套' },
    { id: '3', name: '心电图检查组套' },
    { id: '4', name: 'CT检查组套' },
    { id: '5', name: '输液治疗组套' },
  ];
}

// 获取组套类型
function getGroupType(name) {
  if (name.includes('检查')) return '检查';
  if (name.includes('治疗')) return '治疗';
  return '常规';
}

// 获取组套信息
function getGroupInfo(id) {
  const infoMap = {
    1: '检验科/基础检查',
    2: '检验科/生化项目',
    3: '心电图室/常规检查',
    4: '影像科/影像学检查',
    5: '内科/治疗项目',
  };
  return infoMap[id] || '标准收费项目';
}

// 初始化费用数据
function initFeeDialogData(selectedRows) {
  // 将选中的项目转换为弹窗中的费用项目格式
  feeItemsList.value = selectedRows.map((row) => ({
    itemName: row.chargeItem,
    unitPrice: row.unitPrice,
    quantity: row.quantity,
    amount: row.unitPrice * row.quantity,
    dept: '内科',
    special: false,
    insuranceType: '',
  }));
}

// 选择收费组套
function selectChargeGroup(group) {
  // 模拟根据选中的组套添加对应的费用项目
  const groupItems = {
    1: [
      {
        itemName: '红细胞计数',
        unitPrice: 15.0,
        quantity: 1,
        dept: '检验科',
        special: false,
        insuranceType: '甲类',
      },
    ],
    2: [
      {
        itemName: '肝功能检查',
        unitPrice: 80.0,
        quantity: 1,
        dept: '检验科',
        special: false,
        insuranceType: '甲类',
      },
    ],
    3: [
      {
        itemName: '心电图检查',
        unitPrice: 45.0,
        quantity: 1,
        dept: '心电图室',
        special: false,
        insuranceType: '甲类',
      },
    ],
    4: [
      {
        itemName: 'CT扫描',
        unitPrice: 300.0,
        quantity: 1,
        dept: '影像科',
        special: false,
        insuranceType: '乙类',
      },
    ],
    5: [
      {
        itemName: '静脉输液',
        unitPrice: 20.0,
        quantity: 1,
        dept: '内科',
        special: false,
        insuranceType: '甲类',
      },
    ],
  };

  const items = groupItems[group.id] || [];
  // 计算金额
  items.forEach((item) => {
    item.amount = item.unitPrice * item.quantity;
  });

  // 添加到费用项目列表
  feeItemsList.value = [...feeItemsList.value, ...items];
}

// 添加空白项目
function addEmptyItem() {
  const newItem = {
    itemName: '', // 空白项目名称
    unitPrice: 0, // 默认单价为0
    quantity: 1, // 默认数量为1
    amount: 0, // 默认金额为0
    dept: '内科', // 默认科室
    special: false, // 默认特限不符合
    insuranceType: '', // 空白医保类型
  };

  // 添加到费用项目列表
  feeItemsList.value.push(newItem);

  // 显示提示信息
  ElMessage.success('已添加空白项目，请填写相关信息');
}

// 计算总金额（当数量变化时调用）
function calculateTotalAmount() {
  // 更新每个项目的金额
  feeItemsList.value.forEach((item) => {
    item.amount = (item.unitPrice || 0) * (item.quantity || 0);
  });
}

// 取消操作
function handleCancel() {
  emit('cancel');
  dialogVisible.value = false;
}

// 确认操作
function handleConfirm() {
  // 构建提交数据
  const submitData = {
    feeItems: feeItemsList.value,
    executeTime: executeTime.value,
    department: selectedDept.value,
    doctor: selectedDoctor.value,
    executor: executor.value,
    totalAmount: totalAmount.value,
  };

  // 发送确认事件
  emit('confirm', submitData);
  dialogVisible.value = false;
}

// 重置数据
function resetData() {
  feeItemsList.value = [];
  executeTime.value = '';
  selectedDept.value = '';
  selectedDoctor.value = '';
  executor.value = '';
}
</script>

<style scoped>
:deep(.el-dialog__body) {
  padding: 20px;
}

/* 添加项目按钮样式 */
:deep(
    .el-dialog div[style*='flex: 1; display: flex; flex-direction: column'] > div:nth-child(2):hover
  ) {
  background-color: #ecf5ff;
}

/* 收费组套卡片样式 */
.group-card {
  background: #ffffff;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 12px;
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.group-card:hover {
  border-color: #409eff;
  background-color: #ecf5ff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.group-status {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #606266;
}

.status-dot {
  width: 8px;
  height: 8px;
  background-color: #67c23a;
  border-radius: 50%;
  margin-right: 6px;
}

.group-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
  word-break: break-word;
}

.group-info {
  font-size: 12px;
  color: #909399;
  border-top: 1px dashed #ebeef5;
  padding-top: 8px;
  margin-top: 4px;
}
</style>
