import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Button, Card, DatePicker, Table, Pagination, Spin, Select, message, Col, Row, TreeSelect } 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 [goodsIdArray, setGoodsIdArray] = useState([]);
    const [goodsIdSelect, setGoodsIdSelect] = useState([]);
    //商品类型
    const [goodsTypeArray, setGoodsTypeArray] = useState([]);
    const [goodsTypeSelect, setGoodsTypeSelect] = 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: 'goodsId',
            key: 'goodsId',
            render: (text) => {
                const findGoods = goodsIdSelect.find(item => item.id === text);
                if (findGoods) {
                    return <span>{findGoods.name}</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,
            "goodsId": goodsIdArray[0],
            "goodsTypeId": goodsTypeArray[0],
            "begintime": timeRange[0],
            "endtime": timeRange[1],
            current,
            pageSize
        }
        setShowLoading(true);
        const response = await costSalesAPI.getReportSalesmargin(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 onQueryGoodsList = async () => {
        setShowLoading(true);
        const response = await costSalesAPI.goodsList({});
        setShowLoading(false);
        if (response.statusCode === 200) {
            setGoodsIdSelect(response.data);
        } else {
            message.error('查询商品列表失败');
        }
    }

    //查询商品分类类型列表
    const onQueryGoodsType = async () => {
        setShowLoading(true);
        const response = await costSalesAPI.goodsTypeList({});
        setShowLoading(false);
        if (response.statusCode === 200) {
            setGoodsTypeSelect(response.data);
        } else {
            message.error('查询商品分类列表失败');
        }
    }

    //重置搜索条件
    const onResetSearch = () => {
        setGoodsIdArray([]);
        setStoreIdArray([]);
        setGoodsTypeArray([]);
        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();
        onQueryGoodsList();
        onQueryGoodsType();
    }, []);
    return (
        <PageContainer>
            {showLoading ? <LoadingCard></LoadingCard> : null}
            <Card className={styles['data-search-card']}>
                <Row gutter={20} justify="space-between">
                    <Col xs={24} sm={24} md={12} lg={12} xl={6} 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={6} className={styles['data-search-item']}>
                        <div className={styles['data-search-prefix']}>
                            商品
                        </div>
                        <Select
                            className={styles['data-search-sufixx']}
                            showSearch
                            mode="tags"
                            size="middle"
                            allowClear
                            placeholder="请选择商品"
                            value={goodsIdArray}
                            onChange={(values) => setGoodsIdArray(values)}
                            filterOption={(input, option) => option.children.toLowerCase().includes(input.toLowerCase())}
                        >
                            {
                                goodsIdSelect.map((item, index) => {
                                    return (
                                        <Option key={item.id}>{item.name}</Option>
                                    )
                                })
                            }
                        </Select>
                    </Col>
                    {/* <Col xs={24} sm={24} md={12} lg={12} xl={6} className={styles['data-search-item']}>
                        <div className={styles['data-search-prefix']}>
                            商品类别
                        </div>
                        <Select
                            className={styles['data-search-sufixx']}
                            showSearch
                            mode="tags"
                            size="middle"
                            allowClear
                            placeholder="请选择商品类别"
                            value={goodsTypeArray}
                            onChange={(values) => setGoodsTypeArray(values)}
                            filterOption={(input, option) => option.children.toLowerCase().includes(input.toLowerCase())}
                        >
                            {
                                goodsTypeSelect.map((item) => {
                                    return (
                                        <Option key={item.id}>{item.name}</Option>
                                    )
                                })
                            }
                        </Select>
                    </Col> */}
                    <Col xs={24} sm={24} md={12} lg={12} xl={6} 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>
                </Row>
                <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>
            </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>
    )
}
