<script lang="ts" setup>
import { ref } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';

import { Button } from 'ant-design-vue';

import { getPrescriptionInfoApi } from '#/views/doctor/doctor-reception/api';

const item = ref<Record<string, any>>({});

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const { values } = modalApi.getData<Record<string, any>>();
      if (values) {
        if (typeof values === 'number') {
          getPrescriptionInfoApi(values).then((res) => {
            item.value = res;
          });
        } else {
          item.value = values;
        }
      }
    }
  },
});

function handleWindowPrint(ele, fileName) {
  // 获取要打印的元素
  const printBox = document.querySelector('.print-box');
  if (!printBox) {
    console.error('找不到具有 "print-box" 类的元素');
    return;
  }

  // 创建一个隐藏的iframe
  const iframe = document.createElement('iframe');
  iframe.style.position = 'fixed';
  iframe.style.right = '0';
  iframe.style.bottom = '0';
  iframe.style.width = '0';
  iframe.style.height = '0';
  iframe.style.border = '0';
  document.body.append(iframe);

  const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;

  // 写入HTML结构
  iframeDoc.open();
  iframeDoc.write(`
    <!DOCTYPE html>
    <html>
      <head>
        <title>${fileName || '文档打印'}</title>
      </head>
      <body>
        ${printBox.outerHTML}
      </body>
    </html>
  `);

  // 复制原页面的所有样式
  const styles = document.querySelectorAll('style, link[rel="stylesheet"]');
  styles.forEach((style) => {
    if (style.tagName === 'LINK') {
      const link = document.createElement('link');
      link.rel = 'stylesheet';
      link.href = style.href; // 使用绝对路径
      iframeDoc.head.append(link);
    } else {
      iframeDoc.head.append(style.cloneNode(true));
    }
  });

  iframeDoc.close();

  // 加载完成后触发打印
  iframe.contentWindow.addEventListener('load', () => {
    iframe.contentWindow.print();
    // 打印后移除iframe
    setTimeout(() => {
      iframe.remove();
    }, 1000); // 确保打印对话框已弹出
  });
}

// 解密方法示例（需要根据实际加密方式实现）
const decrypt = (str: string) => str; // 简单base64解码示例

const getImageSource = (imageString) => {
  if (imageString && imageString.includes('http')) {
    return imageString; // 直接使用HTTP URL
  } else {
    return `data:image/jpeg;base64,${imageString}`; // 使用Base64格式
  }
};

function parseRecipeContent(content: string | Record<string, unknown>) {
  if (!content) return {};
  if (typeof content === 'string') {
    try {
      return JSON.parse(content);
    } catch {
      return {};
    }
  }
  return content;
}
</script>

