import * as React from 'react';
import { PageHeaderFoot, Button, Select, Input, Radio, Form, DatePicker, AutoComplete } from 'kts-xui';
import { AdvancedSearch, KtsForm } from 'kts-components';
import { withRouter, RouteChildrenProps } from 'react-router-dom';
import MyEchart from './UI.Echart';
import { FormInstance } from 'kts-components-antd-x4/lib/form';
import agent from '../../Server';
import moment from 'moment';
import debounce from 'lodash/debounce';
const { RangePicker } = DatePicker;
/** Props接口 */
interface IProps {
    changeView: (value) => void
    enabled: boolean
}

export default class UIComponents extends React.Component<IProps, any> {
    formRef:any = React.createRef<FormInstance>();
    constructor(props) {
        super(props);
        this.state = {
            list: [],
            params: {},
            radioValue: 'echart',
            dateParams: [moment().subtract(1, 'month').startOf('month').format('YYYY-MM-DD'), moment().subtract(1, 'month').endOf('month').format('YYYY-MM-DD')],
            companyList: [],
            goodsList: [],
            companyName: '',
            chartData: null
        };
    }
    radioChange = (e) => {
        this.props.changeView(e.target.value);
    }
    onDateChange = (_date, dateString) => {
        this.setState({
            dateParams: dateString
        }, () => {
            this.onRefresh();
        })
    }
    searchCompany = async (value, callback?) => {
        const res: any = await agent.get('/web/verifier/report/getCompany', { startCompanyName: value.trim() }, this);
        if (res.err) {
            return;
        } else {
            this.setState({
                companyList: res.res.items
            }, () => {
                if (callback) callback();
            });

        }
    }
    searchGoods = async (value) => {
        const res: any = await agent.get('/web/verifier/report/getGoods', { goodsName: value.trim() }, this);
        if (res.err) {
            return;
        } else {
            res.res.items = res.res.items.map(item => {
                return {
                    ...item,
                    value: item.goodsName + item.specificationModel + item.unit
                }
            })
            this.setState({
                goodsList: res.res.items
            });
        }
    }
    companySelect = (companyName) => {
        this.setState({
            companyName
        })
    }
    onFinish = async (values) => {
        const { goodsList } = this.state;
        let data = {
            ...values,
            invoiceDateStart: moment(values['invoiceDate'][0]).format('YYYY-MM-DD'),
            invoiceDateEnd: moment(values['invoiceDate'][1]).format('YYYY-MM-DD'),
        }
        let found = [];
        if (values.goodsList && values.goodsList.length > 0) {
            found = goodsList.filter(item => {
                if (values.goodsList.length > 0) {
                    return values.goodsList.includes(item.index)
                }
            });
        } else {
            found = [];
        }
        data = {
            ...data,
            goodsList: found
        }
        delete data.invoiceDate;
        const res: any = await agent.post('/web/verifier/report/throughView', data, this);
        if (res.err) {
            return;
        } else {
            const found = res.res.data.findIndex(item => item.start === true);
            if (~found) {
                const startNode = {
                    ...res.res.data[found],
                    itemStyle: {
                        color: '#3ba272'
                    }
                }
                res.res.data[found] = startNode;
            }
            res.res.links = res.res.links.map(item => {
                return {
                    ...item,
                    label: {
                        fontSize: 12
                    }
                }
            })
            this.setState({
                chartData: res.res
            })

        }
    }
    topExpand = () => {
        const { dateParams, companyList, goodsList } = this.state;
        const { enabled } = this.props;
        return (
            <div style={{ display: 'flex', alignItems: 'flex-start', alignContent: 'flex-start', flexWrap: 'wrap', }}>
                <Radio.Group defaultValue="echart" onChange={this.radioChange} style={{ display: 'flex', marginRight: 10, marginBottom: 10 }}>
                    {enabled && <Radio.Button value="customer">客商信息</Radio.Button>}
                    <Radio.Button value="list">扁平视图</Radio.Button>
                    <Radio.Button value="echart">穿透视图</Radio.Button>
                    {/* <Radio.Button value="rank">排行榜</Radio.Button> */}
                </Radio.Group>
                <Form
                    layout='inline'
                    ref={this.formRef}
                    onFinish={this.onFinish}
                >
                    <Form.Item
                        name='startCompanyName'
                        label='起点公司'
                        rules={[
                            { required: true, message: '请输入必填项' }
                        ]}
                    >
                        <AutoComplete
                            style={{ width: 150 }}
                            onSelect={this.companySelect}
                            allowClear={false}
                            onSearch={debounce(this.searchCompany, 800)}
                        >
                            {companyList.map((item, key: number) => {
                                return <AutoComplete.Option value={item.name} key={key}>{item.name}</AutoComplete.Option>

                            })}
                        </AutoComplete>
                    </Form.Item>
                    <Form.Item
                        name='invoiceDate'
                        label='开票日期'
                        initialValue={[moment(dateParams[0]), moment(dateParams[1])]}
                        rules={[
                            { required: true, message: '请输入必填项' }
                        ]}
                    >
                        <RangePicker style={{ width: 220 }} allowClear={false} />
                    </Form.Item>
                    <Form.Item
                        name='throughDirect'
                        label='穿透方向'
                        initialValue={2}
                        rules={[
                            { required: true, message: '请输入必填项' }
                        ]}
                    >
                        <Select allowClear={false} >
                            <Select.Option value={0}>向下穿透</Select.Option>
                            <Select.Option value={1}>向上穿透</Select.Option>
                            <Select.Option value={2}>全部</Select.Option>
                        </Select>
                    </Form.Item>
                    <Form.Item
                        name='goodsList'
                        label='商品'
                    >
                        <Select
                            showSearch={true}
                            mode="multiple"
                            maxTagCount={4}
                            placeholder="默认全部商品"
                            style={{ width: 200 }}
                            allowClear={false}
                            onSearch={debounce(this.searchGoods, 800)}
                        >
                            {goodsList.map((item) => {
                                return <Select.Option value={item.index} key={item.value}>{item.goodsName + '/' + item.specificationModel + '/' + item.unit}</Select.Option>
                            })}
                        </Select>
                    </Form.Item>
                    <Form.Item >
                        <Button type="primary" htmlType="submit">
                            查询
                        </Button>
                    </Form.Item>
                </Form>
            </div>
        );
    }

