<script setup lang="ts">
import { computed, ref, watch } from 'vue';

import {
  Button,
  DatePicker,
  Drawer,
  Image,
  Input,
  message,
  Table,
  Tabs,
} from 'ant-design-vue';
import dayjs from 'dayjs';

import SalespersonSettlementConfirmModal from '#/components/salesperson/SalespersonSettlementConfirmModal.vue';

import {
  confirmSettlementApi,
  getCommissionListApi,
  getCommissionOrderListApi,
  getSettlementDetailApi,
  getSettlementListApi,
  getSettlementPreviewApi,
} from '#/views/business/store/settings/api';

const emit = defineEmits<{
  settled: [];
}>();

const visible = ref(false);
const salespersonId = ref(0);
const salespersonName = ref('');
const activeTab = ref('pending');
const loading = ref(false);
const commissionData = ref<any[]>([]);
const commissionTotal = ref(0);
const page = ref(1);
const pageSize = ref(20);
const orderNo = ref('');
const dateRange = ref<any[]>([]);
const selectedOrderIds = ref<number[]>([]);
const selectedRowKeys = ref<number[]>([]);
const settlementList = ref<any[]>([]);
const settlementDetail = ref<any>(null);
const detailVisible = ref(false);
const orderDetailVisible = ref(false);
const orderDetailLoading = ref(false);
const orderDetailData = ref<any[]>([]);
const currentOrder = ref<{ order_id: number; order_no: string } | null>(null);
const periodRange = ref<any[]>([]);
const settlementConfirmRef = ref<InstanceType<typeof SalespersonSettlementConfirmModal>>();

const orderCommissionColumns = [
  { title: '订单号', dataIndex: 'order_no', width: 160 },
  { title: '明细数', dataIndex: 'item_count', width: 80 },
  { title: '分成总额', dataIndex: 'commission_amount', width: 100 },
  { title: '支付时间', dataIndex: 'order_pay_at_text', width: 170 },
  { title: '操作', key: 'action', width: 90 },
];

const commissionDetailColumns = [
  { title: '药品信息', dataIndex: 'drug_info', ellipsis: true },
  { title: '分成金额', dataIndex: 'commission_amount', width: 100 },
  { title: '分成时间', dataIndex: 'order_pay_at_text', width: 170 },
];

const settlementLineColumns = [
  { title: '订单号', dataIndex: 'order_no', width: 160 },
  { title: '药品信息', dataIndex: 'drug_info', ellipsis: true },
  { title: '分成金额', dataIndex: 'commission_amount', width: 100 },
  { title: '分成时间', dataIndex: 'order_pay_at_text', width: 170 },
];

const settlementColumns = [
  { title: '结算单号', dataIndex: 'settlement_no', width: 160 },
  { title: '方式', dataIndex: 'settlement_type_text', width: 100 },
  { title: '金额', dataIndex: 'amount', width: 100 },
  { title: '明细数', dataIndex: 'record_count', width: 80 },
  { title: '时间', dataIndex: 'created_at_text', width: 170 },
  { title: '操作', key: 'action', width: 80 },
];

const status = computed(() =>
  activeTab.value === 'pending' ? 0 : activeTab.value === 'settled' ? 1 : undefined,
);

const rowSelection = computed(() =>
  activeTab.value === 'pending'
    ? {
        selectedRowKeys: selectedRowKeys.value,
        onChange: (keys: number[]) => {
          selectedRowKeys.value = keys as number[];
          selectedOrderIds.value = keys as number[];
        },
        getCheckboxProps: () => ({ disabled: false }),
      }
    : undefined,
);

function open(salesperson: { id: number; nick_name?: string }) {
  salespersonId.value = salesperson.id;
  salespersonName.value = salesperson.nick_name || '';
  selectedOrderIds.value = [];
  selectedRowKeys.value = [];
  orderNo.value = '';
  dateRange.value = [];
  periodRange.value = [];
  page.value = 1;
  activeTab.value = 'pending';
  visible.value = true;
  loadCommission();
}

function onPageChange(p: number) {
  page.value = p;
  loadCommission();
}

async function loadCommission() {
  if (!salespersonId.value) return;
  loading.value = true;
  try {
    const params: Record<string, any> = {
      salesperson_id: salespersonId.value,
      page: page.value,
      pageSize: pageSize.value,
      order_no: orderNo.value,
    };
    if (status.value !== undefined) params.status = status.value;
    if (dateRange.value?.length === 2) {
      params.start_at = dayjs(dateRange.value[0]).startOf('day').unix();
      params.end_at = dayjs(dateRange.value[1]).endOf('day').unix();
    }
    const res = await getCommissionOrderListApi(params);
    commissionData.value = res?.items || [];
    commissionTotal.value = res?.total || 0;
  } finally {
    loading.value = false;
  }
}

async function showOrderDetail(record: { order_id: number; order_no: string }) {
  currentOrder.value = record;
  orderDetailVisible.value = true;
  orderDetailLoading.value = true;
  try {
    const res = await getCommissionListApi({
      salesperson_id: salespersonId.value,
      order_id: record.order_id,
      page: 1,
      pageSize: 100,
    });
    orderDetailData.value = res?.items || [];
  } finally {
    orderDetailLoading.value = false;
  }
}

async function loadSettlements() {
  if (!salespersonId.value) return;
  const res = await getSettlementListApi({
    salesperson_id: salespersonId.value,
    page: 1,
    pageSize: 50,
  });
  settlementList.value = res?.items || [];
}

