<script lang="ts" setup>
/**
 * 常用方选择弹窗组件
 *
 * @description 用于在开处方时快速选择已保存的常用方模板
 *              - 支持西药、中药、颗粒药三种类型
 *              - 选择后会自动填充药品列表
 * @author 系统
 * @date 2024
 */
import { ref } from 'vue';

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

import {
  Button,
  Col,
  Empty,
  message,
  Row,
  Spin,
  Tag,
} from 'ant-design-vue';

import {
  getCommonPrescriptionListApi,
  type CommonPrescriptionData,
} from '#/views/doctor/doctor-reception/api';

// ==================== 响应式数据 ====================

/**
 * 常用方数据
 */
const commonPrescriptionData = ref<CommonPrescriptionData | null>(null);

/**
 * 加载状态
 */
const loading = ref(false);

/**
 * 当前选中的药品类型
 * 1-西药，2-中药，3-颗粒药
 */
const currentType = ref(1);

/**
 * 回调函数：选择常用方后的回调
 */
let onSelectCallback: ((data: any, type: number) => void) | null = null;

// ==================== Modal 配置 ====================

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  footer: false,
  onCancel() {
    modalApi.close();
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      // 获取传入的参数
      const data = modalApi.getData<{
        type?: number;
        onSelect?: (data: any, type: number) => void;
      }>();

      if (data?.type) {
        currentType.value = data.type;
      }
      if (data?.onSelect) {
        onSelectCallback = data.onSelect;
      }

      // 加载常用方列表
      loadCommonPrescriptionList();
    }
  },
});

// ==================== 方法定义 ====================

/**
 * 加载常用方列表
 */
async function loadCommonPrescriptionList() {
  loading.value = true;
  try {
    const res = await getCommonPrescriptionListApi();
    commonPrescriptionData.value = res;
  } catch (error) {
    console.error('获取常用方列表失败:', error);
    message.error('获取常用方列表失败');
  } finally {
    loading.value = false;
  }
}

/**
 * 选择常用方
 * @param prescription 常用方信息
 * @param recipes 药品列表
 * @param type 类型：1-西药，2-中药，3-颗粒药
 */
function handleSelectPrescription(
  prescription: any,
  recipes: any[],
  type: number,
) {
  // 调用回调函数，将选中的常用方数据传递给父组件
  if (onSelectCallback) {
    onSelectCallback(
      {
        prescription,
        recipes,
      },
      type,
    );
  }

  message.success('已选择常用方，药品已填充到处方中');
  modalApi.close();
}

/**
 * 空值占位
 */
function formatField(value?: string | null): string {
  return value?.trim() ? value : '—';
}

/**
 * 获取药品名称列表（用于展示）
 * @param recipes 药品列表
 * @param nameField 名称字段
 * @param showNumber 是否显示克数（中药使用）
 */
function getDrugNames(recipes: any[], nameField = 'drug_name', showNumber = false): string {
  if (!recipes || recipes.length === 0) return '暂无药品';
  return recipes.map((item) => {
    const name = item[nameField] || item.name;
    if (showNumber && item.number) {
      return `${name}(${item.number}g)`;
    }
    return name;
  }).join('、');
}

/**
 * 获取药品数量
 * @param recipes 药品列表
 */
function getDrugCount(recipes: any[]): number {
  return recipes?.length || 0;
}
</script>

