import * as React from 'react';
import { PageHeaderFoot, Button, AutoTableContainer, Pagination, Tag, message, TableManual, Modal as Modal2 } from 'kts-xui';
import { AdvancedSearch, KtsForm } from 'kts-components';
import { WrapperDrop } from 'kts-components';
import { Menu, Space, Tooltip, DatePicker, ConfigProvider, Modal } from 'kts-components-antd-x4';
import { InfoCircleOutlined, SettingOutlined } from '@ant-design/icons';
import AddModal from './UI.DenyModal';
import moment from 'moment';
import { columnEnum } from '../CommonComponents/ColumnEnum';
import { withRouter, RouteChildrenProps } from 'react-router-dom';
import { findLabel, invoiceTypeEnum, proveStatusEnum, reviewStatusEnum, taskTypeEnum } from '../CommonComponents/FiledsEnum';
import agent from '../Server';
import VerifyList from './VerifyList';
import { DigitalAssetVerification } from '../..';
import Sort from '../CommonComponents/Sort';
import 'moment/locale/zh-cn';
import zhCNAntd4 from 'kts-components-antd-x4/lib/locale/zh_CN';

const { RangePicker } = DatePicker;
/** Props接口 */
interface IProps {

}

/**
 * 发票明细
 */
class UIComponents extends React.Component<IProps & RouteChildrenProps, any> {
    columnAction = [{
        title: '操作',
        dataIndex: 'invoiceUuid',
        width: 140,
        fixed: 'right',
        render: (text, record) => {
            return <Space>
                <a onClick={() => { this.onSingleFuyan(record); }}>复验</a>
                <a onClick={() => { this.onVerifyRecords(record.invoiceUuid); }}>处理记录</a>
            </Space>


        }
    }]
    constructor(props) {
        super(props);
        this.state = {
            pageMeta: null,
            list: [
            ],
            params: this.props.location.state || {},
            showModal: false,
            selectedRowKeys: [],
            denyList: [],
            invoiceUuid: '',
            columns: [

                {
                    title: '采集方',
                    dataIndex: columnEnum['被核验方'],
                    key: columnEnum['被核验方'],
                    width: 190,
                    ellipsis: true,
                },
                {
                    title: '销售方',
                    dataIndex: columnEnum['销售方'],
                    key: columnEnum['销售方'],
                    width: 160,
                    ellipsis: true,
                }, {
                    title: '采购方',
                    dataIndex: columnEnum['采购方'],
                    key: columnEnum['采购方'],
                    width: 160,
                    ellipsis: true,
                },
                {
                    title: '证明结果',
                    width: 100,
                    align: 'center',
                    dataIndex: columnEnum['证明标识'],
                    key: columnEnum['证明标识'],
                    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 === 1) {
                            return <span style={{ color: '#0074ff' }}>{findLabel(text, proveStatusEnum)}</span>
                        } else {
                            return findLabel(text, proveStatusEnum);
                        }
                    }
                }, {
                    title: '发票类型',
                    width: 120,
                    align: 'center',
                    dataIndex: 'invoiceType',
                    key: 'invoiceType',
                    render: (text, record) => {
                        if (text) {
                            return <Tag>{findLabel(text, invoiceTypeEnum)}</Tag>

                        }
                    }
                }, {
                    title: '发票代码',
                    width: 140,
                    ellipsis: true,
                    dataIndex: 'invoiceCode',
                    key: 'invoiceCode',
                }, {
                    title: '发票号码',
                    width: 190,
                    ellipsis: true,
                    dataIndex: 'invoiceNo',
                    key: 'invoiceNo',
                }, {
                    title: '开票日期',
                    width: 140,
                    dataIndex: 'invoiceDate',
                    key: 'invoiceDate',
                    ellipsis: true,
                    render: (text) => {
                        return text && moment(text).format('YYYY-MM-DD');
                    }
                },
                {
                    title: '提交时间',
                    width: 160,
                    dataIndex: columnEnum['提交时间'],
                    key: columnEnum['提交时间'],
                    ellipsis: true,
                    render: text => {
                        return text && moment(text).format('YYYY-MM-DD HH:mm')
                    }
                },
                {
                    title: '提交用途',
                    width: 150,
                    ellipsis: true,
                    key:'submitPurpose',
                    dataIndex: 'submitPurpose',
                },
                {
                    title: '任务单号',
                    dataIndex: columnEnum['任务单号'],
                    key: columnEnum['任务单号'],
                    width: 160,
                    ellipsis: true,
                    render: (text, record) => {
                        if (record.originPartyType === 1) {
                            return <span>{text}</span>
                        }
                    }
                },
                {
                    title: '关联单据',
                    width: 120,
                    dataIndex: 'invoiceDocRelationList',
                    key: 'invoiceDocRelationList',
                    ellipsis: true,
                    render: (text) => {
                        if (text.length > 0) {
                            let originalDocuments = text.reduce((acc, obj) => {
                                acc.push(obj.originalDocument);
                                return acc;
                            }, [])
                            let str = originalDocuments.join('/');
                            return str
                        }
                    }
                },

            ],
            columnsMok: [
                {
                    title: '采集方',
                    dataIndex: columnEnum['被核验方'],
                    key: columnEnum['被核验方'],
                    type: 'string',
                },
                {
                    title: '销售方',
                    dataIndex: columnEnum['销售方'],
                    key: columnEnum['销售方'],
                    type: 'string',
                }, {
                    title: '采购方',
                    dataIndex: columnEnum['采购方'],
                    key: columnEnum['采购方'],
                    type: 'string',
                },
                {
                    title: '证明结果',
                    type: 'string',
                    dataIndex: columnEnum['证明标识'],
                    key: columnEnum['证明标识'],
                }, {
                    title: '发票类型',
                    type: 'string',
                    dataIndex: 'invoiceType',
                    key: 'invoiceType',
                }, {
                    title: '发票代码',
                    type: 'string',
                    dataIndex: 'invoiceCode',
                    key: 'invoiceCode',
                }, {
                    title: '发票号码',
                    type: 'string',
                    dataIndex: 'invoiceNo',
                    key: 'invoiceNo',
                }, {
                    title: '开票日期',
                    dataIndex: 'invoiceDate',
                    key: 'invoiceDate',
                    type: 'string',
                },
                {
                    title: '提交时间',
                    dataIndex: columnEnum['提交时间'],
                    key: columnEnum['提交时间'],
                    type: 'string',
                },
                {
                    title: '提交用途',
                    type: 'string',
                    dataIndex: 'submitPurpose',
                    key: 'submitPurpose',
                },
                {
                    title: '任务单号',
                    dataIndex: columnEnum['任务单号'],
                    key: columnEnum['任务单号'],
                    type: 'string',
                },
                {
                    title: '关联单据',
                    type: 'string',
                    dataIndex: 'invoiceDocRelationList',
                    key: 'invoiceDocRelationList',
                },
            ],
            sortDataSource: []
        };
    }
    /**
     * 单个复验
     * @param id 
     */
    onSingleFuyan = async (record) => {
        const data = {
            includeManyInvoiceUuid: [record.invoiceUuid],
        }
        const res: any = await agent.post('/web/verifier/review/one/doReview', data, this);
        if (res.err) {
            return;
        } else {
            message.success(res.res.reviewProveMsg);
            this.onRefresh();
        }
    }
    onFuyanAll = () => {
        const data = {
            selectType: 1,
            ...this.state.params
        }
        this.onFuyan(data);
    }
    /**
     * 批量复验
     * @param list 
     */
    onFuyan = async (data) => {

        const res: any = await agent.post('/web/verifier/review/batch/doReview', data, this);
        if (res.err) {
            return;
        } else {
            message.success('已发起复验');
            this.onRefresh();
        }
    }
    onVerifyRecords = id => {
        this.setState({
            invoiceUuid: id
        })
    }
    closeVerify = () => {
        this.setState({
            invoiceUuid: ''
        })
    }
    topExpand = () => {
        const { params } = this.state;
        let cloneData = JSON.parse(JSON.stringify(params));
        delete cloneData.minInvoiceDate
        delete cloneData.maxInvoiceDate
        delete cloneData.minSubmitTime
        delete cloneData.maxSubmitTime
        return (
            <AdvancedSearch
                width={480}
                height={44}
                compact={true}
                initialValues={cloneData}
                defaultKey="verifiedParty"
                placeholder="请输入采集方"
                searchFormSubmit={this.onSearch}
            >
                <KtsForm
                    labelCol={9}
                    wrapperCol={15}
                    labelAlign="left"
                    initialValues={cloneData}
                    compact={true}
                    schema={{
                        type: 'object',
                        properties: {
                            [columnEnum['任务单号']]: {
                                type: 'string',
                                title: '任务单号',
                            },
                            [columnEnum['被核验方']]: {
                                type: 'string',
                                title: '采集方',
                            },
                            [columnEnum['销售方']]: {
                                type: 'string',
                                title: '销售方',
                            },
                            [columnEnum['采购方']]: {
                                type: 'string',
                                title: '采购方',
                            },
                            invoiceNo: {
                                type: 'string',
                                title: '发票号码',
                            },
                            invoiceCode: {
                                type: 'string',
                                title: '发票代码',
                            },
                            kaipiaoriqi: {
                                type: 'daterange',
                                title: '开票日期',
                                'x-props': {
                                    extendsFields: ['minInvoiceDate', 'maxInvoiceDate'],
                                }
                            },
                            [columnEnum['证明标识']]: {
                                type: 'string',
                                title: '证明结果',
                                enum: proveStatusEnum.slice(0, 3),
                                'x-props': {
                                    allowClear: true
                                }
                            },
                            'tijiaoshijian': {
                                type: 'daterange',
                                title: '提交时间',
                                'x-props': {
                                    extendsFields: ['minSubmitTime', 'maxSubmitTime'],
                                }
                            },
                            submitPurpose: {
                                type: 'string',
                                title: '提交用途',
                            },
                            originalDocument: {
                                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);
        this.getLocalSort();
    }
    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,
            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'),
            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'),
            // minReviewTime: params['minReviewTime'] && moment(params['minReviewTime']).format('YYYY-MM-DD 00:00:00'),
            // maxReviewTime: params['maxReviewTime'] && moment(params['maxReviewTime']).format('YYYY-MM-DD 23:59:59'),
        }
        const res: any = await agent.post('/web/verifier/invoice/queryInvoicePage', params, this);
        if (res.err) {
            return;
        } else {
            this.setState({
                pageMeta: res.res.pageMeta,
                list: res.res.items
            });
        }
    }
    onExport = async () => {
        const { params } = this.state;
        const data = {
            ...params,
            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'),
            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'),
        };
        // const res: any = await DigitalAssetVerification.server.post(`${DigitalAssetVerification.prefix_path}/web/verifier/report/exportInvoice`, data).reqFs(DigitalAssetVerification.server.reqFs.filter(v => v !== DigitalAssetVerification.serviceTools.addContentType)).resFs([]).responseType('blob').end(null);
        const res: any = await DigitalAssetVerification.server.post(`${DigitalAssetVerification.prefix_path}/web/verifier/report/exportInvoice`, data).end(null);
        if (res.err) {
            return;
        } else {
            if(res.res){  
                Modal2.info({
                    title: '数据导出中',
                    content: <div style={{textAlign: 'center'}}>导出为异步操作，请稍后查看</div>,
                    onOk: () => {
                        this.props.history.push({ pathname: '/task/list/export', state: {fileType: 'INVOICE_RECORD'} })
                    },
                    okType: 'link',
                    okText: '查看导出记录',
                    closable: true,     // 显示右上角关闭按钮
                });
            } else {
                message.error('导出失败')
            }
            // 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;
        }
    }
    closeModal = () => {
        this.setState({
            showModal: false,
            denyList: []
        })
    }
    successModal = () => {
        this.getData();
        this.closeModal();
    }
    handleTimeRangeExport = async (params) => { 
        let prams = {
            startDate: params && params['0'] && moment(params['0']).format('YYYY-MM-DD'),
            endDate: params && params['1'] && moment(params['1']).format('YYYY-MM-DD'), 
        }
        const res: any = await DigitalAssetVerification.server.post(`${DigitalAssetVerification.prefix_path}/web/verifier/review/range/review`, prams).end(null);;
        if (res.err) {
            return;
        } else {
            if(res.res){  
                Modal2.info({
                    title: '数据导出中',
                    content: <div style={{textAlign: 'center'}}>导出为异步操作，请稍后查看</div>,
                    onOk: () => {
                        this.props.history.push({ pathname: '/task/list/export', state: {fileType: 'INVOICE_REVIEW'} })
                    },
                    okType: 'link',
                    okText: '查看导出记录',
                    closable: true,     // 显示右上角关闭按钮
                });
            } else {
                message.error('导出失败')
            }
        }
    }
    handleMenuClick = (e) => {
        if (e.key === 'all') {
            this.onFuyanAll();
        } else if (e.key === 'timerange'){
            let selectedDates:any = [];
            Modal2.confirm({
                title: '时间范围复验',
                content: <div style={{textAlign: 'center'}}>
                         <ConfigProvider locale={zhCNAntd4}>
                            <RangePicker
                                onChange={(dates) => {
                                    selectedDates = dates; // 获取选择的时间
                                }}
                            />
                        </ConfigProvider>
                </div>,
                okText: '确认复验',
                okType: 'primary',
                cancelText: '取消',
                onCancel: () => {},  // 点击取消按钮的回调函数
                onOk: () => {
                    if (selectedDates && selectedDates.length === 2) {
                        this.handleTimeRangeExport(selectedDates);
                    } else {
                        message.warning('请选择时间范围');
                    }
                    // this.props.history.push({ pathname: '/task/list/export', state: {fileType: 'INVOICE_RECORD'} })
                }, 
                // closable: true,     // 显示右上角关闭按钮
            });
        } else {
            if (this.state.selectedRowKeys.length <= 0) {
                message.error('请先勾选发票，再执行批量勾选复验。')
                return
            }
            const data = {
                includeManyInvoiceUuid: this.state.selectedRowKeys,
                selectType: 2
            }
            this.onFuyan(data);
        }
    }
    setDataSource = (data) => {
        const keys = Sort.filter(this.state.columnsMok, data) || [];
        const checkedKeys = keys.map((item) => {
            return {
                key: item.key,
                checked: true
            }
        })
        this.setState({
            sortDataSource: checkedKeys
        })
        window.localStorage.setItem('masterinvoice', JSON.stringify(data))
    }
    getLocalSort = () => {
        const d = window.localStorage.getItem('masterinvoice');
        let checkedKeys = []
        if (d) {
            checkedKeys = JSON.parse(d);
            this.setDataSource(checkedKeys);
        } else {
            checkedKeys = this.state.columns.map((item) => {
                return {
                    key: item.key,
                    checked: true
                }
            })
        }
        this.setState({
            sortDataSource: checkedKeys
        })

    }
    render() {
        const dataSource = this.state.list;
        const { pageMeta, selectedRowKeys, invoiceUuid, sortDataSource } = this.state;
        const columns = Sort.filter(this.state.columns, this.state.sortDataSource) || [];
        const rowSelection = {
            selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRowKeys
                });
            },
            getCheckboxProps: (record) => ({
                disabled: record.name === 'Disabled User'

            }),
        }
        const menu = (<Menu onClick={this.handleMenuClick}>
            <Menu.Item key='all'>
                全部发票 <Tooltip title='若执行了筛选，则会对筛选结果的全部发票进行复验。'><InfoCircleOutlined style={{ color: '#0074ff' }} /></Tooltip>
            </Menu.Item>
            <Menu.Item key='selected'>
                勾选发票
            </Menu.Item>
            <Menu.Item key='timerange'>
                时间范围
            </Menu.Item>
        </Menu>)
        return (
            <div style={{ height: 'calc(100vh - 97px)', display: 'flex', flexDirection: 'column' }}>
                <div style={{ flex: 'none', position: 'relative', zIndex: 1 }}>
                    <PageHeaderFoot
                        expandLeft={this.topExpand()}
                        expandRight={[
                            <WrapperDrop overlay={menu} key='3'><Button type="primary">批量复验</Button></WrapperDrop>,
                            // <Button key='0' disabled={selectedRowKeys.length > 0 ? false : true} type="primary" onClick={this.onFuyan}>批量复验</Button>,
                            <Button key='1' type="primary" onClick={this.onExport}>导出</Button>,
                            <Sort
                                columns={this.state.columnsMok}
                                dataSource={sortDataSource}
                                onChange={this.setDataSource}
                                mustShows={['verifiedParty', 'salerName', 'buyerName', 'proveStatus', 'invoiceCode', 'invoiceNo',]}
                            >
                                <Button icon={<SettingOutlined />} />
                            </Sort>
                        ]}
                        onRefresh={this.onRefresh}
                    >

                    </PageHeaderFoot>
                </div>
                <AutoTableContainer style={{ flex: 1, padding: '0 20px', background: '#F4F4F4' }} >
                    <TableManual
                        id='masterinvoice'
                        className='fixheight'
                        dataSource={dataSource}
                        bordered={true}
                        columns={[...columns, ...this.columnAction] as any}
                        rowSelection={rowSelection}
                        scroll={{ y: 'max-content' }}
                        pagination={false}
                        rowKey='invoiceUuid'
                    />
                </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(UIComponents as any)