<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="accountNumber" label="账户">
                  <a-input
                    v-model="formModel.accountNumber"
                    placeholder="请输入账户"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="status" label="状态">
                  <a-select v-model="formModel.status" placeholder="请输入状态">
                    <a-option
                      v-for="(status, index) in statusOptions"
                      :key="index"
                      :value="status.value"
                      :label="status.label"
                    />
                    <a-option value="false" label="否" />
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="merchantOrder" label="订单号">
                  <a-input
                    v-model="formModel.merchantOrder"
                    placeholder="请输入订单号"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="thirdMerchantOrder" label="三方订单号">
                  <a-input
                    v-model="formModel.thirdMerchantOrder"
                    placeholder="请输入账户"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="tMallShopOrder" label="淘宝订单号">
                  <a-input
                    v-model="formModel.tMallShopOrder"
                    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-row>
          </a-form>
        </a-col>
        <a-divider style="height: 42px" direction="vertical" />
        <a-col flex="172px" style="text-align: right">
          <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-col>
      </a-row>
      <a-divider style="margin-top: 0" />
      <a-space direction="vertical" fill>
        <a-radio-group
          type="button"
          style="float: right"
          @change="handleCallBackTypeChange"
        >
          <a-radio value="">全部</a-radio>
          <a-radio value="confirm">收货</a-radio>
          <a-radio value="evaluation" label="">评价</a-radio>
        </a-radio-group>
        <a-table
          :loading="loading"
          :pagination="{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            pageSizeOptions: [10, 20, 50, 100],
            showPageSize: true
          }"
          :columns="columns"
          :data="renderData"
          :scroll="{ x: 1080 }"
          @page-change="onPageChange"
          @page-size-change="onPageSizeChange"
        >
          <template #index="{ rowIndex }">
            {{ rowIndex + 1 + (pagination.current - 1) * pagination.pageSize }}
          </template>
          <template #status="{ record }">
            <a-space size="mini">
              <a-tag size="small" :color="transferColor(record.status).color">
                {{ transferColor(record.status).label }}
              </a-tag>
              <a-tag
                v-if="[1, 2].includes(record.notifyStatus)"
                size="small"
                :color="record.notifyStatus === 1 ? 'green' : 'red'"
              >
                回调{{ record.notifyStatus === 1 ? '成功' : '失败' }}
              </a-tag>
            </a-space>
          </template>
          <template #callbackType="{ record }">
            <a-badge
              size="small"
              :text="transferCallbackType(record.callbackType).label"
              :color="transferCallbackType(record.callbackType).color"
            />
          </template>
          <template #operations="{ record }">
            <a-space size="small">
              <a-button
                v-if="['finished'].includes(record.status)"
                size="small"
                status="warning"
                @click="callBackOrderManual(record.orderNo)"
              >
                回调
              </a-button>
              <!-- <a-button
              size="small"
              status="warning"
              @click="(record)"
            >
              回调
            </a-button> -->
              <a-tooltip content="详情">
                <a-button
                  size="small"
                  status="normal"
                  @click="showDetailModel(record)"
                >
                  <template #icon>
                    <icon-list />
                  </template>
                </a-button>
              </a-tooltip>
              <!-- <a-button
              v-if="checkTokenFromIframe()"
              size="small"
              status="danger"
              @click="deleteAppleCardHandler(record.id)"
            >
              删除
            </a-button> -->
            </a-space>
          </template>
        </a-table>
      </a-space>
    </a-card>
  </div>
  <detail
    v-model:visible="state.orderDetailVisible"
    :shop-id="state.currentShopId"
    :order-no="state.currentOrderNo"
  />
</template>

<script setup lang="ts">
import {
  callBackOrderManualAPI,
  queryTMallOrderList,
  TMallOrderParams,
  TMallOrderRecord
} from '@/api/t-mall-game-order';
import useLoading from '@/hooks/loading';
import { Pagination } from '@/types/global';
import detail from './detail.vue';
import { TableColumnData, Notification, Message } from '@arco-design/web-vue';
import { onMounted, reactive, ref } from 'vue';
const basePagination: Pagination = {
  current: 1,
  pageSize: 50
};
const pagination = reactive({
  ...basePagination
});
const generateFormModel = () => {
  return {
    thirdMerchantOrder: '',
    accountNumber: '',
    status: '',
    orderNo: '',
    merchantOrder: '',
    tMallShopOrder: '',
    callbackType: '',
    dateRange: []
  };
};
const statusOptions = [
  { value: 'created', label: '已创建' },
  { value: 'callback', label: '回到回调' },
  { value: 'delivery_failed', label: '虚拟发货失败' },
  { value: 'delivery_succeed', label: '虚拟发货成功' },
  { value: 'finished', label: '完结' },
  { value: 'paid', label: '已付款' },
  { vvalue: 'bind_shop_succeed', label: '绑定天猫订单' },
  { value: 'evaluation', label: '已评价' },
  { value: 'callback_succeed', label: '回调成功' },
  { value: 'callback_failed', label: '回调失败' },
  { value: 'trade_rated_add_succeed', label: '评价成功' },
  { value: 'trade_rated_add_failed', label: '评价失败' },
  { value: 'finished_with_wrong_amount', label: '完结(金额不符)' },
  { value: 'callback_manual_succeed_manuel', label: '手动回调成功' },
  { value: 'callback_manual_failed_manuel', label: '手动回调失败' },
  { value: 'wait_for_evaluation', label: '等待用户评价' },
  { value: 'finished_with_wrong_status', label: '完结(非好评)' }
];
const columns: TableColumnData[] = [
  // {
  //   title: '序号',
  //   dataIndex: 'index',
  //   slotName: 'index'
  // },
  // {
  //   title: '订单号',
  //   dataIndex: 'orderNo'
  // },
  {
    title: '三方订单',
    dataIndex: 'thirdMerhantOrder',
    ellipsis: true,
    tooltip: true
  },
  {
    title: '系统订单',
    dataIndex: 'merchantOrder',
    ellipsis: true,
    tooltip: true
  },
  {
    title: '充值账号',
    dataIndex: 'accountInfo.accountNumber',
    ellipsis: true,
    tooltip: true
  },
  {
    title: '订单金额',
    dataIndex: 'amount'
  },
  {
    title: '淘宝订单',
    dataIndex: 'shopInfo.tMallOrderNo'
  },
  {
    title: '状态',
    dataIndex: 'status',
    slotName: 'status'
  },
  {
    title: '回调类型',
    dataIndex: 'callbackType',
    slotName: 'callbackType'
  },
  {
    title: '创建人',
    dataIndex: 'channelName'
  },
  {
    title: '支付时间',
    dataIndex: 'shopInfo.endTime'
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt'
  },
  // {
  //   title: '备注',
  //   dataIndex: 'remark'
  // },
  {
    title: '操作',
    dataIndex: 'operations',
    slotName: 'operations'
  }
];