<template>
  <Modal class="w-[70%]" title="选择常用方">
    <Page>
      <Spin :spinning="loading">
        <div v-if="!commonPrescriptionData" class="py-8 text-center">
          <Empty description="加载中..." />
        </div>

        <div v-else>
          <Row :gutter="16">
            <!-- 西药常用方 - 只在西药Tab时显示 -->
            <Col v-if="currentType === 2" :span="24" class="mb-6">
              <div class="mb-4 rounded-lg border border-border p-4">
                <h3 class="mb-4 flex items-center gap-2 text-base font-semibold">
                  <Tag color="blue">西药</Tag>
                  西药常用方
                  <span class="text-sm font-normal text-muted-foreground"
                    >({{
                      commonPrescriptionData.west_prescription?.length || 0
                    }})</span
                  >
                </h3>

                <div
                  v-if="
                    commonPrescriptionData.west_prescription &&
                    commonPrescriptionData.west_prescription.length > 0
                  "
                  class="max-h-[60vh] overflow-y-auto pr-1"
                >
                  <div
                    v-for="(item, index) in commonPrescriptionData.west_prescription"
                    :key="item.id"
                    class="mb-3 rounded-lg border border-border bg-muted/30 p-4"
                  >
                    <div
                      class="mb-3 flex items-center justify-between gap-3 border-b border-border pb-3"
                    >
                      <div class="flex min-w-0 flex-1 items-center gap-2">
                        <span class="truncate font-medium">{{
                          item.name || `西药处方 ${index + 1}`
                        }}</span>
                        <Tag color="blue"
                          >{{
                            getDrugCount(commonPrescriptionData.west[index])
                          }}种药品</Tag
                        >
                      </div>
                      <Button
                        type="primary"
                        size="small"
                        @click="
                          handleSelectPrescription(
                            item,
                            commonPrescriptionData.west[index],
                            1,
                          )
                        "
                      >
                        使用
                      </Button>
                    </div>

                    <div class="space-y-2 text-sm leading-relaxed">
                      <p>
                        <span class="font-medium text-muted-foreground">临床诊断：</span>
                        <span>{{ formatField(item.clinical_diagnose) }}</span>
                      </p>
                      <p>
                        <span class="font-medium text-muted-foreground">医嘱：</span>
                        <span>{{ formatField(item.doctor_order) }}</span>
                      </p>
                      <p>
                        <span class="font-medium text-muted-foreground">药品：</span>
                        <span class="text-primary">{{
                          getDrugNames(commonPrescriptionData.west[index])
                        }}</span>
                      </p>
                    </div>
                  </div>
                </div>

                <Empty v-else description="暂无西药常用方" />
              </div>
            </Col>

            <!-- 中药常用方 - 只在中药Tab时显示 -->
            <Col v-if="currentType === 1" :span="24" class="mb-6">
              <div class="mb-4 rounded-lg border border-border p-4">
                <h3 class="mb-4 flex items-center gap-2 text-base font-semibold">
                  <Tag color="green">中药</Tag>
                  中药常用方
                  <span class="text-sm font-normal text-muted-foreground"
                    >({{
                      commonPrescriptionData.chin_prescription?.length || 0
                    }})</span
                  >
                </h3>

                <div
                  v-if="
                    commonPrescriptionData.chin_prescription &&
                    commonPrescriptionData.chin_prescription.length > 0
                  "
                  class="max-h-[60vh] overflow-y-auto pr-1"
                >
                  <div
                    v-for="(item, index) in commonPrescriptionData.chin_prescription"
                    :key="item.id"
                    class="mb-3 rounded-lg border border-border bg-muted/30 p-4"
                  >
                    <div
                      class="mb-3 flex items-center justify-between gap-3 border-b border-border pb-3"
                    >
                      <div class="flex min-w-0 flex-1 items-center gap-2">
                        <span class="truncate font-medium">{{
                          item.name || `中药处方 ${index + 1}`
                        }}</span>
                        <Tag color="green"
                          >{{
                            getDrugCount(commonPrescriptionData.chinese[index])
                          }}种药品</Tag
                        >
                      </div>
                      <Button
                        type="primary"
                        size="small"
                        @click="
                          handleSelectPrescription(
                            item,
                            commonPrescriptionData.chinese[index],
                            2,
                          )
                        "
                      >
                        使用
                      </Button>
                    </div>

                    <div class="space-y-2 text-sm leading-relaxed">
                      <p>
                        <span class="font-medium text-muted-foreground">临床诊断：</span>
                        <span>{{ formatField(item.clinical_diagnose) }}</span>
                      </p>
                      <p>
                        <span class="font-medium text-muted-foreground">医嘱：</span>
                        <span>{{ formatField(item.doctor_order) }}</span>
                      </p>
                      <p>
                        <span class="font-medium text-muted-foreground">调配方式：</span>
                        <span>{{ item.rule_type === 1 ? '自制剂' : '委托调剂' }}</span>
                        <span class="ml-4">剂量：{{ item.dosage || 7 }}天/剂</span>
                        <span class="ml-4">频次：{{ item.day_dosage || 2 }}次/天</span>
                      </p>
                      <p v-if="item.rule_type === 2">
                        <span class="font-medium text-muted-foreground">委托调剂：</span>
                        <span v-if="item.process_rule_name">制剂：{{ item.process_rule_name }}</span>
                        <span v-if="item.child_process_rule_name" class="ml-4">煎法：{{ item.child_process_rule_name }}</span>
                        <span v-if="item.process_rule_note_name" class="ml-4">备注：{{ item.process_rule_note_name }}</span>
                      </p>
                      <p>
                        <span class="font-medium text-muted-foreground">药品：</span>
                        <span class="text-primary">{{
                          getDrugNames(
                            commonPrescriptionData.chinese[index],
                            'drug_name',
                            true,
                          )
                        }}</span>
                      </p>
                    </div>
                  </div>
                </div>

                <Empty v-else description="暂无中药常用方" />
              </div>
            </Col>
          </Row>
        </div>
      </Spin>
    </Page>
  </Modal>
</template>
