<template>
  <el-drawer :model-value="visible" title="中药饮片详情" size="70%" style="--el-drawer-padding-primary: 0"
    :before-close="close">
    <div v-if="order" v-loading="loading" class="h-full bg-[#f2f3f4] overflow-y-auto pb-20px">
      <!-- Status -->
      <div class="bg-white p-15px">
        <div class="inline-block px-15px py-5px rounded text-14px font-bold"
          :class="STATUS_BADGE_CLASS_MAP[order.status] || 'bg-gray-50 text-gray-500'">
          {{ order.statusText }}
        </div>
      </div>

      <!-- Patient Info -->
      <div class="mt-10px bg-white p-15px">
        <div class="font-bold text-16px mb-15px flex items-center">
          <span class="w-4px h-16px bg-blue-500 mr-10px"></span>
          患者就诊信息
        </div>
        <div class="text-14px text-gray-700 leading-30px">
          <el-row>
            <el-col :span="8">
              姓名：
              <span class="text-blue-500 cursor-pointer" @click="handlePatientClick">
                {{ order.name }}
              </span>
            </el-col>
            <el-col :span="8">性别：{{ rxData.sex || "--" }}</el-col>
            <el-col :span="8">年龄：{{ rxData.age || "--" }}</el-col>
          </el-row>
          <div class="flex">
            <span class="flex-shrink-0">诊断：</span>
            <span>{{ rxData.diagnosis || "--" }}</span>
          </div>
          <div class="flex items-center">
            <span class="flex-shrink-0">处方：</span>
            <span>{{ drugsText || "--" }}</span>
            <el-button v-if="rxData._id" link type="primary" class="ml-10px" @click="viewPaper">
              查看处方笺
              <el-icon class="ml-2px">
                <ArrowRight />
              </el-icon>
            </el-button>
          </div>
        </div>
      </div>

      <div class="mt-10px bg-white p-15px">
        <div class="font-bold text-16px mb-15px flex items-center">
          <span class="w-4px h-16px bg-blue-500 mr-10px"></span>
          购药清单
        </div>
        <div class="pt-5px">
          <div v-for="(item, index) in order.wines || []" :key="index" class="flex justify-between items-start mb-15px">
              <div class="w-0 flex-grow text-16px mr-2 font-medium mb-5px">{{ item.name }}</div>
              <!-- <div class="text-gray-400 text-13px">主要用途：{{ item.efficacy }}</div> -->
              <div class="flex-shrink-0 text-gray-400 text-13px mt-5px">x{{ item.quantity }} {{ item.unit }}</div>
          </div>
          <div class="border-t border-gray-100 pt-15px text-right text-14px">
            <span class="text-gray-400 mr-15px">
              （运费{{ order.shippingFeeStr }}）
            </span>
            <span class="font-bold">
              合计：
              <span class="text-red-500 text-18px">{{ order.totalAmount }}</span>
            </span>
          </div>
        </div>
      </div>

      <div class="mt-10px bg-white p-15px">
        <div class="font-bold text-16px mb-15px flex items-center">
          <span class="w-4px h-16px bg-blue-500 mr-10px"></span>
          配送信息
        </div>
        <div class="text-14px text-gray-700 leading-30px">
          <div class="flex">
            <span class="flex-shrink-0">收货地址：</span>
            <span>{{ totalAddress }}</span>
          </div>
          <div class="flex">
            <span class="flex-shrink-0">收件人：</span>
            <span>{{ order.receiveName }} {{ order.receivePhone }}</span>
          </div>
          <div class="flex items-center">
            <span class="flex-shrink-0">配送进度：</span>
            <el-button v-if="order.shippingNo" link type="primary" @click="openShipping">
              查看物流
              <el-icon class="ml-2px">
                <ArrowRight />
              </el-icon>
            </el-button>
            <span v-else>--</span>
          </div>
        </div>
      </div>

      <div class="mt-10px bg-white p-15px">
        <div class="font-bold text-16px mb-15px flex items-center">
          <span class="w-4px h-16px bg-blue-500 mr-10px"></span>
          订单信息
        </div>
        <div class="text-14px text-gray-500 leading-30px">
          <div>订单编号：{{ order.orderNo }}</div>
          <div>创建时间：{{ order.createTime }}</div>
          <div v-if="order.tradeNo">交易订单号：{{ order.tradeNo }}</div>
          <div v-if="order.payTime">支付时间：{{ order.payTime }}</div>
        </div>
      </div>

      <div v-if="refundRecords.length" class="mt-10px bg-white p-15px">
        <div class="font-bold text-16px mb-15px flex items-center">
          <span class="w-4px h-16px bg-blue-500 mr-10px"></span>
          退费记录
        </div>
        <div v-for="(i,idx) in refundRecords" class="text-14px text-gray-700 leading-30px">
          <div>{{ idx +1 }}、{{ i.name }}</div>
          <div>退费金额：<span class="text-red-500">{{ i.fee }}</span></div>
          <div>退费时间：{{ i.time }}</div>
          <div>退费操作人：{{ i.operator }}</div>
        </div>
      </div>
    </div>
  </el-drawer>
  <rx-paper-drawer :visible="paperVisible" :data="rxData" @close="paperVisible = false" />

