import * as React from 'react';
import { PageHeaderFoot, Button, AutoTableContainer, Table, Pagination, MoreMenus, Modal, message } from 'kts-xui';
import { AdvancedSearch, KtsForm } from 'kts-components';
import moment from 'moment';
import { withRouter, RouteChildrenProps } from 'react-router-dom';
import { taskStatusEnum, findLabel } from '../CommonComponents/FiledsEnum';
import agent from '../Server';
import { DigitalAssetVerification } from '../../';
import { Tooltip, Menu, Space, Dropdown } from 'kts-components-antd-x4';
import ExcelImport from './detail/invoiceImport';
import { ReloadOutlined } from '@ant-design/icons';
import DidModal from './add/DIDSelect';
import ConnectMasterTask from './ConnectMasterTask';
import DenyAction from './UI.DenyAction'
/** Props接口 */
interface IProps {

}

class UIComponents extends React.Component<IProps & RouteChildrenProps, any> {
    columns = [
        {
            title: '任务单号',
            dataIndex: 'taskNo',
            width: 160,

        }, {
            title: '核验方',
            dataIndex: 'verifierName',
            width: 200,
            ellipsis: true,
        }, {
            title: '任务状态',
            dataIndex: 'taskStatus',
            width: 100,
            render: (text, record) => {
                if (text === 6) {
                    return <Tooltip title={record.collectorRejectReason}><span style={{color:'red'}}>{findLabel(text, taskStatusEnum)}</span></Tooltip>
                } else {
                    return findLabel(text, taskStatusEnum)
                }
            }
        }, {
            title: '任务截止日期',
            width: 130,
            dataIndex: 'taskEndDate',
            render: (text) => {
                return text && moment(text).format('YYYY-MM-DD');
            }
        },
        {
            title: '核验日期范围',
            width: 200,
            dataIndex: 'effectiveStart',
            render: (text, record) => {
                return text && <span>{moment(text).format('YYYY-MM-DD')}~{moment(record.effectiveEnd).format('YYYY-MM-DD')}</span>;
            }
        },
        {
            title: '关联单据',
            width: 120,
            dataIndex: 'originalDocList',
            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
                }
            }
        },
        {
            title: '关联任务单号',
            width: 120,
            dataIndex: 'taskRelationList',
            ellipsis: true,
            render: (text) => {
                if (text.length > 0) {
                    let originalDocuments = text.reduce((acc, obj) => {
                        acc.push(obj.taskNo);
                        return acc;
                    }, [])
                    let str = originalDocuments.join('/');
                    return str
                }
            }
        }, {
            title: '创建人',
            width: 100,
            dataIndex: 'creator',
            ellipsis: true,
        }, {
            title: '备注',
            width: 140,
            dataIndex: 'remark',
            ellipsis: true,
        }, {
            title: '操作',
            dataIndex: 'taskUuid',
            fixed: 'right',
            width: 180,
            render: (text, record) => {

                if (record.taskStatus === 2) {
                    //待处理
                    const menu = (
                        <Menu>
                            <Menu.Item key='0'>
                                <a onClick={() => { this.onConnectTask(record) }}>关联核验任务</a>
                            </Menu.Item>
                            <Menu.Item key='1'>
                                <a onClick={() => { this.checkBeforeSend(record) }}>提交</a>
                            </Menu.Item>
                            <Menu.Item key='1'>
                                <DenyAction onRefresh={this.onRefresh} list={[text]}>拒绝完成</DenyAction>
                            </Menu.Item>

                        </Menu>
                    )
                    const menu2 = (
                        <Menu onClick={(e) => { this.handleMenuClick(e, record.taskUuid) }}>
                            <Menu.Item key="scangun">
                                扫码枪
                            </Menu.Item>
                            <Menu.Item key="excel">
                                Excel上传
                            </Menu.Item>
                            <Menu.Item key="manual">
                                手工录入
                            </Menu.Item>
                        </Menu>
                    );
                    //草稿
                    return <Space >
                        <a onClick={() => { this.onView(text); }}>查看</a>

                        <Dropdown overlay={menu2}>
                            <a>发票采集</a>
                        </Dropdown>
                        <MoreMenus dropdownProps={{ overlay: menu }} /></Space>
                } else if (record.taskStatus === 2) {
                    //待处理

                    return (
                        <Space>
                            <a onClick={() => { this.onView(text); }}>查看</a>
                        </Space>);
                } else if (record.taskStatus === 3 || record.taskStatus === 4) {
                    //已处理 已截止
                    return (<Space>
                        <a onClick={() => { this.onView(text); }}>查看</a>
                    </Space>);
                } else if (record.taskStatus === 5) {
                    //提交中
                    const menu = (
                        <Menu>
                            <Menu.Item disabled key='1'>
                                <a onClick={() => { this.checkBeforeSend(record) }}>提交</a>
                            </Menu.Item>
                        </Menu>
                    )
                    return (<Space>
                        <a onClick={() => { this.onView(text); }}>查看</a>
                        {/* <span style={{ color: 'rgba(0, 0, 0, 0.25)' }}>发票采集</span>
                        <MoreMenus dropdownProps={{ overlay: menu }} /> */}
                    </Space>);
                } else if (record.taskStatus === 6) {
                    //未完成
                    return (<Space>
                        <a onClick={() => { this.onView(text); }}>查看</a>
                    </Space>);
                }
            }
        },
    ];
    constructor(props) {
        super(props);
        this.state = {
            pageMeta: null,
            list: [],
            params: {},
            showModal: false,
            excelModal: false,
            images: [],
            preview: false,
            currImg: 0,
            didCheck: false,
            record: {},
            loading: false,
            connectModal: false,
            selectedRowKeys: [],
        };

    }
    onConnectTask = (record) => {
        this.setState({
            connectModal: true,
            record
        })
    }
    onCloseConnect = () => {
        this.setState({
            connectModal: false,
            record: null
        })
        this.onRefresh();
    }
    checkBeforeSend = async (record) => {
        this.setState({
            record,
            loading: true
        })
        const res: any = await DigitalAssetVerification.server.post(`${DigitalAssetVerification.prefix_path}/collector/task/submitTask`, {
            taskUuid: record.taskUuid,
            collectorPartyId: record.collectorPartyId,
            verifierName: record.verifierName,
            verifierPartyId: record.verifierPartyId,
        }).resFs([DigitalAssetVerification.serviceTools.repeatCallEnd]).end(this);
        this.setState({ loading: false })
        if (res.err) {
            message.error('提交失败,网络异常');
            return;
        } else {
            if (res.res.body.ok) {
                message.success('操作成功');
                this.onRefresh();
            } else {
                Modal.error({
                    title: '提交失败',
                    content: res.res.body.status.description,
                    okText: '确定',
                });
            }

        }

    }
    send = async (values) => {
        const res: any = await agent.post('/web/verifiedTask/submitTask', { taskUuid: this.state.record.taskUuid, ...values }, this);
        this.setState({ loading: false })
        if (res.err) {
            return false;
        } else {
            message.success('操作成功');
            this.onCloseDid();
            this.onRefresh();
        }
        return false;
    }
    onCloseDid = () => {
        this.setState({
            didCheck: false
        })
    }
    handleMenuClick = (e, id) => {
        this.props.history.push(`${DigitalAssetVerification.rootPath}/task/slaveview/${id}/${e.key}`);
    }
    onPreview = async (list: any[]) => {
        const files = list.reduce((a, b) => {
            a.push(b.fileUploadName);
            return a;
        }, [])
        const response = await agent.post('/web/verifiedTask/getFileDownloadUrl', { fileNameList: files }, this);
        const res = response.res;
        this.setState({
            images: res,
            preview: true,
            currImg: 0
        })
    }
    gotoPrev = () => {
        this.setState({
            currImg: this.state.currImg - 1
        })
    }
    gotoNext = () => {
        this.setState({
            currImg: this.state.currImg + 1
        })
    }
    onDeleteTask = async (id) => {
        const res: any = await agent.get('/web/verifiedTask/deleteVerifiedPartyTask', { taskUuid: id }, this);
        if (res.er) {
            return;
        } else if (res.res) {
            message.success('操作成功');
            this.onRefresh();
        }
    }
    topExpand = () => {
        return (
            <AdvancedSearch
                width={480}
                height={44}
                compact={true}
                defaultKey="taskNo"
                placeholder="请输入任务单号"
                searchFormSubmit={this.onSearch}
            >
                <KtsForm
                    labelCol={9}
                    wrapperCol={15}
                    labelAlign="left"
                    compact={true}
                    schema={{
                        type: 'object',
                        properties: {
                            taskNo: {
                                type: 'string',
                                title: '任务单号',
                            },
                            verifierName: {
                                type: 'string',
                                title: '核验方',
                            },
                            status: {
                                type: 'string',
                                title: '任务状态',
                                enum: taskStatusEnum,
                                'x-props': {
                                    mode: "multiple"
                                }
                            },
                            maxTaskEndDate: {
                                type: 'date',
                                title: '任务截止时间',
                                'x-props': {
                                    style: { width: '100%' }
                                }
                            }, heyan: {
                                type: 'daterange',
                                title: '核验日期范围',
                                'x-props': {
                                    extendsFields: ['minInvoiceEffective', 'maxInvoiceEffective'],
                                }
                            },
                            originalDocument: {
                                type: 'string',
                                title: '关联单据',
                            },
                            relationTaskNo: {
                                type: 'string',
                                title: '关联任务单号',
                            },
                            creator: {
                                type: 'string',
                                title: '创建人',
                            },
                            remark: {
                                type: 'string',
                                title: '备注',
                            },

                        },
                    }}
                >
                </KtsForm>
            </AdvancedSearch>
        );
    }

    componentDidMount() {
        const params = {
            pageNum: 1,
            pageSize: 10
        };
        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);
    }
    getData = async (params) => {
        params = {
            ...params,
            minInvoiceEffective: params['minInvoiceEffective'] && moment(params['minInvoiceEffective']).format('YYYY-MM-DD'),
            maxInvoiceEffective: params['maxInvoiceEffective'] && moment(params['maxInvoiceEffective']).format('YYYY-MM-DD')
        }
        const res: any = await agent.post('/collector/task/queryTaskPage', params, this);
        if (res.er) {
            return;
        } else if (res.res) {
            this.setState({
                pageMeta: res.res?.pageMeta,
                list: res.res?.items
            });
        }
    }
    onSearch = (data = {}) => {
        this.setState({
            params: data,

        });
        const params = {
            ...data,
            ...this.state.pageMeta,
            pageNum: 1,
            pageSize: 10
        };
        this.getData(params);
    }

    onView = (id) => {
        this.props.history.push(`${DigitalAssetVerification.rootPath}/task/slaveview/${id}`);
    }
    onExcel = () => {
        this.setState({
            excelModal: true
        })
    }
    onCloseExcel = () => {
        this.setState({
            excelModal: false
        })
    }
    setPreview = (preview) => {
        this.setState({ preview })
    }
    render() {
        const dataSource = this.state.list;
        const { pageMeta, excelModal, connectModal, didCheck, record, selectedRowKeys } = this.state;
        const rowSelection = {
            selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRowKeys
                });
            },
        }
        return (
            <div style={{ height: 'calc(100vh - 97px)', display: 'flex', flexDirection: 'column', overflow: 'auto' }}>
                <div style={{ flex: 'none', position: 'relative', zIndex: 3 }}>
                    <PageHeaderFoot
                        expandLeft={this.topExpand()}
                        expandRight={[
                            <DenyAction onRefresh={this.onRefresh} list={selectedRowKeys}><Button key='2' type='primary'>批量拒绝</Button></DenyAction>,
                            <Button key='3' onClick={this.onRefresh} icon={<ReloadOutlined />}></Button>,
                        ]}
                    // onRefresh={this.onRefresh}
                    >

                    </PageHeaderFoot>
                </div>
                <AutoTableContainer style={{ flex: 1, padding: '0 20px', background: '#F4F4F4' }} >
                    <Table
                        className='fixheight'
                        bordered
                        dataSource={dataSource}
                        columns={this.columns as any}
                        scroll={{ x: '1800', y: 'max-content' }}
                        pagination={false}
                        rowSelection={rowSelection}
                        rowKey="taskUuid"
                    />
                </AutoTableContainer>

                {didCheck === true && <DidModal verifierParty={record.verifierParty} onClose={this.onCloseDid} onSuccess={this.send} />}
                {excelModal && <ExcelImport urlData={{ url: `${DigitalAssetVerification.prefix_path}/web/verifiedTask/uploadVerifiedTask`, downloadurl: '/taskexcel.xlsx' }} refreshInvoice={this.onRefresh} onClose={this.onCloseExcel} currentActive='excel' />}
                {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} />}
                {connectModal && <ConnectMasterTask value={record} onClose={this.onCloseConnect} />}
            </div>
        );
    }
}

export default withRouter(UIComponents as any)