<template>
  <Modal class="w-[60%]" title="中药处方详情">
    <Page>
      <Button type="primary" @click="handleWindowPrint('#demo', '处方')">
        打印处方
      </Button>
      <div class="prescription-container print-box">
        <!-- 头部信息 -->
        <div class="prescription-header">
          <div class="header-top">
            <span>处方编号: {{ item.prescription_no }}</span>
            <div class="prescription-type">普通处方</div>
          </div>
          <h2 class="clinic-name">{{ item.content?.patient.name }} 处方笺</h2>
          <div class="prescription-date">开具日期: {{ item.created_at }}</div>
        </div>

        <!-- 患者信息 -->
        <div class="patient-info">
          <div class="info-row">
            <span>姓名: {{ decrypt(item.content?.patient.name) }}</span>
            <span>性别: {{ item.content?.patient.sex === 1 ? '男' : '女' }}</span>
            <span>年龄: {{ item.content?.patient.age }}</span>
            <span>类别: {{ item.content?.category }}</span>
          </div>
          <div class="info-row">
            <span>科室: {{ item.content?.doctor.depart?.name }}</span>
            <span>诊断: {{ item.content?.clinical_diagnose }}</span>
          </div>
          <template v-if="item.online_tcm_print?.show">
            <div v-if="item.online_tcm_print.tcm_syndrome" class="info-row">
              <span>中医证候: {{ item.online_tcm_print.tcm_syndrome }}</span>
            </div>
            <div v-if="item.online_tcm_print.tcm_method" class="info-row">
              <span>中医治法: {{ item.online_tcm_print.tcm_method }}</span>
            </div>
            <div v-if="item.online_tcm_print.tcm_disease" class="info-row">
              <span>中医疾病: {{ item.online_tcm_print.tcm_disease }}</span>
            </div>
          </template>
        </div>

        <!-- 药品列表 -->
        <div class="medicine-list">
          <div class="rp-title">Rp</div>
          <div
            v-for="(recipe, index) in item.content?.repice"
            :key="index"
            class="recipe-item"
          >
            <!--            <div class="medicine-item" v-for="drug in JSON.parse(recipe.content)" :key="drug?.id">-->
            <div v-if="item.prescription_type === 1" class="w-full">
              <div
                v-for="drug in JSON.parse(recipe.content)"
                :key="drug?.id"
                class="w-1/3"
                style="display: inline-block"
              >
                <div class="medicine-item">
                  <!--                {{ drug }}-->
                  <span class="drug-name">{{
                    drug?.name || drug?.drug_name
                  }}</span>
                  <span class="drug-quantity mr-5">{{ drug?.number }} /g</span>
                </div>
                <!--                <div class="">煎服方法: {{ drug.use_way?.name || '煎服' }}</div>-->
                <div>
                  方法:
                  <span class="preparation-info">{{
                    drug.use_way?.name || drug.useWay || '煎服'
                  }}</span>
                </div>
              </div>
              <div class="preparation-info">
                <p>
                  用法:每日{{ recipe.consumption }}次，共{{ recipe.dosage }}剂
                </p>
                <p>
                  使用方式：{{
                    `${recipe.process_rule_note}，${recipe.process_rule}`
                  }}
                </p>
              </div>
            </div>
            <div v-else-if="item.prescription_type === 2 || item.prescription_type === 3 || item.prescription_type === 5 || item.prescription_type === 6 || item.prescription_type === 7">
              <template
                v-for="drug in [parseRecipeContent(recipe.content)]"
                :key="`west-${index}`"
              >
                <div class="medicine-item">
                  <span class="drug-name">{{
                    drug?.name || drug?.drug_name
                  }}<span
                    v-if="drug?.specification"
                    class="drug-spec"
                  >{{ drug.specification }}</span></span>
                  <span class="drug-quantity">{{ drug?.number
                    }}{{ drug?.unit?.name }}</span>
                  <div v-if="drug?.useWay" class="usage-info">
                    {{ drug.useWay }}
                  </div>
                </div>
              </template>
              <div class="preparation-info">
                使用方法: {{ recipe.instruction }}
              </div>
            </div>
          </div>
        </div>

        <!-- 医嘱及签名 -->
        <div class="footer-section">
          <div class="medical-advice">
            <label>医嘱:</label>
            {{ item.content?.doctor_order }}
          </div>
          <div class="signature-area">
            <div class="signature">
              <label>开方医生:</label>
              <img
                v-if="item.doctor_info?.identity_info?.sign_image"
                :src="getImageSource(item.doctor_info.identity_info.sign_image)"
                alt="签名"
                style="width: 120px; height: 50px; display: inline-block; "
              />
              <span v-else>{{ item.content?.doctor.name }}</span>
            </div>
            <div class="signature">
              <label>审核药师:</label>
              <img
                v-if="item.pharmacist_info?.identity?.sign_image"
                :src="getImageSource(item.pharmacist_info.identity.sign_image)"
                alt="签名"
                style="width: 120px; height: 50px; display: inline-block"
              />
              <span v-else>{{ item.pharmacist_info?.name }}</span>
            </div>
            <div class="signature">
              <label>调配人:</label>
              <img
                v-if="item.doctor_info?.identity_info?.sign_image"
                :src="getImageSource(item.doctor_info.identity_info.sign_image)"
                alt="签名"
                style="width: 120px; height: 50px; display: inline-block"
              />
              <span v-else>{{ item.content?.doctor.name }}</span>
            </div>
            <div class="signature">
              <label>核对人:</label>
              <img
                v-if="item.pharmacist_info?.identity?.sign_image"
                :src="getImageSource(item.pharmacist_info.identity.sign_image)"
                alt="签名"
                style="width: 120px; height: 50px; display: inline-block"
              />
              <span v-else>{{ item.pharmacist_info?.name }}</span>
            </div>
            <div class="signature">
              <label>发药人:</label>
              <img
                v-if="item.doctor_info?.identity_info?.sign_image"
                :src="getImageSource(item.doctor_info.identity_info.sign_image)"
                alt="签名"
                style="width: 120px; height: 50px; display: inline-block"
              />
              <span v-else>{{ item.content?.doctor.name }}</span>
            </div>
            <!--            <div class="signature">-->
            <!--              <label>加工费:</label>-->

            <!--              <span v-if="item.prescription_type === 1">￥{{ item.content.repice[0].process_price }}</span>-->
            <!--            </div>-->
          </div>
          <div class="price-info"></div>
          <div class="price-info">总价: ￥{{ item.total_pay_price }}</div>
          <div v-if="item.status === 2" class="validity" style="color: red; font-weight: bold">
            该处方未通过审核
          </div>
          <div v-else-if="item.auto_expire_txt === ''" class="validity">
            处方有效期: {{ item.valid_hours }}小时
          </div>
          <div v-else class="validity" style="color: red">
            {{ item.auro_expire_txt }}
          </div>
        </div>
      </div>
    </Page>
  </Modal>
</template>

<style scoped>
.dark .signature img {
  filter: invert(100%);
}
.prescription-container {
  padding: 20px;
  font-family: 'SimSun', serif;
}

.prescription-header {
  border-bottom: 2px solid #000;
  padding-bottom: 15px;
  margin-bottom: 20px;
}

.header-top {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.prescription-type {
  border: 1px solid #666;
  padding: 2px 8px;
  border-radius: 4px;
}

.clinic-name {
  text-align: center;
  font-size: 24px;
  margin: 15px 0;
}

.patient-info .info-row {
  display: flex;
  justify-content: space-between;
  margin: 8px 0;
}

.medicine-list {
  margin: 20px 0 200px 0;
  border-top: 1px solid #ccc;
  padding-top: 15px;
}

.rp-title {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 15px;
}

.recipe-item {
  margin-bottom: 25px;
}

.medicine-item {
  display: flex;
  justify-content: space-between;
  margin: 8px 0;
  padding: 4px 0;
}
.chinese-item {
  width: 28%;
}

.drug-name {
  font-weight: 500;
}

.drug-spec {
  font-size: 12px;
  color: #666;
  margin-left: 8px;
  font-weight: normal;
}

.preparation-info {
  color: #666;
  margin-top: 12px;
  font-size: 0.9em;
}

.footer-section {
  position: absolute;
  bottom: 0;
  margin-top: 30px;
}

.medical-advice {
  color: #c00;
  margin-bottom: 20px;
}

.signature-area {
  display: flex;
  justify-content: space-between;
  margin-top: 40px;
}

.signature {
  min-width: 200px;
}

.price-info {
  margin-top: 20px;
  position: absolute;
  right: 0;
  font-weight: bold;
}

.validity {
  color: #666;
  text-align: center;
  margin-top: 25px;
}
</style>
