<script lang="ts" setup>
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table';

import { h, ref } from 'vue';

import { Page } from '@vben/common-ui';
import { MdiCheckboxMultipleMarked, MdiDetail, MdiPlus } from '@vben/icons';
import { useUserStore } from '@vben/stores';

import { ElMessage, ElMessageBox, ElTag } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  getCoupon2AuditListApi,
  getCoupon2EditListApi,
} from '#/api/coupon/coupon2';
import { $t } from '#/locales';

import AuditForm from './audit-form.vue';
import DetailForm from './detail.vue';
import OrderCouponForm from './order-coupon-form.vue';
import ReceiveCouponForm from './receive-coupon-form.vue';

const userStore = useUserStore();

const receiveCouponFormRef = ref<InstanceType<typeof ReceiveCouponForm> | null>(
  null,
);
const orderCouponFormRef = ref<InstanceType<typeof OrderCouponForm> | null>(
  null,
);

const formOptions: VbenFormProps = {
  collapsed: true,
  showCollapseButton: true,
  submitOnEnter: true,
  schema: [
    {
      component: 'Input',
      fieldName: 'couponmc',
      label: '优惠券名称',
      componentProps: {
        placeholder: $t('ui.placeholder.input'),
        clearable: true,
      },
    },
    {
      component: 'Select',
      fieldName: 'coupon2sype',
      label: '优惠券状态',
      componentProps: {
        placeholder: '请选择优惠券状态',
        clearable: true,
        options: [
          { label: '申请中', value: 0 },
          { label: '审核通过', value: 1 },
          { label: '审核不通过', value: 2 },
        ],
      },
      defaultValue: 0,
    },
    {
      component: 'DatePicker',
      fieldName: 'coupon2adddatetime',
      label: '申请时间',
      componentProps: {
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        // placeholder: ['开始时间', '结束时间'],
        // style: 'width:100%',
      },
    },
    {
      component: 'Input',
      fieldName: 'productsname',
      label: '产品名称',
      componentProps: {
        placeholder: $t('ui.placeholder.input'),
        clearable: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'productsmodel',
      label: '产品型号',
      componentProps: {
        placeholder: $t('ui.placeholder.input'),
        clearable: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'productsjjlx',
      label: '机具类型',
      componentProps: {
        placeholder: $t('ui.placeholder.input'),
        clearable: true,
      },
    },
  ],
  wrapperClass: 'grid-cols-1 md:grid-cols-3 lg:grid-cols-5',
};

const gridOptions: VxeGridProps<any> = {
  toolbarConfig: {
    custom: true,
    export: true,
    refresh: true,
    zoom: true,
  },
  height: 'auto',
  exportConfig: {},
  pagerConfig: {},
  rowConfig: {
    isHover: true,
  },
  stripe: true,

  proxyConfig: {
    response: {
      result: 'Data',
      total: 'Total',
    },
    ajax: {
      query: async ({ page }, formValues) => {
        // 构建查询参数
        const queryParams: any = {
          pageindex: page.currentPage,
          rows: page.pageSize,
          ...formValues,
        };

        // 根据用户角色调用不同的API：代理商且非管理员调用编辑API，否则调用审核API
        return await (userStore.isDLSNotAdmin
          ? getCoupon2EditListApi(queryParams) // editlist接口加了session，只能看自己新增的
          : getCoupon2AuditListApi(queryParams));
      },
    },
  },

  columns: [
    { title: '序号', type: 'seq', width: 50 },
    // { title: '优惠券ID', field: 'coupon2sid', sortable: true },
    // { title: '优惠券代码', field: 'coupon2code', sortable: true },
    { title: '产品名称', field: 'productsname', sortable: true },
    { title: '产品型号', field: 'productsmodel', sortable: true },
    { title: '机具类型', field: 'productsjjlx', sortable: true },
    { title: '生产企业', field: 'scqyinfomc', sortable: true },
    { title: '优惠券名称', field: 'coupon2mc', sortable: true },
    { title: '可用产品', field: 'productsname', sortable: true },
    { title: '购机者', field: 'usersname', sortable: true, width: 140 },
    {
      title: '优惠券状态',
      field: 'coupon2sype',
      sortable: true,
      slots: {
        default: ({ row }) => {
          const type = row.coupon2sype as 0 | 1 | 2;
          const typeMap = {
            0: { text: '申请中', type: 'info' },
            1: { text: '审核通过', type: 'success' },
            2: { text: '审核不通过', type: 'danger' },
          } as const;
          return h(
            ElTag,
            { type: typeMap[type]?.type },
            () => typeMap[type]?.text,
          );
        },
      },
      width: 150,
    },
    {
      title: '使用状态',
      field: 'coupon2isused',
      sortable: true,
      slots: {
        default: ({ row }) => {
          const type = row.coupon2isused as 0 | 1;
          const typeMap = {
            0: { text: '未使用', type: 'info' },
            1: { text: '已使用', type: 'success' },
          } as const;
          return h(
            ElTag,
            { type: typeMap[type]?.type },
            () => typeMap[type]?.text,
          );
        },
      },
      width: 160,
    },
    { title: '申请时间', field: 'coupon2adddatetime', sortable: true },
    { title: '审核时间', field: 'coupon2reviewdatetime', sortable: true },
    {
      title: '操作',
      field: 'action',
      fixed: 'right',
      slots: { default: 'action' },
      width: 200,
    },
  ],
};

const gridEvents: VxeGridListeners<any> = {
  cellDblclick: ({ row }) => {
    handleDetail(row);
  },
};

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

const auditFormRef = ref<any>(null);
const detailFormRef = ref<any>(null);

/* 详情 */
function handleDetail(row: any) {
  detailFormRef.value?.openDetailModal(row);
}

/* 审核 */
function handleAudit(row: any) {
  auditFormRef.value?.openAuditModal(row);
}

/* 下单 */
function handleOrder(row: any) {
  orderCouponFormRef.value?.openOrderCouponModal({
    coupon2sid: row.coupon2sid,
  });
}

function handleFinish() {
  gridApi.reload();
}

// 领取优惠劵
function handleCreate() {
  // 构建传递给弹窗的数据
  const modalData: any = {};

  // 如果是代理商且非管理员，传入merchantId默认值
  if (userStore.isDLSNotAdmin && userStore.userInfo?.workeruserid) {
    modalData.merchantId = userStore.userInfo.workeruserid;
  }

  receiveCouponFormRef.value?.openReceiveCouponModal(modalData);
}

// 处理领取优惠券成功后的逻辑
function handleReceiveSuccess({
  coupon2sid: _coupon2sid,
}: {
  coupon2sid: string;
}) {
  gridApi.reload();
  ElMessageBox.confirm('优惠券领取成功！', '提示', {
    // confirmButtonText: '优惠劵下单',
    confirmButtonText: '确定',
    cancelButtonText: '关闭',
    type: 'success',
  })
    .then(() => {
      // // 用户选择使用优惠券下单，打开下单弹窗
      // orderCouponFormRef.value?.openOrderCouponModal({ coupon2sid });
    })
    .catch(() => {
      // 用户关闭了确认对话框
    });
}

// 处理下单成功后的逻辑
function handleOrderSuccess({ orderId }: { orderId: string }) {
  gridApi.reload();
  ElMessage.success(`下单成功！订单号：${orderId}`);
}
</script>

<template>
  <Page auto-content-height>
    <Grid table-title="优惠券列表">
      <template #toolbar-tools>
        <el-button type="primary" @click="handleCreate"> 领取优惠劵 </el-button>
      </template>
      <template #action="{ row }">
        <el-tooltip
          class="box-item"
          effect="dark"
          content="详情"
          placement="top"
        >
          <el-button
            round
            @click="() => handleDetail(row)"
            :icon="MdiDetail"
            class="!p-2"
          />
        </el-tooltip>
        <!-- <el-tooltip
          class="box-item"
          effect="dark"
          content="编辑"
          placement="top"
        >
          <el-button
            round
            @click="() => handleEdit(row)"
            :icon="MdiEdit"
            class="!p-2"
          />
        </el-tooltip> -->
        <el-tooltip
          class="box-item"
          effect="dark"
          content="审核"
          placement="top"
          v-if="userStore.isSuperAdmin"
        >
          <el-button
            round
            @click="() => handleAudit(row)"
            :icon="MdiCheckboxMultipleMarked"
            class="!p-2"
            :disabled="row.coupon2sype !== 0"
          />
        </el-tooltip>
        <el-tooltip
          class="box-item"
          effect="dark"
          content="下单"
          placement="top"
        >
          <el-button
            round
            @click="() => handleOrder(row)"
            class="!p-2"
            :icon="MdiPlus"
            :disabled="row.coupon2sype !== 1 || row.coupon2isused === 1"
          />
        </el-tooltip>
      </template>
    </Grid>
    <AuditForm ref="auditFormRef" @finish="handleFinish" />
    <DetailForm ref="detailFormRef" />
    <ReceiveCouponForm
      ref="receiveCouponFormRef"
      @finish="handleReceiveSuccess"
    />
    <OrderCouponForm ref="orderCouponFormRef" @finish="handleOrderSuccess" />
  </Page>
</template>
