import * as React from 'react';
import { PageHeaderFoot, Button, AutoTableContainer, Table, Radio, Pagination } from 'kts-xui';
import { AdvancedSearch, KtsForm } from 'kts-components';
import { Form, DatePicker } from 'kts-xui';
import { columnEnum } from '../../CommonComponents/ColumnEnum';
import { withRouter, RouteChildrenProps } from 'react-router-dom';
import { FormInstance } from 'kts-components-antd-x4/lib/form';
import agent from '../../Server';
import moment from 'moment';
import { DigitalAssetVerification } from '../../..';
const { RangePicker } = DatePicker;
/** Props接口 */
interface IProps {
    changeView: (value) => void
    enabled: boolean
}
/**
 * 扁平视图
 */
class UIComponents extends React.Component<IProps & RouteChildrenProps, any> {
    formRef:any = React.createRef<FormInstance>();
    columns = [
        {
            title: '商品名称',
            dataIndex: columnEnum['商品名称'],
            width: 200,
            ellipsis: true,

        }, {
            title: '规格型号',
            dataIndex: columnEnum['规格型号'],
            width: 140,
            ellipsis: true,
            render: (text) => {
                return <span style={{ whiteSpace: 'pre-wrap' }}>{text}</span>
            }
        }, {
            title: '单位',
            dataIndex: columnEnum['单位'],
            width: 100,
        }, {
            title: '卖方',
            width: 200,
            ellipsis: true,
            dataIndex: columnEnum['销售方'],
        }, {
            title: '买方',
            dataIndex: columnEnum['采购方'],
            width: 200,
            ellipsis: true,
        }, {
            title: '数量',
            dataIndex: columnEnum['数量'],
            width: 100,
        }, {
            title: '操作',
            dataIndex: 'id',
            fixed: 'right',
            width: 220,
            render: (_text, record) => {
                return (
                    <span>
                        <a onClick={() => { this.onRecordDetail(record); }} style={{ paddingRight: 5 }}>查看明细</a>
                        <a onClick={() => { this.onExchangeUpper(record); }} style={{ paddingRight: 5 }}>向上穿透</a>
                        <a onClick={() => { this.onExchangeLower(record); }} style={{ paddingRight: 5 }}>向下穿透</a>
                    </span>
                )
            }
        },
    ];
    constructor(props) {
        super(props);
        this.state = {
            pageMeta: null,
            list: [],
            params: {},
            radioValue: 'list',
            setId: 0,
            dateParams: [moment().subtract(1, 'month').startOf('month').format('YYYY-MM-DD'), moment().subtract(1, 'month').endOf('month').format('YYYY-MM-DD')],
        };

    }
    onExchangeUpper = (record: any) => {
        this.setState({
            params: {
                ...this.state.params,
                buyerName: record.salerName,
                salerName: null,
                unit: record.unit,
                goodsName: record.goodsName,
                specificationModel: record.specificationModel,

            },
            pageMeta: {
                ...this.state.pageMeta,
                pageNum: 1
            },
            setId: new Date().getTime(),
        }, () => {
            this.onRefresh();
        })
    }
    onExchangeLower = (record: any) => {
        this.setState({
            params: {
                ...this.state.params,
                salerName: record.buyerName,
                buyerName: null,
                unit: record.unit,
                goodsName: record.goodsName,
                specificationModel: record.specificationModel,
            },
            pageMeta: {
                ...this.state.pageMeta,
                pageNum: 1
            },
            setId: new Date().getTime(),
        }, () => {
            this.onRefresh();
        })
    }
    radioChange = (e) => {
        this.props.changeView(e.target.value);
    }
    onRecordDetail = record => {
        const params = {
            ...this.state.params,
            kaipiao: this.state.dateParams,
            salerName: record.salerName,
            buyerName: record.buyerName,
            goodsName: record.goodsName,
            specificationModel: record.specificationModel,
            unit: record.unit,
            includeManyEffectiveStatus: [1],
            minInvoiceDate: this.state.dateParams && moment(this.state.dateParams[0]).format('YYYY-MM-DD 00:00:00'),
            maxInvoiceDate: this.state.dateParams && moment(this.state.dateParams[1]).format('YYYY-MM-DD 23:59:59'),

        }
        this.toGoodView(params);
    }
    onSubmit = () => {
        this.formRef.current!.submit();
    }
    onSearch = (data = {}) => {
        this.setState({
            params: data,
        }, () => {
            const params = {
                ...data,
                ...this.state.pageMeta,
                pageNum: 1
            };
            this.getData(params);
        });
    }
    toGoodView = (data) => {
        this.props.history.push('/task/list/product', data)
    }
    onDateChange = (_date, dateString) => {
        this.setState({
            dateParams: dateString
        }, () => {
            this.onRefresh();
        })
    }
    topExpand = () => {
        const { dateParams, params, setId } = this.state;
        const { enabled } = this.props;
        return (
            <div style={{ display: 'flex', alignItems: 'center' }}>
                <AdvancedSearch
                    width={380}
                    height={44}
                    initialValues={params}
                    setId={setId}
                    extra={
                        <>
                            <Radio.Group defaultValue="list" onChange={this.radioChange} style={{ display: 'flex', marginRight: 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>
                            <div style={{ height: 32, marginRight: 10 }}>
                                <Form
                                    ref={this.formRef}
                                >
                                    <Form.Item
                                        name='invoiceDate'
                                        label='开票日期'
                                        initialValue={[moment(dateParams[0]), moment(dateParams[1])]}
                                        rules={[
                                            { required: true, message: '请输入必填项' }
                                        ]}
                                    >
                                        <RangePicker allowClear={false} onChange={this.onDateChange} />
                                    </Form.Item>
                                </Form>
                            </div>
                        </>
                    }
                    compact={true}
                    defaultKey="goodsName"
                    placeholder="请输入商品名称"
                    searchFormSubmit={this.onSearch}
                >
                    <KtsForm
                        labelCol={9}
                        wrapperCol={15}
                        labelAlign="left"
                        compact={true}
                        initialValues={params}
                        schema={{
                            type: 'object',
                            properties: {
                                [columnEnum['商品名称']]: {
                                    type: 'string',
                                    title: '商品名称',
                                },
                                [columnEnum['规格型号']]: {
                                    type: 'string',
                                    title: '规格型号',
                                },
                                [columnEnum['销售方']]: {
                                    type: 'string',
                                    title: '卖方',
                                },
                                [columnEnum['采购方']]: {
                                    type: 'string',
                                    title: '买方',
                                },
                                [columnEnum['单位']]: {
                                    type: 'string',
                                    title: '单位',
                                },
                            },
                        }}
                    >
                    </KtsForm>
                </AdvancedSearch>
            </div>
        );
    }

    componentDidMount() {
        const params = {
            pageNum: 1,
            pageSize: 10
        };
        this.getData(params);
    }
    onPageChange = (pageNum, pageSize) => {
        this.setState({
            pageMeta: {
                ...this.state.pageMeta,
                pageNum,
                pageSize
            }
        }, () => {
            this.onRefresh();
        });
    }
    onRefresh = () => {
        const params = {
            ...this.state.params,
            ...this.state.pageMeta,
        };
        this.getData(params);
    }
    getData = async (params) => {
        const data = {
            ...params,
            minInvoiceDate: this.state.dateParams[0],
            maxInvoiceDate: this.state.dateParams[1],
        }
        const res: any = await agent.post('/web/verifier/valid/invoiceDetail/queryFlatView', data, this);
        if (res.err) {
            return;
        } else {
            this.setState({
                pageMeta: res.res.pageMeta,
                list: res.res.items
            });
        }
    }

    onImport = async () => {
        const { params } = this.state;
        const data = {
            ...params,
            minInvoiceDate: this.state.dateParams && moment(this.state.dateParams[0]).format('YYYY-MM-DD 00:00:00'),
            maxInvoiceDate: this.state.dateParams && moment(this.state.dateParams[1]).format('YYYY-MM-DD 23:59:59'),
        };
        const res: any = await DigitalAssetVerification.server.post(`${DigitalAssetVerification.prefix_path}/web/verifier/report/exportFlatView`, data).reqFs(DigitalAssetVerification.server.reqFs.filter(v => v !== DigitalAssetVerification.serviceTools.addContentType)).resFs([]).responseType('blob').end(null);;
        if (res.err) {
            return;
        } else {
            const blob = res.res.body;
            let url = URL.createObjectURL(blob);
            let link = document.createElement('a');
            link.style.display = 'none';
            link.href = url;
            link.setAttribute('download', `扁平视图报表-${moment(new Date()).format('YYYYMMDDHHmmss')}.xls`);
            link.click();
        }
    }
    render() {
        const dataSource = this.state.list;
        const { pageMeta, params } = this.state;
        return (
            <>
                <div style={{ flex: 'none', position: 'relative', zIndex: 1 }}>
                    <PageHeaderFoot
                        expandLeft={this.topExpand()}
                        expandRight={[
                            <Button key='1' type="primary" onClick={this.onImport}>导出</Button>,
                        ]}
                        onRefresh={this.onRefresh}
                    >

                    </PageHeaderFoot>
                </div>
                <AutoTableContainer style={{ flex: 1, padding: '0 20px', background: '#F4F4F4' }} >
                    <Table
                        className='fixheight'
                        bordered={true}
                        dataSource={dataSource}
                        columns={this.columns as any}
                        scroll={{ x: '1500', y: 'max-content' }}
                        pagination={false}
                    />
                </AutoTableContainer>
                {pageMeta && <Pagination onChange={this.onPageChange} showTotal={(total, range) => `第 ${range[0]}-${range[1]} 条,  共有 ${total} 条`} style={{ padding: '16px 0', flex: 'none', background: 'white', textAlign: 'center' }} total={pageMeta.total} pageSize={pageMeta.pageSize} current={pageMeta.pageNum} showSizeChanger={true} />}
            </>
        );
    }
}

export default withRouter<any, any>(UIComponents as any)