<template>
  <my-layout>
    <layout-item class="bg-white">
      <div class="py-5px flex" @keyup.enter="search()">
        <expand-filter-box v-model:can-expand="canExpand" :enable-expand="true" class="flex-grow" :expand="expand">
          <input-filter v-model="queryForm.name" label="患者姓名" placeholder="请输入患者姓名" :width="240" />
          <check-box-filter filterable placeholder="搜索医生" v-if="!doctorView" v-model="queryForm.doctorCodes"
            label="开方医生" :list="doctors" :width="240" />
          <check-box-filter v-model="queryForm.pharmacistNos" label="审方药师" :list="pharmacistList" :width="240" />
          <date-range-filter v-model:dates="queryForm.dates" label="开方时间" :text="datesText" :width="320"
            :showShortcuts="false" />
          <date-range-filter v-model:dates="queryForm.auditDates" label="审核时间" :text="auditDatesText"
            :showShortcuts="false" :width="320" />
          <radio-filter v-model="queryForm.status" label="处方状态" :list="statusList" />
          <radio-filter v-model="queryForm.preType" label="处方类型" :list="precriptionTypeList" />
          <custom-filter label="开具药品" :width="360">
            <div class="flex items-center h-[40px] cursor-pointer" :class="queryForm.drugs.length > 0 ? 'group' : ''"
              @click="show()">
              <div class="mr-1 max-w-[160px] text-right truncate">{{ drugNames || '全部' }}</div>
              <el-icon class="flex-shrink-0 group-hover:hidden" :size="18">
                <CaretBottom />
              </el-icon>
              <el-icon class="flex-shrink-0 text-gray-500 hidden group-hover:block" :size="16"
                @click.stop="clearDrug()">
                <Close />
              </el-icon>
            </div>
          </custom-filter>
        </expand-filter-box>
        <div class="flex-shrink-0 flex items-center h-40px pr-15px">
          <el-button v-if="canExpand" text plain @click="expand = !expand">
            <span class="mr-5px">{{ expand ? "收起筛选" : "更多筛选" }}</span>
            <el-icon v-if="expand">
              <ArrowUpBold />
            </el-icon>
            <el-icon v-else>
              <ArrowDownBold />
            </el-icon>
          </el-button>
          <el-button type="primary" @click="search">查询</el-button>
          <el-button plain @click="clear()">清空筛选</el-button>
          <el-button type="success" @click="download">导出excel</el-button>
        </div>
      </div>
    </layout-item>
    <layout-main :scroll="false">
      <el-table v-loading="loading" border ref="tableRef" height="100%" :data="list"
        @selection-change="handleSelectionChange">
        <el-table-column prop="index" type="index" label="序号" :width="60">
          <template #default="{ $index }">{{ $index + 1 }}</template>
        </el-table-column>
        <el-common-column prop="status" label="状态" :width="100">
          <template #default="{ row }">
            <el-text v-if="row.status === 'INIT'" type="warning">待审核</el-text>
            <div v-else-if="row.status === 'PASS' && row.uploadStatus && row.uploadStatus !== 'uploaded'"
              class="text-red-500 mt-5px">上传his失败</div>
            <div v-else-if="row.status === 'PASS'" class="mx-auto inline-block bg-green-500 text-white rounded-md px-2">
              通过
            </div>
            <el-tooltip v-else-if="row.status === 'UNPASS'" effect="light" :content="row.reasonStr"
              placement="right-start" :disabled="!row.reasonStr" popper-class="max-w-50vw">
              <div class="mx-auto inline-block bg-red-500 text-white rounded-md px-2">未通过</div>
            </el-tooltip>
            <!-- <el-text v-else-if="row.status === 'EXPIRED'" type="info">已过期</el-text> -->
            <div v-else class="mx-auto inline-block bg-gray-300 text-white rounded-md px-2">
              已取消
            </div>
            <!-- <el-text v-if="row.status === 'PASS'" type="success">通过</el-text>
            <el-text v-else-if="row.status === 'INIT'" type="warning">待审核</el-text>
            <el-text v-else-if="row.status === 'UNPASS'" type="danger">不通过</el-text>
            <el-text v-else type="info">已取消</el-text> -->
          </template>
        </el-common-column>
        <el-common-column prop="submitTime" label="提交时间" :width="160" />
        <el-common-column prop="approvalTime" label="审核时间" :width="160" />
        <el-common-column prop="doctorName" label="医生" :width="160" />
        <el-common-column prop="pharmacist" label="药师" :width="160" />
        <el-common-column prop="name" label="患者" :width="160">
          <template #default="{ row }">
            <div class="cursor-pointer" @click="viewArchive(row)">
              <el-text type="primary">{{ row.name }} </el-text>
              <el-text v-if="row.age > 0 || row.sex" class="ml-1" type="primary">| {{ row.sex || '' }} {{ row.age > 0 ?
                row.age + '岁' : '' }}</el-text>
            </div>
          </template>
        </el-common-column>
        <el-common-column prop="diagnosisStr" label="诊断" :width="160" />
        <el-common-column prop="drugStr" label="开具药品" :width="160" />
        <el-common-column prop="preType" label="处方类型" :width="160" />
        <el-common-column prop="orderId" label="订单号" :width="160" />
        <el-table-column fixed="right" type="action" label="操作" :width="120">
          <template #default="{ row }">
            <el-text type="primary" class="cursor-pointer" @click="viewDetails(row)">详情</el-text>
            <el-text
              v-if="row.status === 'PASS' && row.uploadStatus !== 'uploaded' && row.prescriptionType === 'storeMedicinePurchase'"" plain type="
              primary" class="cursor-pointer ml-10px" @click="reUpload(row)">重新上传</el-text>
          </template>
        </el-table-column>
      </el-table>
    </layout-main>
    <layout-item>
      <pagination :totalRow="total" :pageSize="pageSize" :currentPage="page" @handle-size-change="changeSize"
        @handle-current-change="changePage" />
    </layout-item>
  </my-layout>
  <archive-drawer :patient="patient || {}" :visible="archiveVisible" @close="archiveVisible = false" />
  <preview-drawer :record="record" :order="record" :visible="previewVisible"
    :has-shipped-medicine-order="hasShippedMedicineOrder" @change="getList()" @viewPatient="viewArchive(record)"
    @viewMedicineOrder="viewLinkedMedicineOrder" @close="previewVisible = false" />
  <detail-drawer :visible="medicineOrderDetailVisible" :order="medicineOrder"
    @close="medicineOrderDetailVisible = false" />
   <drug-picker-modal :list="queryForm.drugs" :width="width" :visible="drugPickerVisible" @confirm="confirm"
    @close="close" />
