<template>
  <full-page pageStyle="background:#f5f5f5" @reachBottom="getMore()">
    <!-- <template #header>
      <view class="header-tabs" :style="elderVarStyle">
        <view v-for="tab in tabs" :key="tab.value" :class="['tab', { active: activeTab === tab.value }]"
          @click="switchTab(tab.value)">
          {{ tab.label }}
        </view>
      </view>
    </template> -->

    <view class="px-15" :style="elderVarStyle">
      <template v-if="activeTab === 'history-prescription' && list.length">
        <view v-for="i in list" :key="i._id" class="history-item shadow-lg rounded" @click="select(i)">
          <view class="history-item-time">{{ i.time }}</view>
          <view class="history-item-body">
            <view class="history-item-content">
              <view class="history-disease">【诊断】{{ i.disease }}</view>
              <view class="history-drugs">【药品】{{ i.drugNames }}</view>
            </view>
            <image class="checked-icon" :class="elderClass"
              :src="`/static/icons/${selection && selection._id === i._id ? 'checked' : 'unchecked'}.svg`">
            </image>
          </view>
        </view>
      </template>
      <template v-else-if="activeTab === 'purchase-record' && ninetyDaysDrugRecord && ninetyDaysDrugRecord.length">
        <view v-for="i in ninetyDaysDrugRecord" :key="i.mdtrtId" class="history-item shadow-lg rounded"
          @click="select(i)">
          <view class="history-item-time">{{ i.date }}</view>
          <view class="history-item-body">
            <view class="history-item-content">
              <view class="history-disease">【就诊机构】{{ i.medinsName }}</view>
              <view class="history-drugs">【药品】{{ i.drugsStr }}</view>
            </view>
            <image class="checked-icon" :class="elderClass"
              :src="`/static/icons/${selection && selection.mdtrtId === i.mdtrtId ? 'checked' : 'unchecked'}.svg`">
            </image>
          </view>
        </view>
      </template>
      <empty-component v-else height="60vh" text="暂无数据" />
    </view>
    <template #footer>
      <footer-buttons @cancel="cancel" @confirm="confirm" />
    </template>
  </full-page>
  <confirm-popup :consultType="order.consultType" :drugs="displayDrugs" :visible="visible" @close="visible = false"
    @confirm="changeDrugs($event)" />
</template>
<script setup>
import { ref } from 'vue';
import { storeToRefs } from "pinia";
import { onLoad } from '@dcloudio/uni-app';
import dayjs from 'dayjs';
import useElder from '@/hooks/useElder';
import orderStore from '@/store/order';
import usePageList from '@/hooks/usePageList';

import { getAccountHistoryDrugs, getRecent90daysDrugRecord, getOnlineSimilarDrugInfo, getStoreSimilarDrugInfo } from '@/utils/api';
import { confirm as uniConfirm, toast, loading as showLoading, hideLoading } from '@/utils/widget';

import FooterButtons from '@/components/footer-buttons.vue';
import fullPage from '@/components/full-page.vue';
import ConfirmPopup from './confirm-popup.vue';
import EmptyComponent from '@/components/empty.vue';

const { order } = storeToRefs(orderStore());
const { elderClass, elderVarStyle } = useElder();
const tabs = [{ label: '本院历史处方', value: 'history-prescription' }, { label: '医保购药记录', value: 'purchase-record' }];
const activeTab = ref('history-prescription');
const { page, pageSize, list, pages, changePage, loading, hasMore } = usePageList(getList);
const ninetyDaysDrugRecord = ref(null);
const selection = ref(null)
const displayDrugs = ref([])
const visible = ref(false)

function cancel() {
  uni.navigateBack()
}

function changeDrugs(list) {
  visible.value = false;
  list.forEach(i => {
    const index = order.value.drugs.findIndex(j => j.insurance_code === i.insurance_code);
    if (index >= 0) {
      order.value.drugs.splice(index, 1, i);
    } else {
      order.value.drugs.push(i);
    }
  })
  uni.navigateBack()
}

function confirm() {
  if (!selection.value) {
    return toast('请选择药品')
  }
  let drugs = [];
  // 选择的是历史处方记录
  if (selection.value._id) {
    drugs = selection.value.drugs.map(i => ({ ...i, usePreUsage: true }));
  }
  // 选择的是90天的购药记录
  else if (selection.value.mdtrtId) {
    drugs = selection.value.drugList.map(i => ({
      drugName: i.hiListName,
      insurance_code: i.insuranceCode
    }))
  }
  const totalDrugs = [...drugs, ...order.value.drugs];
  const drugTypeCount = new Set(totalDrugs.map(i => i.insurance_code)).size;
  if (drugTypeCount > 5) {
    return uniConfirm('单次问诊药品种类不能超过5种，请重新调整再导入！', { showCancel: false, confirmText: '知道了' })
  }
  getDrugsInfo(drugs);
}

function getMore() {
  if ((loading.value || !hasMore.value) && activeTab.value !== 'history-prescription') return;
  changePage(page.value + 1)
}

function select(item) {
  selection.value = item;
}