const formModel = ref(generateFormModel());
const { loading, setLoading } = useLoading(true);
const renderData = ref<TMallOrderRecord[]>([]);
const state = reactive({
  currentShopId: 0,
  currentOrderNo: '',
  orderDetailVisible: false
});

const fetchData = async (
  params: TMallOrderParams = { current: 1, pageSize: 50 }
) => {
  setLoading(true);
  try {
    const {
      data: { list, total }
    } = await queryTMallOrderList(params);
    renderData.value = list;
    pagination.current = params.current;
    pagination.pageSize = params.pageSize;
    pagination.total = total;
  } catch (err) {
    // you can report use errorHandler or other
  } finally {
    setLoading(false);
  }
};

const transferColor = (status: string): { label: string; color: string } => {
  switch (status) {
    case 'created':
      return { label: '已创建', color: 'arcoblue' };
    case 'callback':
      return { label: '回到回调', color: 'orangered' };
    case 'delivery_failed':
      return { label: '发货失败', color: 'pinkpurple' };
    case 'delivery_succeed':
      return { label: '发货成功', color: 'orange' };
    case 'finished':
      return { label: '完结', color: 'green' };
    case 'paid':
      return { label: '已付款', color: 'orange' };
    case 'evaluation':
      return { label: '已评价', color: 'orange' };
    case 'callback_succeed':
      return { label: '回调成功', color: 'green' };
    case 'callback_failed':
      return { label: '回调失败', color: 'red' };
    case 'trade_rated_add_succeed':
      return { label: '评价成功', color: 'orange' };
    case 'trade_rated_add_failed':
      return { label: '评价失败', color: 'pinkpurple' };
    case 'finished_with_wrong_amount':
      return { label: '失败(金额不符)', color: 'red' };
    case 'callback_manual_succeed_manuel':
      return { label: '手动回调成功', color: 'arcoblue' };
    case 'callback_manual_failed_manuel':
      return { label: '手动回调失败', color: 'red' };
    case 'wait_for_evaluation':
      return { label: '等待用户评价', color: 'blue' };
    case 'finished_with_wrong_status':
      return { label: '失败(非好评)', color: 'red' };
    default:
      return { label: '其他状态，待更新', color: 'gray' };
  }
};

const transferCallbackType = (
  type: string
): { label: string; color: string } => {
  switch (type) {
    case 'evaluation':
      return { label: '评价', color: 'orangered' };
    case 'confirm':
      return { label: '收货', color: 'green' };
    default:
      return { label: '其他状态，待更新', color: 'gray' };
  }
};

const onPageChange = (current: number) => {
  fetchData({ ...pagination, ...formModel.value, current });
};
const onPageSizeChange = (pageSize: number) => {
  fetchData({ ...formModel.value, current: 1, pageSize });
};
const search = () => {
  fetchData({
    ...basePagination,
    ...formModel.value
  });
};
const reset = () => {
  const callbackType = formModel.value.callbackType;
  formModel.value = generateFormModel();
  formModel.value.callbackType = callbackType;
};
const callBackOrderManual = async (orderNo: string) => {
  await callBackOrderManualAPI({ orderNo });
  fetchData({ ...pagination, ...formModel.value });
  Message.success('回调成功');
};
const showDetailModel = (record: TMallOrderRecord) => {
  if (!record.shopId) {
    Notification.error({
      id: `tMallOrderNotice:${record.orderNo}`,
      content: '当前没有淘宝订单',
      closable: true
    });
    return;
  }
  state.currentOrderNo = record.orderNo;
  state.currentShopId = record.shopId;
  state.orderDetailVisible = true;
};
const handleCallBackTypeChange = (value: string) => {
  // 清除所有筛选条件
  formModel.value = generateFormModel();
  formModel.value.callbackType = value;
  fetchData({ ...pagination, ...formModel.value, current: 1 });
};
onMounted(() => {
  fetchData();
});
</script>
