<template>
  <my-layout class="bg-[#f2f3f4]">
    <layout-main ref="mainRef">
      <div class="px-15px py-12px bg-white">
        <slot name="head"></slot>
        <div active-title-bar>问诊人信息</div>
        <el-form class="mt-5px" label-suffix="：">
          <el-form-item class="mb-0" label="姓名">{{ order.name }} </el-form-item>
          <el-form-item class="mb-0" label="性别">{{ order.sex }} </el-form-item>
          <el-form-item class="mb-0" label="年龄">{{ order.age ? order.age + '岁' : '' }} </el-form-item>
        </el-form>
      </div>

      <div class="px-15px py-12px mt-15px bg-white">
        <div active-title-bar>病人主诉</div>
        <el-form class="mt-5px" label-suffix="：">
          <el-form-item v-if="order.diseases && order.diseases.length" class="mb-0" label="线下已确认疾病">
            {{ order.diseases ? order.diseases.join('，') : '' }}
          </el-form-item>
          <el-form-item class="mb-0" label="病情描述">
            {{ wine && wine.cate ? `（${wine.cate}）` : '' }}{{ order.description }}
          </el-form-item>
          <el-form-item class="mb-0" label="病史">{{ order.pastHistoryStr }} </el-form-item>
          <el-form-item class="mb-0" label="相关附件">
            <div class="flex-grow w-0 flex flex-wrap">
              <img v-for="(src, idx) in images" :key="src" :src="src" class="w-80px h-80px mr-10px mb-10px"
                @click="preview(idx)">
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div v-if="order.visitRecord" class="px-15px py-12px mt-15px bg-white">
        <div active-title-bar>就诊记录</div>

        <el-form class="mt-5px" label-suffix="：">
          <el-form-item class="mb-0" label="就诊日期">{{ order.visitRecord.date }} </el-form-item>
          <el-form-item class="mb-0" label="就诊医疗机构">{{ order.visitRecord.medinsName }} </el-form-item>
          <el-form-item class="mb-0" label="药品">{{ order.visitRecord.drugsStr || '无' }} </el-form-item>
        </el-form>
      </div>
      <div v-if="order.consultType === 'wineConsult'" class="px-15px py-12px mt-15px bg-white">
        <div class="flex items-center justify-between">
          <div active-title-bar>申请中药饮片配方</div>
          <el-button v-if="order.authDrugRecord === 'Y'" type="primary" plain
            @click="historyDrugVisible = true">患者历史购药记录</el-button>
        </div>
        <div v-for="(i, idx) in (order.wines || [])" :key=idx class="mt-10px text-14px leading-20px">
          <div class="flex items-start">
            <div class="flex-shrink-0">{{ idx + 1 }}、</div>
            <div class="w-0 flex-grow">
              <span>{{ i.name }}</span>
              <span v-if="i.isFirst" class="text-red-500">（该患者首次在本互联网医院购买此药品，需上传相关证明材料）</span>
            </div>
            <div class="flex-shrink-0 ml-10px">x {{ i.quantity }}{{ i.unit }}</div>
          </div>
          <!-- <div class="mt-5px pl-25px text-gray-500">{{ i.efficacy }} </div> -->
        </div>
      </div>
      <div v-else class="px-15px py-12px mt-15px bg-white">
        <div class="flex items-center justify-between">
          <div active-title-bar>申请药品</div>
          <el-button v-if="order.authDrugRecord === 'Y'" type="primary" plain
            @click="historyDrugVisible = true">患者历史购药记录</el-button>
        </div>
        <div v-for="(i, idx) in (applyDrugs || [])" :key=idx class="mt-10px text-14px leading-20px">
          <div class="flex items-start">
            <div class="flex-shrink-0">{{ idx + 1 }}、</div>
            <div class="w-0 flex-grow">
              <span>{{ i.name }}</span>
              <span v-if="i.medication_proof_desc" class="text-red-500 ml-5px">（该药品需上传用药证明，详见附件图片）</span>
            </div>
            <div class="flex-shrink-0 ml-10px">{{ i.quantity }}{{ i.unit }}</div>
          </div>
          <div class="mt-5px pl-25px text-gray-500">规格：{{ i.specification }} </div>
          <div class="mt-5px pl-25px text-gray-500">厂商：{{ i.manufacturer }} </div>
          <div class="mt-5px pl-25px text-gray-500">用法：{{ i.memo }} </div>
        </div>
      </div>
      <div v-if="rx && rx._id && rx.orderId === order.orderId" class="px-15px py-12px mt-15px bg-white">
        <div active-title-bar>门诊病历</div>
        <el-form class="mt-5px" label-suffix="：">
          <el-form-item class="mb-0" label="主诉">{{ rx.complaint }}</el-form-item>
          <el-form-item class="mb-0" label="现病史">{{ rx.presentIllness }}</el-form-item>
          <el-form-item class="mb-0" label="处置">{{ rx.dispose }}</el-form-item>
          <el-form-item class="mb-0" v-for="(item, idx) in diagnosisList" :label="`诊断${idx + 1}`">
            {{ item.name }} {{ item.desc || '' }}
          </el-form-item>
        </el-form>
        <template v-if="drugList.length">
          <div active-title-bar>西药处方</div>
          <el-table class="mt-10px" :data="drugList">
            <el-table-column label="序号" prop="index" :width="60">
              <template #default="{ $index }">{{ $index + 1 }}</template>
            </el-table-column>
            <el-table-column label="药品" prop="showName" :min-width="200">
              <template #default="{ row }">{{ row.showName }}</template>
            </el-table-column>
            <el-table-column label="数量" prop="quantity" :width="100">
              <template #default="{ row }">{{ row.quantity }} {{ row.unit }}</template>
            </el-table-column>
            <el-table-column label="用法" prop="memo" :min-width="100">
              <template #default="{ row }">{{ row.memo }}</template>
            </el-table-column>
          </el-table>
        </template>
        <template v-else-if="rx && rx.wines && rx.wines.length">
          <div active-title-bar>中药处方</div>
          <el-table class="mt-10px" :data="rx.wines">
            <el-table-column label="序号" prop="index" :width="60">
              <template #default="{ $index }">{{ $index + 1 }}</template>
            </el-table-column>
            <el-table-column label="药品" prop="showName" :min-width="200">
              <template #default="{ row }">
                <span class="mr-2">{{ row.name }}</span>
                <span v-if="row.details" class="text-gray-500">({{ row.details }})</span>
              </template>
            </el-table-column>
            <el-table-column label="数量" prop="quantity" :width="100">
              <template #default="{ row }">{{ row.quantity }} {{ row.unit }}</template>
            </el-table-column>
          </el-table>
        </template>
      </div>
      <div class="px-15px py-12px mt-15px bg-white">
        <div active-title-bar>问诊订单信息</div>
        <el-form class="mt-5px" label-suffix="：">
          <el-form-item class="mb-0" label="订单编号">{{ order.orderId }} </el-form-item>
          <el-form-item class="mb-0" label="下单时间">
            {{ order.createTime ? dayjs(order.createTime).format('YYYY-MM-DD HH:mm') : '' }}
          </el-form-item>
          <el-form-item v-if="order.settlement" class="mb-0" label="诊查费"> <span class="text-orange-500">￥{{
            order.settlement.total_fee }}</span> </el-form-item>
          <el-form-item v-if="order.settlement" class="mb-0" label="支付方式">
            {{ order.orderSource === 'MATEPAD' ? ' 线下支付' : '支付宝医保结算' }}
          </el-form-item>
          <el-form-item v-if="order.settlement" class="mb-0" label="支付时间">{{ order.settlement.chage_date }}
          </el-form-item>
          <el-form-item v-if="order.drugStoreName" class="mb-0" label="来源">{{ order.drugStoreName }}</el-form-item>
          <el-form-item class="mb-0" label="终端">{{ OrderSource[order.orderSource] || '' }}</el-form-item>
          <el-form-item v-if="order.pickUpType && PickUpType[order.pickUpType]" class="mb-0" label="取药方式">
            {{ PickUpType[order.pickUpType] }}
          </el-form-item>
          <template v-if="order.refundInfo && order.refundInfo.status === 'PASS'">
            <el-form-item v-if="order.refundInfo.updateTime" class="mb-0" label="退费时间">{{
              dayjs(order.refundInfo.updateTime).format('YYYY-MM-DD HH:mm:ss') }}</el-form-item>
            <el-form-item class="mb-0" label="退费操作人">{{ order.refundInfo.operator }}</el-form-item>
          </template>
        </el-form>
      </div>
    </layout-main>
    <layout-item>
      <slot name="footer"></slot>
    </layout-item>
  </my-layout>
  <el-image-viewer v-if="showViewer" :url-list="images" :initial-index="initialIndex" @close="cancel()" />
  <history-drug-drawer :order="order" :visible="historyDrugVisible" @close="historyDrugVisible = false" />