function switchTab(value) {
  if (activeTab.value === value) return;
  activeTab.value = value;
  if (value === 'purchase-record' && !ninetyDaysDrugRecord.value) {
    getNinetyDaysDrugRecord()
  }
}

async function getDrugsInfo(drugs) {
  showLoading()
  const payload = {
    accountId: order.value.accountId,
    patientId: order.value.patientId,
    patientName: order.value.name,
    phone: order.value.mobile,
    drugs: drugs.map(i => ({
      drugName: i.drugName,
      spec: i.specification,
      manufacturer: i.manufacturer,
      insurance_code: i.insurance_code
    }))
  }
  const apiName = order.value.consultType === 'onlineMedicinePurchase' ? getOnlineSimilarDrugInfo : getStoreSimilarDrugInfo;
  const res = await apiName(payload);
  hideLoading();
  if (!res || !res.success) {
    return toast(res?.message || '查询失败')
  }
  const matchDrugs = Array.isArray(res.drugs) ? res.drugs : [];
  const similarDrugs = Array.isArray(res.similarDrugs) ? res.similarDrugs : [];
  displayDrugs.value = drugs.map(i => {
    const matchDrug = matchDrugs.find(drug => drug.insurance_code === i.insurance_code);
    if (matchDrug) {
      return { ...i, matchDrug }
    }
    const key = i.insurance_code.slice(0, -5);
    const replaceDrugs = similarDrugs.filter(i => i.insurance_code.startsWith(key)).slice(0, 2);
    return { ...i, usePreUsage: false, replaceDrugs }
  })
  visible.value = true;
}

async function getList(changeTabWhenEmpty = false) {
  if (loading.value) return;
  loading.value = true;
  showLoading()
  const { success, data, message, pages: totalPages } = await getAccountHistoryDrugs({
    accountId: order.value.accountId,
    patientId: order.value.patientId,
    page: page.value,
    pageSize: pageSize.value
  });
  hideLoading();
  pages.value = typeof totalPages === 'number' ? totalPages : 0;
  const arr = Array.isArray(data) ? data.map(i => ({
    ...i,
    time: dayjs(i.createTime).format('YYYY-MM-DD HH:mm'),
    disease: Array.isArray(i.diagnosisList) ? i.diagnosisList.map(i => i.name || '').join(',') : '',
    drugNames: Array.isArray(i.drugs) ? i.drugs.map(i => i.drugName || '').join(',') : '',
  })) : []
  list.value = page.value === 1 ? arr : [...list.value, ...arr];
  if (!success) {
    toast(message || '未查询到历史处方')
  }
  loading.value = false;
  if (changeTabWhenEmpty && list.value.length === 0) {
    switchTab('purchase-record')
  }
}


async function getNinetyDaysDrugRecord() {
  showLoading()
  const res = await getRecent90daysDrugRecord(order.value.patientId);
  const recordList = res && Array.isArray(res.recordList) ? res.recordList : [];
  // x,z开头的药品判定为草药 过滤掉
  const drugList = res && Array.isArray(res.drugList) ? res.drugList.filter(i => typeof i.insuranceCode === 'string' && ['x', 'z', 'X', 'Z'].includes(i.insuranceCode[0])) : [];
  const arr = recordList.map(item => {
    return {
      ...item,
      drugsStr: drugList.filter(drug => drug.mdtrtId === item.mdtrtId).map(drug => drug.hiListName).join('、'),
      drugList: drugList.filter(drug => drug.mdtrtId === item.mdtrtId)
    }
  }).filter(i => Boolean(i.drugsStr))
  hideLoading();
  if (res && res.success) {
    ninetyDaysDrugRecord.value = arr;
  } else {
    toast(message || '未查询到购药记录')
  }
}

onLoad(() => {
  getList(true)
})

</script>
<style lang="scss" scoped>
.header-tabs {
  display: flex;
  background: #fff;
  text-align: center;
  margin-bottom: 24rpx;

  .tab {
    position: relative;
    flex-grow: 1;
    padding: 24rpx 30rpx;
    font-size: var(--text-base);
    color: #333;

    &.active {
      color: $theme-brown-primary;
      font-weight: bold;
    }

    &.active::after {
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      bottom: 0;
      content: "";
      width: 120rpx;
      height: 8rpx;
      border-radius: 4rpx;
      background: $theme-brown-primary;
    }
  }
}

.history-item {
  margin-bottom: 30rpx;
  background: #fff;

  .history-item-time {
    padding: 24rpx 30rpx;
    font-size: var(--text-sm);
    color: #333;
    border-bottom: 1px solid #eee;
  }

  .history-item-body {
    display: flex;
    align-items: center;
    padding: 24rpx 30rpx;
  }

  .history-item-content {
    width: 0;
    flex-grow: 1;
    word-break: break-all;
    line-height: 1.5;
    font-size: var(--text-base);
  }

  .checked-icon {
    margin-left: 16rpx;
    width: 40rpx;
    height: 40rpx;

    @at-root &.caring-mode-active {
      width: 60rpx;
      height: 60rpx;
    }
  }
}
</style>