import React, { useState, useEffect } from 'react';
import { useAjax } from "@/Hook/useAjax";
import { Button, Card, Select, Input, Badge, Table, Tag } from "antd";
import { SearchOutlined } from "@ant-design/icons";
import SearchBox from "@/pages/weComTask/components/searchBox";
import { getLicenseOrderListApi, GetLicenseOrderListProps } from "@/pages/weComTask/API/weChatApiLicense";
import { copy } from "@/utils/utils";

const orderTypeEnum = {
    1: <Tag color="#f50">购买账号</Tag>,
    2: <Tag color="#2db7f5">续期账号</Tag>,
    5: <Tag color="#87d068">应用版本付费迁移订单</Tag>,
    6: <Tag color="#108ee9">历史合同迁移订单</Tag>
}

const orderStatusEnum = {
    0: <Badge status="processing" text="待支付" />,
    1: <Badge status="success" text="已支付" />,
    2: <Badge status="default" text="已取消（未支付，订单已关闭）" />,
    3: <Badge status="default" text="未支付，订单已过期" />,
    4: <Badge status="warning" text="申请退款中" />,
    5: <Badge status="error" text="退款成功" />,
    6: <Badge status="error" text="退款被拒绝" />,
    7: <Badge status="warning" text="订单已失效" />,
}


const EnterpriseOrder: React.FC = () => {

    /***********************************/
    const [queryParams, setQueryParams] = useState<GetLicenseOrderListProps>({ pageNum: 1, pageSize: 20 })
    const [oldQueryParams, setOldQueryParams] = useState<GetLicenseOrderListProps>({ pageNum: 1, pageSize: 20 })

    const getLicenseOrderList = useAjax((params) => getLicenseOrderListApi(params))
    /***********************************/

    useEffect(() => {
        getLicenseOrderList.run(queryParams)
    }, [queryParams])

    return <Card>
        <SearchBox
            bodyPadding={`0 0 10px`}
            buttons={<>
                <Button type="primary" onClick={() => {
                    setQueryParams({ ...oldQueryParams, pageNum: 1, pageSize: queryParams.pageSize })
                }} loading={getLicenseOrderList.loading} icon={<SearchOutlined />}>搜索</Button>
            </>}
        >
            <>
                <Input
                    placeholder="企业名称"
                    style={{ width: 120 }}
                    allowClear
                    onChange={(e) => setOldQueryParams({ ...oldQueryParams, corpName: e.target.value })}
                    value={oldQueryParams?.corpName}
                />
                <Input
                    placeholder="订单号"
                    style={{ width: 120 }}
                    allowClear
                    onChange={(e) => setOldQueryParams({ ...oldQueryParams, orderId: e.target.value })}
                    value={oldQueryParams?.orderId}
                />
                <Select
                    allowClear
                    placeholder="订单类型"
                    showSearch
                    options={Object.keys(orderTypeEnum).map(key => ({ label: orderTypeEnum[key], value: key }))}
                    filterOption={(input, option) =>
                        ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                    }
                    style={{ width: 160 }}
                    value={oldQueryParams?.orderType}
                    onChange={(e) => setOldQueryParams({ ...oldQueryParams, orderType: e })}
                />
                <Select
                    allowClear
                    placeholder="订单状态"
                    showSearch
                    options={Object.keys(orderStatusEnum).map(key => ({ label: orderStatusEnum[key], value: key }))}
                    filterOption={(input, option) =>
                        ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                    }
                    style={{ width: 160 }}
                    value={oldQueryParams?.orderStatus}
                    onChange={(e) => setOldQueryParams({ ...oldQueryParams, orderStatus: e })}
                />
            </>
        </SearchBox>

        {/* 表 */}
        <Table
            style={{ marginTop: 10 }}
            dataSource={getLicenseOrderList?.data?.data?.records}
            loading={getLicenseOrderList?.loading}
            bordered
            columns={[
                {
                    title: '企业名称',
                    dataIndex: 'corpName',
                    key: 'corpName',
                    width: 200,
                    ellipsis: true,
                    render: (text) => <a onClick={() => copy(text)}>{text}</a>
                },
                {
                    title: '企业ID',
                    dataIndex: 'corpId',
                    key: 'corpId',
                    width: 280,
                    ellipsis: true,
                },
                {
                    title: '订单号',
                    dataIndex: 'orderId',
                    key: 'orderId',
                    width: 280,
                    ellipsis: true,
                },
                {
                    title: '订单类型',
                    dataIndex: 'orderType',
                    key: 'orderType',
                    width: 120,
                    align: 'center',
                    render: (text) => orderTypeEnum[text]
                },
                {
                    title: '订单状态',
                    dataIndex: 'orderStatus',
                    key: 'orderStatus',
                    width: 120,
                    align: 'center',
                    render: (text) => orderStatusEnum[text]
                },
                {
                    title: '订单金额',
                    dataIndex: 'price',
                    key: 'price',
                    width: 60,
                    align: 'right'
                },
                {
                    title: '席位数量',
                    dataIndex: 'accountCount',
                    key: 'accountCount',
                    width: 70,
                    align: 'center'
                },
                {
                    title: '下单时间',
                    dataIndex: 'createTime',
                    key: 'createTime',
                    width: 135,
                    align: 'center',
                    ellipsis: true,
                    render: (text) => text || '--'
                },
                {
                    title: '支付时间',
                    dataIndex: 'payTime',
                    key: 'payTime',
                    width: 135,
                    align: 'center',
                    ellipsis: true,
                    render: (text) => text || '--'
                },
                {
                    title: '更新时间',
                    dataIndex: 'updateTime',
                    key: 'updateTime',
                    width: 135,
                    align: 'center',
                    ellipsis: true,
                    render: (text) => text || '--'
                }
            ]}
            scroll={{ x: 1000 }}
            rowKey={'orderId'}
            size='small'
            pagination={{
                total: getLicenseOrderList?.data?.data?.total,
                showTotal: (total) => <Tag color="cyan">总共{total}数据</Tag>,
                showSizeChanger: true,
                showLessItems: true,
                defaultCurrent: 1,
                defaultPageSize: 20,//默认初始的每页条数
                current: getLicenseOrderList?.data?.data?.current || 1,
                pageSize: getLicenseOrderList?.data?.data?.size || 20,
            }}
            onChange={(pagination, _, sortData: any) => {
                let { current, pageSize } = pagination
                let newQueryForm = JSON.parse(JSON.stringify(queryParams))
                let newOldQueryParams = JSON.parse(JSON.stringify(oldQueryParams))
                if (sortData && sortData?.order) {
                    newQueryForm['sortAsc'] = sortData?.order === 'ascend' ? true : false
                    newQueryForm['sortFiled'] = sortData?.field
                } else {
                    delete newQueryForm['sortAsc']
                    delete newQueryForm['sortFiled']
                }
                newQueryForm.pageNum = current || newQueryForm.pageNum
                newQueryForm.pageSize = pageSize || newQueryForm.pageSize
                setQueryParams({ ...newQueryForm })
                setOldQueryParams({ ...newOldQueryParams })
            }}
        />
    </Card>
};

export default EnterpriseOrder;