<template>
  <my-layout v-loading="loading">
    <layout-item>
      <div class="px-15px py-10px bg-white border-b border-gray-200">
        <el-button type="primary" :icon="CreditCard" :loading="reading" @click="getCardInfo">刷实体卡</el-button>
        <el-button v-if="cardInfo.IDNum || patient.patientid" plain type="info" :icon="DeleteFilled" :loading="reading"
          @click="clearAll()">清空信息</el-button>
        <!-- <el-button type="primary" :icon="CreditCard" :loading="reading" @click="scan">刷医保码</el-button> -->
      </div>
      <div class="py-10px px-10px mb-10px flex bg-white">
        <el-form inline label-suffix="：">
          <el-row>
            <el-col :lg="6" :sm="12">
              <el-form-item class="mr-15px mb-0" label="患者">
                <div class="min-w-100px">{{ patient.name || '' }}</div>
              </el-form-item>
            </el-col>
            <el-col :lg="6" :sm="12">
              <el-form-item class="mr-15px mb-0" label="性别">
                <div class="min-w-100px">{{ patient.sex }}</div>
              </el-form-item>
            </el-col>
            <el-col :lg="6" :sm="12">
              <el-form-item class="mr-15px mb-0" label="年龄">
                <div class="min-w-100px">{{ patient.age }}</div>
              </el-form-item>
            </el-col>
            <el-col :lg="6" :sm="12">
              <el-form-item class="mr-15px mb-0" label="身份">
                <div v-if="patient.isyb" class="min-w-100px">{{ patient.isyb === '1' ? '医保' : '非医保' }}</div>
              </el-form-item>
            </el-col>
            <el-col :lg="6" :sm="12">
              <el-form-item class="mr-15px mb-0" label="手机号">
                <div class="min-w-100px">{{ patient.tel }}</div>
              </el-form-item>
            </el-col>
            <el-col :lg="6" :sm="12">
              <el-form-item class="mr-15px mb-0" label="病历号">
                <div class="min-w-100px">{{ patient.blhno }}</div>
              </el-form-item>
            </el-col>
            <el-col :lg="6" :sm="12">
              <el-form-item class="mr-15px mb-0" label="证件类型">
                <div class="min-w-100px">{{ patient.isIdCard ? '身份证' : '' }}</div>
              </el-form-item>
            </el-col>
            <el-col :lg="6" :sm="12">
              <el-form-item class="mr-15px mb-0" label="证件号">
                <div class="min-w-100px">{{ patient.socialno }}</div>
              </el-form-item>
            </el-col>
            <el-col :lg="6" :sm="12">
              <el-form-item class="mr-15px mb-0" label="地址">
                <div class="min-w-100px">{{ patient.address || '' }}</div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="flex justify-between items-center px-15px py-10px bg-white border-b border-gray-200">
        <el-radio-group v-model="tab" @change="changeTab">
          <el-radio-button label="reg" value="reg">
            <el-icon class="transform translate-y-1px">
              <Promotion />
            </el-icon> 线下挂号
          </el-radio-button>
          <el-radio-button label="record" value="record">
            <el-icon class="mr-3px transform translate-y-1px">
              <EditPen />
            </el-icon>挂号记录
          </el-radio-button>
        </el-radio-group>
        <div class="flex items-center">
          <el-date-picker v-if="tab === 'record'" style="width: 190px" v-model="date" class="mr-20px"
            placeholder="请选择挂号日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" @change="changeDate" />
          <el-button type="primary" :icon="RefreshRight" @click="refresh">刷新</el-button>
        </div>
      </div>
    </layout-item>
    <layout-main :scroll="false">
      <el-table v-if="tab === 'reg'" border stripe :loading="tableLoading" :data="list" ref="tableRef" height="100%">
        <el-common-column prop="name" label="来源" :width="140">
          <template #default>互联网推荐医生</template>
        </el-common-column>
        <el-common-column prop="deptName" label="科室" :width="160" />
        <el-common-column prop="doctorName" label="医生" :width="160">
          <template #default="{ row: { doctorName } }">
            <span>{{ doctorName }}</span>
          </template>
        </el-common-column>
        <el-common-column prop="title" label="职称" :width="160">
          <template #default="{ row: { title } }">
            <span>{{ title }}</span>
          </template>
        </el-common-column>
        <el-common-column prop="chargeFee" label="价格" :width="100" />
        <el-common-column prop="pendingOrdersCount" label="候诊数" :width="120" />
        <el-common-column v-if="enableWineReg" prop="pendingOrdersCount" label="咨询类别" :width="120">
          <template #default>
            <el-switch v-model="isWineReg" style="--el-switch-on-color: #13ce66; --el-switch-off-color: #0074ff"
              size="large" inline-prompt active-text="中药饮片咨询" inactive-text="普通咨询" />
          </template>
        </el-common-column>
        <el-common-column fixed="right" prop="action" label="操作" :width="80">
          <template #default="{ row }">
            <div class="text-center">
              <el-button type="primary" @click="reg(row)">挂号</el-button>
            </div>
          </template>
        </el-common-column>
        <template #empty>
          <el-empty description="请先获取患者信息" />
        </template>
      </el-table>
      <record-table ref="recordTableRef" v-else-if="tab === 'record'" :date="date" :patientId="patient.patientid"
        :cardInfo="cardInfo" :storeId="memberInfo.drugStoreId" />
    </layout-main>
  </my-layout>
  <result-modal :visible="visible" :status="status" :msg="msg" @close="visible = false" />
  <settle-modal :patient="patient" :data="settlement" :visible="settleVisible" :width="width" @close="close"
    @change="changeResult" />
  <build-modal :card-info="cardInfo" :visible="buildVisible" :width="buildWidth" @close="closeBuildModal"
    @confirm="confirmBuild" />
