<template>
  <my-layout>
    <layout-item class="bg-white">
      <div class="py-5px flex" @keyup.enter="search">
        <expand-filter-box v-model:can-expand="canExpand" :enable-expand="false" class="flex-grow" :expand="expand">
          <input-filter v-model="queryForm.patientName" label="患者姓名" placeholder="请输入搜索内容" :width="240" />
          <input-filter v-model="queryForm.recipientName" label="收件人" placeholder="请输入搜索内容" :width="240" />
          <input-filter v-model="queryForm.afterSaleWaybillNo" label="退回运单号" placeholder="请输入搜索内容" :width="240" />

          <custom-filter label="状态" :width="200">
            <el-select v-model="queryForm.status" class="w-full" placeholder="全部" clearable>
              <el-option v-for="i in statusList" :key="i.value" :label="i.label" :value="i.value" />
            </el-select>
          </custom-filter>

          <date-range-filter v-model:dates="queryForm.dates" label="创建时间" :text="orderDatesText" :width="240"
            :showShortcuts="false" />
        </expand-filter-box>
        <div class="flex-shrink-0 flex items-center h-40px pr-15px">
          <el-button type="primary" @click="search">查询</el-button>
          <el-button plain @click="clear">重置</el-button>
        </div>
      </div>
    </layout-item>

    <layout-main :scroll="false">
      <el-table v-loading="loading" border ref="tableRef" height="100%" :data="tableList">
        <el-common-column prop="status" label="状态" :width="100">
          <template #default="{ row }">
            <span :class="row.statusColorClass">{{ row.statusText }}</span>
          </template>
        </el-common-column>
        <el-common-column prop="name" label="患者姓名" :width="120">
          <template #default="{ row }">
            <el-text type="primary" class="cursor-pointer" @click="viewPatient(row)">
              {{ row.name }}
            </el-text>
          </template>
        </el-common-column>
        <el-common-column prop="medicineList" label="药品清单" min-width="180" show-overflow-tooltip />
        <el-common-column prop="totalAmount" label="合计金额" :width="100" />
        <el-common-column prop="drugFeeStr" label="药品金额" :width="100" />
        <el-common-column prop="regFeeStr" label="互联网诊查费" :width="120" />
        <el-common-column prop="shippingFeeStr" label="运费" :width="100" />
        <el-common-column prop="deliveryProgress" label="配送进度" :width="120">
          <template #default="{ row }">
            <el-text :type="row.canViewShipping ? 'primary' : 'info'"
              :class="row.canViewShipping ? 'cursor-pointer' : 'cursor-default'" @click="viewShipping(row)">
              查看物流
              <el-icon>
                <ArrowRight />
              </el-icon>
            </el-text>
          </template>
        </el-common-column>
        <el-common-column prop="receiveName" label="收件人" :width="100" />
        <el-common-column prop="receivePhone" label="联系电话" :width="120" />
        <el-table-column prop="afterSaleNotes" label="跟进备注(可编辑)" :width="160">
          <template #default="{ row }">
            <div class="w-full flex items-center flex-nowrap group">
              <el-tooltip v-if="row && row.afterSale && row.afterSale.notes" :content="row.afterSale.notes"
                placement="top" popper-class="max-w-480px">
                <div class="w-0 flex-grow truncate">
                  {{ row.afterSale.notes }}
                </div>
              </el-tooltip>
              <div v-else class="w-0 flex-grow truncate">--</div>
              <svg-icon name="pen" class="ml-5px hidden group-hover:block text-blue-500 font-normal cursor-pointer"
                @click="editAfterSale(row)" />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="afterSaleWaybillNo" label="退回运单号(可编辑)" :width="160">
          <template #default="{ row }">
            <div class="w-full flex items-center flex-nowrap group">
              <el-tooltip v-if="row && row.afterSale && row.afterSale.waybillNo" :content="row.afterSale.waybillNo"
                placement="top" popper-class="max-w-480px">
                <div class="w-0 flex-grow truncate">
                  {{ row.afterSale.waybillNo }}
                </div>
              </el-tooltip>
              <div v-else class="w-0 flex-grow truncate">--</div>
              <svg-icon name="pen" class="ml-5px hidden group-hover:block text-blue-500 font-normal cursor-pointer"
                @click="editAfterSale(row)" />
            </div>
          </template>
        </el-table-column>

        <el-common-column prop="createTime" label="创建时间" :width="160" />
        <el-common-column prop="orderNo" label="订单编号" :width="160" />
        <el-table-column fixed="right" type="action" label="操作" :width="160">
          <template #default="{ row }">
            <el-text type="primary" class="cursor-pointer" @click="viewDetails(row)">详情</el-text>
            <el-text v-if="row.showRefundYb" type="primary" class="ml-2 cursor-pointer"
              @click="showRefundModal(row)">退费</el-text>
            <el-text v-if="row.showRefundZf" type="primary" class="ml-2 cursor-pointer"
              @click="showRefundModal(row)">退运费</el-text>
          </template>
        </el-table-column>
      </el-table>
    </layout-main>

    <layout-item class="bg-white h-40px flex items-center px-20px border-b text-sm">
      <span class="font-bold mr-4">合计</span>
      <span class="mr-4">合计金额: <span class="font-bold">{{ totalAmountStr }}</span></span>
      <span class="mr-4">药品金额: {{ totalDrugFeeStr }}</span>
      <span class="mr-4">互联网诊查费: {{ totalRegFeeStr }}</span>
      <span>运费: {{ totalShippingFeeStr }}</span>
    </layout-item>
    <layout-item>
      <pagination :totalRow="total" :pageSize="pageSize" :currentPage="page" @handle-size-change="changeSize"
        @handle-current-change="changePage" />
    </layout-item>
  </my-layout>
  <detail-drawer :visible="detailVisible" :order="currentOrder" @close="detailVisible = false"
    @show-patient-detail="viewPatient" @show-shipping-info="viewShipping" />
  <archive-drawer :patient="currentPatient || {}" :visible="archiveVisible" @close="archiveVisible = false" />
  <shipping-info-drawer :visible="shippingVisible" :order-id="shippingOrder.orderId"
    :account-id="shippingOrder.accountId" @close="shippingVisible = false" />
  <refund-modal :width="width" :visible="refundVisible" :order="currentOrder" @close="close" @replace="replaceOrder"
    @change="search" />
  <after-sale-modal :width="afterSaleWidth" :visible="afterSaleVisible" :order="currentOrder" @close="afterSaleClose"
    @change="updateAfterSale" />
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { dayjs, ElMessage } from "element-plus";
import BigNumber from "bignumber.js";
import useElPagination from "@/hooks/useElPagination";
import useModal from '@/hooks/useModal';
import { getMedicinePurchaseShippingList, getOrderPatientList, getHisCustomer } from "@/api/hlw";
import { ArrowRight } from "@element-plus/icons-vue";
import { InputFilter, expandFilterBox, CustomFilter, DateRangeFilter } from "@/components/filter-bar";
import MyLayout, { LayoutMain, LayoutItem } from "@/components/layout";
import pagination from "@/components/pagination/pagination.vue";
import elCommonColumn from "@/components/el-common-column/el-common-column.vue";
import archiveDrawer from "@/components/archive-drawer/archive-drawer.vue";
import detailDrawer from "./detail-drawer.vue";
import shippingInfoDrawer from "./shipping-info-drawer.vue";
import refundModal from "./refund-modal.vue";
import afterSaleModal from "./after-sale-model.vue";
import SvgIcon from "@/components/svg-icon";

