import Constants from '@/constants';
import {
  getOrderPageForAdminUsingPost,
  exportOrderPageForAdminUsingPost,
  deliverGoodForOrderAdminUsingGet,
  confirmReceiveForOrderAdminUsingGet
} from '@/services/pop-b2b2c/pbcOrderController';
import { isNumeric } from '@/utils/utils';
import { ActionType, ProFormInstance, ProList } from '@ant-design/pro-components';
import { PageContainer } from '@ant-design/pro-layout';
import { Access, history, useAccess } from '@umijs/max';
import { Button, message, Tag, Table } from 'antd';
import React, { useRef, useState } from 'react';
import './index.less';

/**
 * 查询表格
 * @param param0
 */
const fetchData = async (params: any) => {
  const msg = await getOrderPageForAdminUsingPost(params);
  return {
    data: msg.data?.records,
    total: msg.data?.total,
    success: msg.retcode,
  } as any;
};

const handleExport = async (values?: API.PbcOrder_) => {
  
  const hide = message.loading('正在处理', 0);
  try {
    await exportOrderPageForAdminUsingPost(
      { ...values },
      {
        responseType: 'blob',
        getResponse: true,
        parseResponse: false,
        data: { ...values, fileName: '导出' },
      },
    );
    hide();
    return false;
  } catch (error) {
    console.log(error);
    hide();
    message.error('处理失败，请重试');
    return false;
  }
};


