<template>
  <div class="container">
    <Breadcrumb :items="['京东ck管理', '订单管理']" />
    <a-card class="general-card" title="流水记录">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="formModel"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
            label-align="left"
          >
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="giftCardPwd" label="卡密">
                  <a-input
                    v-model="formModel.giftCardPwd"
                    placeholder="请输入卡密"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="attach" label="商户订单号">
                  <a-input
                    v-model="formModel.attach"
                    placeholder="请输入商户订单号"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="merchantId" label="系统订单号">
                  <a-input
                    v-model="formModel.merchantId"
                    placeholder="请输入系统订单号"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="dateRange" label="创建时间">
                  <a-range-picker v-model="formModel.dateRange" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="accountNickName" label="账户昵称">
                  <a-input
                    v-model="formModel.accountNickName"
                    placeholder="请输入账户昵称"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="accountCk" label="账户Ck">
                  <a-input
                    v-model="formModel.accountCk"
                    placeholder="请输入账户Ck"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 42px" direction="vertical" />
        <a-col flex="172px" style="text-align: right">
          <a-space direction="vertical" :size="18">
            <a-space direction="horizontal" :size="18">
              <a-button type="primary" @click="search">
                <template #icon>
                  <icon-search />
                </template>
                搜索
              </a-button>
              <a-button @click="reset">
                <template #icon>
                  <icon-refresh />
                </template>
                重置
              </a-button>
            </a-space>
          </a-space>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />
      <a-space direction="vertical" fill>
        <a-table
          :loading="loading"
          :pagination="{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            pageSizeOptions: [10, 20, 50, 100],
            showPageSize: true,
            showTotal: true
          }"
          table-layout-fixed
          column-resizable
          :columns="columns"
          :data="renderData"
          :bordered="false"
          column-resizable:bordered="{cell:true}"
          @page-change="onPageChange"
          @page-size-change="onPageSizeChange"
        ></a-table>
      </a-space>
    </a-card>
    <order-history
      v-model:visible="state.orderHistoryModalVisible"
      :order-no="state.selectedOrderNo"
    />
  </div>
</template>

<script lang="ts" setup>
import { TableColumnData } from '@arco-design/web-vue';
import useLoading from '@/hooks/loading';
import { Pagination } from '@/types/global';
import { onMounted, reactive, ref } from 'vue';
import OrderHistory from './components/history.vue';
import { checkTokenFromIframe } from '@/utils/auth';
import { walmartCardOrderParams } from '@/api/card-walmart-order.ts';
import {
  ApiCookieInfoJdOrderListGetPageSizeEnum,
  KamiApiCardRedeemJdV1OrderListSchema,
  KamiInternalModelEntityV1CardRedeemAccountGroup,
  KamiInternalModelEntityV1CardRedeemOrderInfo
} from '@/api/generated/index.ts';
import { apiCkClient } from '@/api/index.ts';

const basePagination: Pagination = {
  current: 1,
  pageSize: 50
};

const state = reactive({
  orderHistoryModalVisible: false,
  selectedOrderNo: '',
  showConfig: false,
  activeTableKey: 0
});

const pagination = reactive({
  ...basePagination
});

const columns: TableColumnData[] = [
  {
    title: '序号',
    dataIndex: 'index',
    render: ({ rowIndex }) => {
      return rowIndex + 1 + (pagination.current - 1) * pagination.pageSize;
    }
  },
  {
    title: '订单号',
    dataIndex: 'merchantId'
  },
  {
    title: '京东订单号',
    dataIndex: 'attach'
  },
  {
    title: '系统订单号',
    dataIndex: 'cardTypeName'
  },
  {
    title: '支付链接',
    dataIndex: 'wxPay'
  },
  {
    title: '提取信息',
    dataIndex: 'cardNo',
    tooltip: true,
    ellipsis: true
  },
  {
    title: '订单金额',
    dataIndex: 'orderAmount'
  },
  {
    title: '状态',
    dataIndex: 'status',
    slotName: 'status'
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt'
  },
  {
    title: '操作',
    dataIndex: 'operation',
    slotName: 'operation'
  }
];

const generateFormModel = () => {
  return {
    merchantId: '',
    attach: '',
    giftCardPwd: '',
    accountNickName: '',
    accountCk: '',
    status: null,
    dateRange: [],
    groupId: null
  };
};

const { loading, setLoading } = useLoading(false);
const renderData = ref<KamiApiCardRedeemJdV1OrderListSchema[]>([]);
const formModel = ref<{
  merchantId: string;
  accountNickName: string;
  accountCk: string;
  attach: string;
  giftCardPwd: string;
  status: number;
  dateRange: string[];
  groupId: number | null;
}>(generateFormModel());

const fetchData = async (
  params: Pagination = {
    current: 1,
    pageSize: 50
  }
) => {
  setLoading(true);
  try {
    const res = await apiCkClient.apiCookieInfoJdOrderListGet({
      current: pagination.current,
      pageSize: pagination.pageSize as ApiCookieInfoJdOrderListGetPageSizeEnum
    });
    renderData.value = res.data.list;
    pagination.current = params.current;
    pagination.pageSize = params.pageSize;
    pagination.total = res.data.total;
  } catch (err) {
    console.error(err);
  } finally {
    setLoading(false);
  }
};

const onPageChange = (current: number) => {
  fetchData({ ...pagination, current });
};
const onPageSizeChange = (pageSize: number) => {
  fetchData({ ...pagination, pageSize, current: 1 });
};
const search = () => {
  fetchData({
    current: 1,
    ...basePagination,
    ...formModel.value
  });
};
const showOrderHistory = (orderNo: string) => {
  state.orderHistoryModalVisible = true;
  state.selectedOrderNo = orderNo;
};

const reset = () => {
  formModel.value = generateFormModel();
};
onMounted(() => {
  if (checkTokenFromIframe()) {
    state.showConfig = true;
  }
  fetchData({ ...pagination });
});
const callback = async (orderNo: string) => {
  try {
    // await apiClient.apiCardInfoWalmartOrderCallbackGet(orderNo);
    // Notification.success({
    //   title: '成功',
    //   content: '等待回调'
    // });
  } catch (error) {}
};

onMounted(() => {
  fetchData({ ...pagination });
});
</script>
