import * as React from 'react';
import { Button, Table, message, Modal } from 'kts-xui';
import { Pagination, Space, Tag, Tooltip } from 'kts-components-antd-x4';
import { AdvancedSearch, KtsForm } from 'kts-components';
import agent from '../../../Server';
import { withRouter, RouteChildrenProps } from 'react-router-dom';
import { invoiceTypeEnum, proveStatusEnum, findLabel } from '../../../CommonComponents/FiledsEnum'
import moment from 'moment';
import InvoiceModal from './invoiceModal';
import { CheckCircleOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import {
    WarningOutlined, ReloadOutlined
} from '@ant-design/icons';
import InvoiceComponent from '../UI.InvoiceComponent'
import VerifyList from '../../../CommonComponents/VerifiedList';
import RecordList from '../recordlist';
import ConnectPanel from './ConnectDrawer';
import { columnEnum } from '../../../CommonComponents/ColumnEnum';
import { submitStatusEnum } from '../../../CommonComponents/FiledsEnum';
/** Props接口 */
interface IProps {
    onSuccess?: () => void;
    taskUuid: string;
    changeView?: (value) => void;
    status: number;
    type: string;
    originalDocList: string[]
}
class UIComponents extends React.Component<IProps & RouteChildrenProps, any> {
    columns = [
        {
            title: '发票类型',
            dataIndex: 'invoiceType',
            width: 120,
            align: 'center',
            key: 'invoiceType',
            render: (text, record) => {
                if (text) {
                    return <Tag>{findLabel(text, invoiceTypeEnum)}</Tag>
                } else {
                    if (record.errorMsg) {
                        return <Tooltip title={record.errorMsg}><WarningOutlined style={{ color: 'red' }} /></Tooltip>
                    }
                }

            }
        },
        {
            title: '合规状态',
            dataIndex: 'complianceStatus',
            width: 100,
            align: 'center',
            key: 'complianceStatus',
            render: (text, record) => {
                if (text !== 1) {
                    return <Tooltip title={record.complianceMsg}><ExclamationCircleOutlined style={{ color: 'red' }} /></Tooltip>
                } else {
                    return <CheckCircleOutlined style={{ color: '#0074ff' }} />
                }
            }
        },
        {
            title: '证明结果',
            dataIndex: 'proveStatus',
            width: 120,
            align: 'center',
            key: 'proveStatus',
            render: (text, record) => {
                if (text === 2 || text === 4) {
                    return <Tooltip title={record.proveMsg}><span style={{ color: 'red' }}>{findLabel(text, proveStatusEnum)}</span></Tooltip>
                } else if (!text) {
                    return '-';
                } else {
                    return findLabel(text, proveStatusEnum)
                }
            }
        },
        {
            title: '提交状态',
            width: 100,
            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: '销售方',
            dataIndex: 'salerName',
            width: 190,
            key: 'salerName',
            ellipsis: true,
        },
        {
            title: '采购方',
            dataIndex: 'buyerName',
            width: 190,
            key: 'buyerName',
            ellipsis: true,
        },
        {
            title: '发票号码',
            dataIndex: 'invoiceNo',
            width: 190,
            key: 'invoiceNo',
        },
        {
            title: '发票代码',
            dataIndex: 'invoiceCode',
            width: 160,
            key: 'invoiceCode',
        },
        {
            title: '开票日期',
            dataIndex: 'invoiceDate',
            width: 160,
            key: 'invoiceDate',
            render: text => {
                return moment(text).format('YYYY-MM-DD')
            }
        },
        {
            title: '关联单据',
            width: 120,
            dataIndex: 'invoiceDocRelationList',
            ellipsis: true,
            render: (text, record) => {
                if (text.length > 0) {
                    let originalDocuments = text.reduce((acc, obj) => {
                        acc.push(obj.originalDocument);
                        return acc;
                    }, [])
                    let str = originalDocuments.join('/');
                    return str
                }
            }
        },
        {
            title: '操作',
            dataIndex: 'invoiceUuid',
            width: 220,
            key: 'invoiceUuid',
            fixed: 'right',
            render: (text, record) => {
                return <Space>
                    <a onClick={() => { this.onView(record); }}>查看</a>
                    {this.props.status <= 2 &&
                        <a onClick={() => { this.onRecheck(text); }}>重验</a>
                    }
                    {/* <a onClick={() => { this.onConnect(record); }}>关联</a> */}
                    {
                        this.props.status <= 2 &&
                        <a onClick={() => { this.beforeDelete([text]); }}>删除</a>
                    }
                </Space>;
            }
        }
    ];
    constructor(props) {
        super(props);
        this.state = {
            list: [
            ],
            menuKey: '',
            pageMeta: null,
            params: {},
            visible: false,
            taskUuid: this.props.taskUuid,
            recordUuid: '',
            invoiceModal: false,
            selectedRowKeys: [],
            record: {},
            invoiceUuid: '',
            historyModal: false,
            connectModal: false,
            originalDocList: this.props.originalDocList || []
        };
    }

    onConnect = record => {
        this.setState({
            record,
            connectModal: true
        })
    }
    onRecheck = async (text) => {
        const res: any = await agent.get('/collector/asset/reCheck', { invoiceUuid: text }, this);
        if (res.err) {
            return;
        } else {
            this.onRefresh();
            message.success('操作成功');
        }
    }
    onRecord = id => {
        this.setState({
            invoiceUuid: id
        })
    }
    closeVerify = () => {
        this.setState({
            invoiceUuid: '',
        })
    }
    componentDidMount() {
        const params = {
            pageNum: 1,
            pageSize: 10
        };
        this.getData(params);
    }
    onView = async (record) => {
        this.setState({
            recordUuid: record.invoiceUuid,
            invoiceModal: true,
            record
        })
    }
    closeInvoice = () => {
        this.setState({
            invoiceModal: false
        })
    }
    beforeDelete = (id) => {
        Modal.confirm({
            title: '确认删除',
            content: '此发票采集记录会一起删除。',
            okText: '删除',
            onOk: () => {
                this.onDelete(id);
            },
            onCancel() {
                console.log('Cancel');
            },
        });
    }
    onDelete = async (keys: string) => {
        const res: any = await agent.post('/collector/task/deleteInvoiceAsset',
            keys,
            // taskUuid: this.state.taskUuid
            this);
        if (res.er) {
            return;
        } else if (res.res) {
            this.onRefresh();
        }
    }
    getData = async (params) => {
        params = {
            ...params,
            taskUuid: this.state.taskUuid
        }
        const res: any = await agent.post('/collector/task/assetInvoicePage', params, this);
        if (res.er) {
            return;
        } else if (res.res) {
            this.setState({
                pageMeta: res.res.pageMeta,
                list: res.res.items,
            });
        }
    }
    onClose = () => {
        this.setState({
            visible: false,
        });
    }
    onSuccess = (list: any[]) => {
        console.log(list);
    }
    handleMenuClick = e => {
        this.setState({
            visible: true,
            menuKey: e.key
        });
    };
    onSearch = (data = {}) => {
        this.setState({
            params: data
        });
        const params = {
            ...data,
            ...this.state.pageMeta,
            pageNum: 1,
            pageSize: 10
        };
        this.getData(params);
    }
    radioChange = (e) => {
        this.props.changeView!(e.target.value);
    }
    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);
    }
    /**
     * 发票采集成功后回掉，刷新列表，还要请求任务详情接口
     */
    onCaijiRefresh = () => {
        this.onRefresh();
        this.props.onSuccess!();
    }
    onBatchProve = async (list?) => {
        const data = {
            taskUuid: this.state.taskUuid,
            invoiceUuidList: list || this.state.selectedRowKeys
        };
        const res: any = await agent.post('/web/verifiedTask/toProved', data, this);
        if (res.err) {
            return;
        } else if (res.res) {
            message.success('操作成功');
            this.props.onSuccess!();
            this.onRefresh();
            this.setState({
                selectedRowKeys: []
            })
        }
    }
    onSyncProve = async (list) => {
        const data = {
            taskUuid: this.state.taskUuid,
            invoiceUuidList: list || this.state.selectedRowKeys
        };
        const res: any = await agent.post('/web/verifiedTask/reProved', data, this);
        if (res.err) {
            return;
        } else if (res.res) {
            message.success('操作成功');
            this.onRefresh();
            this.setState({
                selectedRowKeys: []
            })
        }
    }
    topExpand = () => {
        return (
            <AdvancedSearch
                width={400}
                height={44}
                compact={true}
                defaultKey="invoiceNo"
                placeholder="请输入发票号码"
                searchFormSubmit={this.onSearch}
            >
                <KtsForm
                    labelCol={6}
                    wrapperCol={18}
                    labelAlign="left"
                    compact={true}
                    schema={{
                        type: 'object',
                        properties: {
                            // invoiceType: {
                            //     type: 'string',
                            //     title: '发票类型',
                            //     enum: invoiceTypeEnum,
                            //     'x-props': {
                            //         mode: "multiple",
                            //         filterOption: (input, option) =>
                            //             option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            //     }
                            // },
                            proveStatus: {
                                type: 'string',
                                title: '证明结果',
                                enum: proveStatusEnum
                            },
                            salerName: {
                                type: 'string',
                                title: '销售方',
                            },
                            buyerName: {
                                type: 'string',
                                title: '采购方',
                            },
                            invoiceNo: {
                                type: 'string',
                                title: '发票号码',
                            },
                            invoiceCode: {
                                type: 'string',
                                title: '发票代码',
                            },
                            kaipiaoriqi: {
                                type: 'daterange',
                                title: '开票日期范围',
                                'x-props': {
                                    extendsFields: ['minInvoiceDate', 'maxInvoiceDate'],

                                }
                            },
                            originalDocument: {
                                type: 'string',
                                title: '关联单据',
                            },
                            // relationTaskNo: { 
                            //     type: 'string',
                            //     title: '关联任务单号',
                            // },
                        },
                    }}
                >
                </KtsForm>
            </AdvancedSearch>
        );
    }
    onShowHistory = () => {
        this.setState({
            historyModal: true
        })
    }
    onCloseHistroy = () => {
        this.setState({
            historyModal: false
        })
    }
    onConnectClose = () => {
        this.onRefresh();
        this.setState({
            connectModal: false
        })
    }
    onConnectSave = async data => {
        data = {
            ...data,
        }
        const res: any = await agent.post('/collector/task/linkGoodsWithDoc', data, this);
        if (res.er) {
            return;
        } else if (res.res) {
            this.onConnectClose();
        }
        this.onConnectClose();
    }

    onBatchDelete = () => {
        const ids = this.state.selectedRowKeys;
        if(ids.length === 0){
            message.error('请先选择需要删除的项');
            return;
        }
        Modal.confirm({
            title: '确认删除',
            content: '选中的发票采集记录会一起删除。',
            okText: '删除',
            onOk: () => {
                this.onDelete(ids);
            },
            onCancel() {
                console.log('Cancel');
            },
        }); 
    }
    render() {
        const { list, pageMeta, invoiceModal, selectedRowKeys, invoiceUuid, historyModal, connectModal, originalDocList, record } = this.state;
        const { status } = this.props;
        const dataSource = list && list.map((item, index) => {
            return {
                ...item,
                index
            };
        });
        const rowSelection = {
            onChange: (selectedRowKeys) => {
                this.setState({
                    selectedRowKeys
                })
            },
            // getCheckboxProps: (record) => ({
            //     disabled: record.proveStatus === 1 || record.proveStatus === 3,
            // }),
            selectedRowKeys
        };
        return (
            <>
                <div style={{ display: 'flex', padding: '0 20px 10px' }}>
                    <div style={{ flex: 1 }}>
                        {this.topExpand()}
                    </div>
                    <Space>
                        {(status === 1 || status === 2) && <InvoiceComponent value={this.props.type} key='0' taskUuid={this.state.taskUuid} onSuccess={this.onCaijiRefresh}><Button type="primary">发票采集</Button></InvoiceComponent>}
                        {/* <Button disabled={selectedRowKeys.length > 0 ? false : true} onClick={() => { this.onBatchProve(); }}>请求证明</Button> */}
                        <Button disabled={!selectedRowKeys.length} key='2' type="default" onClick={this.onBatchDelete}>批量删除</Button>
                        <Button key='1' onClick={this.onShowHistory}>采集记录</Button>
                        <Button key='3' onClick={this.onRefresh} icon={<ReloadOutlined />}></Button>
                    </Space>
                </div>
                <div style={{ padding: '0 20px' }} className="content">
                    <div style={{ paddingBottom: 10 }}>
                        <Table
                            rowSelection={rowSelection}
                            dataSource={dataSource}
                            columns={this.columns as any}
                            scroll={{ x: '1400' }}
                            pagination={false}
                            rowKey='invoiceUuid'
                        />
                        {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} />}
                    </div>
                </div>
                {invoiceModal && <InvoiceModal originalDocList={originalDocList} status={status} data={this.state.record} onClose={this.closeInvoice} recordUuid={this.state.recordUuid} taskUuid={this.state.taskUuid} />}
                {invoiceUuid && <VerifyList url='/web/verifiedHandle/queryInvoicePage' goodsUuid={{ invoiceUuid }} onClose={this.closeVerify} />}
                {historyModal && <RecordList taskUuid={this.state.taskUuid} onSuccess={this.onCloseHistroy} />}
                {connectModal && <ConnectPanel onSave={this.onConnectSave} onClose={this.onConnectClose} value={[]} list={originalDocList} />}
            </>
        );
    }

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