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 styles from './index.less';
import moment from 'moment';
import marketAPI from "./service";
import * as echarts from 'echarts';

/**
 * 会员报表
 * @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("");

    //会员图表
    const [memberReport, setMemberReport] = useState({
        userCount: 0,
        newAddUser: [],
        repurChase: []
    });
    //新增会员数
    const [newMemberNum, setNewMemberNum] = useState(0);
    //复购次数
    const [repurChaseNum, setRepurChaseNum] = useState(0);

    //新增会员图表实例
    let newMemberObj = null;
    //复购图表实例
    let repurChaseObj = 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 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;
                }
            }
        });
    }

    //初始化会员报表数据
    const initMemberReport = async () => {
        const jsonData = {
            "shopIds": [
                currentOrg.key
            ],
            "startTime": timeRange[0],
            "endTime": timeRange[1]
        }
        if (!currentOrg.key) delete jsonData.shopIds;
        setShowLoading(true);
        const response = await marketAPI.getMemberReport(jsonData);
        setShowLoading(false);
        if (response.statusCode === 200) {
            let sumNewMember = 0;
            let sumRepurChase = 0;
            response.data.newAddUser.forEach(item => {
                sumNewMember += item.userValue
            });
            response.data.repurChase.forEach(item => {
                sumRepurChase += item.userValue
            });
            setNewMemberNum(sumNewMember);
            setRepurChaseNum(sumRepurChase);
            setMemberReport(response.data);
        } else {
            message.error(response.errors || '获取会员报表失败');
        }
    }


    //初始化新增会员图表
    const initNewMemberCharts = () => {
        const chartDom = document.getElementById('new-member');
        if (!newMemberObj) {
            newMemberObj = echarts.init(chartDom);
        }
        const xAxisData = [];
        const seriesData = [];
        memberReport.newAddUser.forEach(item => {
            const date = new Date(item.userKey);
            xAxisData.push(date.toLocaleDateString());
            seriesData.push(item.userValue);
        });
        const option = {
            title: {
                text: '新增会员'
            },
            tooltip: {
                trigger: 'axis'
            },
            toolbox: {
                feature: {
                    saveAsImage: {}
                }
            },
            xAxis: {
                type: 'category',
                data: xAxisData
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    data: seriesData,
                    type: 'bar'
                }
            ]
        };
        newMemberObj.setOption(option);
    }

    //复购次数图表
    const initRepurChaseCharts = () => {
        const chartDom = document.getElementById('repur-chase');
        if (!repurChaseObj) {
            repurChaseObj = echarts.init(chartDom);
        }
        const xAxisData = [];
        const seriesData = [];
        memberReport.repurChase.forEach(item => {
            xAxisData.push(item.userKey);
            seriesData.push(item.userValue);
        });
        const option = {
            title: {
                text: '复购次数'
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    label: {
                        show: true,
                        formatter: '复购{value}次'
                    }
                }
            },
            toolbox: {
                feature: {
                    saveAsImage: {}
                }
            },
            xAxis: {
                type: 'category',
                data: xAxisData
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    data: seriesData,
                    type: 'line',
                    smooth: true
                }
            ]
        };
        repurChaseObj.setOption(option);
    }

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

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

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

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

    useEffect(() => {
        initNewMemberCharts();
        initRepurChaseCharts();
        window.onresize = () => {
            if (newMemberObj && repurChaseObj) {
                newMemberObj.resize();
                repurChaseObj.resize();
            }
        }
    }, [memberReport]);

    return (
        <PageContainer>
            <ConditionQuery
                orgTree={orgTree}
                timeRange={timeRange}
                searchDayIndex={searchDayIndex}
                currentOrg={currentOrg}
                showLoading={showLoading}
                onTimePickerChange={onTimePickerChange}
                onChangeTimeIndex={onChangeTimeIndex}
                onCurrentOrgChange={onCurrentOrgChange}
                onResetSearch={onResetSearch}
                onQueryBtn={initMemberReport}
            >
            </ConditionQuery>
            <Row gutter={10} className={styles['member-row-common']}>
                <Col xs={24} sm={24} md={24} lg={8} xl={6}>
                    <Card className={styles['member-card']}>
                        <div className={styles['member-card-box']}>
                            <div className={styles['member-card-prefix']}>
                                会员总量
                            </div>
                            <div className={styles['member-card-sufixx']}>
                                {memberReport.userCount}
                            </div>
                        </div>
                        <div className={styles['member-card-box']}>
                            <div className={styles['member-card-prefix']}>
                                新增会员
                            </div>
                            <div className={styles['member-card-sufixx']}>
                                {newMemberNum}
                            </div>
                        </div>
                        <div className={styles['member-card-box']}>
                            <div className={styles['member-card-prefix']}>
                                复购数量
                            </div>
                            <div className={styles['member-card-sufixx']}>
                                {repurChaseNum}
                            </div>
                        </div>
                    </Card>
                </Col>
                <Col xs={24} sm={24} md={24} lg={16} xl={18}>
                    <Card>
                        {/* 复购次数图表 */}
                        <div id="repur-chase" className={styles['repur-chase']}></div>
                    </Card>

                </Col>
            </Row>
            <Row>
                <Col xs={24} sm={24} md={24} lg={24} xl={24} >
                    <Card>
                        {/* 新增会员图表 */}
                        <div id="new-member" className={styles['new-member']}></div>
                    </Card>
                </Col>
            </Row>
        </PageContainer>
    )
}
