import * as React from 'react';
import { PageHeaderFoot, Button, AutoTableContainer, Table, Pagination, MoreMenus, message, TableManual } from 'kts-xui';
import { AdvancedSearch, KtsForm } from 'kts-components';
import { withRouter, RouteChildrenProps } from 'react-router-dom';
import moment from 'moment';
import { columnEnum } from '../CommonComponents/ColumnEnum';
import { Tag, Menu, Space, Dropdown, Tooltip } from 'kts-components-antd-x4';
import { DigitalAssetVerification } from '../..';
import { ExclamationCircleOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { SettingOutlined } from '@ant-design/icons';
import agent from '../Server';
import { taskStatusEnum, findLabel } from '../CommonComponents/FiledsEnum';
import './index.less';
import DenyModal from './UI.DenyModal';
import AddBatch from './AddBatch';
import DIDSelect from './add/DIDSelect';
import Sort from '../CommonComponents/Sort'
// import ImgsViewer from "react-images-viewer";
/** Props接口 */
interface IProps {

}

class UIComponents extends React.Component<IProps & RouteChildrenProps, any> {
   
    columnAction=[{
        title: '操作',
        dataIndex: 'taskUuid',
        key: 'taskUuid',
        width: 150,
        fixed: 'right',
        render: (text, record) => {
            if (record.status === 1) {
                const menu = (
                    <Menu>
                        <Menu.Item key='1'>
                            <a onClick={() => { this.onSend(text, record); }}>发送</a>
                        </Menu.Item>
                        <Menu.Item key='2'>
                            <a onClick={() => { this.onDelete(text); }}>删除</a>
                        </Menu.Item>
                    </Menu>
                )
                //草稿
                return <Space >
                    <a onClick={() => { this.onView(text); }}>查看</a>
                    <a onClick={() => { this.onEdit(text); }}>编辑</a>
                    <MoreMenus dropdownProps={{ overlay: menu }} />
                </Space>
            } else if (record.status === 2) {
                //待处理
                return (
                    <Space>
                        <a onClick={() => { this.onView(text); }}>查看</a>
                        {/* <a onClick={() => { this.onCloseTask(text); }}>关闭</a> */}
                    </Space>);
            } else if (record.status === 3) {
                //已完成 
                return (<Space>
                    <a onClick={() => { this.onView(text); }}>查看</a>
                </Space >);
            } else if (record.status === 4) {
                return (<Space>
                    <a onClick={() => { this.onView(text); }}>查看</a>
                    <a onClick={() => { this.onCreateold(record); }}>重新发起</a>
                </Space>);
            } else if (record.status === 6) {
                return (<Space>
                    <a onClick={() => { this.onView(text); }}>查看</a>
                    <a onClick={() => { this.onCreateold(record); }}>重新发起</a>
                </Space>);
            }
        }
    }]
    
    constructor(props) {
        super(props);
        this.state = {
            pageMeta: null,
            list: [],
            params: {},
            showModal: false,
            images: [],
            preview: false,
            currImg: 0,
            closeModal: false,
            processList: [],
            didCheck: false,
            record: null,
            createBatch: false,
            selectedRowKeys: [],
            columns : [
                {
                    title: '任务单号',
                    key: columnEnum.任务单号,
                    dataIndex: columnEnum.任务单号,
                    type: 'string',
                    width: 160,
                },
                {
                    title: '采集方',
                    key: columnEnum.被核验方,
                    dataIndex: columnEnum.被核验方,
                    width: 180,
                    type: 'string',
                    ellipsis: true,
                },
                {
                    title: '任务状态',
                    key: columnEnum.任务状态,
                    dataIndex: columnEnum.任务状态,
                    width: 100,
                    type: 'string',
                    align: 'center',
                    render: (text, record) => {
                        if (text === 6) {
                            return <Tooltip title={record.unfinishedReason}><span style={{color:'red'}}>{findLabel(text, taskStatusEnum)}</span></Tooltip>
                        } else {
                            return findLabel(text, taskStatusEnum)
                        }
                    }
                }, {
                    title: '任务截止日期',
                    width: 120,
                    type: 'string',
                    key: 'taskEndDate',
                    dataIndex: 'taskEndDate',
                    render: (text) => {
                        return text && moment(text).format('YYYY-MM-DD');
                    }
                }, {
                    title: '核验日期范围',
                    width: 200,
                    type: 'string',
                    key: 'effectiveStart',
                    dataIndex: 'effectiveStart',
                    render: (text, record) => {
                        return text && <span>{moment(text).format('YYYY-MM-DD')}~{moment(record.effectiveEnd).format('YYYY-MM-DD')}</span>;
                    }
                },
                {
                    title: '关联单据',
                    width: 180,
                    type: 'string',
                    key: 'originalDocList',
                    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: <span>风险等级 <Tooltip title='1.经营状态：吊销、停业、注销、清算,（吊销，注销、）（吊销，未注销、）（吊销，已注销、）税务评级为D,风险总数量10以上为高风险。2.税务评级为C,风险总数量1～10为中风险。3.低风险则该公司经营状态正常，税务评级良好，风险数量为0'><QuestionCircleOutlined /></Tooltip></span>,
                    width: 120,
                    type: 'string',
                    align: 'center',
                    key: 'riskGrade',
                    dataIndex: 'riskGrade',
                    render: (text, record) => {
                        if (text === 10) {
                            return <Tooltip title={record.riskGradeMsg}><ExclamationCircleOutlined onClick={() => { this.toRisk(record) }} style={{ color: 'red' }} /></Tooltip>
                        } else if (text === 20) {
                            return <Tooltip title={record.riskGradeMsg}><ExclamationCircleOutlined onClick={() => { this.toRisk(record) }} style={{ color: 'orange' }} /></Tooltip>
                        } else if (text === 30) {
                            return <Tooltip title={record.riskGradeMsg}><ExclamationCircleOutlined onClick={() => { this.toRisk(record) }} style={{ color: '#0074ff' }} /></Tooltip>
                        }
                    }
                },
                {
                    title: '关联任务单号',
                    width: 180,
                    type: 'string',
                    key: 'taskRelationList',
                    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,
                    ellipsis: true,
                    key: columnEnum.创建人,
                    dataIndex: columnEnum.创建人,
                },
                {
                    title: '备注',
                    width: 140,
                    key: columnEnum.备注,
                    dataIndex: columnEnum.备注,
                    ellipsis: true,
                }, 
            ],
            columnsMok:[
                {
                    title: '任务单号',
                    key: columnEnum.任务单号,
                    dataIndex: columnEnum.任务单号,
                    type: 'string',
                },
                {
                    title: '采集方',
                    key: columnEnum.被核验方,
                    dataIndex: columnEnum.被核验方,
                    type: 'string',
                },
                {
                    title: '任务状态',
                    key: columnEnum.任务状态,
                    dataIndex: columnEnum.任务状态,
                    type: 'string',
                }, {
                    title: '任务截止日期',
                    type: 'string',
                    key: 'taskEndDate',
                    dataIndex: 'taskEndDate',
                }, {
                    title: '核验日期范围',
                    type: 'string',
                    key: 'effectiveStart',
                    dataIndex: 'effectiveStart',
                },
                {
                    title: '关联单据',
                    type: 'string',
                    key: 'originalDocList',
                    dataIndex: 'originalDocList',
        
                },
                {
                    title: '风险等级',
                    type: 'string',
                    key: 'riskGrade',
                    dataIndex: 'riskGrade',
                },
                {
                    title: '关联任务单号',
                    type: 'string',
                    key: 'taskRelationList',
                    dataIndex: 'taskRelationList',
        
                }, {
                    title: '创建人',
                    type: 'string',
                    key: columnEnum.创建人,
                    dataIndex: columnEnum.创建人,
                },
                {
                    title: '备注',
                    type: 'string',
                    key: columnEnum.备注,
                    dataIndex: columnEnum.备注,
                },
            ],
            sortDataSource:[]
        };
    }
    onCloseTask = id => {
        this.setState({
            closeModal: true,
            processList: id
        })
    }
    closeModal = () => {
        this.setState({
            closeModal: false,
        })
    }
    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
        })
    }
    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: {
                            [columnEnum['任务单号']]: {
                                type: 'string',
                                title: '任务单号',
                            },

                            [columnEnum['被核验方']]: {
                                type: 'string',
                                title: '采集方',
                            },
                            [columnEnum.任务状态]: {
                                type: 'string',
                                title: '任务状态',
                                enum: taskStatusEnum,
                                'x-props': {
                                    mode: "multiple"
                                }
                            },
                            heyan: {
                                type: 'daterange',
                                title: '核验日期范围',
                                'x-props': {
                                    extendsFields: ['minInvoiceEffective', 'maxInvoiceEffective'],
                                }
                            },
                            taskEndDate: {
                                type: 'date',
                                title: '任务截止日期',
                                'x-props': {
                                    style: { width: '100%' }
                                }
                            },
                            originalDocument: {
                                type: 'string',
                                title: '关联单据',
                            },
                            [columnEnum['创建人']]: {
                                type: 'string',
                                title: '创建人',
                            },
                            'relationTaskNo': {
                                type: 'string',
                                title: '关联任务单号',
                            }

                        },
                    }}
                >
                </KtsForm>
            </AdvancedSearch>
        );
    }
    onCloseDid = () => {
        this.setState({
            didCheck: false
        })
    }
    componentDidMount() {
        const params = {
            pageNum: 1,
            pageSize: 10
        };
        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);
    }
    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('/web/verifierTask/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);
    }
    //从已关闭/未完成中重新创建
    onCreateold = (record) => {
        this.props.history.push({ pathname: `${DigitalAssetVerification.rootPath}/task/masteradd`, state: record });
    }
    onCreateNew = () => {
        this.props.history.push(`${DigitalAssetVerification.rootPath}/task/masteradd`);
    }
    toRisk = (record) => {
        this.props.history.push({ pathname: '/task/list/echart', search: 'radio=customer', state: { taskNo: record.taskNo } })
    }
    onView = (id) => {
        this.props.history.push(`${DigitalAssetVerification.rootPath}/task/masterview/${id}`);
    }
    onDelete = async (id) => {
        const data = {
            taskUuid: id
        }
        const res: any = await agent.post('/web/verifierTask/deleteTask', data, this);
        if (res.er) {
            return;
        } else if (res.res) {
            message.success('操作成功');
            this.onRefresh();
        }
    }
    onEdit = (id) => {
        this.props.history.push(`${DigitalAssetVerification.rootPath}/task/edit/${id}`);
    }
    onSend = async (id, record) => {
        const res: any = await agent.get('/web/verifierTask/submitCheck', { taskUuid: id }, this);
        this.setState({
            loading: false,
            record
        })
        if (res.err) {
            return;
        } else {
            if (res.res.passCheck) {
                const data = {
                    taskUuid: id,
                    ...record,
                    collectorPartyId: res.res.verifiedPartyId,
                    verifierPartyId: res.res.verifierPartyId
                }
                this.send(data);
            } else {

                if (res.res.missingId) {
                    this.setState({
                        didCheck: res.res.missingId
                    })
                }
            }
        }
    }
    send = async (values) => {
        const res: any = await agent.post('/web/verifierTask/sendTask', { ...values, ...this.state.record }, this);
        this.setState({ loading: false })
        if (res.err) {
            return false;
        } else {
            message.success('操作成功');
            this.onRefresh();
            this.onCloseDid();
        }
        return false
    }

    onSuccess = () => {
        this.closeModal();
        this.onRefresh();
    }
    setPreview = (preview) => {
        this.setState({ preview })
    }
    createBatch = () => {
        this.setState({
            createBatch: true
        })
    }
    handleMenuClick = (e) => {
        if (e.key === 'create') {
            this.createBatch();
        }
    }
    setDataSource = (data) => {
        const keys=Sort.filter(this.state.columnsMok, data)||[];
        const checkedKeys=keys.map((item)=>{
            return {
                key:item.key,
                checked:true
            }
        })
        this.setState({
            // columns,
            sortDataSource:checkedKeys
        })
        window.localStorage.setItem('mastertasksort',JSON.stringify(data))
    }
    getLocalSort=()=>{
        const d=window.localStorage.getItem('mastertasksort');
        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, didCheck, record, selectedRowKeys,sortDataSource } = this.state;
        const columns=Sort.filter(this.state.columns, this.state.sortDataSource)||[];
        const rowSelection = {
            onChange: (selectedRowKeys) => {
                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={[
                            <Button key='1' type="primary" onClick={this.onCreateNew}>创建</Button>,
                            <AddBatch key='2' list={selectedRowKeys} />,
                            <Sort
                                key='3'
                                columns={this.state.columnsMok}
                                dataSource={sortDataSource}
                                onChange={this.setDataSource}
                                mustShows={['taskNo', 'verifiedParty', 'status']}
                            >
                                <Button icon={<SettingOutlined />} />
                            </Sort>
                        ]}
                        onRefresh={this.onRefresh}
                    >
                    </PageHeaderFoot>
                </div>
                <AutoTableContainer style={{ flex: 1, padding: '0 20px', background: '#F4F4F4' }} >
                    <TableManual
                        id='mastertask'
                        className='fixheight'
                        bordered
                        dataSource={dataSource}
                        columns={[...columns, ...this.columnAction] as any}
                        scroll={{ y: 'max-content' }}
                        pagination={false}
                        rowKey="taskUuid"
                        rowSelection={rowSelection}
                    />
                </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} />}
                {didCheck === true && <DIDSelect verifierParty={record.verifiedParty} onClose={this.onCloseDid} onSuccess={this.send} />}
                {
                    this.state.closeModal && <DenyModal id={this.state.processList} onClose={this.closeModal} onSuccess={this.onSuccess} />
                }
            </div>
        );
    }
}

export default withRouter(UIComponents as any)