import * as React from 'react';
import { PageHeaderFoot, Button, Modal, message, } from 'kts-xui';
import { WrapperDrop } from 'kts-components';
import { Tag, Menu, Space,  } from 'kts-components-antd-x4';
import Icon, { InfoCircleOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
// import agent from '../Server';
import moment from 'moment';
import { DigitalAssetVerification as agent } from '../..';
import InvoiceImport from '../SlaveInvoiceList/invoiceImport';
interface IProps {
    list: []
}
const AddBatch = (props: IProps) => {
    const [visible, setVisible] = React.useState(false);
    const [tip, setTip] = React.useState('');
    const [downloadFilePath, setDownlad] = React.useState('');
    const [successNo, setSuccess] = React.useState(0);
    const [failureNo, setfailure] = React.useState(0);
    const [errorModal, setModal] = React.useState(false);
    const handleMenuClick = React.useCallback((e) => {
        if (e.key === 'create') {
            setVisible(true);
        } else if (e.key === 'send') {
            sendBatch()
        }
    }, [props.list])
    const sendBatch = React.useCallback(async () => {
        if (props.list.length > 0) {
            const res: any = await agent.server.post(`${agent.prefix_path}/web/verifierTask/batch/send`, { includeManyTaskUuid: props.list }).resFs(agent.server.resFs.filter(v => v !== agent.serviceTools.verificationResponse)).end(null);
            if (res.err) {
                if (res.err.body?.status.description.indexOf('只有草稿状态的任务才能发送') >= 0) {
                    Modal.confirm({
                        title:'操作失败!',
                        icon: <CloseCircleOutlined style={{ color: '#FF5F58', fontSize: 30 }} /> ,
                        content: (
                            <>
                            只有任务状态为<span style={{ color: '#0074ff' }}>草稿</span>的任务才可以发送，请重新勾选。
                            </>
                        ),
                    })
                } else {

                    Modal.confirm({
                        title:'操作失败!',
                        icon: null,
                        content: (
                            <>
                               
                            网络异常，请稍后重试
                            </>
                        ),
                    })
                }

            } else {
                setDownlad(res.res.downloadUrl);
                setSuccess(res.res.successNo);
                setfailure(res.res.failureNo);
                if (res.res.failureNo === res.res.failureNo + res.res.successNo) {
                    setTip('failure')
                } else if (res.res.successNo === res.res.failureNo + res.res.successNo) {
                    setTip('success')
                } else {
                    setTip('half')
                }
                setModal(true)
            }
        }else{
            message.error('请勾选发送任务');
        }
    }, [props.list])
    const menu = (<Menu onClick={handleMenuClick}>
        <Menu.Item key='create'>
            批量创建
        </Menu.Item>
        <Menu.Item key='send'>
            批量发送
        </Menu.Item>
    </Menu>)
    const uploadExcel = async (values) => {
        const res: any = await agent.server
            .post(`${agent.prefix_path}/web/verifierTask/import`)
            .reqFs(agent.server.reqFs.filter(v => v !== agent.serviceTools.addContentType))
            .resFs(agent.server.resFs.filter(v => v !== agent.serviceTools.verificationResponse))
            .field('fileName', values.name)
            .attach('file', values, values.name).end(this);

        if (res.err) {
            Modal.confirm({
                title:'操作失败!',
                icon: null,
                content: (
                    <>
                      
                    网络异常，请稍后重试
                    </>
                ),
            })
        }
        return res;
    }
    const downloadExcel = async () => {
        const res: any = await agent.server.post(`${agent.prefix_path}/web/verifierTask/import-template`, {}).reqFs(agent.server.reqFs.filter(v => v !== agent.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();
        }
    }
    const urlData = {
        commonUploadCb: uploadExcel,
        commonDownloadCb: downloadExcel
    }
    const onCloseExcel = React.useCallback(() => {
        setVisible(false);
    }, [])
    const onRefresh = React.useCallback(() => {

    }, []);
    const handleOk = async () => {

        if (downloadFilePath.indexOf('http') >= 0 || downloadFilePath.indexOf('//') === 0) {
            window.open(downloadFilePath);
        } else {
            const response: any = await agent.server.post(`${agent.prefix_path}/web/verifiedTask/getFileDownloadUrl`, { fileNameList: [downloadFilePath] }).end(this);
            const res = response.res[0];
            const href = `${res}`;
            let a = window.document.createElement('a');
            a.setAttribute('href', href);
            a.setAttribute('target', '_blank');
            a.setAttribute('download', `下载文件_${moment(new Date()).format('YYYYMMDDHHmmss')}.xls`);
            a.click();
        }
    }
    const handleCancel = () => {
        setModal(false)
    }
    const gotoDID = () => {
        let url = '';
        if (window.top) {
            url = window.top.location.host + agent.didPath
            window.top.location!.href = '//' + url
        } else {
            url = window.location.host + agent.didPath;
            window!.location!.href = '//' + url
        }
    }
    const tipModal = () => {
        let info;
        let title = '已发送';
        let icon, download;
        if (tip === 'success') {
            icon = <CheckCircleOutlined style={{ color: '#0074ff', fontSize: 30 }} />;
            info = <span>勾选任务<span style={{ color: '#0074ff' }}>{successNo + failureNo}个</span>，已发送<span style={{ color: '#0074ff' }}>{successNo}个，</span>请稍后查看发送结果。</span>
        } else if (tip === 'failure') {
            download = <a onClick={handleOk}>下载失败结果</a>
            title = '发送失败';
            icon = <CloseCircleOutlined style={{ color: '#FF5F58', fontSize: 30 }} />;
            info = <span>勾选任务<span style={{ color: '#0074ff' }}>{successNo + failureNo}个</span>，发送失败<span style={{ color: '#0074ff' }}>{failureNo}个</span>！失败原因：未找到采集方DID。</span>
        } else {
            download = <a onClick={handleOk}>下载失败结果</a>
            title = '发送结果';
            icon = <InfoCircleOutlined style={{ color: '#FFD900', fontSize: 30 }} />;
            info = <span>勾选任务<span style={{ color: '#0074ff' }}>{successNo + failureNo}个</span>，已发送<span style={{ color: '#0074ff' }}>{successNo}个</span>，发送失败<span style={{ color: '#0074ff' }}>{failureNo}个</span>！失败原因：未找到采集方DID。</span>
        }
        return (
            <Modal
                className='specail'
                title={' '}
                width={396}
                footer={null}
                maskClosable={false}
                visible={errorModal}
                onCancel={handleCancel}
            >
                <p style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18, textAlign: 'center', marginBottom: 15, fontWeight: 500, color: '#212223' }}>{icon} <span style={{ paddingLeft: 5 }}>{title}</span></p>
                {info}
                <div style={{ display: 'flex', justifyContent: 'space-between', padding: '35px 0 0' }}>
                    <div>
                        {download}
                    </div>
                    <div>
                        <Space size={20}>
                            {tip !== 'success' &&
                                <a onClick={gotoDID}>前往客商管理</a>
                            }
                            {tip === 'success' && <a onClick={handleCancel}>确认</a>}
                            <a onClick={handleCancel}>取消</a>
                        </Space>
                    </div>
                </div>
            </Modal>
        )
    }
    return (
        <>
            <WrapperDrop overlay={menu} key='2'><Button type="primary">批量操作</Button></WrapperDrop>
            {visible && <InvoiceImport currentActive={'commonexcel'} onClose={onCloseExcel} refreshInvoice={onRefresh} urlData={urlData} />}
            {tipModal()}
        </>
    )
}
export default AddBatch;