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

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

import { h, onMounted, ref } from 'vue';

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

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

import { useVbenVxeGrid } from '#/adapter/vxe-table';
// import { deleteOrdersApi, getOrdersListApi } from '#/api/orders';
import { getOrdersListApi } from '#/api/orders';
import { getCustomerListApi } from '#/api/user';
import { $t } from '#/locales';

import OrdersAuditForm from './audit-form.vue';
import OrdersDetail from './detail.vue';
import OrdersForm from './form.vue';

const dealerOptions = ref<Array<{ label: string; value: string }>>([]);
const userStore = useUserStore();

const fetchDealerOptions = async () => {
  try {
    const result = await getCustomerListApi({
      usersnature: '经销商',
      pageindex: 1,
      rows: 999,
    });
    if (result && result.Data) {
      dealerOptions.value = result.Data.map((item: any) => ({
        label: item.usersname,
        value: item.usersid,
      }));
    }
  } catch (error) {
    console.error('Failed to fetch dealer options:', error);
    dealerOptions.value = [];
  }
};

onMounted(async () => {
  await fetchDealerOptions();
});

const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: true,
  // 控制表单是否显示折叠按钮
  showCollapseButton: true,
  // 按下回车时是否提交表单
  submitOnEnter: true,
  schema: [
    {
      component: 'Input',
      fieldName: 'ordersnumber',
      label: '订单号',
      componentProps: {
        placeholder: $t('ui.placeholder.input'),
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'ordersproductname',
      label: '产品名称',
      componentProps: {
        placeholder: $t('ui.placeholder.input'),
        allowClear: true,
      },
    },
    {
      component: 'Select',
      fieldName: 'ordersuserid1',
      label: '经销商',
      // 如果是代理商且非管理员，设置默认值为当前用户的workeruserid
      defaultValue: userStore.isDLSNotAdmin
        ? userStore.userInfo?.workeruserid
        : undefined,
      componentProps: {
        options: dealerOptions,
        placeholder: $t('ui.placeholder.select'),
        allowClear: true,
        filterable: true,
        // 如果是代理商且非管理员，禁用该字段
        disabled: userStore.isDLSNotAdmin,
      },
    },
    {
      component: 'DatePicker',
      fieldName: 'ordersorderdate',
      label: '下单时间',
      componentProps: {
        type: 'daterange',
        startPlaceholder: '开始日期',
        endPlaceholder: '结束日期',
        valueFormat: 'YYYY-MM-DD', // 根据后端接口调整日期格式
        allowClear: true,
      },
    },
  ],
  wrapperClass: 'grid-cols-1 md:grid-cols-3 lg:grid-cols-5',
};

const gridOptions: VxeGridProps<any> = {
  toolbarConfig: {
    custom: true,
    export: true,
    // import: 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 params: Record<string, any> = {
          pageindex: page.currentPage,
          rows: page.pageSize,
          ...formValues,
        };

        return await getOrdersListApi(params as OrdersQueryParams);
      },
    },
  },

  columns: [
    { title: '序号', type: 'seq', width: 50 },
    // { title: '订单号', field: 'ordersnumber', sortable: true },
    // { title: '订单关联用户id', field: 'ordersuserid', sortable: true },
    // { title: '订单关联产品id', field: 'ordersproductid', sortable: true },
    { title: '产品名称', field: 'ordersproductname', sortable: true },
    { title: '产品型号', field: 'productsmodel', sortable: true },
    { title: '产品sn', field: 'ordersproductsn', sortable: true },
    { title: '生产企业', field: 'scqyinfomc', sortable: true },
    { title: '订单总金额', field: 'orderstotalprice', sortable: true },
    { title: '优惠金额', field: 'ordersyhprice', sortable: true },
    {
      title: '订单优惠后金额',
      field: 'ordersdiscountprice',
      sortable: true,
      width: 150,
    },
    // { title: '优惠卷id', field: 'orderscouponid', sortable: true },
    { title: '经销商', field: 'jxsname', sortable: true },
    { title: '购机者姓名', field: 'usersname', sortable: true },
    { title: '购机者电话', field: 'usersphone', sortable: true },
    { title: '购机者地址', field: 'usersaddress', sortable: true },
    {
      title: '订单状态',
      field: 'ordersorderstatus',
      sortable: true,
      slots: {
        default: ({ row }) => {
          const type = row.ordersorderstatus as 0 | 1 | 2;
          const typeMap = {
            0: { text: '待审核', type: 'info' },
            1: { text: '已支付', type: 'success' },
            2: { text: '已完成', type: 'warning' },
            3: { text: '审核不通过', type: 'danger' },
          } as const;
          return h(
            ElTag,
            { type: typeMap[type]?.type },
            () => typeMap[type]?.text,
          );
        },
      },
    },
    // {
    //   title: '审核状态',
    //   field: 'ordsesshzt',
    //   sortable: true,
    //   slots: {
    //     default: ({ row }) => {
    //       const type = row.ordsesshzt 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,
    //       );
    //     },
    //   },
    // },
    { title: '下单时间', field: 'ordersorderdate', 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 [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  closeOnClickModal: false,
  closeOnPressEscape: false,
  connectedComponent: OrdersForm,
});

const [DetailModal, detailModalApi] = useVbenModal({
  fullscreenButton: false,
  closeOnClickModal: false,
  closeOnPressEscape: false,
  connectedComponent: OrdersDetail,
});

const [AuditModal, auditModalApi] = useVbenModal({
  fullscreenButton: false,
  closeOnClickModal: false,
  closeOnPressEscape: false,
  connectedComponent: OrdersAuditForm,
});

/* 创建 */
function handleCreate() {
  modalApi.setState({ showCancelButton: true });
  modalApi.setData({ formType: 'create' }).open();
}

/* 编辑 */
// function handleEdit(row: any) {
//   modalApi.setState({ showCancelButton: true });
//   modalApi.setData({ formType: 'edit', row }).open();
// }

/* 详情 */
function handleDetail(row: any) {
  detailModalApi.setData({ row }).open();
}

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

/* 审核 */
function handleAudit(row: any) {
  auditModalApi.setData({ row }).open();
}

/* 删除 */
// async function handleDelete(row: any) {
//   try {
//     await ElMessageBox.confirm('确认要删除该订单吗?', '提示', {
//       confirmButtonText: '确定',
//       cancelButtonText: '取消',
//       type: 'warning',
//     });
//     await deleteOrdersApi({ 'ordersid.value': row.ordersid });
//     ElMessage.success('删除成功');
//     gridApi.reload();
//   } catch (error) {
//     console.error(error);
//   }
// }
</script>

<template>
  <Page auto-content-height>
    <Grid table-title="订单列表">
      <template #toolbar-tools>
        <el-button
          type="primary"
          @click="handleCreate"
          v-if="!userStore.isDLSNotAdmin"
        >
          新增
        </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.isDLSNotAdmin"
        >
          <el-button
            round
            @click="() => handleAudit(row)"
            :icon="MdiCheckboxMultipleMarked"
            class="!p-2"
            :disabled="row.ordersorderstatus !== 0"
          />
        </el-tooltip>
        <!-- <el-tooltip
          class="box-item"
          effect="dark"
          content="删除"
          placement="top"
        >
          <el-button
            round
            @click="() => handleDelete(row)"
            :icon="MdiDelete"
            class="!p-2"
          />
        </el-tooltip> -->
      </template>
    </Grid>
    <Modal @finish="handleFinish" />
    <DetailModal />
    <AuditModal @finish="handleFinish" />
  </Page>
</template>