// 购药订单状态枚举（与后端 status 字段保持一致）
// 注意:配药订单只有在患者支付第一笔药费后才会生成记录,所以列表中不会出现unpay和expired状态
const STATUS_MAP = {
  ybPaid: { value: "ybPaid", label: "待支付运费", colorClass: "text-orange-500" },
  shipped: { value: "shipped", label: "已配送", colorClass: "text-green-500" },
  refunded: { value: "refunded", label: "已退费", colorClass: "text-gray-500" },
  ybFeeRefunded: { value: "ybFeeRefunded", label: "药诊费已退", colorClass: "text-gray-500" },
  selfFeeRefunded: { value: "selfFeeRefunded", label: "运费已退", colorClass: "text-gray-500" },
};
const statusList = [
  { label: '全部', value: 'all' },
  { label: '待支付运费', value: 'ybPaid' },
  { label: '已配送', value: 'shipped' },
  { label: '已退费', value: 'refunded' },
  { label: '药诊费已退', value: 'ybFeeRefunded' },
  // { label: '运费已退', value: 'selfFeeRefunded' },
]
const statusMap = statusList.reduce((acc, i) => {
  acc[i.value] = i.label;
  return acc;
}, {});

const queryForm = ref({
  patientName: "",
  recipientName: "",
  afterSaleWaybillNo: "",
  status: "all",
  dates: [],
});