</template>
<script setup>
import { ref, onMounted, computed, watch } from "vue";
import { storeToRefs } from 'pinia'
import { ElMessage, ElMessageBox } from "element-plus";
import dayjs from 'dayjs';
import { scanCodeApi, getReadCardApi } from '@/api/card-jsonp.js';
import { getHisCustomer, getRecommendDoctor, hlwWebReg } from '@/api/hlw';
import useModal from "@/hooks/useModal";
import { memberStore } from "@/store/member";
import validate from "@/utils/validate";

import { CreditCard, EditPen, RefreshRight, DeleteFilled } from "@element-plus/icons-vue";
import MyLayout, { LayoutMain, LayoutItem } from "@/components/layout";
import elCommonColumn from "@/components/el-common-column/el-common-column.vue";
import resultModal from "./result-modal.vue";
import settleModal from "./settle-modal.vue";
import buildModal from "./build-modal.vue";
import recordTable from "./record-table.vue";

const patient = ref({});
const cardInfo = ref({});
const list = ref([]);
const reading = ref(false);
const visible = ref(false);
const status = ref('loading');
const date = ref('');
const settlement = ref({});
const msg = ref('');
const loading = ref(false);
const tableLoading = ref(false);
const isWineReg = ref(false);
const enableWineReg = ref(false);

const { close, show, visible: settleVisible, width } = useModal(560);
const { close: closeBuildModal, show: showBuildModal, visible: buildVisible, width: buildWidth } = useModal(560);
const { memberInfo } = storeToRefs(memberStore());
const tab = ref('reg')
const recordTableRef = ref(null);

async function scan() {
  scanCodeApi()
}

function changeTab() {
  date.value = ''
}

/**
 * 刷实体卡
 * 步骤一 调用读卡器接口获取 实体卡信息
 * 步骤二 根据实体卡信息 查询建档信息， 未建档则去建档
 * 步骤三 获取在线医生 
 */
async function getCardInfo() {
  if (loading.value) return;
  loading.value = true;
  cardInfo.value = {};
  patient.value = {};
  try {
    const readRes = await readCard();
    if (!readRes) {
      loading.value = false;
      return
    };
    cardInfo.value = { ...readRes };
    const { success, card, message } = await getPatientInfo(readRes.IDNum);
    if (!success) {
      loading.value = false;
      return ElMessage.error(message || '查询档案信息失败')
    }
    if (!card) {
      loading.value = false;
      showBuildModal();
      return
    }
    patient.value = { ...card };
    const { sex, age, isIdCard } = calcPersonInfo(patient.value.socialno, dayjs());
    patient.value.sex = sex;
    patient.value.age = age;
    patient.value.isIdCard = isIdCard;
    await getRandomDoctor();
  } catch (e) {
    console.log(e)
    ElMessage.info(e)
  }
  loading.value = false;
}

