<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="account" label="账户">
                  <a-input
                    v-model="formModel.account"
                    placeholder="请输入账户"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="status" label="天猫订单">
                  <a-select
                    v-model="formModel.tMallOrderNo"
                    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="orderNo" label="订单号">
                  <a-input
                    v-model="formModel.orderNo"
                    placeholder="请输入订单号"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="buyerNickName" label="买家昵称">
                  <a-input
                    v-model="formModel.buyerNickName"
                    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="cardNo" 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-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-tag size="small" :color="transferColor(record.status).color">
              {{ transferColor(record.status).label }}
            </a-tag>
          </template>
          <template #tradeStatus="{ record }">
            {{ transfromTradeStatusLabel(record.tradeStatus) }}
          </template>
          <template #operations="{ record }">
            <a-button
              size="small"
              status="normal"
              @click="showDetailModel(record)"
            >
              日志
            </a-button>
          </template>
          <!-- <template #operations="{ record }">
            <a-space size="small">
            </a-space>
          </template> -->
        </a-table>
      </a-space>
    </a-card>
  </div>
  <detail
    v-model:visible="state.orderRecordVisible"
    :shop-id="state.currentShopId"
  />
</template>

<script setup lang="ts">
import { TMallOrderParams } from '@/api/t-mall-game-order';
import useLoading from '@/hooks/loading';
import { Pagination } from '@/types/global';
import detail from './detail.vue';
import { TableColumnData, Notification } from '@arco-design/web-vue';
import { onMounted, reactive, ref } from 'vue';
import {
  queryTMallShopOrderList,
  ShopOrderRecord
} from '@/api/t-mall-game-shop-order';
const basePagination: Pagination = {
  current: 1,
  pageSize: 50
};
const pagination = reactive({
  ...basePagination
});
const generateFormModel = () => {
  return {
    account: null,
    tMallOrderNo: null,
    buyerNickName: null,
    orderNo: null,
    dateRange: []
  };
};
const statusOptions = [
  { value: 'receive_callback', label: '收到回调' },
  { value: 'paid', label: '支付订单' },
  { value: 'delivery_succeed', label: '发货成功' },
  { value: 'delivery_failed', label: '发货失败' },
  { value: 'confirm_order', label: '确认收货' },
  { value: 'bind_order_fail', label: '绑定订单失败' },
  { value: 'bind_order_succeed', label: '绑定订单成功' },
  { value: 'evaluation_good', label: '用户好评' },
  { value: 'evaluation_bad', label: '用户差评' },
  { value: 'evaluated_succeed', label: '好评成功' },
  { value: 'evaluated_failed', label: '好评失败' }
];
const columns: TableColumnData[] = [
  // {
  //   title: '序号',
  //   dataIndex: 'index',
  //   slotName: 'index'
  // },
  {
    title: '订单号',
    dataIndex: 'orderNo'
  },
  {
    title: '天猫订单号',
    dataIndex: 'tMallOrderNo'
  },
  {
    title: '充值账号',
    dataIndex: 'account'
  },
  {
    title: '买家昵称',
    dataIndex: 'buyerNick',
    ellipsis: true,
    tooltip: true
  },
  {
    title: '状态',
    dataIndex: 'status',
    slotName: 'status'
  },
  {
    title: '实付金额',
    dataIndex: 'payment',
    slotName: 'payment'
  },
  // {
  //   title: '商品金额',
  //   dataIndex: 'totalFee',
  //   slotName: 'totalFee'
  // },
  {
    title: '交易创建时间',
    dataIndex: 'create_time',
    ellipsis: true,
    tooltip: true
  },
  {
    title: '支付时间',
    dataIndex: 'payTime',
    slotName: 'payTime'
  },
  {
    title: '收货时间',
    dataIndex: 'endTime',
    slotName: 'endTime'
  },
  // {
  //   title: '交易状态',
  //   dataIndex: 'tradeStatus',
  //   slotName: 'tradeStatus'
  // },
  // {
  //   title: '买家留言(系统订单)',
  //   dataIndex: 'BuyerMessage',
  //   slotName: 'BuyerMessage'
  // },
  // {
  //   title: '支付宝流水',
  //   dataIndex: 'alipayNo',
  //   slotName: 'alipayNo'
  // },
  {
    title: '操作',
    dataIndex: 'operations',
    slotName: 'operations'
  }
];

const formModel = ref(generateFormModel());
const { loading, setLoading } = useLoading(true);
const renderData = ref<ShopOrderRecord[]>([]);
const state = reactive<{
  currentShopId: number;
  orderRecordVisible: boolean;
}>({
  currentShopId: null,
  orderRecordVisible: false
});

const fetchData = async (
  params: TMallOrderParams = { current: 1, pageSize: 50 }
) => {
  setLoading(true);
  try {
    const {
      data: { list, total }
    } = await queryTMallShopOrderList(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 'receive_callback':
      return { label: '接收回调', color: 'arcoblue' };
    case 'paid':
      return { label: '支付订单', color: 'orangered' };
    case 'delivery_succeed':
      return { label: '发货成功', color: 'green' };
    case 'delivery_failed':
      return { label: '发货失败', color: 'red' };
    case 'confirm_order':
      return { label: '确认收货', color: 'orange' };
    case 'bind_order_fail':
      return { label: '绑定订单失败', color: 'pinkpurple' };
    case 'bind_order_succeed':
      return { label: '绑定订单成功', color: 'green' };
    case 'evaluation_good':
      return { label: '用户好评', color: 'orange' };
    case 'evaluation_bad':
      return { label: '用户差评', color: 'red' };
    case 'evaluated_succeed':
      return { label: '好评成功', color: 'green' };
    case 'evaluated_failed':
      return { label: '好评失败', color: 'pinkpurple' };
    default:
      return { label: '未知状态', color: 'gray' };
  }
};

const showDetailModel = (record: ShopOrderRecord) => {
  if (!record.id) {
    Notification.error({
      id: `tMallOrderNotice:${record.orderNo}`,
      content: '当前没有淘宝订单',
      closable: true
    });
    return;
  }
  state.currentShopId = record.id;
  state.orderRecordVisible = true;
};

const transfromTradeStatusLabel = (tradeStatus: string): string => {
  switch (tradeStatus) {
    case 'TRADE_NO_CREATE_PAY':
      return '没有创建支付宝交易';
    case 'WAIT_BUYER_PAY':
      return '等待买家付款';
    case 'SELLER_CONSIGNED_PART':
      return '卖家部分发货';
    case 'WAIT_SELLER_SEND_GOODS':
      return '等待卖家发货，即：买家已付款';
    case 'WAIT_BUYER_CONFIRM_GOODS':
      return '等待买家确认收货，即：卖家已发货';
    case 'TRADE_BUYER_SIGNED':
      return '买家已签收，货到付款专用';
    case 'TRADE_FINISHED':
      return '交易成功';
    case 'TRADE_CLOSED':
      return '付款以后用户退款成功，交易自动关闭';
    case 'TRADE_CLOSED_BY_TAOBAO':
      return '付款以前，卖家或买家主动关闭交易';
    case 'PAY_PENDING':
      return '国际信用卡支付付款确认中';
    case 'WAIT_PRE_AUTH_CONFIRM':
      return '0元购合约中';
    case 'PAID_FORBID_CONSIGN':
      return '拼团中订单或者发货强管控的订单，已付款但禁止发货';
    default:
      return '其他状态，待更新';
  }
};
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;
};
onMounted(() => {
  fetchData();
});
</script>