async function handleSettleByPeriod() {
  if (!periodRange.value?.length || periodRange.value.length !== 2) {
    message.warning('请选择结算时间段');
    return;
  }
  const params = {
    salesperson_id: salespersonId.value,
    settlement_type: 1,
    period_start: dayjs(periodRange.value[0]).startOf('day').unix(),
    period_end: dayjs(periodRange.value[1]).endOf('day').unix(),
  };
  const preview = await getSettlementPreviewApi(params);
  settlementConfirmRef.value?.open('确认按时间段结算', preview, params);
}

function onSettlementSuccess() {
  selectedOrderIds.value = [];
  selectedRowKeys.value = [];
  loadCommission();
  loadSettlements();
  emit('settled');
}

async function handleSettleByOrders() {
  if (!selectedOrderIds.value.length) {
    message.warning('请勾选订单');
    return;
  }
  const params = {
    salesperson_id: salespersonId.value,
    settlement_type: 2,
    order_ids: selectedOrderIds.value,
  };
  const preview = await getSettlementPreviewApi(params);
  settlementConfirmRef.value?.open('确认结算选中订单', preview, params);
}

async function showSettlementDetail(id: number) {
  settlementDetail.value = await getSettlementDetailApi({ id });
  detailVisible.value = true;
}

watch(activeTab, (tab) => {
  page.value = 1;
  if (tab === 'history') loadSettlements();
  else loadCommission();
});

defineExpose({ open });
</script>

<template>
  <Drawer
    v-model:open="visible"
    :title="`分成与结算 - ${salespersonName}`"
    width="920"
    destroy-on-close
  >
    <div class="mb-4 flex flex-wrap items-center gap-3">
      <Input
        v-model:value="orderNo"
        allow-clear
        placeholder="订单号"
        style="width: 180px"
        @press-enter="loadCommission"
      />
      <DatePicker.RangePicker v-model:value="dateRange" />
      <Button type="primary" @click="loadCommission">查询</Button>
    </div>

    <Tabs v-model:activeKey="activeTab">
      <Tabs.TabPane key="pending" tab="待结算">
        <div class="mb-3 flex flex-wrap gap-2">
          <DatePicker.RangePicker
            v-model:value="periodRange"
            placeholder="['开始','结束']"
          />
          <Button type="primary" @click="handleSettleByPeriod">按时间段结算</Button>
          <Button type="primary" ghost @click="handleSettleByOrders">
            结算选中订单
          </Button>
        </div>
        <Table
          :columns="orderCommissionColumns"
          :data-source="commissionData"
          :loading="loading"
          :pagination="{
            current: page,
            pageSize,
            total: commissionTotal,
            onChange: onPageChange,
          }"
          :row-key="(r) => r.order_id"
          :row-selection="rowSelection"
          size="small"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <Button type="link" size="small" @click="showOrderDetail(record)">
                查看明细
              </Button>
            </template>
          </template>
        </Table>
      </Tabs.TabPane>
      <Tabs.TabPane key="settled" tab="已结算">
        <Table
          :columns="orderCommissionColumns"
          :data-source="commissionData"
          :loading="loading"
          :pagination="{
            current: page,
            pageSize,
            total: commissionTotal,
            onChange: onPageChange,
          }"
          :row-key="(r) => r.order_id"
          size="small"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <Button type="link" size="small" @click="showOrderDetail(record)">
                查看明细
              </Button>
            </template>
          </template>
        </Table>
      </Tabs.TabPane>
      <Tabs.TabPane key="history" tab="结算记录">
        <Table
          :columns="settlementColumns"
          :data-source="settlementList"
          :row-key="(r) => r.id"
          size="small"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <Button type="link" size="small" @click="showSettlementDetail(record.id)">
                详情
              </Button>
            </template>
          </template>
        </Table>
      </Tabs.TabPane>
    </Tabs>

    <SalespersonSettlementConfirmModal
      ref="settlementConfirmRef"
      :confirm-fn="confirmSettlementApi"
      @success="onSettlementSuccess"
    />

    <Drawer
      v-model:open="orderDetailVisible"
      :title="`订单明细 - ${currentOrder?.order_no || ''}`"
      width="720"
      destroy-on-close
    >
      <Table
        :columns="commissionDetailColumns"
        :data-source="orderDetailData"
        :loading="orderDetailLoading"
        :row-key="(r) => r.id"
        size="small"
      />
    </Drawer>

    <Drawer v-model:open="detailVisible" title="结算单详情" width="720" destroy-on-close>
      <div v-if="settlementDetail" class="mb-3">
        <p>单号：{{ settlementDetail.settlement_no }}</p>
        <p>
          金额：¥{{ settlementDetail.amount }}（{{ settlementDetail.record_count }} 条）
        </p>
        <p v-if="settlementDetail.remark">备注：{{ settlementDetail.remark }}</p>
        <div v-if="settlementDetail.proof_images?.length" class="mt-3">
          <p class="mb-2 text-sm text-gray-600">结算凭证</p>
          <Image.PreviewGroup>
            <Image
              v-for="(url, idx) in settlementDetail.proof_images"
              :key="idx"
              :src="url"
              :width="96"
              :height="96"
              class="mr-2 rounded object-cover"
            />
          </Image.PreviewGroup>
        </div>
      </div>
      <Table
        :columns="settlementLineColumns"
        :data-source="settlementDetail?.records || []"
        :row-key="(r) => r.id"
        size="small"
      />
    </Drawer>
  </Drawer>
</template>
