<template>
  <uni-popup ref="popup" type="bottom" :mask-click="false">
    <view class="bg-white" :style="elderVarStyle">
      <view class="popup-header flex items-center justify-between px-15 py-12">
        <view class="popup-title">提示</view>
        <uni-icons type="closeempty" :size="elderMode ? 32 : 24" color="#999" @click="close"></uni-icons>
      </view>
      <view class="px-15 py-12">
        <text class="text-base text-dark">共导入{{ drugs.length }}种药品</text>
        <template v-if="list.length">
          <text class="text-base text-dark">，</text>
          <text class="text-base text-primary">{{ list.length }}</text>
          <text class="text-base text-dark">种有货</text>
        </template>
        <template v-if="lackList.length">
          <text class="text-base text-dark">，</text>
          <text class="text-base text-primary">{{ lackList.length }}</text>
          <text class="text-base text-dark">种需确认</text>
        </template>
      </view>
      <scroll-view scroll-y="true" class="popup-content-scroll">
        <view class="px-15 py-12">
          <view v-if="lackList.length" class="bg-white rounded px-15 py-12">
            <view class="text-base text-danger">缺货（{{ lackList.length }}）</view>
            <view v-for="i in lackList" :key="i.insurance_code">
              <view class="text-base text-gray py-5">{{ i.drugName }}（暂不支持购买）</view>
              <view v-if="i.replaceDrugs.length" class="pl-15">
                <view class="text-base text-dark">为您推荐同成分药品，您可以勾选导入：</view>
                <view v-for="med in i.replaceDrugs" :key="med._id" class="flex py-5"
                  @click="selectReplaceDrug(med, i.insurance_code)">
                  <image class="flex-shrink-0 drug-checked-icon" :class="elderClass"
                    :src="`/static/icons/${selectMap[i.insurance_code] === med._id ? 'checked' : 'unchecked'}.svg`">
                  </image>
                  <view class="flex-grow">
                    <view>
                      <text class="text-base text-drak">{{ med.name }}</text>
                      <text class="mr-10 text-base text-gray">{{ med.specification }}</text>
                    </view>
                    <view class="text-base text-gray">{{ med.manufacturer }}</view>
                  </view>
                </view>
              </view>
            </view>
          </view>
          <view v-if="list.length" class="bg-white rounded mt-12 px-15 py-12">
            <view class="text-base text-success">有货（{{ list.length }}）</view>
            <view v-for="i in list" :key="i.insurance_code" class="flex py-5" @click="toggle(i)">
              <image class="flex-shrink-0 drug-checked-icon" :class="elderClass"
                :src="`/static/icons/${selectMap[i.insurance_code] === i.insurance_code ? 'checked' : 'unchecked'}.svg`">
                <!-- <image class="flex-shrink-0 drug-checked-icon" :class="elderClass" src="/static/icons/checked.svg"> -->
              </image>
              <view class="flex-grow leading-normal break-all">
                <view>
                  <text class="text-base text-drak mr-5">{{ i.drugName }}</text>
                  <text v-if="i.matchDrug && i.matchDrug.specification" class="text-base text-gray">
                    {{ i.matchDrug.specification }}
                  </text>
                </view>
                <view v-if="i.matchDrug && i.matchDrug.manufacturer" class="pt-5 text-base text-gray">
                  {{ i.matchDrug.manufacturer }}
                </view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
      <view class="footer-buttons">
        <footer-buttons :showConfirm="hasValidDrugs" :cancelText="hasValidDrugs ? '取消' : '关闭'" confirmText="导入勾选药品"
          @cancel="close" @confirm="confirm" />
      </view>
    </view>
  </uni-popup>
</template>

<script setup>
import { computed, ref, watch } from 'vue';
import { storeToRefs } from "pinia";
import useElder from '@/hooks/useElder';
import useDb from '@/store/db';
import FooterButtons from '@/components/footer-buttons.vue';
const emits = defineEmits(['close', 'confirm'])
const props = defineProps({
  drugs: {
    type: Array,
    default: () => []
  },
  visible: {
    type: Boolean,
    default: false
  }
})
const selectMap = ref({});
const popup = ref()
const { elderClass, elderVarStyle, elderMode } = useElder();
const { onlineMedicine, storeMedicine } = storeToRefs(useDb());

const list = computed(() => props.drugs.filter(i => i.matchDrug))
const lackList = computed(() => props.drugs.filter(i => !i.matchDrug))
const hasValidDrugs = computed(() => props.drugs.some(i => i.matchDrug || (!i.matchDrug && i.replaceDrugs && i.replaceDrugs.length)))

const usageList = computed(() => {
  return props.consultType === 'onlineMedicinePurchase' ? onlineMedicine.value.usageList : storeMedicine.value.usageList;
})
const frequencyList = computed(() => {
  return props.consultType === 'onlineMedicinePurchase' ? onlineMedicine.value.frequencyList : storeMedicine.value.frequencyList;
})

