import React, { useEffect, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { DownloadOutlined } from '@ant-design/icons';
import { Button, Table, Card, DatePicker, message, Pagination, Spin, TreeSelect } from 'antd';
import styles from './index.less';
import moment from 'moment';
import marketAPI from "./service";
import ExportJsonExcel from "js-export-excel"

const { TreeNode } = TreeSelect;
const { RangePicker } = DatePicker;
const columns = [
    {
        title: '时间',
        dataIndex: 'date',
        key: 'date',
        width: 170,
        align: 'center',
        fixed: 'left'
    },
    {
        title: '店铺',
        dataIndex: 'shopName',
        key: 'shopName',
        width: 170,
        align: 'center',
        fixed: 'left',
        filters: [
            {
                text: '四川黑菠萝科技',
                value: '四川黑菠萝科技',
            },
            {
                text: '四川白菠萝科技',
                value: '四川白菠萝科技',
            }
        ],
        onFilter: (value, record) => record.shopName.indexOf(value) === 0,
    },
    {
        title: '营收',
        dataIndex: 'revenue',
        key: 'revenue',
        children: [
            {
                title: '营业额',
                dataIndex: 'turnover',
                key: 'turnover',
                children: [
                    {
                        title: '流水',
                        dataIndex: 'revenueFlow',
                        key: 'revenueFlow',
                        width: 100,
                        align: 'center',
                    },
                    {
                        title: '实收',
                        dataIndex: 'paidAmount',
                        key: 'paidAmount',
                        width: 100,
                        align: 'center',
                    },
                ]
            },
            {
                title: '优惠明细',
                dataIndex: 'discountDetails',
                key: 'discountDetails',
                children: [
                    {
                        title: '会员价',
                        dataIndex: 'discountMember',
                        key: 'discountMember',
                        width: 100,
                        align: 'center',
                    },
                    {
                        title: '优惠券',
                        dataIndex: 'discountCoupon',
                        key: 'discountCoupon',
                        width: 100,
                        align: 'center',
                    },
                    {
                        title: '活动',
                        dataIndex: 'discountActivity',
                        key: 'discountActivity',
                        width: 100,
                        align: 'center',
                    }
                ]
            },
        ]
    },
    {
        title: '分类营收',
        dataIndex: 'classifiedRevenue',
        key: 'classifiedRevenue',
        children: [
            {
                title: '外卖营业额',
                dataIndex: 'takeOutTurnover',
                key: 'takeOutTurnover',
                children: [
                    {
                        title: '外卖营收',
                        dataIndex: 'takeOutRevenue',
                        key: 'takeOutRevenue',
                        width: 100,
                        align: 'center',
                    },
                    {
                        title: '美团外卖',
                        dataIndex: 'meituanTakeout',
                        key: 'meituanTakeout',
                        width: 100,
                        align: 'center',
                    },
                    {
                        title: '饿了么外卖',
                        dataIndex: 'hungryTakeOut',
                        key: 'hungryTakeOut',
                        width: 100,
                        align: 'center',
                    },
                ]
            },
            {
                title: '食堂营收',
                dataIndex: 'canteenRevenue',
                key: 'canteenRevenue',
                children: [
                    {
                        title: '堂食流水',
                        dataIndex: 'freshWaterInTheHall',
                        key: 'freshWaterInTheHall',
                        width: 100,
                        align: 'center',
                    },
                    {
                        title: '堂食实收',
                        dataIndex: 'paidInFood',
                        key: 'paidInFood',
                        width: 100,
                        align: 'center',
                    }
                ]
            },
            {
                title: '第三方平台营收',
                dataIndex: 'thirdPartyPlatformRevenue',
                key: 'thirdPartyPlatformRevenue',
                children: [
                    {
                        title: '大众点评',
                        dataIndex: 'publicComments',
                        key: 'publicComments',
                        width: 100,
                        align: 'center',
                    },
                    {
                        title: '口碑',
                        dataIndex: 'wordOfMouth',
                        key: 'wordOfMouth',
                        width: 100,
                        align: 'center',
                    },
                    {
                        title: '抖音',
                        dataIndex: 'tiktok',
                        key: 'tiktok',
                        width: 100,
                        align: 'center',
                    }
                ]
            },
        ]
    },
    {
        title: '堂食单价',
        dataIndex: 'unitPriceCanteenFood',
        key: 'unitPriceCanteenFood',
        children: [
            {
                title: '客单价',
                dataIndex: 'customerUnitPrice',
                key: 'customerUnitPrice',
                children: [
                    {
                        title: '流水单价',
                        dataIndex: 'customerRevenueFlow',
                        key: 'customerRevenueFlow',
                        width: 100,
                        align: 'center',
                    },
                    {
                        title: '实收单价',
                        dataIndex: 'customerPaidAmount',
                        key: 'customerPaidAmount',
                        width: 100,
                        align: 'center',
                    }
                ]
            },
            {
                title: '单单价',
                dataIndex: 'singleUnitPrice',
                key: 'singleUnitPrice',
                children: [
                    {
                        title: '流水单价',
                        dataIndex: 'orderRevenueFlow',
                        key: 'orderRevenueFlow',
                        width: 100,
                        align: 'center',
                    },
                    {
                        title: '实收单价',
                        dataIndex: 'orderPaidAmount',
                        key: 'orderPaidAmount',
                        width: 100,
                        align: 'center',
                    }
                ]
            },
        ]
    },
    {
        title: '交易笔数',
        dataIndex: 'numberOfTransactions',
        key: 'numberOfTransactions',
        children: [
            {
                title: '现金',
                dataIndex: 'sourceCashCount',
                key: 'sourceCashCount',
                width: 100,
                align: 'center',
            },
            {
                title: '微信支付',
                dataIndex: 'sourceWeChatCount',
                key: 'sourceWeChatCount',
                width: 100,
                align: 'center',
            },
            {
                title: '大众点评',
                dataIndex: 'numPublicComments',
                key: 'numPublicComments',
                width: 100,
                align: 'center',
            },
            {
                title: '口碑',
                dataIndex: 'numWordOfMouth',
                key: 'numWordOfMouth',
                width: 100,
                align: 'center',
            },
            {
                title: '抖音',
                dataIndex: 'numTiktok',
                key: 'numTiktok',
                width: 100,
                align: 'center',
            },
            {
                title: '美团外卖',
                dataIndex: 'numMeituanTakeout',
                key: 'numMeituanTakeout',
                width: 100,
                align: 'center',
            },
            {
                title: '饿了么外卖',
                dataIndex: 'numHungryTakeOut',
                key: 'numHungryTakeOut',
                width: 100,
                align: 'center',
            },
        ]
    },
    {
        title: '收入构成',
        dataIndex: 'revenueComposition',
        key: 'revenueComposition',
        children: [
            {
                title: '收入来源',
                dataIndex: 'sourceOfIncome',
                key: 'sourceOfIncome',
                children: [
                    {
                        title: '会员',
                        dataIndex: 'memberIncomeMoney',
                        key: 'memberIncomeMoney',
                        width: 100,
                        align: 'center',
                    },
                    {
                        title: '非会员',
                        dataIndex: 'nonMemberIncomeMoney',
                        key: 'nonMemberIncomeMoney',
                        width: 100,
                        align: 'center',
                    },
                    {
                        title: '外卖',
                        dataIndex: 'incomeTakeOut',
                        key: 'incomeTakeOut',
                        width: 100,
                        align: 'center',
                    },
                    {
                        title: '团购',
                        dataIndex: 'incomeGroupPurchase',
                        key: 'incomeGroupPurchase',
                        width: 100,
                        align: 'center',
                    },
                ]
            },
            {
                title: '收入结构',
                dataIndex: 'revenueStructure',
                key: 'revenueStructure',
                children: [
                    {
                        title: '微信支付',
                        dataIndex: 'sourceWeChatMoney',
                        key: 'sourceWeChatMoney',
                        width: 100,
                        align: 'center',
                    },
                    {
                        title: '现金支付',
                        dataIndex: 'sourceCashMoney',
                        key: 'sourceCashMoney',
                        width: 100,
                        align: 'center',
                    },
                    {
                        title: '大众点评',
                        dataIndex: 'incomePublicComments',
                        key: 'incomePublicComments',
                        width: 100,
                        align: 'center',
                    },
                    {
                        title: '口碑',
                        dataIndex: 'incomeWordOfMouth',
                        key: 'incomeWordOfMouth',
                        width: 100,
                        align: 'center',
                    },
                    {
                        title: '抖音',
                        dataIndex: 'incomeTiktok',
                        key: 'incomeTiktok',
                        width: 100,
                        align: 'center',
                    },
                    {
                        title: '美团外卖',
                        dataIndex: 'incomeMeituan',
                        key: 'incomeMeituan',
                        width: 100,
                        align: 'center',
                    },
                    {
                        title: '饿了么外卖',
                        dataIndex: 'incomeHungry',
                        key: 'incomeHungry',
                        width: 100,
                        align: 'center',
                    },
                ]
            },
        ]
    }
]

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

/**
 * 营收报表
 * @returns 
 */
export default function Index() {

    const [data, setData] = useState([]);
    const [current, setCurrent] = useState(1);
    const [pageSize, setPageSize] = useState(10);
    const [total, setTotal] = useState(0);
    const [orgTree, setOrgTree] = useState([]);
    const [showLoading, setShowLoading] = useState(false);
    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')),
    ]);	//日期选择器
    const [currentOrg, setCurrentOrg] = useState('');

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

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

    //计算总计
    const calcTotal = () => {
        const originData = JSON.parse(JSON.stringify(data));
        const totalData = {}
        data.forEach(dataObj => {
            Object.keys(dataObj).forEach(key => {
                if (key === 'date') {
                    totalData.date = '合计';
                } else if (key == 'shopName') {
                    totalData.shopName = '';
                } else if (typeof dataObj[key] === 'number') {
                    if (totalData[key] && typeof totalData[key] === 'number') {
                        totalData[key] += dataObj[key];
                    } else {
                        totalData[key] = 0;
                        totalData[key] += dataObj[key];
                    }
                } else {
                    totalData[key] = '暂无统计'
                }
            });
        });
        originData.push(totalData);
        setData(originData);
    }

    const queryMarketReport = async () => {
        const jsonData = {
            startTime: timeRange[0],
            endTime: timeRange[1],
            current: current,
            pageSize: pageSize
        }
        currentOrg.key && (jsonData.shopId = currentOrg.key);
        setShowLoading(true);
        const response = await marketAPI.getMarketReportList(jsonData);
        setShowLoading(false);
        if (response.statusCode === 200) {
            setData(response.data.data);
            setTotal(response.data.total);
        } else {
            message.error(response.errors || '获取营销报表失败');
        }
    }

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

    //下载Excel
    const onDownloadExcel = async () => {
        const jsonData = {
            startTime: timeRange[0],
            endTime: timeRange[1],
        }
        currentOrg.key && (jsonData.shopId = currentOrg.key);
        setShowLoading(true);
        const response = await marketAPI.marketingReportExport(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);
            });
            console.log('sheetHeader', sheetHeader);
            option.datas = [
                {
                    sheetData: response.data,            //excel文件中的数据源
                    sheetName: excelName,       //excel文件中sheet页名称
                    sheetFilter: sheetHeader,   //excel文件中需显示的列数据
                    sheetHeader: ['ID', '时间', '店铺名称', '店铺ID', '营收流水',
                        '实际营收', '会员折扣', '优惠券折扣', '活动折扣','客单价-流水单价', '客单价-实收单价', 
                        '单单价-总流水', '单单价-总实收',
                        '现金-交易笔数', '现金收入', '微信-交易笔数', '微信收入', '会员收入', '非会员收入'
                    ]    //excel文件中每列的表头名称
                }
            ]
            let toExcel = new ExportJsonExcel(option);  //生成excel文件
            toExcel.saveExcel();
        } else {
            message.error(response.errors || '导出失败');
        }
    }

    //获取组织树
    const onGetOrgTree = async () => {
        setShowLoading(true);
        const response = await marketAPI.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;
                }
            }
        });
    }

    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) => {
                                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={queryMarketReport}>查询</Button>
                    </div>
                </div>
            </Card>
            <Card className={styles['table-card']}>
                <Table dataSource={data} columns={columns} bordered={true} sticky={true} scroll={{ x: 1000 }} pagination={false}>
                </Table>
                <div className={styles['table-page']}>
                    <Pagination current={current} pageSize={pageSize} total={total} onChange={onPageChange} />
                </div>
            </Card>
        </PageContainer>
    )
}
