<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="true" class="flex-grow" :expand="expand">
          <date-range-filter v-model:dates="queryForm.dates" :clearable="false" label="时间范围" :text="datesText"
            :width="240" :showShortcuts="false" />
          <custom-filter label="寄送次数" :width="240">
            <div class="flex items-center">
              <el-select v-model="queryForm.operator" placeholder="请选择操作人" class="w-100px">
                <el-option value="gte" label="大于等于" />
                <el-option value="eq" label="等于" />
              </el-select>
              <el-input v-model="queryForm.times" placeholder="请输入数量" class="w-120px ml-5px" />
            </div>
          </custom-filter>
        </expand-filter-box>
        <div class="flex-shrink-0 flex items-center h-40px pr-15px">
          <el-button v-if="canExpand" text plain @click="expand = !expand">
            <span class="mr-5px">{{ expand ? "收起筛选" : "更多筛选" }}</span>
            <el-icon v-if="expand">
              <ArrowUpBold />
            </el-icon>
            <el-icon v-else>
              <ArrowDownBold />
            </el-icon>
          </el-button>
          <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="list">
        <el-common-column prop="receiveAddress" label="收货地址" :width="400" />
        <el-common-column prop="count" label="寄送次数" :width="120" />
        <el-table-column fixed="right" type="action" label="操作" :width="150">
          <template #default="{ row }">
            <el-text type="primary" class="cursor-pointer" @click="viewOrders(row)">查看关联订单</el-text>
          </template>
        </el-table-column>
      </el-table>
    </layout-main>
  </my-layout>

  <!-- 订单详情抽屉 -->
  <el-drawer v-model="drawerVisible" title="订单详情" size="80%" style="--el-drawer-padding-primary: 0">
    <el-table v-loading="orderLoading" border :data="orderList" height="100%">
      <el-common-column prop="orderTime" label="下单时间" :width="160" />
      <el-common-column prop="name" label="患者" :width="120" />
      <el-common-column prop="medicineList" label="药品" :width="180" />
      <el-common-column prop="receiveName" label="收货人" :width="100" />
      <el-common-column prop="receivePhone" label="联系电话" :width="130" />
      <el-common-column prop="orderNo" label="订单编号" :width="180" />
      <el-common-column prop="status" label="状态" :width="100">
        <template #default="{ row }">
          <span :class="row.statusColorClass">{{ row.statusText }}</span>
        </template>
      </el-common-column>
    </el-table>

  </el-drawer>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { dayjs, ElMessage } from "element-plus";
import { getHighFreqAddressOrders, getMedicinePurchaseShippingList } from "@/api/hlw";
import useElPagination from "@/hooks/useElPagination";

import { ArrowUpBold, ArrowDownBold } from "@element-plus/icons-vue";
import { InputFilter, expandFilterBox, DateRangeFilter, CustomFilter } 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";

const { list, page, pageSize, total, changePage, changeSize } = useElPagination(fetchAddresses);

const today = dayjs().format("YYYY-MM-DD");
const queryForm = ref({
  dates: [dayjs().subtract(14, "day").format("YYYY-MM-DD"), today],
  times: 2,
  operator: "gte",
});

const loading = ref(false);
const canExpand = ref(true);
const expand = ref(false);
const datesText = computed(() => queryForm.value.dates.length > 0 ? `${queryForm.value.dates[0]} - ${queryForm.value.dates[1]}` : "全部");

// 订单详情抽屉
const drawerVisible = ref(false);
const orderLoading = ref(false);
const orderList = ref([]);
const currentAddress = ref(null);

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" },
};

function clear() {
  queryForm.value = {
    dates: [dayjs().subtract(14, "day").format("YYYY-MM-DD"), today],
    times: 2,
    operator: "gte",
  };
  search();
}

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

async function fetchAddresses() {
  if (loading.value) return;
  const params = {
    startDate: queryForm.value.dates[0],
    endDate: queryForm.value.dates[1],
    times: Number(queryForm.value.times),
    operator: queryForm.value.operator,
  };
  if (!(params.times > 1 && Number.isInteger(params.times))) {
    ElMessage.error('寄送次数必须大于1且为整数');
    return;
  }
  loading.value = true;
  try {
    const { success, data, message } = await getHighFreqAddressOrders(params);
    list.value = Array.isArray(data.data) ? data.data.map(item => ({
      ...item,
      address: item.address || item.receiverAddress || '',
      count: item.count || item.deliveryCount || 0
    })) : [];

    if (!success) {
      ElMessage.error(message);
    }
    total.value = data.total || 0;
  } catch (err) {
    ElMessage.error(err.message);
  }
  loading.value = false;
}

async function viewOrders(row) {
  currentAddress.value = row;
  drawerVisible.value = true;
  orderLoading.value = true;

  const { success, data, message } = await getMedicinePurchaseShippingList({
    page: 1,
    pageSize: row.count,
    ids: row.orderIds
  });

  orderList.value = data && data.data && Array.isArray(data.data.list) ? data.data.list.map(order => {
    const meta = STATUS_MAP[order.status];
    const statusText = meta ? meta.label : '';
    const statusColorClass = meta ? meta.colorClass : '';
    const medicineList = Array.isArray(order.drugs) ? order.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("、") : "";
    return {
      ...order,
      orderTime: dayjs(order.createTime).format("YYYY-MM-DD HH:mm"),
      medicineList,
      statusText,
      statusColorClass
    };
  }) : [];
  console.log(orderList.value, data)
  if (!success) {
    ElMessage.error(message);
  }
  orderLoading.value = false;
}

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

<style scoped></style>