<template>
  <div class="container">
    <!-- 顶部操作区域 -->
    <el-card class="header-card" shadow="never">
      <el-row :gutter="20" align="middle">
        <el-col :span="6">
          <span class="descriptions-item-label">住院号：</span>
          <el-input
            v-model="queryParams.searchKey"
            placeholder="请输入内容"
            clearable
            style="width: 300px"
            @keyup.enter="getPatientInfo"
          />
          <el-button type="primary" @click="getPatientInfo" style="margin-left: 10px">
            查询
          </el-button>
        </el-col>
        <el-col :span="18" style="text-align: right">
          <el-space>
            <el-button type="primary" @click="confirmCharge()">收预交金</el-button>
            <el-button type="primary" @click="showPatient()">在院患者</el-button>
          </el-space>
        </el-col>
      </el-row>
    </el-card>

    <!-- 患者信息区域 -->
    <el-card class="patient-info-card" shadow="never">
      <el-row align="middle" :gutter="20">
        <el-avatar
          :size="40"
          src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
          style="margin-left: 20px"
        />
        <el-col :span="10">
          <div>
            <span
              class="descriptions-item-label"
              style="font-size: 16px; margin: 0 0"
              v-if="patientInfo.patientName"
            >
              {{ patientInfo.patientName }} / {{ patientInfo.genderEnum_enumText }} /
              {{ patientInfo.age }}
            </span>
            <span class="descriptions-item-label"> 住院号: </span>
            <span class="descriptions-item-value"> {{ patientInfo.busNo }} </span>
          </div>
        </el-col>
        <el-col :span="4" style="text-align: left; margin-top: 10px">
          <span class="descriptions-item-label">预交金总额：</span>
          <el-text type="primary" size="large">
            {{ patientInfo.totalAmount ? patientInfo.totalAmount.toFixed(2) + ' 元' : '0.00 元' }}
          </el-text>
        </el-col>
        <el-col :span="4" style="text-align: left; margin-top: 10px">
          <span class="descriptions-item-label">余额：</span>
          <el-text type="primary" size="large">
            {{
              patientInfo.balanceAmount ? patientInfo.balanceAmount.toFixed(2) + ' 元' : '0.00 元'
            }}
          </el-text>
        </el-col>
      </el-row>
      <el-row :gutter="24" style="margin-top: 10px">
        <el-col :span="23">
          <span class="descriptions-item-label">在院科室/病区: </span>
          <span class="descriptions-item-value" v-if="patientInfo.inHospitalOrgName">
            {{ patientInfo.inHospitalOrgName }} /
            {{
              patientInfo.wardName +
              formatValue(patientInfo.houseName) +
              formatValue(patientInfo.bedName)
            }}
          </span>
        </el-col>
        <el-col :span="1">
          <el-button type="primary" @click="refund()">退费</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card" shadow="never">
      <el-table
        :data="tableData"
        style="width: 100%"
        :row-class-name="tableRowClassName"
        v-loading="loading"
        border
      >
        <!-- <el-table-column prop="payWay" label="支付方式" /> -->
        <!-- <el-table-column prop="paymentEnum_enumText" label="状态" /> -->
        <el-table-column type="index" label="序号" width="70" align="center" />
        <el-table-column prop="paymentNo" label="收据号" width="280" align="center" />
        <el-table-column prop="tenderedAmount" label="金额" align="center">
          <template #default="scope">
            <span :class="{ 'negative-amount': scope.row.tenderedAmount < 0 }">
              {{
                scope.row.tenderedAmount ? scope.row.tenderedAmount.toFixed(2) + ' 元' : '0.00 元'
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="paymentEnum_enumText"
          label="票据类型"
          align="center"
          min-width="120"
        />
        <!-- <el-table-column prop="afterBalance" label="可退金额" min-width="120">
          <template #default="scope">
            <span>
              {{
                scope.row.afterBalance ? scope.row.afterBalance.toFixed(2) : scope.row.afterBalance
              }}
            </span>
          </template>
        </el-table-column> -->
        <el-table-column prop="operateTime" label="收款时间" align="center" min-width="180" />
        <el-table-column prop="enterer" label="收款员" align="center" min-width="100" />
        <!-- <el-table-column label="操作" min-width="100" align="center" fixed="right">
          <template #default="scope">
            <el-button link type="primary" size="small">补打</el-button>
          </template>
        </el-table-column> -->
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getPatientInfo"
      />
    </el-card>
    <!-- 患者列表弹窗 -->
    <PatientList
      :drawerVisible="showPatientList"
      ref="showPatientRef"
      :wardListOptions="wardListOptions"
      @patientSelected="handlePatientSelected"
    />
    <ChargeDialog
      ref="chargeListRef"
      :open="openDialog"
      @close="handleClose"
      :patientInfo="patientInfo"
      :payLists="payLists"
    />
    <RefundDialog
      :open="openRefundDialog"
      @close="handleClose"
      :patientInfo="patientInfo"
      :payLists="payLists"
    />
  </div>
</template>

<script setup>
import { ref, nextTick } from 'vue';
import { getDepositInfo, getDepositInfoPage } from './components/api';
import PatientList from './components/patientList.vue';
import ChargeDialog from './components/chargeDialog.vue';
import RefundDialog from './components/refundDialog.vue';
const showPatientList = ref(false);
const showPatientRef = ref();
const openDialog = ref(false);
const openRefundDialog = ref(false);
const chargeListRef = ref();
const loading = ref(false);
const tableData = ref([]);
const wardListOptions = ref(undefined);
const payLists = ref(undefined);
const total = ref(0);
const { proxy } = getCurrentInstance();
const patientInfo = ref({});
const queryParams = ref({
  pageNo: 1,
  pageSize: 10,
  searchKey: undefined, // 供应商名称
  searchKey: 'ZY202507310001',
});
const tableRowClassName = ({ row, rowIndex }) => {
  if (row.amount < 0) {
    // 根据图片，当金额为负数时，整行（或特定列）文字变红
    // 这里我们给整行添加一个class，然后在style中定义颜色
    // 或者也可以只给特定列的文字变红，如金额列
    return 'negative-row-text';
  }
  return '';
};

/**
 * 获取患者信息
 */
function getPatientInfo() {
  console.log(queryParams.searchKey, 'queryParams.searchKey');
  if (!queryParams.value.searchKey) {
    proxy.$modal.msgError('请先输入住院号！');
    return;
  }
  console.log(queryParams.value, 'queryParams.value');
  getDepositInfo({ busNo: queryParams.value.searchKey }).then((res) => {
    if (res.code == 200 && res.data.records[0].encounterId) {
      patientInfo.value = res.data.records[0];
      getDepositInfoPage({ encounterId: res.data.records[0].encounterId }).then((res) => {
        tableData.value = res.data;
      });
    }
  });
}

/**
 * 显示患者列表
 */
function showPatient() {
  showPatientList.value = true;
  nextTick(() => {
    proxy.$refs['showPatientRef'].show();
  });
}

// 确认收费
function confirmCharge() {
  console.log(patientInfo.value, 'patientInfo.valueconfirmCharge');
  if (patientInfo.value.patientId) {
    openDialog.value = true;
  } else {
    proxy.$modal.msgError('请先选择病人！');
  }
}

function refund() {
  if (patientInfo.value.patientId) {
    openRefundDialog.value = true;
  } else {
    proxy.$modal.msgError('请先选择病人！');
  }
}

/** 选择病人 */
function handlePatientSelected(row) {
  console.log(row, 'rowwwwwwwwhandlePatientSelected');
  queryParams.value.searchKey = row.admissionNo;
  patientInfo.value = row;
  nextTick(() => {
    getPatientInfo();
  });
}
/** 重置操作表单 */
function reset() {
  form.value = {
    id: undefined,
    patientName: undefined,
    genderEnum_enumText: undefined,
    ageString: undefined,
    payWay: undefined,
    patientId: undefined,
    organizationId_dictText: undefined,
    totalPrice: undefined,
    deposit: undefined,
    balanceAmount: undefined,
    bedLocationId_dictText,
  };
  proxy.resetForm('formRef');
}

// 复制文本到剪贴板
async function copyText() {
  console.log('复制文本:', form.value);
  try {
    // 使用 navigator.clipboard.writeText 复制文本
    await navigator.clipboard.writeText(form.value.admissionNo);
    proxy.$modal.msgSuccess('复制成功！');
  } catch (err) {
    proxy.$modal.msgError('复制失败！' + err);
  }
}

function formatValue(value) {
  return value ? '-' + value : '';
}

/**
 * 处理关闭事件
 *
 * @returns {void} 无返回值
 */
function handleClose(str) {
  openDialog.value = false;
  openRefundDialog.value = false;
  if (str === 'success') {
    getPatientInfo();
    proxy.$modal.msgSuccess('操作成功！');
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding: 15px;
  background-color: #f0f2f5; // 类似图片背景色
  min-height: 90vh;
}

.header-card,
.patient-info-card,
.table-card {
  margin-bottom: 15px;
  border: none; // 移除卡片边框，更接近图片效果
  :deep(.el-card__body) {
    // 调整卡片内边距
    padding: 15px;
  }
}
.patient-info-card {
  :deep(.el-card__body) {
    padding-bottom: 0; // 患者信息卡片底部不需要太多padding
  }
}

.patient-details {
  margin-top: 15px;
  :deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
    background-color: #fafafa; // 表头背景色
  }
  :deep(td),
  :deep(th) {
    // 移除边框，更像图片
    border: none;
  }
}

:deep(.custom-label .el-input__inner) {
  color: #ff7100 !important; // 橙色高亮
  font-weight: bold;
}
.amount-highlight-balance {
  color: #ff7100; // 橙色高亮
  font-weight: bold;
}

// 表格样式调整
.el-table {
  :deep(th) {
    background-color: #f0f8ff !important; // 表头淡蓝色背景
    color: #333;
    font-weight: normal;
  }
  :deep(td),
  :deep(th.is-leaf) {
    border-bottom: 1px solid #ebeef5; // 只保留底部边框
    border-left: none;
    border-right: none;
    border-top: none;
  }
  :deep(.el-table__row):hover > td {
    // 鼠标悬浮时背景色
    background-color: #f5f7fa;
  }
}

.negative-amount {
  color: red;
}

// 如果需要整行文字变红
.el-table .negative-row-text {
  color: red;
  td {
    color: red !important; // 确保覆盖默认样式
  }
  .el-button--primary.is-link {
    // 如果按钮也需要变红
    color: red !important;
  }
}
.action-red {
  // 单独给退还按钮变红
  color: red !important;
}

// 移除el-input-group__append的边框，使其与输入框融为一体
:deep(.el-input-group__append) {
  border-left: 0;
  background-color: #409eff;
  color: white;
  .el-button {
    color: white;
    &:hover {
      background-color: #66b1ff;
    }
  }
}

:deep(.custom-label .el-form-item__label) {
  background-color: #fafafa; /* 设置背景色 */
  padding: 4px 8px; /* 可选：添加一些内边距 */
  border: #e9e8e8 solid 1px; /* 可选：添加边框 */
  display: flex; /* 使用 flex 布局 */
  align-items: center; /* 垂直居中 */
  // justify-content: center; /* 水平居中 */
}
</style>
