<template>
  <div class="container">
    <Breadcrumb :items="['充值账户管理', '充值流水']" />
    <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>
        <config v-if="state.showConfig" />
        <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"
        >
          <template #status="{ record }">
            <a-tag size="small" :color="statusMapper(record.status).color">
              {{ statusMapper(record.status).text }}
            </a-tag>
          </template>
          <template #orderStatus="{ record }">
            <a-tag
              v-if="record.orderStatus !== 0"
              size="small"
              :color="statusMapper(record.orderStatus).color"
            >
              {{ statusMapper(record.orderStatus).text }}
            </a-tag>
          </template>
          <template #notifyStatus="{ record }">
            <a-tag
              v-if="[1, 2].includes(record.notifyStatus)"
              size="small"
              :color="record.notifyStatus === 1 ? 'green' : 'red'"
            >
              回调{{ record.notifyStatus === 1 ? '成功' : '失败' }}
            </a-tag>
            <a-tag v-else size="small" color="gray">未回调</a-tag>
          </template>
          <template #operation="{ record }">
            <a-space size="small">
              <a-tooltip content="详情">
                <a-button
                  size="small"
                  @click="showOrderHistory(record.orderNo)"
                >
                  <template #icon>
                    <icon-list />
                  </template>
                </a-button>
              </a-tooltip>
              <!-- 回调 -->
              <a-tooltip content="回调">
                <a-button
                  v-if="
                    record.notifyStatus !== 1 &&
                    [1, 100, 17].includes(record.orderStatus)
                  "
                  size="small"
                  status="warning"
                  @click="callback(record.orderNo)"
                >
                  <template #icon>
                    <icon-send />
                  </template>
                </a-button>
              </a-tooltip>
            </a-space>
          </template>
        </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, Notification } from '@arco-design/web-vue';
import useLoading from '@/hooks/loading';
import { Pagination } from '@/types/global';
import { onMounted, reactive, ref } from 'vue';
import config from './components/config.tsx';
import OrderHistory from './components/history.vue';
import { checkTokenFromIframe } from '@/utils/auth';
import {
  ApiCardInfoCTripOrderListGetPageSizeEnum,
  KamiInternalModelEntityV1CardRedeemOrderInfo
} from '@/api/generated/index.ts';
import { apiClient } from '@/api/index.ts';

const basePagination: Pagination = {
  current: 1,
  pageSize: 50
};
const state = reactive({
  orderHistoryModalVisible: false,
  selectedOrderNo: '',
  showConfig: false
});
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: 'accountName'
  },
  {
    title: '卡种',
    dataIndex: 'cardTypeName'
  },
  {
    title: '卡号',
    dataIndex: 'cardNo',
    tooltip: true,
    ellipsis: true
  },
  {
    title: '礼品卡密码',
    dataIndex: 'giftCardPwd'
  },
  {
    title: '卡面金额',
    dataIndex: 'orderAmount'
  },
  {
    title: '实际金额',
    dataIndex: 'actualAmount'
  },
  {
    title: '充值状态',
    dataIndex: 'status',
    slotName: 'status'
  },
  {
    title: '状态明细',
    dataIndex: 'orderStatus',
    slotName: 'orderStatus'
  },
  {
    title: '回调状态',
    dataIndex: 'notifyStatus',
    slotName: 'notifyStatus'
  },
  // {
  //   title: '备注',
  //   dataIndex: 'remark'
  // },
  {
    title: '创建时间',
    dataIndex: 'createdAt'
  },
  {
    title: '操作',
    dataIndex: 'operation',
    slotName: 'operation'
  }
];
const generateFormModel = () => {
  return {
    merchantId: '',
    attach: '',
    giftCardPwd: '',
    accountNickName: '',
    accountCk: '',
    status: null,
    dateRange: []
  };
};
const { loading, setLoading } = useLoading(true);
const renderData = ref<KamiInternalModelEntityV1CardRedeemOrderInfo[]>([]);
const formModel = ref<{
  giftCardPwd: string;
  merchantId: string;
  attach: string;
  accountNickName: string;
  accountCk: string;
  dateRange: Array<string>;
}>(generateFormModel());

const fetchData = async (
  params: Pagination = {
    current: 1,
    pageSize: 50
  }
) => {
  setLoading(true);
  try {
    const {
      data: { list, total }
    } = await apiClient.apiCardInfoCTripOrderListGet({
      current: params.current,
      pageSize: params.pageSize as ApiCardInfoCTripOrderListGetPageSizeEnum,
      giftCardPwd: formModel.value.giftCardPwd,
      merchantId: formModel.value.merchantId,
      attach: formModel.value.attach,
      accountNickName: formModel.value.accountNickName,
      accountCk: formModel.value.accountCk,
      dateRange: formModel.value.dateRange
    });
    renderData.value = list;
    pagination.current = params.current;
    pagination.pageSize = params.pageSize;
    pagination.total = 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({
    ...basePagination,
    ...formModel.value,
    current: 1
  });
};
const showOrderHistory = (orderNo: string) => {
  state.orderHistoryModalVisible = true;
  state.selectedOrderNo = orderNo;
};
const statusMapper = (status: number): { text: string; color: string } => {
  switch (status) {
    case 100:
      return { text: '失败', color: 'red' };
    case 1:
      return { text: '成功', color: 'green' };
    case 2:
      return { text: '待处理', color: 'orange' };
    case 3:
      return { text: '验证失败', color: 'red' };
    case 4:
      return { text: '账号失效', color: 'red' };
    case 5:
      return { text: '账号充值频繁', color: 'red' };
    case 6:
      return { text: '未知', color: 'gray' };
    case 7:
      return { text: '禁用(充值次数超限)', color: 'red' };
    case 8:
      return { text: '金额异议(充值成功)', color: 'pinkpurple' };
    case 9:
      return { text: '卡密类型错误', color: 'red' };
    case 10:
      return { text: '金额异议(充值失败)', color: 'red' };
    case 11:
      return { text: '卡密被绑定', color: 'red' };
    case 12:
      return { text: '重复绑卡', color: 'red' };
    case 13:
      return { text: '账号受限', color: 'red' };
    case 14:
      return { text: '匹配账号', color: 'orange' };
    case 15:
      return { text: '卡片无效/不存在', color: 'red' };
    case 16:
      return { text: '卡片过期', color: 'red' };
    case 17:
      return { text: '补卡成功', color: 'green' };
    case 18:
      return { text: '开始处理', color: 'green' };
    case 19:
      return { text: '订单重复上传', color: 'red' };
    case 20:
      return { text: '卡号不符合规则', color: 'red' };
    default:
      return { text: '未知', color: 'gray' };
  }
};
const reset = () => {
  formModel.value = generateFormModel();
};
onMounted(() => {
  if (checkTokenFromIframe()) {
    state.showConfig = true;
  }
  fetchData({ ...pagination });
});
const callback = async (orderNo: string) => {
  try {
    await apiClient.apiCardInfoCTripOrderCallbackGet({
      orderNo: orderNo
    });
    Notification.success({
      title: '成功',
      content: '等待回调'
    });
  } catch (error) {}
};
</script>
