<template>
  <div style="height: calc(100vh - 126px)">
    <!-- 操作工具栏 -->
    <div
      style="
        height: 51px;
        border-bottom: 2px solid #e4e7ed;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 15px;
      "
    >
      <div style="display: flex; align-items: center">
        <!-- 日期选择tabs -->
        <el-tabs
          v-model="dateRange"
          type="card"
          class="date-tabs"
          @tab-click="handleDateTabClick"
          style="margin-right: 20px"
        >
          <el-tab-pane label="今日" name="today"></el-tab-pane>
          <el-tab-pane label="昨日" name="yesterday"></el-tab-pane>
          <el-tab-pane label="其他" name="other"></el-tab-pane>
        </el-tabs>

        <!-- 日期选择器 -->
        <el-date-picker
          v-model="dateRangeValue"
          type="daterange"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleDatePickerChange"
          style="width: 240px; margin-right: 20px"
        />

        <!-- 执行科室选择 -->
        <el-select
          v-model="execDepartment"
          placeholder="请选择执行科室"
          clearable
          style="width: 150px; margin-right: 20px"
        >
          <el-option
            v-for="dept in departmentOptions"
            :key="dept.value"
            :label="dept.label"
            :value="dept.value"
          />
        </el-select>

        <!-- 查询按钮 -->
        <el-button type="primary" @click="handleQuery">查询</el-button>
      </div>

      <div style="display: flex; align-items: center">
        <!-- 全选开关 -->
        <div style="display: flex; align-items: center; margin-right: 20px">
          <span style="margin-right: 8px">全选：</span>
          <el-switch v-model="selectAll" @change="handleSelectAll" />
        </div>

        <!-- 计费按钮 -->
        <el-button type="primary" @click="handleCalculate">计费</el-button>

        <!-- 批量划价按钮 -->
        <el-button type="primary" plain @click="handleBatchPrice" style="margin-left: 20px"
          >批量划价</el-button
        >
      </div>
    </div>

    <!-- 费用列表区域 -->
    <div
      style="padding: 10px; background-color: #eef9fd; height: 100%; overflow-y: auto"
      v-loading="loading"
    >
      <el-table
        ref="tableRef"
        :data="billingList"
        border
        style="width: 100%"
        :header-cell-style="{ background: '#eef9fd !important' }"
      >
        <el-table-column type="selection" align="center" width="50" />
        <el-table-column label="医嘱内容" prop="orderContent" min-width="200" />
        <el-table-column label="应执行日期" prop="executeDate" width="120" align="center" />
        <el-table-column label="执行收费项目" prop="chargeItem" min-width="180" />
        <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"
              style="width: 100px"
            />
          </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" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center">
          <template #default="scope">
            <!-- <el-button type="primary" size="small" @click="handlePrice(scope.row)">划价</el-button> -->

            <el-button type="primary" size="small" @click="handleDelete(scope.row)">撤销</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 无数据提示 -->
      <el-empty v-if="!loading && billingList.length === 0" description="暂无数据" />
    </div>

    <!-- 使用计费弹窗组件 -->
    <FeeDialog
      v-model:visible="dialogVisible"
      :initial-data="selectedFeeItems"
      :patient-info="currentPatientInfo"
      @confirm="handleFeeDialogConfirm"
      @cancel="handleFeeDialogCancel"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { patientInfoList } from '../../medicalOrderExecution/store/patient.js';
import { formatDateStr } from '@/utils/index';
import FeeDialog from './FeeDialog.vue';

// 响应式数据
const loading = ref(false);
const billingList = ref([]);
const dateRange = ref('today'); // today, yesterday, other
const dateRangeValue = ref([]);
const execDepartment = ref('');
const selectAll = ref(false);
const departmentOptions = ref([]);
const tableRef = ref(null);

// 计费弹窗相关数据
const dialogVisible = ref(false);
const selectedFeeItems = ref([]);
const currentPatientInfo = ref('');

// 初始化
onMounted(() => {
  // 设置默认日期
  const today = new Date();
  dateRangeValue.value = [formatDateStr(today, 'YYYY-MM-DD'), formatDateStr(today, 'YYYY-MM-DD')];

  // 加载科室选项
  loadDepartmentOptions();
});

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

// 处理日期tabs点击
function handleDateTabClick(tab) {
  const rangeType = tab.paneName;
  const today = new Date();
  const yesterday = new Date();
  yesterday.setDate(today.getDate() - 1);

  switch (rangeType) {
    case 'today':
      dateRangeValue.value = [
        formatDateStr(today, 'YYYY-MM-DD'),
        formatDateStr(today, 'YYYY-MM-DD'),
      ];
      break;
    case 'yesterday':
      dateRangeValue.value = [
        formatDateStr(yesterday, 'YYYY-MM-DD'),
        formatDateStr(yesterday, 'YYYY-MM-DD'),
      ];
      break;
    // other 情况保持用户选择的值
  }
}

