import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Button, Card, DatePicker, Table, message, Pagination, Space, Tag, Spin, TreeSelect } from 'antd';
import styles from './index.less';
const { RangePicker } = DatePicker;
import orderReportAPI from "./service";
import moment from 'moment';
import { history } from "umi";
import { CheckCircleOutlined, CloseCircleOutlined, DownloadOutlined } from '@ant-design/icons';
import ExportJsonExcel from "js-export-excel"

const columns = [
    {
        title: '交易单号',
        dataIndex: 'transactionId',
        key: 'transactionId',
    },
    {
        title: '店铺名称',
        dataIndex: 'shopName',
        key: 'shopName',
    },
    {
        title: '原价（￥）',
        dataIndex: 'orderOriginalMoney',
        key: 'orderOriginalMoney',
    },
    {
        title: '优惠（￥）',
        dataIndex: 'discountMoney',
        key: 'discountMoney',
    },
    {
        title: '实际支付（￥）',
        dataIndex: 'orderRealMoney',
        key: 'orderRealMoney',
    },
    {
        title: '创建时间',
        dataIndex: 'createdAt',
        key: 'createdAt',
    },
    {
        title: '订单状态',
        key: 'orderStatus',
        render: (record) => {
            let orderStatus = '';
            switch (record.orderStatus) {
                case 0:
                    orderStatus = '未付款';
                    break;
                case 1:
                    orderStatus = '已付款';
                    break;
                case -1:
                    orderStatus = '退单申请';
                    break;
                case -2:
                    orderStatus = '退单中';
                    break;
                case -3:
                    orderStatus = '已退单';
                    break;
                case -4:
                    orderStatus = '取消交易';
                    break;
                case -5:
                    orderStatus = '撤销申请';
                    break;
            }
            return (
                <>
                    {
                        <Tag icon={<CheckCircleOutlined />} color="success">
                            {orderStatus}
                        </Tag>
                    }
                </>
            )
        },
    },
    {
        title: '售后信息',
        key: 'orderStatus',
        render: (record) => {
            return (
                <>
                    {
                        record.isRefund ? <Tag color="error">
                            有
                        </Tag>
                            :
                            <Tag color="success">
                                无
                            </Tag>
                    }
                </>
            )
        },
    },
    {
        title: '操作',
        key: 'action',
        render: (_, record) => (
            <Space size="middle">
                <a onClick={() => {
                    history.push({
                        pathname: '/order/order-report/order-report-detail',
                        query: {
                            orderNumber: record.orderNumber
                        }
                    });
                }}>详情</a>
            </Space>
        ),
    },
];

const LoadingCard = () => {
    return (
        <div className={styles['loading-card']}>
            <Spin size="large" />
        </div>
    )
}

/**
 * 订单报表
 * @returns 
 */
