import * as React from 'react';
import { PageHeaderFoot, Button, AutoTableContainer, Table, Pagination, Tag, Radio, message } from 'kts-xui';
import { AdvancedSearch, KtsForm } from 'kts-components';
import AddModal from './UI.DenyModal';
import moment from 'moment';
import { columnEnum } from '../CommonComponents/ColumnEnum';
import { findLabel, invoiceTypeEnum, proveStatusEnum, submitStatusEnum } from '../CommonComponents/FiledsEnum';
import { withRouter, RouteChildrenProps } from 'react-router-dom';
import agent from '../Server';
import { Space, Tooltip } from 'kts-components-antd-x4';
import VerifyList from '../CommonComponents/VerifyList';
import { DigitalAssetVerification } from '../..';
/** Props接口 */
interface IProps {
    changeView: (value) => void
}

class UIComponents extends React.Component<IProps & RouteChildrenProps, any> {
    columns = [
        {
            title: '核验方',
            dataIndex: 'verifierName',
            width: 190,
            ellipsis: true,
        },
        {
            title: '证明结果',
            width: 120,
            dataIndex: 'proveStatus',
            align: 'center',
            render: (text, record) => {
                if (text === 1) {
                    return <span style={{ color: '#0074ff' }}>{findLabel(text, proveStatusEnum)}</span>
                } else if (text === 2 || text === 4) {
                    return <Tooltip title={record.proveMsg}><Tag style={{ color: 'red' }}>{findLabel(text, proveStatusEnum)}</Tag></Tooltip>
                } else {
                    return <Tag>{findLabel(text, proveStatusEnum)}</Tag>
                }
            }
        }, {
            title: '提交状态',
            width: 120,
            align: 'center',
            dataIndex: columnEnum['提交状态'],
            render: (text, record) => {
                if (text === 4 || text === 5) {
                    return <Tooltip title={record.submitMsg}><Tag style={{ color: 'red' }}>{findLabel(text, submitStatusEnum)}</Tag></Tooltip>
                } else {
                    return <Tag>{findLabel(text, submitStatusEnum)}</Tag>
                }
            }
        },
        {
            title: '发票类型',
            width: 120,
            align: 'center',
            dataIndex: 'invoiceType',
            render: (text, record) => {
                if (text) {
                    return <Tag>{findLabel(text, invoiceTypeEnum)}</Tag>

                }
            }
        },
        {
            title: '销售方',
            dataIndex: columnEnum['销售方'],
            width: 160,
            ellipsis: true,
        }, {
            title: '购买方',
            dataIndex: columnEnum['采购方'],
            width: 160,
            ellipsis: true,
        }, {
            title: '发票号码',
            width: 190,
            dataIndex: 'invoiceNo',
        }, {
            title: '发票代码',
            width: 140,
            dataIndex: 'invoiceCode',
        }, {
            title: '开票日期',
            width: 130,
            dataIndex: 'invoiceDate',
            render: (text) => {
                return text && moment(text).format('YYYY-MM-DD');
            }
        }, {
            title: '提交时间',
            width: 160,
            dataIndex: columnEnum['提交时间'],
            ellipsis: true,
            render: text => {
                return text && moment(text).format('YYYY-MM-DD HH:mm')
            }
        },
        {
            title: '提交用途',
            width: 150,
            ellipsis: true,
            dataIndex:'submitPurpose',
            // render:text=>text&&text.join(',')
        },
        {
            title: '提交人',
            width: 120,
            ellipsis: true,
            dataIndex: columnEnum['提交人'],
        },
        
        {
            title: '操作',
            dataIndex: 'recordUuid',
            width: 150,
            fixed: 'right',
            render: (text, record) => {
                if (record.submitStatus === 4 || record.submitStatus === 1) {
                    return <Space>
                        <a onClick={() => { this.onBatchSubmit([text]); }}>重新提交</a>
                    </Space>
                }

            }
        },
    ];
    constructor(props) {
        super(props);
        this.state = {
            pageMeta: null,
            list: [
            ],
            params: this.props.location.state || {},
            showModal: false,
            selectedRowKeys: [],
            denyList: [],
            invoiceUuid: ''
        };
    }
    onSubmit = async recordUuid => {
        const res: any = await agent.post('/asset/submit/reSubmit', { recordUuid }, this);
        if (res.err) {
            return;
        } else {
            this.onRefresh();
        }
    }
    onVerifyRecords = id => {
        this.setState({
            invoiceUuid: id
        })
    }
    closeVerify = () => {
        this.setState({
            invoiceUuid: ''
        })
    }
    radioChange = (e) => {
        this.props.changeView(e.target.value);
    }
    topExpand = () => {
        const { params } = this.state;
        return (
            <AdvancedSearch
                width={400}
                height={44}
                compact={true}
                defaultKey="invoiceNo"
                placeholder="请输入发票号码"
                searchFormSubmit={this.onSearch}
                extra={
                    <>
                        <Radio.Group defaultValue="sublist" onChange={this.radioChange} style={{ display: 'flex', marginRight: 10 }}>
                            <Radio.Button value="collect">发票采集</Radio.Button>
                            <Radio.Button value="sublist">提交列表</Radio.Button>
                        </Radio.Group>
                    </>
                }
            >
                <KtsForm
                    labelCol={9}
                    wrapperCol={15}
                    labelAlign="left"
                    compact={true}
                    schema={{
                        type: 'object',
                        properties: {
                            'verifierName': {
                                type: 'string',
                                title: '核验方',
                            },
                            [columnEnum['发票类型']]: {
                                type: 'string',
                                title: '发票类型',
                                enum: invoiceTypeEnum,
                                'x-props': {
                                    mode: "multiple"
                                }
                            },
                            [columnEnum['销售方']]: {
                                type: 'string',
                                title: '销售方',
                            },
                            [columnEnum['采购方']]: {
                                type: 'string',
                                title: '购买方',
                            },
                            invoiceNo: {
                                type: 'string',
                                title: '发票号码',
                            },
                            invoiceCode: {
                                type: 'string',
                                title: '发票代码',
                            },

                            kaipiao: {
                                type: 'daterange',
                                title: '开票日期',
                                'x-props': {
                                    extendsFields: ['minInvoiceDate', 'maxInvoiceDate'],
                                }
                            },
                            proveStatus: {
                                type: 'string',
                                title: '证明结果',
                                enum: proveStatusEnum,
                                'x-props': {
                                    mode: "multiple"
                                }
                            },
                            submitStatus: {
                                type: 'string',
                                title: '提交状态',
                                enum: submitStatusEnum,
                                'x-props': {
                                    mode: "multiple"
                                }
                            },
                            endDate: {
                                type: 'daterange',
                                title: '提交时间',
                                'x-props': {
                                    extendsFields: ['minSubmitTime', 'maxSubmitTime'],
                                }
                            },
                            submitPurpose:{
                                type: 'string',
                                title: '提交用途',
                            },
                            [columnEnum['提交人']]: {
                                type: 'string',
                                title: '提交人',
                            },
                           

                        },
                    }}
                >
                </KtsForm>
            </AdvancedSearch>
        );
    }
    /**
     * 拒绝
     * @param keys 
     */
    onDenyHandler = (keys: string[]) => {
        this.setState({
            denyList: keys,
            showModal: true
        })
    }
    componentDidMount() {
        const params = {
            pageNum: 1,
            pageSize: 10,
            ...this.state.params,
        };
        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);
    }
    onSearch = (data = {}) => {
        this.setState({
            params: data,
        });
        const params = {
            ...data,
            ...this.state.pageMeta,
            pageNum: 1
        };
        this.getData(params);
    }
    getData = async (params?) => {
        params = {
            ...params,
            minInvoiceDate: params['minInvoiceDate'] && moment(params['minInvoiceDate']).format('YYYY-MM-DD 00:00:00'),
            maxInvoiceDate: params['maxInvoiceDate'] && moment(params['maxInvoiceDate']).format('YYYY-MM-DD 23:59:59'),
            minSubmitTime: params['minSubmitTime'] && moment(params['minSubmitTime']).format('YYYY-MM-DD 00:00:00'),
            maxSubmitTime: params['maxSubmitTime'] && moment(params['maxSubmitTime']).format('YYYY-MM-DD 23:59:59'),
        }
        const res: any = await agent.post('/asset/submit/submitInvoicePage', params, this);
        if (res.err) {
            return;
        } else {
            if (res.res) {
                this.setState({
                    pageMeta: res.res.pageMeta,
                    list: res.res.items
                });
            }
        }
    }
    onBatchSubmit = async (list) => {
        const res: any = await agent.post('/asset/submit/reSubmitBatch', list, this);
        if (res.err) {
            return;
        } else {
            if (res.res) {
                this.setState({
                    selectedRowKeys: []
                })
                message.success('提交中，请稍后查看');
                this.onRefresh();
            }
        }
    }
    onDeny = () => {
        this.setState({
            showModal: true,
            denyList: [...this.state.selectedRowKeys]
        })
    }
    closeModal = () => {
        this.setState({
            showModal: false,
            denyList: []
        })
    }
    successModal = () => {
        this.onRefresh();
        this.closeModal();
    }
    onExport = async () => {
        const { params } = this.state;
        const data = {
            ...params,
            minInvoiceDate: params['minInvoiceDate'] && moment(params['minInvoiceDate']).format('YYYY-MM-DD 00:00:00'),
            maxInvoiceDate: params['maxInvoiceDate'] && moment(params['maxInvoiceDate']).format('YYYY-MM-DD 23:59:59'),
            minSubmitTime: params['minSubmitTime'] && moment(params['minSubmitTime']).format('YYYY-MM-DD 00:00:00'),
            maxSubmitTime: params['maxSubmitTime'] && moment(params['maxSubmitTime']).format('YYYY-MM-DD 23:59:59'),
        };
        const res: any = await DigitalAssetVerification.server.post(`${DigitalAssetVerification.prefix_path}/asset/submit/exportSubmitInvoice`, 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();
            // link = null;
        }
    }
    onCaijiRefresh = () => {
        this.onRefresh();
    }
    render() {
        const dataSource = this.state.list;
        const { pageMeta, selectedRowKeys, invoiceUuid } = this.state;
        const rowSelection = {
            selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRowKeys
                });
            },
            getCheckboxProps: (record) => ({
                disabled: record.submitStatus === 2 || record.submitStatus === 3
            }),
        }
        return (
            <div style={{ height: 'calc(100vh - 97px)', display: 'flex', flexDirection: 'column' }}>
                <div style={{ flex: 'none', position: 'relative', zIndex: 1 }}>
                    <PageHeaderFoot
                        expandLeft={this.topExpand()}
                        expandRight={[

                            <Button key='0' type="primary" onClick={() => { this.onBatchSubmit(selectedRowKeys); }}>批量重新提交</Button>,
                            <Button type="primary" onClick={this.onExport}>导出</Button>
                        ]}
                        onRefresh={this.onRefresh}
                    >
                    </PageHeaderFoot>
                </div>
                <AutoTableContainer style={{ flex: 1, padding: '0 20px', background: '#F4F4F4' }} >
                    <Table
                        className='fixheight'
                        dataSource={dataSource}
                        columns={this.columns as any}
                        bordered={true}
                        rowSelection={rowSelection}
                        scroll={{ x: '1600', y: 'max-content' }}
                        pagination={false}
                        rowKey='recordUuid'
                    />
                </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} />}
                {
                    this.state.showModal && <AddModal list={this.state.denyList} onClose={this.closeModal} onSuccess={this.successModal} />
                }
                {
                    invoiceUuid && <VerifyList onClose={this.closeVerify} invoiceUuid={invoiceUuid} />
                }
            </div>
        );
    }
}
export default withRouter<any, any>(UIComponents as any)