// 处理日期选择器变化
function handleDatePickerChange() {
  if (dateRangeValue.value.length > 0) {
    dateRange.value = 'other';
  }
}

// 生成模拟数据
function generateMockData() {
  const mockData = [
    {
      orderContent: '血常规检查',
      executeDate: dateRangeValue.value[0],
      chargeItem: '血液分析',
      unitPrice: 35.0,
      quantity: 1,
      id: '1',
    },
    {
      orderContent: '静脉注射',
      executeDate: dateRangeValue.value[0],
      chargeItem: '静脉输液',
      unitPrice: 20.0,
      quantity: 2,
      id: '2',
    },
    {
      orderContent: 'CT检查',
      executeDate: dateRangeValue.value[0],
      chargeItem: '胸部CT平扫',
      unitPrice: 320.0,
      quantity: 1,
      id: '3',
    },
    {
      orderContent: '药物治疗',
      executeDate: dateRangeValue.value[0],
      chargeItem: '抗生素注射',
      unitPrice: 58.5,
      quantity: 1,
      id: '4',
    },
  ];

  // 根据科室筛选模拟数据
  if (execDepartment.value) {
    // 模拟根据科室筛选
    return mockData.filter((_, index) => index % 2 === 0);
  }

  return mockData;
}

// 查询按钮点击
function handleQuery() {
  if (patientInfoList.value.length === 0) {
    ElMessage.warning('请先选择患者');
    return;
  }

  loading.value = true;

  // 模拟API调用延迟
  setTimeout(() => {
    // 使用模拟数据
    billingList.value = generateMockData();
    loading.value = false;
  }, 500);
}

// 全选/取消全选
function handleSelectAll(value) {
  selectAll.value = value;
  if (tableRef.value) {
    if (value) {
      tableRef.value.toggleAllSelection();
    } else {
      // 取消全选
      tableRef.value.clearSelection();
    }
  }
}

// 打开计费弹窗
function handleCalculate() {
  // 获取选中的数据
  const selectedRows = getSelectedRows();
  // if (selectedRows.length === 0) {
  //   ElMessage.warning('请先选择要计费的项目');
  //   return;
  // }

  // 设置弹窗初始数据
  selectedFeeItems.value = [...selectedRows];

  // 设置患者信息
  if (patientInfoList.value.length > 0) {
    const patient = patientInfoList.value[0];
    currentPatientInfo.value = `${patient.patientName || '未知患者'}`;
  }

  // 显示弹窗
  dialogVisible.value = true;
}

// 处理计费弹窗确认
function handleFeeDialogConfirm(data) {
  // 模拟计费操作
  setTimeout(() => {
    ElMessage.success('计费成功');
    // 刷新数据
    handleQuery();
  }, 300);
}

// 处理计费弹窗取消
function handleFeeDialogCancel() {
  // 可以在这里添加取消后的处理逻辑
}

// 批量划价
function handleBatchPrice() {
  // 获取选中的数据
  const selectedRows = getSelectedRows();
  if (selectedRows.length === 0) {
    ElMessage.warning('请先选择要划价的项目');
    return;
  }

  // 模拟批量划价操作
  setTimeout(() => {
    ElMessage.success(`批量划价成功，共${selectedRows.length}项`);
    // 更新状态，模拟已划价
    selectedRows.forEach((row) => {
      row.status = 'priced';
    });
  }, 300);
}

// 单项划价
function handlePrice(row) {
  // 模拟单项划价操作
  setTimeout(() => {
    ElMessage.success('划价成功');
    // 更新状态，模拟已划价
    row.status = 'priced';
  }, 300);
}
function handleDelete(row) {
  // 从数据列表中删除当前行
  const index = billingList.value.findIndex((item) => item.id === row.id);
  if (index !== -1) {
    billingList.value.splice(index, 1);
    ElMessage.success('撤销成功');
  }
}

// 获取选中的行
function getSelectedRows() {
  if (tableRef.value) {
    return tableRef.value.selection || [];
  }
  return [];
}

// 暴露方法供父组件调用
defineExpose({
  handleQuery,
});
</script>

<style scoped>
/* 日期tabs样式 */
.date-tabs .el-tabs__header {
  margin-bottom: 0;
}

.date-tabs .el-tabs__content {
  display: none;
}

:deep(.el-table__header th) {
  background-color: #eef9fd !important;
}

:deep(.el-table__row:hover > td) {
  background-color: #eef9fd !important;
}
</style>