</template>
<script setup>
import { ref, computed, watch } from "vue";
import dayjs from 'dayjs';
import MyLayout, { LayoutMain } from "@/components/layout";
import OrderSource from '@/baseData/source'
import { getDrugs } from '@/api/hlw.js'
import historyDrugDrawer from "./history-drug-drawer.vue";

const PickUpType = { selfTake: '门店自取', delivery: '快递配送' };

const props = defineProps({
  order: {
    type: Object,
    default: () => ({})
  },
  rx: {
    type: Object,
    default: () => ({})
  }
});
const historyDrugVisible = ref(false);
const images = computed(() => {
  return props.order && Array.isArray(props.order.images) ? props.order.images : []
})
const diagnosisList = computed(() => props.rx && Array.isArray(props.rx.diagnosisList) ? props.rx.diagnosisList.filter(i => i.code && i.name) : [])
const drugList = computed(() => props.rx && Array.isArray(props.rx.drugs) ? props.rx.drugs.map((drug) => {
  const spec = drug.specification ? `（${drug.specification}）` : '';
  const showName = drug.drugName + spec;
  const memo = [drug.usageName, drug.frequencyName, (drug.dosage || '') + (drug.dosage_unit || '')].filter(Boolean).join('，')
  return { ...drug, memo, showName }
}).filter(i => i.insurance_code) : [])

