<script setup lang="ts">
import type { VbenFormProps } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { UserOrder } from '#/api/core/log';
import type { AppData } from '#/api/core/server';

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

import { Page, useVbenModal } from '@vben/common-ui';
import { useAccess } from '@vben/access';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  approveOrderReissueApi,
  getUserlogOrderApi,
  rejectOrderReissueApi,
} from '#/api/core/log';
import { getAppListApi } from '#/api/core/server';
import { globalState } from '#/store/globalState';
import { rechargeData } from '#/store/recharge';
import OrderReissueModal from '#/views/userlog/components/order-reissue-modal.vue';
import { Button, message, Modal, Space, Tag } from 'ant-design-vue';

const state = inject('globalState', globalState);
const { hasAccessByRoles } = useAccess();

interface RowType extends UserOrder {
  Uid: string;
}
const appList = ref<AppData[]>([]);

function getReissueStatusText(status?: number) {
  if (status === 1) return '待审核';
  if (status === 2) return '已通过';
  if (status === 3) return '已驳回';
  return '-';
}

function getReissueStatusColor(status?: number) {
  if (status === 1) return 'processing';
  if (status === 2) return 'success';
  if (status === 3) return 'error';
  return 'default';
}

function canApplyReissue(row: RowType) {
  return !row.ReissueStatus && [0, 3].includes(row.PayStatus ?? -1);
}

const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: 'Uid',
      },
      defaultValue: state.uid,
      fieldName: 'Uid',
      label: 'Uid',
    },
    {
      component: 'Select',
      defaultValue: 1,
      componentProps: {
        filterOption: true,
        options: [],
        placeholder: '请选择',
        showSearch: true,
      },
      fieldName: 'AppId',
      label: 'APP：',
    },
  ],
  // 控制表单是否显示折叠按钮
  showCollapseButton: true,
  submitButtonOptions: {
    content: '查询',
  },
  // 是否在字段值改变时提交表单
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: false,
};
const gridOptions: VxeGridProps<RowType> = {
  columns: [
    { field: 'Uid', title: 'id' },
    { field: 'OrderId', title: '订单号' },
    { field: 'PayChannelOrderId', title: '3th订单号' },
    { field: 'Price', title: '金额' },
    {
      field: 'ProductId',
      title: 'chargeId',
      formatter: ({ cellValue }) => {
        return rechargeData[cellValue] || cellValue;
      },
    },
    { field: 'CreateTimeStr', title: '创建时间' },
    {
      field: 'ReissueStatus',
      title: '补单状态',
      width: 100,
      slots: { default: 'reissue_status' },
    },
    { field: 'ReissueThirdOrder', title: '补单三方单号', minWidth: 160 },
    { field: 'ReissueReason', title: '补单理由', minWidth: 180 },
    { field: 'PayTimeStr', title: '支付时间' },
    {
      field: 'PayType',
      title: '支付类型',
      formatter: ({ cellValue }) => {
        if (cellValue === 0) return '谷歌';
        if (cellValue === 1) return '微信';
        if (cellValue === 2) return '支付宝';
        if (cellValue === 3) return '苹果内购';
        return cellValue;
      },
    },
    { field: 'Param', title: '参数' },
    { title: '操作', width: 220, fixed: 'right', slots: { default: 'action' } },
  ],
  exportConfig: {
    filename: '用户订单日志',
    type: 'csv',
    mode: 'current',
    download: true,
  },
  toolbarConfig: {
    custom: true,
    export: true,
    refresh: true,
    zoom: true,
  },
  stripe: true,
  height: 'auto',
  pagerConfig: {},
  proxyConfig: {
    response: {
      total: 'total',
      result: 'data',
    },
    ajax: {
      query: async ({ page }, formValues) => {
        const Uid = Number.parseInt(formValues.Uid, 10);
        state.uid = Uid;
        state.Event = formValues.Event;
        return await getUserlogOrderApi({
          Id: Uid,
          Event: formValues.Event,
          CurrentPage: page.currentPage,
          PageSize: page.pageSize,
          AppId: formValues.AppId,
        });
      },
    },
  },

  rowConfig: {
    isHover: true,
  },
  showOverflow: true,
};

const [Grid, GridApi] = useVbenVxeGrid({ formOptions, gridOptions });
const [OrderReissueM, OrderReissueApi] = useVbenModal({
  connectedComponent: OrderReissueModal,
  onClosed: async () => {
    OrderReissueApi.close();
    await GridApi.query();
  },
});

function openOrderReissue(row: RowType) {
  OrderReissueApi.setData({
    AppId: row.AppId || 1,
    OrderId: row.OrderId,
    PayChannelOrderId: row.PayChannelOrderId,
    ServerId: row.ServerId || 1,
    Uid: Number(row.Uid),
  });
  OrderReissueApi.open();
}

async function refreshGrid() {
  await GridApi.query();
}

function approveReissue(row: RowType) {
  const auditId = row.ReissueAuditId;
  if (!auditId) {
    message.error('缺少补单审核单ID');
    return;
  }
  Modal.confirm({
    title: '确认通过这条补单申请吗？',
    async onOk() {
      await approveOrderReissueApi({ audit_id: auditId });
      message.success('补单审核通过');
      await refreshGrid();
    },
  });
}

function rejectReissue(row: RowType) {
  const auditId = row.ReissueAuditId;
  if (!auditId) {
    message.error('缺少补单审核单ID');
    return;
  }
  Modal.confirm({
    title: '确认驳回这条补单申请吗？',
    async onOk() {
      await rejectOrderReissueApi({ audit_id: auditId });
      message.success('补单申请已驳回');
      await refreshGrid();
    },
  });
}

onMounted(async () => {
  try {
    const response = await getAppListApi();
    appList.value = Array.isArray(response) ? response : [];
    const app = appList.value[0];
    if (!app) return;
    GridApi.formApi.updateSchema([
      {
        component: 'Select',
        componentProps: {
          options: appList.value.map((item) => ({
            label: item.AppName,
            value: item.AppId,
          })),
        },
        fieldName: 'AppId',
      },
    ]);
  } catch {
    appList.value = [];
    // console.log(e);
  }
});
</script>

<template>
  <Page auto-content-height>
    <OrderReissueM />
    <Grid>
      <template #reissue_status="{ row }">
        <Tag :color="getReissueStatusColor(row.ReissueStatus)">
          {{ getReissueStatusText(row.ReissueStatus) }}
        </Tag>
      </template>
      <template #action="{ row }">
        <Space>
          <Button
            v-if="canApplyReissue(row) && hasAccessByRoles(['super', 'AC2006'])"
            type="primary"
            @click="openOrderReissue(row)"
          >
            申请补单
          </Button>
          <Button
            v-if="row.ReissueStatus === 1 && hasAccessByRoles(['super', 'AC2007'])"
            type="primary"
            @click="approveReissue(row)"
          >
            通过
          </Button>
          <Button
            v-if="row.ReissueStatus === 1 && hasAccessByRoles(['super', 'AC2008'])"
            danger
            type="primary"
            @click="rejectReissue(row)"
          >
            驳回
          </Button>
        </Space>
      </template>
    </Grid>
  </Page>
</template>
