import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Button, Card, DatePicker, Table, Pagination, Spin, TreeSelect, message, Col, Row } from 'antd';
import styles from './index.less';
const { RangePicker } = DatePicker;
import costSalesAPI from "./service";
import moment from 'moment';
import { DownloadOutlined } from '@ant-design/icons';


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

/**
 * 门店销售毛利分析
 * @returns
 */
export default function Index() {

    //订单报表列表
    const [costSalesData, setCostSalesData] = useState([]);
    const [current, setCurrent] = useState(1);
    const [pageSize, setPageSize] = useState(10);
    const [total, setTotal] = useState(0);
    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 [storeIdArray, setStoreIdArray] = useState([]);
    const [storeSelect, setStoreSelect] = useState([]);
    const [storeList, setStoreList] = useState([]);

    const columns = [
        {
            title: '门店名称',
            dataIndex: 'storeId',
            key: 'storeId',
            render: (text) => {
                const findGoods = storeList.find(item => item.key === text);
                if (findGoods) {
                    return <span>{findGoods.title}</span>
                } else {
                    return <span>暂无门店名称</span>
                }
            },
        },
        {
            title: '毛利率（%）',
            dataIndex: 'marginRatio',
            key: 'marginRatio',
        }
    ];

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

    //查询
    const onQueryReportSalescost = async () => {
        const jsonData = {
            "storeId": storeIdArray[0],
            "begintime": timeRange[0],
            "endtime": timeRange[1],
            current,
            pageSize
        }
        setShowLoading(true);
        const response = await costSalesAPI.getReportOrgsalesmargin(jsonData);
        setShowLoading(false);
        if (response.statusCode === 200) {
            setCostSalesData(response.data.data);
        } else {
            message.error(response.errors || '获取销售成本失败');
        }
    }

    /**
     * 查询店铺列表
     */
    const onQueryStoreList = async () => {
        setShowLoading(true);
        const response = await costSalesAPI.gettree({});
        setShowLoading(false);
        if (response.statusCode === 200) {
            setStoreSelect(response.data);
            setStoreList(treeArrayToFlat(response.data));
        } else {
            message.error('查询店铺列表失败');
        }
    }

    //重置搜索条件
    const onResetSearch = () => {
        setStoreIdArray([]);
        setTimeRange([
            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 treeArrayToFlat = (tree, arr = []) => {
        tree.forEach(item => {
            const { children, ...props } = item;
            arr.push(props);
            if (children && children.length > 0) {
                treeArrayToFlat(children, arr);
            }
        });
        return arr;
    }

    useEffect(() => {
        onQueryReportSalescost();
        onQueryStoreList();
    }, []);

    return (
        <PageContainer>
            {showLoading ? <LoadingCard></LoadingCard> : null}
            <Card className={styles['data-search-card']}>
                <Row gutter={20} justify="start">
                    <Col xs={24} sm={24} md={12} lg={12} xl={8} className={styles['data-search-item']}>
                        <div className={styles['data-search-prefix']}>
                            门店
                        </div>
                        <TreeSelect
                            className={styles['data-search-sufixx']}
                            value={storeIdArray}
                            dropdownStyle={{
                                maxHeight: 400,
                                overflow: 'auto',
                            }}
                            treeData={storeSelect}
                            placeholder="请选择门店"
                            treeDefaultExpandAll
                            onChange={(values) => setStoreIdArray(values)}
                        />
                    </Col>
                    <Col xs={24} sm={24} md={12} lg={12} xl={8} className={styles['data-search-item']}>
                        <div className={styles['data-search-prefix']}>
                            起始时间
                        </div>
                        <RangePicker size='middle' className={styles['data-search-sufixx']} 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);
                        }} />
                    </Col>
                    <div className={styles['data-search-btns']}>
                        <Button className={styles['search-btn-item']} onClick={onResetSearch}>重置</Button>
                        <Button className={styles['search-btn-item']} type="primary" onClick={onQueryReportSalescost}>查询</Button>
                    </div>
                </Row>
            </Card>
            <Card className={styles['table-card']}>
                <div className={styles['download-btn']}>
                    <Button type="primary" icon={<DownloadOutlined />} size="middle">
                        下载
                    </Button>
                </div>
                <Table dataSource={costSalesData} columns={columns} pagination={false} />
                <div className={styles['table-page']}>
                    <Pagination current={current} pageSize={pageSize} total={total} onChange={onPageChange} />
                </div>
            </Card>
        </PageContainer>
    )
}