</template>

<script setup>
import { computed, ref, onMounted } from "vue";
import { ElMessage, ElLoading } from "element-plus";
import { storeToRefs } from "pinia";
import { useHlw, reUploadDiagnosticRecord, downloadExcel, getAllDoctorNos, getRxMedicinePurchaseOrderId, getMedicinePurchaseOrder } from "@/api/hlw";
import dayjs from 'dayjs';
import { memberStore } from "@/store/member";
import useElPagination from "@/hooks/useElPagination";
import { InputFilter, expandFilterBox, RadioFilter, CheckBoxFilter, DateRangeFilter, CustomFilter } from "@/components/filter-bar";
import MyLayout, { LayoutMain, LayoutItem } from "@/components/layout";
import pagination from "@/components/pagination/pagination.vue";
import elCommonColumn from "@/components/el-common-column/el-common-column.vue";
import { ArrowUpBold, ArrowDownBold } from "@element-plus/icons-vue";
import validate from "../../utils/validate";
import archiveDrawer from "@/components/archive-drawer/archive-drawer.vue";
import previewDrawer from './preview-drawer.vue'
import detailDrawer from "@/views/hlw-order/detail-drawer.vue";
import drugPickerModal from './drug-picker-modal.vue'
import useModal from '@/hooks/useModal';

const props = defineProps({
  doctorView: {
    type: Boolean,
    default: false
  }
});
const { list, page, pageSize, total, changePage, changeSize } = useElPagination(getList);
const { close, show, visible: drugPickerVisible, width } = useModal(640);