const canExpand = ref(false);
const expand = ref(false);
const loading = ref(false);
const detailVisible = ref(false);
const currentOrder = ref({});
const archiveVisible = ref(false);
const currentPatient = ref({});
const shippingVisible = ref(false);

const shippingOrder = ref({ orderId: "", accountId: "" });
const totalStatistics = ref({ totalDrugFee: 0, totalShippingFee: 0, totalRegFee: 0 }); // 统计数据
const { close, show, visible: refundVisible, width } = useModal(640);
const { close: afterSaleClose, show: afterSaleShow, visible: afterSaleVisible, width: afterSaleWidth } = useModal(640);


const { list, page, pageSize, total, changePage, changeSize } = useElPagination(fetchList);
const tableList = computed(() => list.value.map(i => {
  const meta = STATUS_MAP[i.status];
  const statusText = meta ? meta.label : '';
  const statusColorClass = meta ? meta.colorClass : '';
  const drugFee = typeof i.drugFee === 'number' ? `¥${i.drugFee.toFixed(2)}` : '';
  const shippingFee = typeof i.shippingFee === 'number' ? `¥${i.shippingFee.toFixed(2)}` : '';
  const regFee = typeof i.regFee === 'number' ? `¥${i.regFee.toFixed(2)}` : '';
  const totalFee = new BigNumber(i.drugFee >= 0 ? i.drugFee : 0).plus(shippingFee > 0 ? shippingFee : 0).plus(regFee >= 0 ? regFee : 0).toNumber();
  const totalAmount = `¥${totalFee.toFixed(2)}`
  const medicineList = Array.isArray(i.drugs) ? i.drugs.map((d) => {
    const parts = [d.drugName || ""];
    if (d.spec) parts.push(d.spec);
    if (typeof d.quantity === "number") parts.push(`x${d.quantity}`);
    return parts.filter(Boolean).join(" ");
  }).join("、") : "";
  const orderId = i._id;
  const canViewShipping = Boolean(i.shippingNo);
  const showRefundYb = ['ybPaid', 'shipped'].includes(i.status);
  const showRefundZf = i.shippingFee > 0 && 'ybFeeRefunded' === i.status && i.payTime;
  return {
    ...i,
    statusText,
    statusColorClass,
    drugFeeStr: drugFee,
    shippingFeeStr: shippingFee,
    regFeeStr: regFee,
    totalAmount,
    medicineList,
    orderId,
    canViewShipping,
    showRefundYb,
    showRefundZf,
    createTime: dayjs(i.createTime).format("YYYY-MM-DD HH:mm"),
  }
}))

const totalAmountStr = computed(() => {
  const { totalDrugFee, totalShippingFee, totalRegFee } = totalStatistics.value;
  const sum = new BigNumber(totalDrugFee || 0).plus(totalShippingFee || 0).plus(totalRegFee || 0);
  return `¥${sum.toFixed(2)}`;
});

const totalDrugFeeStr = computed(() => {
  return `¥${new BigNumber(totalStatistics.value.totalDrugFee || 0).toFixed(2)}`;
});

const totalRegFeeStr = computed(() => {
  return `¥${new BigNumber(totalStatistics.value.totalRegFee || 0).toFixed(2)}`;
});

const totalShippingFeeStr = computed(() => {
  return `¥${new BigNumber(totalStatistics.value.totalShippingFee || 0).toFixed(2)}`;
});

const orderDatesText = computed(() => {
  if (Array.isArray(queryForm.value.dates) && queryForm.value.dates.length === 2) {
    return `${queryForm.value.dates[0]} - ${queryForm.value.dates[1]}`;
  }
  return "全部";
});

function clear() {
  queryForm.value = {
    patientName: "",
    recipientName: "",
    afterSaleWaybillNo: "",
    status: "all",
    dates: [],
  };
  search();
}

function editAfterSale(row) {
  currentOrder.value = row;
  afterSaleShow();
}

