import * as React from 'react';
import { PageHeaderFoot, Button, AutoTableContainer, Table, Pagination, Tag, Radio, MoreMenus, message } from 'kts-xui';
import { AdvancedSearch, KtsForm, WrapperDrop } from 'kts-components';
import AddModal from './UI.DenyModal';
import moment from 'moment';
import { columnEnum } from '../CommonComponents/ColumnEnum';
import { findLabel, invoiceTypeEnum, complianceStatusEnum } from '../CommonComponents/FiledsEnum';
import { withRouter, RouteChildrenProps } from 'react-router-dom';
import agent from '../Server';
import { Space, Dropdown, Menu, Tooltip, Modal } from 'kts-components-antd-x4';
import { DigitalAssetVerification } from '../..';
import { CheckCircleOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import InvoiceComponent from './UI.InvoiceComponent';
import CollectRecord from './UI.Child.CollectRecord';
import InvoiceModal from './invoiceModal';
// import DIDSelect from './DIDSelect';
import Subrecordlist from './UI.Child.Subrecordlist';
import NoneButton from './UI.NoneConfigBtn';
import PurposeModal from './UI.UsedforModal'
const { confirm } = Modal;
/** Props接口 */
interface IProps {
    changeView: (value) => void
}

class UIComponents extends React.Component<IProps & RouteChildrenProps, any> {
    columns = [
        {
            title: '发票类型',
            width: 120,
            align: 'center',
            dataIndex: 'invoiceType',
            render: (text, record) => {
                if (text) {
                    return <Tag>{findLabel(text, invoiceTypeEnum)}</Tag>

                }
            }
        },
        {
            title: '合规状态',
            dataIndex: columnEnum['合规状态'],
            width: 100,
            ellipsis: true,
            align: 'center',
            render: (text, record) => {
                if (text !== 1) {
                    return <Tooltip title={record.complianceMsg}><ExclamationCircleOutlined style={{ color: 'red' }} /></Tooltip>
                } else {
                    return <CheckCircleOutlined style={{ color: '#0074ff' }} />
                }
            }
        },
        {
            title: '销售方',
            dataIndex: columnEnum['销售方'],
            width: 200,
            ellipsis: true,
        }, {
            title: '购买方',
            dataIndex: columnEnum['采购方'],
            width: 200,
            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: '操作',
            dataIndex: 'invoiceUuid',
            width: 150,
            fixed: 'right',
            render: (text, record) => {
                const menu = (
                    <Menu>
                        <Menu.Item >
                            <a onClick={() => { this.onRecheck(text) }}>重验</a>
                        </Menu.Item>
                        <Menu.Item disabled={record.submitStatus === 1 ? false : true}>
                            <a onClick={() => { this.onViewHistory(text) }}>提交记录</a>
                        </Menu.Item>
                        <Menu.Item disabled={record.canDelete === 1 ? false : true}>
                            {record.canDelete === 1 && <a onClick={() => { this.onDelete([text]); }}>删除</a>}
                        </Menu.Item>
                    </Menu>
                )
                return <Space>
                    <Button style={{ padding: 0, fontSize: 12 }} disabled={record.salerName ? false : true} type="link" onClick={() => { this.onView(record); }}>查看</Button>
                    {this.showSubmitButton(record)}
                    <MoreMenus dropdownProps={{ overlay: menu }} />
                </Space>

            }
        },
    ];
    constructor(props) {
        super(props);
        this.state = {
            pageMeta: null,
            list: [],
            params: this.props.location.state || {},
            showModal: false,
            selectedRowKeys: [],
            denyList: [],
            invoiceUuid: '',
            recordModal: false,
            invoiceModal: false,
            record: {},
            selectParty: {},
            config: [],
            showDid: false,
            sublistModal: false,
            loading: false
        };
    }
    /**
     * 查看单张发票提交记录
     * @param text 
     */
    onViewHistory = (text) => {
        this.setState({
            sublistModal: true,
            invoiceUuid: text
        })
    }
    closeSubrecord = () => {
        this.setState({
            sublistModal: false,
        })
    }
    onRecheck = async (text) => {
        const res: any = await agent.get('/collector/asset/reCheck', { invoiceUuid: text }, this);
        if (res.err) {
            return;
        } else {
            this.onRefresh();
            message.success('操作成功');
        }
    }
    onView = record => {
        this.setState({
            invoiceModal: true,
            invoiceUuid: record.invoiceUuid,
            record
        })
    }

    // showDid = (id) => {
    //     this.setState({
    //         showDid: true,
    //         selectedRowKeys: [id]
    //     })
    // }
    //批量提交前检查是否有配置项
    beforeSubmit = async idlist => {
        const configlist = this.state.config;
        if (configlist.length === 1) {
            const data = {
                ...configlist[0],
                invoiceUuidList: idlist
            }
            this.submitBatch(data, configlist[0]);
        } else {
            this.setState({
                showDid: true
            })
        }
    }
    //批量提交
    submitBatch = async (data, config) => {
        if (!this.state.loading) {
            this.setState({
                loading: true
            })
            const res: any = await agent.post('/collector/asset/submitBatch', data, this);
            this.setState({
                loading: false
            })
            if (res.err) {
                return;
            } else {
                //验证通过直接调用提交接口
                if (res.res.checkPass) {
                    const list = res.res.invoiceUuidList;
                    const data = {
                        ...config,
                        invoiceUuidList: list
                    };
                    this.onFinalSubmit(data);
                } else {
                    //验证部分数据失败，弹框提示
                    const list = res.res.invoiceUuidList;
                    const total = this.state.selectedRowKeys.length;
                    confirm({
                        title: '重复提交',
                        content: <p>您已勾选的{total}行发票数据，有{total - list.length}行已经提交过，无法重复提交，是否提交剩余发票
                            <a href={res.res.downloadUrl} target="_blank">下载重复发票信息</a>
                        </p>,
                        onOk: () => {
                            const data = {
                                ...config,
                                invoiceUuidList: list
                            };
                            this.onFinalSubmit(data);
                        },
                    });
                }
            }
        }
    }
    //验证通过后提交
    onFinalSubmit = async (data) => {
        const res: any = await agent.post('/collector/asset/submitBatchConfirm', data, this);
        if (res.err) {
            return;
        } else {
            message.success('操作成功');
        }
    }
    getSubmitConfig = async () => {
        const res: any = await agent.get('/collector/asset/getVerifierConfigList', {}, this);
        if (res.err) {
            return null;
        } else {
            res.res = res.res.map((item, index) => {
                return {
                    ...item,
                    // id: index
                }
            })
            this.setState({
                config: res.res
            })
        }
        return res.res
    }
    /**
     * 删除
     * @param idlist 
     */
    onDelete = async (idlist) => {
        const res: any = await agent.post('/collector/asset/deleteInvoiceAsset', idlist, this);
        if (res.err) {
            return;
        } else {
            this.onRefresh();
        }
    }
    closeVerify = () => {
        this.setState({
            invoiceUuid: ''
        })
    }
    radioChange = (e) => {
        this.props.changeView(e.target.value);
    }
    topExpand = () => {
        return (
            <AdvancedSearch
                width={400}
                height={44}
                compact={true}
                defaultKey="invoiceNo"
                placeholder="请输入发票号码"
                searchFormSubmit={this.onSearch}
                extra={
                    <>
                        <Radio.Group defaultValue="collect" 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: {
                            [columnEnum['发票类型']]: {
                                type: 'string',
                                title: '发票类型',
                                enum: invoiceTypeEnum,
                                'x-props': {
                                    mode: "multiple"
                                }
                            },
                            [columnEnum['合规状态']]: {
                                type: 'string',
                                title: '合规状态',
                                enum: complianceStatusEnum,
                                'x-props': {
                                    mode: "multiple"
                                }
                            },
                            [columnEnum['销售方']]: {
                                type: 'string',
                                title: '销售方',
                            },
                            [columnEnum['采购方']]: {
                                type: 'string',
                                title: '购买方',
                            },
                            invoiceCode: {
                                type: 'string',
                                title: '发票代码',
                            },
                            invoiceNo: {
                                type: 'string',
                                title: '发票号码',
                            },
                            kaipiao: {
                                type: 'daterange',
                                title: '开票日期',
                                'x-props': {
                                    extendsFields: ['minInvoiceDate', 'maxInvoiceDate'],
                                }
                            },
                            endDate: {
                                type: 'daterange',
                                title: '采集时间',
                                'x-props': {
                                    extendsFields: ['minCreateTime', 'maxCreateTime'],
                                }
                            },
                            submitStatus: {
                                type: 'string',
                                title: '是否提交过',
                                enum: [
                                    { label: '未提交', value: 0 },
                                    { label: '已提交', value: 1 }
                                ],
                                'x-props': {
                                    mode: "multiple"
                                }
                            }

                        },
                    }}
                >
                </KtsForm>
            </AdvancedSearch>
        );
    }
    /**
     * 拒绝
     * @param keys 
     */
    onDenyHandler = (keys: string[]) => {
        this.setState({
            denyList: keys,
            showModal: true
        })
    }
    async componentDidMount() {
        const params = {
            pageNum: 1,
            pageSize: 10,
            ...this.state.params,
        };
        await this.getSubmitConfig();
        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'),
            minCreateTime: params['minCreateTime'] && moment(params['minCreateTime']).format('YYYY-MM-DD 00:00:00'),
            maxCreateTime: params['maxCreateTime'] && moment(params['maxCreateTime']).format('YYYY-MM-DD 23:59:59'),
        }
        const res: any = await agent.post('/collector/asset/assetInvoicePage', params, this);
        if (res.err) {
            return;
        } else {
            this.setState({
                pageMeta: res.res.pageMeta,
                list: res.res.items
            });
        }
    }
    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'),
            minCreateTime: params['minCreateTime'] && moment(params['minCreateTime']).format('YYYY-MM-DD 00:00:00'),
            maxCreateTime: params['maxCreateTime'] && moment(params['maxCreateTime']).format('YYYY-MM-DD 23:59:59'),
        };
        const res: any = await DigitalAssetVerification.server.post(`${DigitalAssetVerification.prefix_path}/web/verifier/report/exportInvoiceDetail`, 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();
    }
    handleMenuClick = (e) => {
        if (e.key === 'record') {
            this.setState({
                recordModal: true
            })
        } else if (e.key === 'delete') {
            this.onDelete(this.state.selectedRowKeys)
        }
    }
    onCloseRecord = () => {
        this.setState({
            recordModal: false
        })
    }
    closeInvoice = () => {
        this.setState({
            invoiceModal: false
        })
    }
    // onCloseDid = () => {
    //     this.setState({
    //         showDid: false,
    //     })
    // }
    // onSuccessDid = () => {
    //     this.setState({
    //         showDid: false,
    //         selectedRowKeys: []
    //     })
    // }
    handleDidClick = (e) => {
        const { config, selectedRowKeys } = this.state;
        const selectData = {
            verifierName: config[e.key].verifierName,
            verifierPartyId: config[e.key].verifierPartyId,
            collectorPartyId: config[e.key].collectorPartyId,
        }
        const data = {
            ...selectData,
            invoiceUuidList: selectedRowKeys
        }
        this.submitBatch(data, selectData);
    }
    //单个提交
    showSubmitButton = (record: any) => {
        const { config } = this.state;
        //多个配置
        if (config.length > 1) {
            return record.salerName ?
                <a><PurposeModal config={config} record={record} >提交</PurposeModal></a> :
                <Button style={{ padding: 0, fontSize: 12 }} type='link' disabled={true}>提交</Button>
            // const menu = (
            //     <Menu>
            //         {config && config.map((item, index) => {
            //             return <Menu.Item key={index}>
            //                 <PurposeModal config={item} record={record} >{item.verifierName}</PurposeModal>
            //             </Menu.Item>
            //         })}
            //     </Menu>
            // );
            // return <Dropdown key='1' disabled={record.salerName ? false : true} overlay={menu}><Button style={{ padding: 0,fontSize:12 }} type='link'>提交</Button></Dropdown>
        } else if (config.length === 1) {
            //1个配置
            if (record.salerName) {
                return <a><PurposeModal config={config} record={record} >提交</PurposeModal></a>
            } else {
                return <Button style={{ padding: 0, fontSize: 12 }} disabled={true} key='1' type='link'>提交</Button>
            }
        } else {
            //未设置配置
            if (record.salerName) {
                return <NoneButton record={record} ><a>提交</a></NoneButton>
            } else {
                return <Button style={{ padding: 0, fontSize: 12 }} type='link' disabled={true}>提交</Button>
            }

        }
    }

    showBatchSubmitButton = () => {
        const { config, selectedRowKeys, } = this.state;
        if (config.length > 1) {
            return <Button><PurposeModal config={config} invoiceUuidList={selectedRowKeys} >批量提交</PurposeModal></Button>
        } else if (config.length === 1) {
            if (selectedRowKeys.length === 0) {
                return <Button disabled={true} key='1' type='primary' >批量提交</Button>
            } else {
                return <PurposeModal config={config} invoiceUuidList={selectedRowKeys} ><Button type='primary' >批量提交</Button></PurposeModal>
            }
        } else {
            return <NoneButton ><Button disabled={selectedRowKeys.length === 0 ? true : false} key='1' type='primary' >批量提交</Button></NoneButton>
        }

    }
    render() {
        const dataSource = this.state.list;
        const { pageMeta, selectedRowKeys, recordModal, invoiceModal, showDid, sublistModal } = this.state;
        const rowSelection = {
            selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRowKeys
                });
            },
            getCheckboxProps: (record) => ({
                // disabled: record.effectiveStatus !== 1
            }),
        }
        const menu = (
            <Menu onClick={(e) => { this.handleMenuClick(e) }}>
                <Menu.Item key="record">
                    采集记录
                </Menu.Item>
                <Menu.Item disabled={selectedRowKeys.length === 0 ? true : false} key="delete">
                    批量删除
                </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={[
                            <InvoiceComponent key='0' onSuccess={this.onCaijiRefresh}>
                                <Button type="primary">采集</Button>
                            </InvoiceComponent>,
                            this.showBatchSubmitButton(),
                            <WrapperDrop overlay={menu}>
                                <Button>更多</Button>
                            </WrapperDrop>
                        ]}
                        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: '1700', 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} />
                }
                {
                    recordModal && <CollectRecord onClose={this.onCloseRecord} />
                }
                {
                    invoiceModal && <InvoiceModal data={this.state.record} onClose={this.closeInvoice} invoiceUuid={this.state.invoiceUuid} />
                }
                {/* {
                    showDid && <DIDSelect onSuccess={this.onSuccessDid} onClose={this.onCloseDid} data={this.state.config} list={selectedRowKeys} />
                } */}
                {
                    sublistModal && <Subrecordlist invoiceUuid={this.state.invoiceUuid} onClose={this.closeSubrecord} />
                }
            </div>
        );
    }
}
export default withRouter<any, any>(UIComponents as any)