import { orderPage, orderExport, orderRefund } from '@/services/order';
import { exportData } from '@/utils/func';
import React, { useRef, useEffect, useState } from 'react';
import { useIntl, useAccess } from '@umijs/max';
import { message, Tag, Col, Row, Card, Image, Button, Select } from 'antd';
import { ActionType, PageContainer, ProTable } from '@ant-design/pro-components';
import BonusFormModal from './components/BonusFormModal';
import EscFormModal from './components/EscFormModal';
import { usersPage } from '@/services/user/user';



const LogTableList: React.FC = () => {
    const actionRef = useRef<ActionType>();
    const [searchParams, setSearchParams] = useState(null);
    const [bonusFormModal, setBonusFormModal] = useState(false);
    const [row, setRow] = useState();
    const [selectedRowsState, setSelectedRows] = useState([]);
    const [escFormModal, setEscFormModal] = useState(false);
    const access = useAccess()
    const count = useState({})


    const [shopOption, setShopOption] = useState([]);
    const searchShop = async (value) => {
        const { success, data } = await usersPage({
            userName: value
        });
        data.records.map((i) => {
            i.userName = i.userName + ' ' + i.phone
        })
        setShopOption(data.records)
    }


    const columns = [
        {
            title: '订单号',
            dataIndex: 'orderNo',
            valueType: 'text',
            search: true,
            render: (_: any, record: any) => {
                return <div className={'flex items-center'}>
                    {record.orderNo}
                    <Button type="link" onClick={() => {
                        setRow(record);
                        setBonusFormModal(true);
                    }}>查看</Button>
                </div>
            }
        },
        {
            title: '用户信息',
            dataIndex: 'usersId',
            valueType: 'text',
            render: (_: any, record: any) => {
                return <div className={'flex'}>
                    <div>
                        <div>
                            用户ID：{record?.usersDto?.id}
                        </div>
                        <div>
                            用户昵称：{record?.usersDto?.nickName || '-'}
                        </div>
                        <div>
                            用户账号：{record?.usersDto?.userName}
                        </div>
                        <div>
                            手机号：{record?.usersDto?.phone || '-'}
                        </div>
                    </div>
                </div>
            },
            renderFormItem: (
                _,
                { type, defaultRender, formItemProps, fieldProps, ...rest },
                form,
            ) => {
                return <Select
                    {...fieldProps}
                    allowClear
                    showSearch
                    placeholder="请输入用户名"
                    style={{ width: "100%" }}
                    filterOption={false}
                    onSearch={
                        (e) => {
                            if (!e) {
                                return;
                            }
                            searchShop(e);
                        }
                    }
                    fieldNames={{
                        label: "userName",
                        value: "id"
                    }}
                    options={shopOption}
                />
            },
        },
        {
            title: '商品信息',
            dataIndex: 'ordersGoodsList',
            valueType: 'text',
            search: false,
            render: (_: any, record: any) => {
                return record.ordersGoodsList ? record.ordersGoodsList.map((i) => {
                    let _Img = null
                    if (i?.sourceType == 1) {
                        _Img = i?.goodsSnapshot?.picture ? JSON.parse(i?.goodsSnapshot?.picture)[0] : ''
                    } else {
                        _Img = i?.goodsPackagesSnapshot?.picture ? JSON.parse(i?.goodsPackagesSnapshot?.picture)[0] : ''
                    }

                    return <div className={'flex items-center'} key={i.id}>
                        <Image width={60} src={_Img} height={60}></Image>
                        <div>
                            <div>
                                商品名称：{i?.sourceType == 1 ? i?.goodsSnapshot?.goodsName : i?.goodsPackagesSnapshot?.packagesName}
                            </div>
                            <div>
                                商品价格：{i?.sourceType == 1 ? i?.goodsSnapshot?.salePrice : i?.goodsPackagesSnapshot?.salePrice}
                            </div>
                        </div>
                    </div>
                }) : '-'
            }
        },
        {
            title: '订单金额',
            dataIndex: 'amount',
            valueType: 'text',
            search: false,
        },
        {
            title: '订单利润',
            dataIndex: 'profit',
            valueType: 'text',
            search: false,
        },
        {
            title: '支付类型',
            dataIndex: 'orderPlatform',
            valueType: 'text',
            search: true,
            render: (_: any, record: any) => {
                let color = record.orderPlatform == 1 ? 'volcano' : record.orderPlatform == 2 ? 'orange' : 'red'
                return <Tag color={color}>{record.orderPlatform == 1 ? '钱包' : record.orderPlatform == 2 ? '钱包' : record.orderPlatform == 3 ? '支付宝' : '-'}</Tag>
            },
            renderFormItem: (
                _,
                { type, defaultRender, formItemProps, fieldProps, ...rest },
                form,
            ) => {
                const statusMap = [
                    { label: '微信', value: 2 },
                    { label: '支付宝', value: 3 },
                    { label: '钱包', value: 1 },
                ]
                return <Select
                    {...fieldProps}
                    allowClear
                    style={{ width: "100%" }}
                    filterOption={false}
                    fieldNames={{
                        label: "label",
                        value: "value"
                    }}
                    options={statusMap}
                />
            },
        },
        {
            title: '订单状态',
            dataIndex: 'status',
            valueType: 'text',
            search: true,
            render: (_: any, record: any) => {
                let colors = ['gold', 'green', 'volcano', 'red', 'magenta']
                return <Tag color={colors[record.status]}>{record.status == 0 ? '待支付' : record.status == 1 ? '支付成功' : record.status == -1 ? '取消' : record.status == -2 ? '退款' : ''}</Tag>
            },
            renderFormItem: (
                _,
                { type, defaultRender, formItemProps, fieldProps, ...rest },
                form,
            ) => {
                const statusMap = [
                    { label: '待支付', value: 0 },
                    { label: '支付成功', value: 1 },
                    { label: '取消', value: -1 },
                    { label: '退款', value: -2 },
                ]
                return <Select
                    {...fieldProps}
                    allowClear
                    style={{ width: "100%" }}
                    filterOption={false}
                    fieldNames={{
                        label: "label",
                        value: "value"
                    }}
                    options={statusMap}
                />
            },
        },
        {
            title: '备注',
            dataIndex: 'remarks',
            valueType: 'text',
            search: false,
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            valueType: 'dateRange',
            search: {
                transform: (value) => {
                    return {
                        createTimeBegin: value[0],
                        createTimeEnd: value[1],
                    };
                },
            },
            render: (_, record) => {
                return record?.createTime
            },
        },
    ];

    const escSubmit = async (fields) => {
        const { success } = await orderRefund(fields);
        if (success) {
            message.success('退单成功');
            actionRef.current?.reload();
            setEscFormModal(false);
        }
    }

    return (
        <PageContainer>
            <Row gutter={10} className='mb-30'>
                <Col span={6}>
                    <Card>
                        <div>汇总</div>
                        <div>金额: {count?.all0?.money}</div>
                        <div className='flex '>
                            <div>订单数：{count?.all0?.order_num}</div>
                            <div className='w-6'></div>
                            <div>商品数：{count?.all0?.goods_num}</div>
                        </div>
                    </Card>
                </Col>
                <Col span={6}>
                    <Card>
                        <div>微信支付</div>
                        <div>金额: {count?.all1?.money}</div>
                        <div className='flex '>
                            <div>订单数：{count?.all1?.order_num}</div>
                            <div className='w-6'></div>
                            <div>商品数：{count?.all1?.goods_num}</div>
                        </div>
                    </Card>
                </Col>
                <Col span={6}>
                    <Card>
                        <div>余额支付</div>
                        <div>金额: {count?.all3?.money}</div>
                        <div className='flex '>
                            <div>订单数：{count?.all3?.order_num}</div>
                            <div className='w-6'></div>
                            <div>商品数：{count?.all3?.goods_num}</div>
                        </div>
                    </Card>
                </Col>
                <Col span={6}>
                    <Card>
                        <div>线下支付</div>
                        <div>金额: {count?.all4?.money}</div>
                        <div className='flex '>
                            <div>订单数：{count?.all4?.order_num}</div>
                            <div className='w-6'></div>
                            <div>商品数：{count?.all4?.goods_num}</div>
                        </div>
                    </Card>
                </Col>
            </Row>
            <div style={{ width: '100%', float: 'right', marginTop: "20px" }}>

                <EscFormModal
                    modalOpenState={escFormModal}
                    onModalOpenState={setEscFormModal}
                    onSubmit={escSubmit}
                />
                <BonusFormModal
                    values={row}
                    modalOpenState={bonusFormModal}
                    onModalOpenState={setBonusFormModal}
                />
                <ProTable
                    actionRef={actionRef}
                    rowKey="id"
                    key="logList"
                    search={{
                        labelWidth: 120,
                        defaultCollapsed: false,
                    }}
                    toolBarRender={() => [
                        <Button
                            danger
                            hidden={!access.hasPerms('/api/orders/orderRefund')}
                            onClick={() => {
                                setEscFormModal(true);
                            }}
                        >
                            退单
                        </Button>,
                        <Button hidden={!access.hasPerms('/api/orders/export')} type="primary" onClick={async () => {
                            let _res: any = await orderExport(searchParams)
                            exportData(_res, '订单信息')
                        }}>导出表格</Button>
                    ]}
                    request={async (params, sorter, filter) => {
                        setSearchParams({ ...params });
                        let { data } = await orderPage(params)
                        return {
                            data: data?.records || [],
                            total: data?.total,
                        };
                    }}
                    rowSelection={{
                        onChange: (_, selectedRows) => {
                            setSelectedRows(selectedRows)
                        },
                    }}
                    columns={columns}
                />
            </div>
        </PageContainer>
    );
};

export default LogTableList;