    componentDidMount() {
        this.searchGoods('');
        this.searchCompany('', () => {
            if (this.state.companyList.length > 0) {
                this.setState({
                    companyName: this.state.companyList[0].name
                })
                this.formRef.current?.setFieldsValue({ startCompanyName: this.state.companyList[0].name })
            }
        });
    }

    onRefresh = () => {
        const params = {
            ...this.state.params,
            ...this.state.pageMeta,
        };
        this.getData(params);
    }
    getData = async (params) => {
        const { dateParams, companyName, goods } = this.state;
        const data = {
            startCompanyName: companyName,
            invoiceDateStart: dateParams[0],
            invoiceDateEnd: dateParams[1],
            goodsList: [goods]
        }
        const res: any = await agent.post('/web/verifier/report/throughView', params, this);
        if (res.err) {
            return;
        } else if (res.res) {
            this.setState({
                list: res.res.items
            });
        }
    }
    onSearch = (data = {}) => {
        this.setState({
            params: data
        });
        const params = {
            ...data,
            ...this.state.pageMeta,
            pageNum: 1
        };
        this.getData(params);
    }
    render() {
        const { chartData } = this.state;
        const dataSource = this.state.list;
        return (
            <>
                <div style={{ flex: 'none', position: 'relative', zIndex: 1 }}>
                    <PageHeaderFoot
                        expandLeft={this.topExpand()}
                    >

                    </PageHeaderFoot>

                </div>
                {chartData && <MyEchart data={chartData} />}
            </>
        );
    }
}
