import * as React from 'react';
import { PageHeaderFoot, Button, Table, message } from 'kts-xui';
import { Pagination, Space, Tag, Tooltip, Modal,  } from 'kts-components-antd-x4';
import { AdvancedSearch, KtsForm } from 'kts-components';
import agent from '../../../Server';
import { withRouter, RouteChildrenProps } from 'react-router-dom';
import { invoiceTypeEnum, nationStatusEnum, proveStatusEnum, findLabel, reviewStatusEnum } from '../../../CommonComponents/FiledsEnum';
import moment from 'moment';
import InvoiceModal from './invoiceModal';
import VerifyList from '../../../CommonComponents/VerifyList'
import {
    WarningOutlined,
} from '@ant-design/icons';
/** Props接口 */
interface IProps {
    onSuccess?: () => void;
    taskUuid: string;
    changeView?: (value) => void;
    status: number;
}
class UIComponents extends React.Component<IProps & RouteChildrenProps, any> {
    columns = [
        {
            title: '销售方',
            dataIndex: 'salerName',
            width: 190,
            key: 'salerName',
            ellipsis: true,
        },
        {
            title: '采购方',
            dataIndex: 'buyerName',
            width: 190,
            key: 'buyerName',
            ellipsis: true,
        },
        {
            title: '发票类型',
            dataIndex: 'invoiceType',
            width: 120,
            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: 'invoiceNo',
            width: 190,
            key: 'invoiceNo',
        },
        {
            title: '发票代码',
            dataIndex: 'invoiceCode',
            width: 160,
            key: 'invoiceCode',
        },

        {
            title: '开票日期',
            dataIndex: 'invoiceDate',
            width: 160,
            key: 'invoiceDate',
            render: text => {
                return text && moment(text).format('YYYY-MM-DD')
            }
        },
        {
            title: '关联单据',
            dataIndex: 'originalDocList',
            width: 160,
            ellipsis: true,
            render: (text, record) => {
                if (record.originalDocList?.length > 0) {
                    let originalDocuments=record.originalDocList.reduce((acc, obj)=>{
                        acc.push(obj.originalDocument);
                        return acc;
                    },[])
                    let str=originalDocuments.join('/');
                    return str
                } 
            }
        },
        {
            title: '证明结果',
            dataIndex: 'proveStatus',
            width: 120,
            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 <span>{findLabel(text, proveStatusEnum)}</span>
                }
            }
        },
        // {
        //     title: '是否复验',
        //     dataIndex: 'reviewStatus',
        //     width: 120,
        //     key: 'reviewStatus',
        //     render: (text,record) => {
        //         if (text === 3) {
        //             return <Tooltip title={record.reviewMsg}><span style={{ color: 'red' }}>{findLabel(text, reviewStatusEnum)}</span></Tooltip>
        //         } else {
        //             return <span>{findLabel(text, reviewStatusEnum)}</span>
        //         }
        //     }
        // },
        {
            title: '操作',
            dataIndex: 'id',
            width: 140,
            key: 'id',
            fixed: 'right',
            render: (text, record) => {
                return <Space>
                    <a onClick={() => { this.onView(record); }}>查看</a>

                    {/* {record.reviewStatus !== 0 && <a onClick={() => { this.onRecord(text); }}>复验记录</a>} */}

                </Space>;
            }
        }
    ];
    constructor(props) {
        super(props);
        this.state = {
            list: [
            ],
            pageMeta: null,
            params: {},
            visible: false,
            taskUuid: this.props.taskUuid,
            recordUuid: '',
            invoiceModal: false,
            record: {},
            selectedRowKeys: [],
            isFullReview: false,
            verifyId: ''
        };
    }

    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
        })
    }
    onRecord = async (id) => {
        this.setState({
            verifyId: id
        })
    }
    onDelete = async (keys: string) => {
        const res: any = await agent.post('/web/verifiedTask/deleteCollectInvoice', {
            invoiceUuid: keys,
            taskUuid: this.state.taskUuid
        }, this);
        if (res.err) {
            return;
        } else if (res.res) {
            this.onRefresh();
        }
    }
    getData = async (params) => {
        params = {
            ...params,
            taskUuid: this.state.taskUuid
        }
        const res: any = await agent.post('/web/verifier/invoice/queryInvoicePage', 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);
    }
    onSearch = (data = {}) => {
        this.setState({
            params: data
        });
        const params = {
            ...data,
            ...this.state.pageMeta,
            pageNum: 1,
        };
        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);
    }
    topExpand = () => {
        return (
            <AdvancedSearch
                width={480}
                height={44}
                compact={true}
                defaultKey="invoiceNo"
                placeholder="请输入发票号码"
                searchFormSubmit={this.onSearch}
            >
                <KtsForm
                    labelCol={6}
                    wrapperCol={18}
                    labelAlign="left"
                    compact={true}
                    schema={{
                        type: 'object',
                        properties: {
                            includeManyInvoiceType: {
                                type: 'string',
                                title: '发票类型',
                                enum: invoiceTypeEnum,
                                'x-props': {
                                    mode: "multiple"
                                }
                            },
                            proveStatus: {
                                type: 'string',
                                title: '证明结果',
                                enum: proveStatusEnum.slice(0,2)
                            },
                            salerName: {
                                type: 'string',
                                title: '销售方',
                            },
                            buyerName: {
                                type: 'string',
                                title: '采购方',
                            },
                            invoiceNo: {
                                type: 'string',
                                title: '发票号码',
                            },
                            invoiceCode: {
                                type: 'string',
                                title: '发票代码',
                            },
                            kaipiao: {
                                type: 'daterange',
                                title: '开票日期范围',
                                'x-props': {
                                    extendsFields: ['minInvoiceDate', 'maxInvoiceDate'],
                                }
                            },
                        },
                    }}
                >
                </KtsForm>
            </AdvancedSearch>
        );
    }
    onVerify = async () => {
        const { selectedRowKeys, isFullReview, taskUuid } = this.state;
        const params = {
            includeManyInvoiceUuid: selectedRowKeys,
            taskUuid: taskUuid,
            isFullReview: isFullReview
        }
        const res: any = await agent.post('/web/verifier/review/doReview', params, this);
        if (res.err) {
            return;
        } else if (res.res) {
            message.success('操作成功');
            this.setState({
                selectedRowKeys:[]
            })
            this.onRefresh();
        }
    }
    closeVerify = () => {
        this.setState({
            verifyId: ''
        })
    }
    render() {
        const { list, pageMeta, invoiceModal, selectedRowKeys, verifyId, taskUuid } = this.state;
        const dataSource = list && list.map((item, index) => {
            return {
                ...item,
                index
            };
        });
        const rowSelection = {
            onChange: (selectedRowKeys) => {
                this.setState({
                    selectedRowKeys
                })
            },
            getCheckboxProps: (record) => ({
                disabled: record.proveStatus === 2,
            }),
            selectedRowKeys
        };
        return (
            <>
                <div style={{ display: 'flex', padding: '0 20px 10px' }}>
                    <div style={{ flex: 1 }}>
                        {this.topExpand()}
                    </div>
                    <Button disabled={selectedRowKeys.length > 0 ? false : true} onClick={this.onVerify}>复验</Button>
                </div>
                <div style={{ padding: '0 20px' }} className="content">
                    <div style={{ paddingBottom: 10 }}>
                        <Table
                            rowSelection={rowSelection}
                            className='fixheight'
                            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 data={this.state.record} onClose={this.closeInvoice} recordUuid={this.state.recordUuid} taskUuid={this.state.taskUuid} />}
                {verifyId && <VerifyList onClose={this.closeVerify} dataId={verifyId} />}
            </>
        );
    }

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