// eslint-disable-next-line @typescript-eslint/ban-types
const TableList: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const access: any = useAccess();
  const ref = useRef<ProFormInstance<API.PbcOrder_>>();
  const [tabActiveKey, setTabActiveKey] = useState<string>('0'); // 默认显示全部样单

  return (
    <PageContainer
      header={{
        title: '',
        breadcrumb: {},
      }}
      tabActiveKey={tabActiveKey}
      onTabChange={(key) => setTabActiveKey(key)}
      tabList={[
        {
          tab: "全部",
          key: "0"
        },
        {
          tab: "预订单",
          key: "1"
        },
        {
          tab: "已配货",
          key: "2"
        },
        {
          tab: "已完成",
          key: "4"
        },
        {
          tab: "已取消",
          key: "3"
        },
      ]}
    >
      <ProList<API.PbcOrder_>
        rowKey="pbcId"
        actionRef={actionRef}
        formRef={ref}
        itemLayout='vertical'
        request={(param: any) => {
          const queryParam = {
            ...param,
            pbcOrderState: tabActiveKey !== '0' ? parseInt(tabActiveKey) : undefined
          };
          return fetchData(queryParam);
        }}
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: true,
        }}
        search={{
          labelWidth: 'auto',
          span: 6,
        }}
        params={{ pbcOrderState: tabActiveKey !== '0' ? parseInt(tabActiveKey) : undefined }}
        dateFormatter="string"
        toolBarRender={() => [
          <Access key="export" accessible={access.orderExport}>
            <Button
              type="primary"
              onClick={() => {
                const params = ref.current?.getFieldsValue();
                handleExport(params);
              }}
            >
              导出
            </Button>
          </Access>,
        ]}
        metas={{
          pbcOrderNo: {
            title: '订单编号',
          },
          productName: {
            title: '商品名称',
          },
          pbcOrderReceiverName: {
            title: '买家姓名',
          },
          pbcOrderReceiverPhone: {
            title: '买家手机号',
          },
          pbcBusinessName: {
            title: '所属商户',
          },
          pbcUpdateAt: {
            search: {
              transform: (value) => {
                return {
                  expectedStartTime: value[0],
                  expectedEndTime: value[1] + ' 23:59:59',
                };
              },
            },
            valueType: 'dateRange',
            title: '期望交货时间',
          },
          pbcCreateAt: {
            search: {
              transform: (value) => {
                return {
                  startTime: value[0],
                  endTime: value[1] + ' 23:59:59',
                };
              },
            },
            valueType: 'dateRange',
            title: '下单时间',
          },
          title: {
            search: false,
            render: (_, record) => (
              <div style={{ display: 'flex', alignItems: 'center', width: '100%', fontSize: 14 }}>
                <div style={{ display: 'flex', alignItems: 'center', width: '100%' }}>
                  <Tag color={Constants.orderStateEnum[String(record.pbcOrderState || 1)]?.status} style={{ marginRight: '8px' }}>
                    {Constants.orderStateEnum[String(record.pbcOrderState || 1)]?.text}
                  </Tag>
                  <Tag style={{ marginRight: '8px' }}>{Constants.orderTypeEnum[record.pbcOrderType || 1]?.text}</Tag>
                  <span style={{ marginRight: '16px' }}>订单编号: {record.pbcOrderNo}</span>
                  <span style={{ marginRight: '16px' }}>买家姓名: {record.pbcOrderReceiverName}</span>
                  <span style={{ marginRight: '16px' }}>买家手机号: {record.pbcOrderReceiverPhone}</span>
                  <span style={{ marginRight: '16px' }}>期望交货日期: {record.pbcExpectedDeliveryDate || '无'}</span>
                  <span style={{ marginRight: '16px' }}>下单时间: {record.pbcCreateAt}</span>
                  <span style={{ marginLeft: 'auto' }}>所属商户: {record.pbcBusinessName}</span>
                </div>
              </div>
            ),
          },
          content: {
            search: false,
            render: (_, record) => {
              const columns1 = [
                {
                  title: '商品名',
                  dataIndex: 'pbcProductName',
                  key: 'pbcProductName',
                  render: (text: string, item: API.PbcOrderItem_) => (
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                      {item.pbcProductImage && (
                        <img
                          src={item.pbcProductImage}
                          alt={item.pbcProductName}
                          style={{ width: 60, height: 60, marginRight: 12, objectFit: 'cover' }}
                        />
                      )}
                      <div>
                        <div style={{ fontWeight: 'bold' }}>{text}</div>
                        <div>颜色: {item.pbcSkuColorName || '默认'}</div>
                      </div>
                    </div>
                  ),
                },
                {
                  title: '单价',
                  dataIndex: 'pbcSkuPrice',
                  key: 'pbcSkuPrice',
                  render: (text: any) => typeof text === 'number' || (typeof text === 'string' && isNumeric(text)) ? `¥${text}` : text,
                  width: 100,
                },
                {
                  title: '数量',
                  dataIndex: 'pbcSkuCnt',
                  key: 'pbcSkuCnt',
                  width: 80,
                },
                {
                  title: '总金额',
                  key: 'totalPrice',
                  render: (_: any, item: API.PbcOrderItem_) => typeof item.pbcSkuPrice === 'number' || (typeof item.pbcSkuPrice === 'string' && isNumeric(item.pbcSkuPrice)) ? `¥${Number(item.pbcSkuPrice) * (item.pbcSkuCnt || 0)}` : item.pbcSkuPrice,
                  width: 100,
                },
                {
                  title: '实付金额',
                  key: 'actualPrice',
                  render: () => `-`,
                  width: 100,
                },
              ];
              
              return (
                <Table 
                  dataSource={record.orderItemList || []} 
                  columns={columns1} 
                  pagination={false} 
                  rowKey={(item) => item.pbcId || Math.random().toString(36).slice(2)}
                  size="small"
                  bordered
                />
              );
            },
          },
          actions: {
            render: (_, record) => [
              <Button key="detail" onClick={() => history.push(`/order/detail/${record.pbcId}`)}>详情</Button>,
              <Access key="manage" accessible={access.orderManage}>
                {record.pbcOrderState === 1 && (
                  <Button
                    type="primary"
                    onClick={() => {
                      deliverGoodForOrderAdminUsingGet({ orderId: record.pbcId || 0 }).then(
                        (res) => {
                          if (res.retcode) {
                            message.success('已配货完成');
                            actionRef.current?.reload();
                          } else {
                            message.error(res.retmsg);
                          }
                        },
                      );
                    }}
                  >
                    配货完成
                  </Button>
                )}
                {record.pbcOrderState === 2 && (
                  <Button
                    type="primary"
                    onClick={() => {
                      confirmReceiveForOrderAdminUsingGet({ orderId: record.pbcId || 0 }).then(
                        (res) => {
                          if (res.retcode) {
                            message.success('已完成交易');
                            actionRef.current?.reload();
                          } else {
                            message.error(res.retmsg);
                          }
                        },
                      );
                    }}
                  >
                    完成交易
                  </Button>
                )}
              </Access>
            ],
          },
        }}
        headerTitle=""
      />
    </PageContainer>
  );
};

export default TableList;