async function readCard() {
  try {
    const { close } = ElMessage.info('正常读取卡信息...')
    const readRes = await getReadCardApi();
    const IDNum = readRes && validate.isChinaId(readRes.IDNum || '')[0] ? readRes.IDNum : '';
    const msg = typeof readRes === 'string' ? readRes : '';
    const objMsg = readRes && typeof readRes.Message ? readRes.Message : '';
    close()
    if (!IDNum) {
      ElMessage.info(objMsg || msg || '读取卡信息失败')
      return false
    }
    return readRes
  } catch (e) {
    ElMessage.info(e)
  }
}

/**
 * 根据证件号 查询建档信息
 * @param IDNum 
 */
async function getPatientInfo(IDNum) {
  const { success, data, message } = await getHisCustomer(IDNum);
  const card = data && Array.isArray(data.list) && data.list[0] ? data.list[0] : null;
  return { success, card, message }
}

/**
 * 完成新用户建档 并且随机获取一个在线医生
 * @param card 
 */
async function confirmBuild(card) {
  patient.value = { ...card };
  const { sex, age, isIdCard } = calcPersonInfo(patient.value.socialno, dayjs());
  patient.value.sex = sex;
  patient.value.age = age;
  patient.value.isIdCard = isIdCard;
  getRandomDoctor()
}

function refresh() {
  if (tab.value === 'reg') {
    if (!tableLoading.value && patient.value.patientid) getRandomDoctor()
  } else {
    recordTableRef.value && recordTableRef.value.refresh()
  }
}

/**
 * 随机获取一个在线医生
 */
async function getRandomDoctor() {
  if (!memberInfo.value || !memberInfo.value.drugStoreId) {
    return ElMessage.info('当前账户未关联门店')
  }
  tableLoading.value = true;
  const payload = { storeCode: memberInfo.value.drugStoreId, presType: enableWineReg.value && isWineReg.value ? 'chinese' : 'west' };
  const { success, data } = await getRecommendDoctor(payload);
  list.value = data && data.data ? [data.data] : [];
  tableLoading.value = false;
  if (!success || list.value.length === 0) {
    ElMessage.info('没有获取到推荐医生')
  }
}

/**
 * 根据证件号以及当前时间 计算年龄和性别
 * @param idCard 
 * @param currentTime 
 */
function calcPersonInfo(idCard, currentTime) {
  const [isIdCard, birthday, gender] = validate.isChinaId(idCard);
  if (isIdCard && currentTime) {
    const startDate = dayjs(currentTime);
    const year = startDate.year();
    const birthYear = dayjs(birthday).year();
    const thisYearBirthday = dayjs(birthday).year(year);
    const gap =
      year - birthYear - (startDate.isBefore(thisYearBirthday) ? 1 : 0); // 生日是否过了
    const age = Math.max(1, gap);
    return {
      isIdCard,
      birthday,
      age,
      sex: gender === "MALE" ? "男" : "女"
    };
  }
  return {
    birthday,
    age: '',
    sex: ""
  };
}

async function reg() {
  if (loading.value) return;
  loading.value = true;
  const readRes = await readCard();
  if (!readRes) {
    loading.value = false;
    return
  }
  if (readRes.CardNum !== cardInfo.value.CardNum || readRes.CardIDCode !== cardInfo.value.CardIDCode) {
    ElMessage.info('患者信息与挂号信息不匹配, 请插入正确的实体卡')
    loading.value = false;
    return false
  }
  status.value = 'loading'
  msg.value = '请稍等，挂号中...';
  visible.value = true
  const payload = {
    name: patient.value.name,
    patientId: patient.value.patientid,
    doctorNo: list.value[0].doctorNo,
    deptCode: list.value[0].deptCode,
    feeCode: list.value[0].feeCode,
    storeId: memberInfo.value.drugStoreId,
    mdtrtCertType: '03',
    mdtrtCertNo: cardInfo.value.CardNum,
    cardSn: cardInfo.value.CardIDCode
  }
  if (enableWineReg.value && isWineReg.value) {
    payload.channel = 1
  }
  const { success, message, data } = await hlwWebReg(payload);
  loading.value = false;
  if (success) {
    visible.value = false;
    settlement.value = { ...data.data, id: data.id };
    show()
  } else {
    status.value = 'error';
    msg.value = message || '挂号失败'
  }
}

function changeResult({ status: newStatus, msg: newMsg }) {
  if (newStatus === 'success') {
    clearAll()
  }
  status.value = newStatus
  msg.value = newMsg
  visible.value = true
}

function clearAll() {
  cardInfo.value = {}
  patient.value = {}
  list.value = []
}
</script>
<style lang="scss" scoped></style>