function updateAfterSale(data) {
  const index = list.value.findIndex(i => i._id === data.id);
  if (index >= 0) {
    list.value[index].afterSale = data.afterSale;
  }
}

function replaceOrder(order) {
  const index = list.value.findIndex(i => i._id === order._id);
  if (index >= 0) {
    list.value[index] = order;
    currentOrder.value = tableList.value[index];
  }
}

function search() {
  page.value = 1;
  fetchList();
}

function viewDetails(row) {
  currentOrder.value = row;
  detailVisible.value = true;
}

function showRefundModal(row) {
  currentOrder.value = row;
  show();
}

function viewShipping(row) {
  if (!row || !row.canViewShipping) {
    ElMessage.warning("暂无物流信息");
    return;
  }
  shippingOrder.value = {
    orderId: row.orderId || row.id || "",
    accountId: row.accountId || "",
  };
  shippingVisible.value = true;
}

async function fetchList() {
  loading.value = true;
  try {
    const params = {
      page: page.value,
      pageSize: pageSize.value,
    };

    if (queryForm.value.patientName) {
      params.patientName = queryForm.value.patientName.trim();
    }
    if (queryForm.value.recipientName) {
      params.recipientName = queryForm.value.recipientName.trim();
    }

    if (queryForm.value.afterSaleWaybillNo) {
      params.afterSaleWaybillNo = queryForm.value.afterSaleWaybillNo.trim();
    }

    if (Array.isArray(queryForm.value.dates) && queryForm.value.dates.length === 2) {
      params.startDate = queryForm.value.dates[0];
      params.endDate = queryForm.value.dates[1];
    }

    // 配送状态筛选：直接按后端购药订单 status 过滤
    // 如果未指定状态,默认只查询ybPaid和shipped状态(已支付药费的订单)
    params.statusList = queryForm.value.status === 'all' ? statusList.map(i => i.value).filter(i => i !== 'all') : [queryForm.value.status];
    // 兼容后端返回结构：data.statistics 或 直接在 res.statistics
    const res = await getMedicinePurchaseShippingList(params);
    const { success, data, message } = res;

    if (!success) {
      ElMessage.error(message || "获取购药配送订单失败");
      list.value = [];
      total.value = 0;
      return;
    }

    // 统一优先从标准的 res.data 中获取数据，兼容旧的平铺结构
    // 强制打印日志以便调试
    console.log('Search Result Full:', res);

    const standardData = res.data || {};
    // 支持 axios.js 对标准结构进行二次封装导致的 data.data 层级
    const realData = (standardData.data && Array.isArray(standardData.data.list)) ? standardData.data : standardData;

    // 列表赋值
    const rawList = Array.isArray(realData.list) ? realData.list : (Array.isArray(res.list) ? res.list : []);
    list.value = rawList;

    // 总数赋值
    const rawTotal = typeof realData.total === 'number' ? realData.total : (typeof res.total === "number" ? res.total : 0);
    total.value = rawTotal;

    // 统计赋值
    const stats = realData.statistics || res.statistics || {};

    totalStatistics.value = {
      totalDrugFee: stats.totalDrugFee || 0,
      totalShippingFee: stats.totalShippingFee || 0,
      totalRegFee: stats.totalRegFee || 0
    };
    console.log('Final Stats:', totalStatistics.value);
  } finally {
    loading.value = false;
  }
}

async function viewPatient(row) {
  const res = await getHisCustomer('', row.anotherIdNo);
  if (res && res.data && res.data.patient) {
    currentPatient.value = {
      name: res.data.patient.name,
      mobile: res.data.patient.tel,
      idCard: res.data.patient.socialno,
      address: res.data.patient.address,
      blhno: res.data.patient.blhno,
      age: res.data.patient.age,
      sex: res.data.patient.sex === '1' ? '男' : '女',
      patientId: res.data.patient.patientid,
    }
    archiveVisible.value = true;
  } else {
    ElMessage.info('查询患者档案失败')
  }
}

onMounted(() => {
  search();
});
</script>

<style scoped>
.text-gray-500 {
  color: #909399;
}

.text-gray-400 {
  color: #c0c4cc;
}

.text-orange-500 {
  color: #e6a23c;
}

.text-green-500 {
  color: #67c23a;
}
</style>