const wine = computed(() => {
  if (props.order && props.order.consultType === 'wineConsult') {
    return props.order.wines && props.order.wines[0] ? props.order.wines[0] : null
  }
  return null
})

const showViewer = ref(false);
const initialIndex = ref(0);
// 本地副本，便于补充 medication_proof_desc
const applyDrugs = ref([]);

async function enrichMedicationProof(drugs = []) {
  if (!Array.isArray(drugs) || !drugs.length) {
    applyDrugs.value = [];
    return;
  }
  const list = drugs.map(d => ({ ...d }));
  const missingIds = list.filter(d => !d.medication_proof_desc && d._id).map(d => d._id);
  if (missingIds.length) {
    try {
      const { data } = await getDrugs({ ids: missingIds, page: 1, pageSize: missingIds.length });
      const arr = data && Array.isArray(data.data) ? data.data : [];
      const map = arr.reduce((m, cur) => { m[cur._id] = cur; return m; }, {});
      list.forEach(d => {
        if (!d.medication_proof_desc && map[d._id] && map[d._id].medication_proof_desc) {
          d.medication_proof_desc = map[d._id].medication_proof_desc;
        }
      });
    } catch (e) {
      // 忽略错误，保持已有数据
    }
  }
  applyDrugs.value = list;
}

watch(() => props.order && props.order.drugs, (n) => {
  enrichMedicationProof(Array.isArray(n) ? n : []);
}, { immediate: true });
function cancel() {
  showViewer.value = false;
}
function preview(index) {
  initialIndex.value = index || 0;
  showViewer.value = true;
}

</script>
<style lang="scss" scoped></style>
