<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="68px">
      <el-form-item label="内容" prop="searchKey">
        <el-input
          v-model="queryParams.searchKey"
          style="max-width: 600px"
          placeholder="请输入内容"
          class="input-with-select"
          @keydown.enter="handleQuery"
        >
        </el-input>
      </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>

    <div class="table-container">
      <el-table
        :data="treatHospitalizedData"
        style="width: 100%"
        height="100%"
        show-overflow-tooltip
      >
        <el-table-column type="index" width="54" align="center" label="序号" />
        <el-table-column prop="patientName" align="center" label="患者姓名" />
        <el-table-column prop="genderEnum_enumText" label="性别" align="center" />
        <el-table-column prop="age" label="年龄" align="center" />
        <el-table-column prop="requestTime" align="center" label="申请时间" width="180" />
        <el-table-column prop="sourceName" align="center" label="申请来源" />
        <el-table-column prop="wardName" align="center" label="入院病区" />
        <el-table-column prop="statusText" align="center" label="医保登记状态">
          <template #default="scope">
            <el-tag :type="tagType(scope.row.statusText)">
              {{ scope.row.statusText || '--' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          align="center"
          label="操作"
          class-name="small-padding fixed-width"
          width="600"
        >
          <template #default="scope">
            <el-button type="primary" icon="Edit" link @click="doRegistering(scope.row)">
              医保登记
            </el-button>
            <el-button type="success" icon="Edit" link @click="doYbOut(scope.row)">
              医保出院
            </el-button>
            <el-button type="danger" icon="Edit" link @click="doYbChange(scope.row)">
              信息变更
            </el-button>
            <el-button type="warning" icon="Remove" link @click="doYbInCancel(scope.row)">
              入院撤销
            </el-button>
            <el-button type="warning" icon="Remove" link @click="doYbOutCancel(scope.row)">
              出院撤销
            </el-button>

            <!-- 更多操作下拉菜单 -->
            <el-dropdown>
              <el-button type="primary" link style="margin-top: 4px; margin-left: 10px">
                更多
                <el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="doYbUpload(scope.row)">
                    <el-icon><Upload /></el-icon>
                    <span>病案上传</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
  </div>
</template>
<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import {
  getRegisteInfoPage,
  getInHospitalInfo,
  getInpatientCheckInfo,
  cancelInpatientRegister,
  cancelDischargeRegister,
  uploadEmr,
} from './components/api';
import { ElMessage, ElMessageBox, ElDropdown, ElDropdownMenu, ElDropdownItem } from 'element-plus';
import { ArrowDown, Close, Upload } from '@element-plus/icons-vue';
const total = ref(0);
const queryParams = ref({
  pageNo: 1,
  pageSize: 10,
  searchKey: '',
});
// 医保状态标签
const registerStatusTags = [
  {
    value: '1',
    label: '待登记',
    type: 'primary',
  },
  {
    value: '2',
    label: '已登记',
    type: 'success',
  },
  {
    value: '3',
    label: '待退费',
    type: 'danger',
  },
];
// 标签类型
const tagType = (value) => {
  return registerStatusTags.find((item) => item.value === value)?.type;
};
// 列表数据
const treatHospitalizedData = ref([]);
const queryRef = ref(null);
// 就诊信息
const mdtrtinfo = ref({});
// 诊断信息
const mdtrtdiag = ref([]);
const router = useRouter();
// 医保登记
const doRegistering = async (row) => {
  // 跳转
  router.push({
    name: 'YbregisterEdit',
    query: {
      encounterId: row.encounterId,
      operationType: 'register', // 添加操作类型参数，标识这是医保登记操作
    },
  });
};
// 医保出院
const doYbOut = async (row) => {
  router.push({
    name: 'YbregisterEdit',
    query: {
      encounterId: row.encounterId,
      operationType: 'discharge', // 添加操作类型参数，标识是医保出院
      mdtrtId: row.mdtrtId,
    },
  });
};
// 医保信息变更
const doYbChange = (row) => {
  router.push({
    name: 'YbregisterEdit',
    query: {
      encounterId: row.encounterId,
      operationType: 'change', // 添加操作类型参数，标识是信息变更
      mdtrtId: row.mdtrtId,
    },
  });
};
// 医保入院撤销
const doYbInCancel = async (row) => {
  try {
    // 添加确认弹窗
    await ElMessageBox.confirm('确定要撤销该入院登记吗？此操作不可恢复！', '入院撤销', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    // 用户确认后执行撤销操作 传就诊ID
    const res = await cancelInpatientRegister({ mdtrtId: row.mdtrtId });

    if (res && res.code === 200) {
      ElMessage.success('入院撤销成功');
      getList();
    } else {
      ElMessage.error(res?.message || '入院撤销失败');
    }
  } catch (error) {
    // 用户取消操作或请求失败
    if (error === 'cancel' || error === 'close') {
      ElMessage.info('已取消操作');
    } else {
      ElMessage.error('操作失败，请重试');
      console.error('入院撤销操作失败:', error);
    }
  } finally {
    loading.close && loading.close();
  }
};
// 医保出院撤销
const doYbOutCancel = async (row) => {
  try {
    // 添加确认弹窗
    await ElMessageBox.confirm('确定要撤销该入院登记吗？此操作不可恢复！', '出院撤销', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    // 用户确认后执行撤销操作 传就诊ID
    const res = await cancelDischargeRegister({ mdtrtId: row.mdtrtId });

    if (res && res.code === 200) {
      ElMessage.success('出院撤销成功');
      getList();
    } else {
      ElMessage.error(res?.message || '出院撤销失败');
    }
  } catch (error) {
    // 用户取消操作或请求失败
    if (error === 'cancel' || error === 'close') {
      ElMessage.info('已取消操作');
    } else {
      ElMessage.error('操作失败，请重试');
      console.error('入院撤销操作失败:', error);
    }
  } finally {
    loading.close && loading.close();
  }
};
// 病案上传
const doYbUpload = (row) => {
  const res = uploadEmr({ mdtrtId: row.mdtrtId });
  if (res && res.code === 200) {
    ElMessage.success('病案上传成功');
    getList();
  } else {
    ElMessage.error(res?.message || '病案上传失败');
  }
};
// 加载中
const loading = ref(false);
// 获取列表
const getList = () => {
  loading.value = true;
  getRegisteInfoPage(queryParams.value).then((res) => {
    console.log(res);
    treatHospitalizedData.value = res.data.records;
    total.value = res.data.total;
    loading.value = false;
  });
};

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNo = 1;
  getList();
}
// 重置按钮操作
function resetQuery() {
  queryParams.value = {
    pageNo: 1,
    pageSize: 10,
    searchKey: '',
  };
  getList();
}

getList();
</script>