</template>

<script setup>
import { computed, ref, watch } from "vue";
import { ElMessage, dayjs } from "element-plus";
import { ArrowRight } from "@element-plus/icons-vue";
import RxPaperDrawer from "@/components/rx-paper-drawer/rx-paper-drawer.vue";
import { getRxDetail } from "@/api/hlw.js";
import shippingInfoDrawer from "./shipping-info-drawer.vue";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  order: {
    type: Object,
    default: () => ({}),
  },
});

const emits = defineEmits(["close", "showPatientDetail", "showShippingInfo"]);

const rxData = ref({});
const paperVisible = ref(false);
const shippingVisible = ref(false);
const loading = ref(false);
const drugsText = computed(() => {
  return props.order && Array.isArray(props.order.wines) ? props.order.wines.map(d => d.name).filter(Boolean).join("、") : "";
})

const refundRecords = computed(() => {
  const list = props.order && Array.isArray(props.order.refundRecords) ? props.order.refundRecords.filter(i => i.result === 'refunded') : [];
  return list.map(i => ({
    fee: `¥${i.amount.toFixed(2)}`,
    name: `退费（${i.type === 'goodsFee' ? '药品费' : '运费'}）`,
    time: dayjs(i.refundTime || i.applyTime).format('YYYY-MM-DD HH:mm:ss'),
    operator: i.operator || '--',
  }))
})

const totalAddress = computed(() => {
  const region = Array.isArray(props.order.receiveInfo?.region) ? props.order.receiveInfo.region.join("") : "";
  const address = props.order.receiveInfo?.address || "";
  return (region + address) || "--";
})



// 购药订单状态样式映射（与列表页保持一致）
const STATUS_BADGE_CLASS_MAP = {
  unpay: "bg-gray-50 text-gray-500",
  expired: "bg-gray-50 text-gray-400",
  ybPaid: "bg-red-50 text-red-500",
  shipped: "bg-green-50 text-green-500",
  refunded: "bg-gray-50 text-gray-500",
};

function close() {
  emits("close");
}

function formatPrice(val) {
  if (!val) return "0.00";
  return Number(val).toFixed(2);
}

function handlePatientClick() {
  emits("showPatientDetail", props.order);
}

function openShipping() {
  emits('showShippingInfo', props.order)
}

async function fetchRx() {
  loading.value = true;
  const { data } = await getRxDetail({ id: props.order.rpNo });
  loading.value = false;
  if (data && data.data) {
    data.data.diagnosis = data.data.diagnosisList.map(d => d.name).filter(Boolean).join("、");
    rxData.value = data.data;
  } else {
    rxData.value = {};
  }
}

// 点击“查看处方笺”时，如果没有已加载的处方，则重新拉取；失败时给出提示
async function viewPaper() {
  paperVisible.value = true;
}

watch(
  () => props.visible,
  async (val) => {
    if (val && props.order && props.order.rpNo) {
      fetchRx()
    }
  },
  { immediate: true }
);
</script>

<style scoped>
/* Scoped styles overrides can go here */
</style>