export default function Index() {

    //订单报表列表
    const [orderReportList, setOrderReportList] = useState([]);
    const [current, setCurrent] = useState(1);
    const [pageSize, setPageSize] = useState(10);
    const [total, setTotal] = useState(0);
    const [showLoading, setShowLoading] = useState(false);
    const [currentOrg, setCurrentOrg] = useState('');
    const [orgTree, setOrgTree] = useState([]);


    const [timeRange, setTimeRange] = useState([
        moment(moment(new Date(Date.now() - 24 * 60 * 60 * 1000 * 7)).format('YYYY-MM-DD 00:00:00')),
        moment(moment(new Date(Date.now())).format('YYYY-MM-DD 23:59:59')),
    ]);	//日期选择器

    useEffect(() => {
        onQueryOrderReportList();
    }, [current, pageSize]);


    useEffect(() => {
        onGetOrgTree();
    }, []);


    //获取订单列表
    const onQueryOrderReportList = async () => {
        const jsonData = {
            startTime: timeRange[0],
            endTime: timeRange[1],
            current,
            pageSize
        }
        currentOrg.key && (jsonData.shopId = currentOrg.key);
        setShowLoading(true);
        const response = await orderReportAPI.getOrderReportList(jsonData);
        setShowLoading(false);
        if (response.statusCode === 200) {
            setOrderReportList(response.data.data);
            setTotal(response.data.total)
        } else {
            message.error(response.errors || '获取订单报表列表失败');
        }
    }

    //页码变化
    const onPageChange = (current, pageSize) => {
        setCurrent(current);
        setPageSize(pageSize);
    }

    //获取组织树
    const onGetOrgTree = async () => {
        setShowLoading(true);
        const response = await orderReportAPI.getOrgTree();
        setShowLoading(false);
        if (response.statusCode === 200) {
            const originTree = response.data;
            onSetOrgTreeStatus(originTree);
            setOrgTree(originTree);
        } else {
            message.error(response.errors || '获取组织树出错');
        }
    }

    //设置组织树不可选择状态
    const onSetOrgTreeStatus = (originTree) => {
        originTree.forEach(treeItem => {
            if (treeItem.children && treeItem.children.length > 0) {
                onSetOrgTreeStatus(treeItem.children);
            } else {
                if (treeItem.type === 2 || treeItem.type === 3) {
                    treeItem.disabled = false;
                } else {
                    treeItem.disabled = true;
                }
            }
        });
    }

    //下载Excel
    const onDownloadExcel = async () => {
        const jsonData = {
            startTime: timeRange[0],
            endTime: timeRange[1],
        }
        currentOrg.key && (jsonData.shopId = currentOrg.key);
        setShowLoading(true);
        const response = await orderReportAPI.orderReportExport(jsonData);
        setShowLoading(false);
        if (response.statusCode === 200) {
            let option = {};  //option代表的就是excel文件
            const date = new Date();
            const excelName = "订单报表-" + date.toLocaleString().replaceAll('\/', '-');
            option.fileName = excelName;  //excel文件名称
            const sheetHeader = [];
            Object.keys(response.data[0]).forEach(item => {
                sheetHeader.push(item);
            });
            option.datas = [
                {
                    sheetData: response.data,            //excel文件中的数据源
                    sheetName: excelName,       //excel文件中sheet页名称
                    sheetFilter: sheetHeader,   //excel文件中需显示的列数据
                    sheetHeader: ['ID', '取餐号', '用户Id', '优惠合集', '订单号（本系统）',
                        '交易号', '店铺ID', '店铺名字', '商品总价', '优惠金额', '实付金额',
                        '创建时间', '支付金额异常',
                        '订单支付时间异常', '订单异常', '售后金额异常', '售后时间异常', '售后订单异常'
                    ]    //excel文件中每列的表头名称
                }
            ]
            let toExcel = new ExportJsonExcel(option);  //生成excel文件
            toExcel.saveExcel();
        } else {
            message.error(response.errors || '导出失败');
        }
    }

    return (
        <PageContainer>
            {showLoading ? <LoadingCard></LoadingCard> : null}
            <Card className={styles['data-search-card']}>
                <div className={styles['data-search-box']}>
                    <div className={styles['data-search-left']}>
                        <RangePicker className={styles['my-range-picker']} value={timeRange} onChange={(date, dateStrings) => {
                            let tempDate = [
                                moment(moment(new Date(dateStrings[0])).format('YYYY-MM-DD 00:00:00')),
                                moment(moment(new Date(dateStrings[1])).format('YYYY-MM-DD 23:59:59')),
                            ]
                            setTimeRange(tempDate);
                        }} />
                        <TreeSelect
                            style={{
                                width: '300px',
                                marginLeft: '50px'
                            }}
                            dropdownStyle={{
                                maxHeight: 400,
                                overflow: 'auto',
                            }}
                            treeData={orgTree}
                            onSelect={(value, node) => {
                                console.log('node>>>', node);
                                if (node.type === 2 || node === 3) {
                                    setCurrentOrg(node);
                                } else {
                                    setCurrentOrg("");
                                }
                            }}
                            placeholder="请选择组织架构"
                            treeDefaultExpandAll
                        />
                    </div>
                    <div className={styles['data-search-btns']}>
                        <Button type="primary" icon={<DownloadOutlined />} size='middle' onClick={onDownloadExcel}>
                            下载
                        </Button>
                        <Button className={styles['search-btn-item']}>重置</Button>
                        <Button className={styles['search-btn-item']} type="primary" onClick={onQueryOrderReportList}>查询</Button>
                    </div>
                </div>
            </Card>
            <Card className={styles['table-card']}>
                <Table dataSource={orderReportList} columns={columns} pagination={false} />
                <div className={styles['table-page']}>
                    <Pagination current={current} pageSize={pageSize} total={total} onChange={onPageChange} />
                </div>
            </Card>
        </PageContainer>
    )
}