const today = dayjs().format("YYYY-MM-DD");
const queryForm = ref({ name: "", doctorCodes: [], pharmacistNos: [], dates: [today, today], auditDates: [], status: '', drugs: [] });
const statusList = [
  { label: "待审核", value: "待审核", status: ['INIT'] },
  { label: "通过", value: "通过", status: ['PASS'] },
  { label: "不通过", value: "不通过", status: ['UNPASS'] },
  { label: "已过期", value: "已过期", status: ['EXPIRED'] },
  { label: "已取消", value: "已取消", status: ['PASS_INVALID', 'UNPASS_INVALID', 'INVALID'] },
];
const precriptionTypeList = [
  { label: "全部", value: "all" },
  { label: "中药处方", value: "chinese" },
  { label: "西药处方", value: "west" },
]
const loading = ref(false);
const canExpand = ref(true);
const expand = ref(false);
const params = ref({});
const patient = ref({})
const record = ref({});
const hasShippedMedicineOrder = ref(false);
const linkedMedicineOrderId = ref("");
const medicineOrderDetailVisible = ref(false);
const medicineOrder = ref({});
const doctors = ref([]);
const pharmacistList = ref([]);
const archiveVisible = ref(false);
const previewVisible = ref(false);
const datesText = computed(() => queryForm.value.dates.length > 0 ? `${queryForm.value.dates[0]} - ${queryForm.value.dates[1]}` : "全部");
const auditDatesText = computed(() => queryForm.value.auditDates.length > 0 ? `${queryForm.value.auditDates[0]} - ${queryForm.value.auditDates[1]}` : "全部");
const { memberInfo } = storeToRefs(memberStore());
const drugNames = computed(() => queryForm.value.drugs.map(i => i.name).join('、'));

function clear() {
  queryForm.value = { name: "", doctorCodes: [], pharmacistNos: [], dates: [], auditDates: [], status: '', drugs: [] };
  search();
}

function confirm(selections) {
  queryForm.value.drugs = selections;
  close();
}

function getPatient(row, endDate = dayjs()) {
  const patient = {
    name: row.name,
    blhno: row.blhno,
    idCard: row.idCard,
    address: row.address,
    patientId: row.patientId,
    mobile: row.mobile
  }
  const [pass] = validate.isChinaId(row.idCard);
  if (pass) {
    const year = row.idCard.substring(6, 10);
    const month = row.idCard.substring(10, 12);
    const day = row.idCard.substring(12, 14);
    const sexNumber = row.idCard.substring(16, 17);
    const sex = sexNumber % 2 === 0 ? '女' : '男';
    const birthday = `${year}-${month}-${day}`;// 计算出生日期
    // const endDate = dayjs();
    const birthDate = dayjs(birthday);
    const age = Math.max(endDate.diff(birthDate, 'year'), 1);
    patient.age = age;
    patient.sex = sex;
  }
  return patient
}

function viewArchive(row) {
  patient.value = row.patient;
  archiveVisible.value = true;
}

function search() {
  params.value = {
    name: queryForm.value.name,
    startDate: queryForm.value.dates[0],
    endDate: queryForm.value.dates[1],
    auditStartDate: queryForm.value.auditDates[0],
    auditEndDate: queryForm.value.auditDates[1],
  }
  if (['west', 'chinese'].includes(queryForm.value.preType)) {
    params.value.preType = queryForm.value.preType;
  }
  if (props.doctorView) {
    params.value.doctorCodes = [memberInfo.value.doctorNo || ''];
  } else if (queryForm.value.doctorCodes.length) {
    params.value.doctorCodes = [...queryForm.value.doctorCodes];
  }
  if (queryForm.value.pharmacistNos.length) {
    params.value.pharmacistNos = [...queryForm.value.pharmacistNos];
  }
  if (queryForm.value.drugs.length) {
    params.value.insuranceCodes = [...queryForm.value.drugs.map(i => i.insurance_code)];
  }
  const item = statusList.find(item => item.value === queryForm.value.status);
  if (item) {
    params.value.status = item.status;
  }
  page.value = 1;
  getList();
}

function clearDrug() {
  queryForm.value.drugs = [];
}


