import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Col, Row, message } from 'antd';
import ConditionQuery from "../../../components/ConditionQuery";
import * as echarts from 'echarts';
import moment from 'moment';
import styles from './index.less';
import productAPI from "./service";
/**
 * 产品报表
 * @returns 
 */
export default function Index() {

    //日期选择下标：0：今天、1：昨天、2：近7天、3、近30天
    const [searchDayIndex, setSearchDayIndex] = useState(0);
    //日期选择器
    const [timeRange, setTimeRange] = useState([
        moment(moment(new Date(Date.now())).format('YYYY-MM-DD 00:00:00')),
        moment(moment(new Date(Date.now())).format('YYYY-MM-DD 23:59:59'))
    ]);
    //组织树
    const [orgTree, setOrgTree] = useState([]);
    //加载中
    const [showLoading, setShowLoading] = useState(false);
    //当前选中门店
    const [currentOrg, setCurrentOrg] = useState("");
    //产品Top
    const [topGoods, setTopGoods] = useState([]);

    //热销商品折线图实例
    let topGoodsLine = null;
    //热销商品柱状图实例
    let topGoodsBar = null;

    //切换时间
    const onChangeTimeIndex = (dayIndex) => {
        setSearchDayIndex(dayIndex);
        let tempDate = [];
        switch (dayIndex) {
            case 0:
                tempDate = [
                    moment(moment(new Date(Date.now())).format('YYYY-MM-DD 00:00:00')),
                    moment(moment(new Date(Date.now())).format('YYYY-MM-DD 23:59:59'))
                ]
                break;
            case 1:
                tempDate = [
                    moment(moment(new Date(Date.now() - 24 * 60 * 60 * 1000)).format('YYYY-MM-DD 00:00:00')),
                    moment(moment(new Date(Date.now() - 24 * 60 * 60 * 1000)).format('YYYY-MM-DD 23:59:59'))
                ]
                break;
            case 2:
                tempDate = [
                    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')),
                ]
                break;
            case 3:
                tempDate = [
                    moment(moment(new Date(Date.now() - 24 * 60 * 60 * 1000 * 30)).format('YYYY-MM-DD 00:00:00')),
                    moment(moment(new Date(Date.now())).format('YYYY-MM-DD 23:59:59')),
                ]
                break;
        }
        setTimeRange(tempDate);
    }

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

    //重置
    const onResetSearch = () => {
        setCurrentOrg("");
    }

    //子组件切换组织架构
    const onCurrentOrgChange = (curOrg) => {
        setCurrentOrg(curOrg)
    }

    //子组件时间改变
    const onTimePickerChange = (nowTimeRange) => {
        setTimeRange(nowTimeRange);
    }

    //获取热销产品数据
    const onGetTopGoods = async () => {
        const jsonData = {
            "top": 10,
            "shopIds": [
                currentOrg.key
            ],
            "startTime": timeRange[0],
            "endTime": timeRange[1]
        }
        if (!currentOrg.key) delete jsonData.shopIds;
        setShowLoading(true);
        const response = await productAPI.getProductEcharts(jsonData);
        setShowLoading(false);
        if (response.statusCode === 200) {
            setTopGoods(response.data.topGoods);
        } else {
            message.error(response.errors || '获取热销产品数据出错')
        }
    }

    //初始化热销商品柱状图
    const initHotTopGoods = () => {
        const chartDom = document.getElementById('top-goods');
        topGoodsBar = echarts.init(chartDom);
        const xData = [];
        const seriesData = [];
        topGoods.forEach(item => {
            xData.push(item.name);
            seriesData.push(item.count);
        });
        const option = {
            title: {
                show: true,
                text: '热销商品'
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    label: {
                        show: true,
                        formatter: '热销商品'
                    }
                }
            },
            toolbox: {
                feature: {
                    saveAsImage: {}
                }
            },
            xAxis: {
                type: 'category',
                data: xData
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    data: seriesData,
                    type: 'bar',
                    showBackground: true,
                    backgroundStyle: {
                        color: 'rgba(180, 180, 180, 0.2)'
                    }
                }
            ]
        };
        option && topGoodsBar.setOption(option);
    }

    //初始化热销商品折线图
    const initHotTopLine = () => {
        const chartDom = document.getElementById('top-goods-line');
        topGoodsLine = echarts.init(chartDom);
        const option = {
            title: {
                show: true,
                text: '热销商品'
            },
            toolbox: {
                feature: {
                    saveAsImage: {}
                }
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    label: {
                        show: true,
                        formatter: '热销商品'
                    }
                }
            },
            xAxis: {
                type: 'category',
                data: ['00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00']
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    data: [150, 230, 224, 218, 135, 147, 260],
                    type: 'line'
                }
            ]
        };
        option && topGoodsLine.setOption(option);
    }

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

    useEffect(() => {
        initHotTopGoods();
        initHotTopLine();
        window.onresize = () => {
            if (topGoodsLine && topGoodsBar) {
                topGoodsLine.resize();
                topGoodsBar.resize();
            }
        }
    }, [topGoods]);


    return (
        <PageContainer>
            <ConditionQuery
                orgTree={orgTree}
                timeRange={timeRange}
                searchDayIndex={searchDayIndex}
                currentOrg={currentOrg}
                showLoading={showLoading}
                onTimePickerChange={onTimePickerChange}
                onChangeTimeIndex={onChangeTimeIndex}
                onCurrentOrgChange={onCurrentOrgChange}
                onResetSearch={onResetSearch}
                onQueryBtn={onGetTopGoods}
            >
            </ConditionQuery>
            <Row gutter={10}>
                <Col xs={24} sm={24} md={24} lg={8} xl={8}>
                    <Card>
                        <div id="top-goods" className={styles['top-goods']}></div>
                    </Card>
                </Col>
                <Col xs={24} sm={24} md={24} lg={16} xl={16}>
                    <Card>
                        <div id="top-goods-line" className={styles['top-goods-line']}></div>
                    </Card>
                </Col>
            </Row>
        </PageContainer>
    )
}