function close() {
  emits('close')
}

function confirm() {
  const data = props.drugs.reduce((acc, drug) => {
    if (!selectMap.value[drug.insurance_code]) return acc;
    const { usePreUsage, ...item } = drug;
    const matchDrug = item.matchDrug;
    const replaceDrug = matchDrug ? null : item.replaceDrugs.find(i => selectMap.value[item.insurance_code] === i._id);
    if (usePreUsage) {
      acc.push(usePreUsageData(JSON.parse(JSON.stringify(matchDrug)), item))
    } else if (matchDrug || replaceDrug) {
      const drug = JSON.parse(JSON.stringify(matchDrug || replaceDrug));
      acc.push(useStandardUsage(drug, drug))
    }
    return acc;
  }, [])
  emits('confirm', data)
}

function initSelect() {
  selectMap.value = {};
  props.drugs.forEach(i => {
    selectMap.value[i.insurance_code] = i.matchDrug ? i.insurance_code : '';
  });
  if (props.drugs.every(i => i.matchDrug)) {
    confirm()
  }
}

function selectReplaceDrug(med, insurance_code) {
  if (selectMap.value[insurance_code] === med._id) {
    selectMap.value[insurance_code] = '';
  } else {
    selectMap.value[insurance_code] = med._id;
  }
}

function toggle(i) {
  selectMap.value[i.insurance_code] = selectMap.value[i.insurance_code] === i.insurance_code ? '' : i.insurance_code;
}

/**
 * 
 * @param matchDrug 带入之前的用法用量
 * @param item 
 */
function usePreUsageData(matchDrug, item) {
  matchDrug.quantity = Number.isInteger(item.quantity) && item.quantity > 0 ? item.quantity : matchDrug.quantity;
  const frequency = frequencyList.value.find(i => i.name === item.frequencyName);
  matchDrug.frequencyName = frequency ? frequency.name : '';
  matchDrug.frequencyCode = frequency ? frequency.code : '';
  const usage = usageList.value.find(i => i.name === item.usageName);
  matchDrug.usageName = usage ? usage.name : '';
  matchDrug.usageCode = usage ? usage.code : '';
  const dosage = item.dosage > 0 ? item.dosage : matchDrug.dosage;
  matchDrug.dosage = dosage;
  const days = Number.isInteger(item.days) && item.days > 0 ? item.days : matchDrug.days;
  matchDrug.days = days;
  const arr = [matchDrug.usageName, matchDrug.frequencyName, matchDrug.dosage ? `每次${matchDrug.dosage}${matchDrug.dosage_unit || ''}` : ''].filter(Boolean);
  matchDrug.memo = arr.join('，');
  return matchDrug;
}

function useStandardUsage(matchDrug, item) {
  matchDrug.quantity = Number.isInteger(item.recommended_quantity) && item.recommended_quantity > 0 ? item.recommended_quantity : matchDrug.recommended_quantity;
  const frequency = frequencyList.value.find(i => i.name === item.frequency);
  matchDrug.frequencyName = frequency ? frequency.name : '';
  matchDrug.frequencyCode = frequency ? frequency.code : '';
  const usage = usageList.value.find(i => i.name === item.administration_method);
  matchDrug.usageName = usage ? usage.name : '';
  matchDrug.usageCode = usage ? usage.code : '';
  const dosage = item.dosage > 0 ? item.dosage : '';
  matchDrug.dosage = dosage;
  const days = Number.isInteger(item.days) && item.days > 0 ? item.days : matchDrug.days;
  matchDrug.days = days;
  const arr = [matchDrug.usageName, matchDrug.frequencyName, matchDrug.dosage ? `每次${matchDrug.dosage}${matchDrug.dosage_unit || ''}` : ''].filter(Boolean);
  matchDrug.memo = arr.join('，');
  return matchDrug;
}

watch(() => props.visible, n => {
  if (n) {
    popup.value && popup.value.open()
    initSelect()
  } else {
    popup.value && popup.value.close()
  }
})

</script>

<style lang="scss" scoped>
.popup-header {
  border-bottom: 1px solid #eee;
}

.popup-title {
  font-size: var(--text-base);
  font-weight: bold;
  color: #333;
}

.popup-content-scroll {
  max-height: 55vh;
  background-color: #f5f5f5;
}

.text-base {
  font-size: var(--text-base);
  line-height: 1.5;
}

.pl-15 {
  padding-left: 30rpx;
}

.py-5 {
  padding-top: 10rpx;
  padding-bottom: 10rpx;
}

.drug-checked-icon {
  width: 36rpx;
  height: 36rpx;
  transform: translateY(2rpx);

  @at-root &.caring-mode-active {
    width: 54rpx;
    height: 54rpx;
    transform: translateY(4rpx);
  }
}
</style>