async function getList() {
  loading.value = true;
  const { success, data, message } = await useHlw({ type: 'getAllDiagnosisRecord', ...params.value, page: page.value, pageSize: pageSize.value });
  list.value = data && Array.isArray(data.list) ? data.list.map(i => {
    const item = {
      ...i,
      submitTime: i.createTime ? dayjs(i.createTime).format('YYYY-MM-DD HH:mm') : '',
      approvalTime: i.auditTime ? dayjs(i.auditTime).format('YYYY-MM-DD HH:mm') : '-',
      diagnosisStr: Array.isArray(i.diagnosisList) ? i.diagnosisList.map(d => d.name).join(',') : '',
      drugStr: Array.isArray(i.drugs) ? i.drugs.map(d => d.drugName).join(',') : '',
      reasonStr: Array.isArray(i.reasons) ? i.reasons.join(',') : '',
      patient: getPatient(i),
      preType: i.prescriptionType === 'medicalWinePurchase' ? '中药处方' : '西药处方'
    }
    if (item.prescriptionType === 'medicalWinePurchase') {
      item.drugStr = item.wines && item.wines[0] && item.wines[0].name ? item.wines[0].name : ''
    }
    return item
  }) : [];
  total.value = data && data.total ? data.total : 0;
  if (!success) {
    ElMessage.error(message);
  }
  loading.value = false;
}

function viewDetails(row) {
  record.value = { ...row };
  previewVisible.value = true
  getLinkedMedicineOrder(row);
}

async function reUpload(row) {
  loadingInstance.value = ElLoading.service({})
  const { success } = await reUploadDiagnosticRecord(row._id);
  loadingInstance.value.close();
  loadingInstance.value = null;
  if (success) {
    ElMessage.success("重新上传成功");
  } else {
    ElMessage.error("重新上传失败");
  }
  search();
}

async function download() {
  downloadExcel({ ...params.value, type: 'downloadRx' })
}

async function getDoctors() {
  const jobs = props.doctorView ? ['pharmacist'] : ['doctor', 'pharmacist'];
  const { data } = await getAllDoctorNos({ jobs });
  const list = data && data.data && Array.isArray(data.data)
    ? data.data.map((i) => ({
      label: i.doctorName,
      value: i.doctorNo,
      job: i.job,
    }))
    : [];
  doctors.value = list.filter(i => i.job === 'doctor');
  pharmacistList.value = list.filter(i => i.job === 'pharmacist');
}


onMounted(() => {
  search();
  getDoctors()
});

// 根据处方查询已配送的购药订单（用于“关联购药订单”按钮展示）
async function getLinkedMedicineOrder(row) {
  hasShippedMedicineOrder.value = false;
  linkedMedicineOrderId.value = "";
  if (!row || !row._id || !row.accountId) return;
  try {
    const res = await getRxMedicinePurchaseOrderId({
      rpNo: String(row._id),
      accountId: row.accountId,
    });
    const payload = res && res.data ? res.data : null;
    if (res && res.success && payload && payload.id && payload.status === "shipped") {
      linkedMedicineOrderId.value = payload.id;
      hasShippedMedicineOrder.value = true;
    }
  } catch (e) {
    // 查询失败时忽略，不影响处方详情展示
    hasShippedMedicineOrder.value = false;
    linkedMedicineOrderId.value = "";
  }
}

// 查看已关联的购药订单详情
async function viewLinkedMedicineOrder() {
  if (!linkedMedicineOrderId.value || !record.value || !record.value.accountId) {
    return;
  }
  try {
    const res = await getMedicinePurchaseOrder({
      id: linkedMedicineOrderId.value,
      accountId: record.value.accountId,
    });
    const payload = res && res.data ? res.data.data || res.data : null;
    if (!res || !res.success || !payload) {
      ElMessage.error((res && res.message) || "获取购药订单失败");
      return;
    }
    const statusTextMap = {
      unpay: "未支付",
      expired: "已过期",
      ybPaid: "医保支付",
      shipped: "配送中",
      refunded: "已退款",
    };
    const status = payload.status || "";
    const statusText = statusTextMap[status] || status;
    medicineOrder.value = {
      ...payload,
      status,
      statusText,
      raw: payload,
    };
    medicineOrderDetailVisible.value = true;
  } catch (e) {
    ElMessage.error("获取购药订单失败");
  }
}
</script>
