<script lang="ts" setup>
import type { VxeGridListeners } from "#/adapter/vxe-table";

import { nextTick, onMounted, ref } from "vue";
import { useRoute } from "vue-router";

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

import { Button, Image, message, Modal as AntdModal, Tag } from "ant-design-vue";

import { useVbenVxeGrid } from "#/adapter/vxe-table";
import { TableAction } from "#/components/table-action";
import { simulatePayApi } from "#/views/business/order/api/order-ops";
import PrescriptionDetail from "#/views/doctor/doctor-reception/components/PrescriptionDetail.vue";

import { formOptions } from "./config/search";
import { gridOptions } from "./config/table";
import Refund from "./components/refund.vue";

const hasTopTableDropDownActions = ref(false);

const gridEvents: VxeGridListeners<any> = {
  checkboxChange() {
    // eslint-disable-next-line no-use-before-define
    const records = gridApi.grid.getCheckboxRecords();
    hasTopTableDropDownActions.value = records.length > 0;
  },
  checkboxAll() {
    // eslint-disable-next-line no-use-before-define
    const records = gridApi.grid.getCheckboxRecords();
    hasTopTableDropDownActions.value = records.length > 0;
  }
};

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents
});

const route = useRoute();

onMounted(() => {
  void nextTick(async () => {
    const raw = route.query.order_no;
    const orderNo = Array.isArray(raw) ? raw[0] : raw;
    if (!orderNo || !gridApi.formApi?.setValues) {
      return;
    }
    await gridApi.formApi.setValues({ order_no: String(orderNo) });
    await gridApi.query();
  });
});

const [PrescriptionDetailModal, PrescriptionDetailModalApi] = useVbenModal({
  connectedComponent: PrescriptionDetail
});

const [RefundModal, RefundModalApi] = useVbenModal({
  connectedComponent: Refund
});

function openPrescriptionDetail(id: number) {
  PrescriptionDetailModalApi.setData({
    values: id
  });
  PrescriptionDetailModalApi.open();
}

function handleSimulatePay(row: Record<string, any>) {
  AntdModal.confirm({
    title: "模拟支付",
    content: `确认为挂号订单 ${row.order_no} 模拟易票联支付回调？`,
    okText: "确认",
    cancelText: "取消",
    onOk: async () => {
      await simulatePayApi({ order_type: "register", order_id: row.id });
      message.success("模拟支付成功");
      await gridApi.query();
    }
  });
}

function openRefundModal(id: number) {
  RefundModalApi.setData({
    values: {
      register_id: id
    },
    gridApi
  });
  RefundModalApi.open();
}

function canRefund(row: Record<string, any>) {
  return row.is_pay === 1 && row.refund_status !== 1 && row.refund_status !== 3;
}

function formatRegisterPrice(price: unknown) {
  const n = Number(price);
  if (!Number.isFinite(n)) {
    return "—";
  }
  return `¥${n.toFixed(2)}`;
}
</script>

<template>
  <Page auto-content-height title="订单管理">
    <PrescriptionDetailModal />
    <RefundModal />
    <Grid>
      <template #toolbar-buttons>
        <TableAction :actions="[]" :drop-down-actions="[]">
          <template #more>
            <Button style="margin-left: 16px">
              批量操作
              <Icon icon="ant-design:down-outlined" />
            </Button>
          </template>
        </TableAction>
      </template>
      <template #prescription="{ row }">
        <div v-for="item in row.prescription" :key="item.id">
          <Button type="link" @click="openPrescriptionDetail(item.id)">
            {{ item.prescription_no }}
          </Button>
        </div>
      </template>
      <template #salesperson="{ row }">
        <div v-if="row.salesperson?.id" class="flex items-center gap-2 text-sm">
          <Image
            :src="row.salesperson.avatar || '/img/user-default-avatar.png'"
            :width="28"
            :height="28"
            class="rounded-full object-cover"
          />
          <span>{{ row.salesperson.nick_name || "—" }}</span>
        </div>
        <span v-else class="text-sm text-gray-500">无推广员</span>
      </template>
      <template #price="{ row }">
        <span>{{ formatRegisterPrice(row.price) }}</span>
      </template>
      <template #is_pay="{ row }">
        <Tag :color="row.is_pay === 1 ? 'green' : 'red'">
          {{ row.is_pay === 1 ? "已支付" : "未支付" }}
        </Tag>
      </template>
      <template #refund_status="{ row }">
        <Tag v-if="row.refund_status === 1" color="pink">退款中</Tag>
        <Tag v-else-if="row.refund_status === 3" color="green">已退款</Tag>
        <Tag v-else color="default">未退款</Tag>
      </template>
      <template #type="{ row }">
        <div class="mt-3">
          <Tag v-if="row.type === 0" color="purple">线下就诊</Tag>
          <Tag v-else-if="row.type === 1" color="blue">在线问诊</Tag>
          <Tag v-else-if="row.type === 3" color="green">在线复诊</Tag>
          <Tag v-else color="default">未知</Tag>
        </div>
      </template>
      <template #status="{ row }">
        <div class="mt-3">
          <Tag v-if="row.status === 0" color="red">代支付</Tag>
          <Tag v-else-if="row.status === 1" color="green">待接诊</Tag>
          <Tag v-else-if="row.status === 2" color="red">接诊中</Tag>
          <Tag v-else-if="row.status === 3" color="purple">已结束</Tag>
          <Tag v-else-if="row.status === 4" color="orange">已取消</Tag>
          <Tag v-else-if="row.status === 5" color="purple">待评价</Tag>
          <Tag v-else-if="row.status === 6" color="purple">已评价</Tag>
          <Tag v-else-if="row.status === 7" color="red">已拒诊</Tag>
        </div>
      </template>
      <template #toolbar-tools></template>
      <template #action="{ row }">
        <TableAction
          :actions="[
            {
              label: '退款',
              type: 'link',
              icon: 'mingcute:refund-dollar-fill',
              ifShow: canRefund(row),
              onClick: openRefundModal.bind(null, row.id),
            },
          ]"
          :drop-down-actions="[]"
        />
      </template>
    </Grid>
  </Page>
</template>

<style scoped lang="scss">
.custom-list {
  list-style-type: none;
  padding-left: 0;
}

.custom-list-item {
  background-color: rgba(64, 158, 255, 0.04);
  border-radius: 4px;
  margin-bottom: 8px;
  padding: 8px 12px;
  font-size: 14px;
  transition: background-color 0.3s;

  &:hover {
    background-color: rgba(64, 158, 255, 0.1);
  }

  &::before {
    content: '';
    display: inline-block;
    width: 6px;
    height: 6px;
    background-color: #409eff;
    border-radius: 50%;
    margin-right: 8px;
    vertical-align: middle;
  }
}
</style>
