import * as React from 'react';
import { PageHeaderFoot, DatePicker, Input, Form, Button, PageHeaderTop, message } from 'kts-xui';
import { FormInstance } from 'kts-components-antd-x4/lib/form';
import { Col, Row } from 'antd';
import agent from '../../Server';
import { PlusCircleOutlined, PlusOutlined, MinusCircleOutlined } from '@ant-design/icons';
import DidModal from './UI.DIDModal';
import DIDSelect from './DIDSelect'
import moment from 'moment';
import { withRouter, RouteChildrenProps } from 'react-router-dom';
import { taskStatusEnum, findLabel } from '../../CommonComponents/FiledsEnum';
import { CloseOutlined } from '@ant-design/icons'
import {  Space, Tag } from 'kts-components-antd-x4';
interface IProps {
    onSuccess: () => void;
}
interface IState{
    /**
     * 核验任务数据
     */
    data:any,
    didModal: boolean,
    didCheck: boolean,
    /**
     * taskUuid
     */
    id: string, 
    /**
     * 采集任务数据
     */
    caijiInfo: any
    loading: boolean,

}
/**
 * 关联任务修改
 */
class UIComponents extends React.Component<IProps & RouteChildrenProps, IState> {
    formRef:any = React.createRef<FormInstance>();
    constructor(props: any) {
        super(props);
        this.state = {
            didModal: false,
            didCheck: false,
            data: null,//核验任务数据
            id: props.match.params.id,  //taskUuid
            caijiInfo: props.location.state,//采集任务数据
            loading: false,
        }
    }

    componentDidMount() {
        this.getDetail();
    }
    getDetail = async () => {
        const id = this.state.id;
        const res: any = await agent.post('/web/verifierTask/getDetail', { taskUuid: id }, this);
        if (res.res) {

            res.res.taskEndDate = moment(res.res.taskEndDate);
            if (res.res.originalDocList.length === 0) {
                res.res.originalDocList = [{ originalDocument: undefined }]
            }
            this.setState({
                data: res.res
            })


        }
    }
    /**
     * 
     * @returns 
     */
    checkBeforeSend = async () => {
        const { data } = this.state;
        this.setState({
            loading: true
        })
        const res: any = await agent.get('/web/verifierTask/submitCheck', { taskUuid: data.taskUuid }, this);
        if (res.err) {
            this.setState({
                loading: false
            })
            return;
        } else {
            if (res.res.passCheck) {
                const party = {
                    collectorPartyId: res.res.verifiedPartyId,
                    verifierPartyId: res.res.verifierPartyId
                }
                this.send(party);
            } else {
                this.setState({ loading: false })
                if (res.res.missingId) {
                    this.setState({
                        didCheck: res.res.missingId
                    })
                }
            }
        }
    }
    send = async (values) => {
        let formData = this.formRef?.current?.getFieldsValue();
        let cloneoriginalDocList = this.dirtData(JSON.parse(JSON.stringify(formData.originalDocList)));
        const res: any = await agent.post('/web/verifierTask/sendTask', { taskUuid: this.state.data.taskUuid, ...values, ...formData, originalDocList: cloneoriginalDocList }, this);
        this.setState({ loading: false })
        if (res.err) {
            return false;
        } else {
            message.success('操作成功');
            this.goback();
        }
        return false;
    }

    autoSave = () => {
        this.update(true);
    }
    autoSend = () => {
        this.update(false);
    }
    dirtData = data => {
        const length = data.length - 1;
        for (var i = length; i >= 0; i--) {
            if (!data[i].originalDocument) {
                data.splice(i, 1);
            }
        }
        return data;
    };
    /**
     * 
     * @returns 新建任务 主动触犯新建，和被动触发新建两个流程
     */
    create = async (initiative: boolean = true) => {
        const { data } = this.state;
        this.formRef?.current?.validateFields().then(async values => {
            values.originalDocList = this.dirtData(values.originalDocList);
            values = {
                ...values,
                taskEndDate: moment(values['taskEndDate']).format('YYYY-MM-DD'),
                taskRelation: {
                    taskNo: data.taskNo,
                    taskUuid: data.taskUuid
                }
            }
            const res: any = await agent.post('/web/verifierTask/createTask', values, this);
            this.setState({ loading: false })
            if (res.err) {
                return;
            } else {
                if (initiative) {
                    this.goback();
                    message.success('操作成功');
                } else {
                    //如果是被动，就要去走发送流程 新建后要先设置taskUuid
                    this.setState({
                        data: res.res,
                        id: res.res.taskUuid
                    }, () => {
                        this.checkBeforeSend();
                    })
                }
            }
        });
    }
    /**
     * 
     * @param initiative 是否主动更新
     */
    update = async (initiative: boolean = true) => {
        this.formRef?.current?.validateFields().then(async values => {
            const { data } = this.state;
            let cloneoriginalDocList = this.dirtData(JSON.parse(JSON.stringify(values.originalDocList)));
            values = {
                ...data,
                ...values,
                originalDocList: cloneoriginalDocList,
                taskEndDate: moment(values['taskEndDate']).format('YYYY-MM-DD'),
            }
            const res: any = await agent.post('/web/verifierTask/updateTask', values, this);
            this.setState({ loading: false })
            if (res.err) {
                return;
            } else {
                if (initiative) {
                    this.goback();
                    message.success('操作成功');
                } else {
                    this.checkBeforeSend();
                }
            }
        }).catch(error => {
            this.setState({
                loading: false
            })
        });
    }

    goback = () => {
        this.props.history.goBack();
    }
    showDidModal = () => {
        this.setState({
            didModal: true
        })
    }
    closeDid = () => {
        this.setState({
            didModal: false
        })
    }
    onCloseDid = () => {
        this.setState({
            didCheck: false
        })
    }
    onSelectDid = (data: any) => {
        this.formRef.current!.setFieldsValue({ verifiedParty: data.verifiedParty, verifiedPartyId: data.verifiedPartyId });
        this.closeDid();
    }
    // onSuccess = async (values) => {
    //     const res: any = await agent.post('/web/verifierTask/sendTask', { taskUuid: this.state.id, ...values }, this);
    //     this.setState({ loading: false })
    //     if (res.err) {
    //         return false;
    //     } else {
    //         message.success('操作成功');
    //         this.onCloseDid();
    //     }
    //     return false; 
    // }
    onCloseTask = async () => {
        const { id } = this.state;
        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.goback();
        }
    }
    /**
     * 取消关联
     */
    onRemoveConnect = async () => {
        const { id, caijiInfo } = this.state;
        const params = {
            taskUuid: caijiInfo.taskUuid,
            relationTaskUuidList: [id]
        }
        const res: any = await agent.post('/collector/task/unLinkTask', params, this);
        if (res.er) {
            return;
        } else if (res.res) {
            message.success('操作成功');
            this.goback();
        }
    }
    titleDom = () => {
        const { data, caijiInfo } = this.state;

        return <span style={{ whiteSpace: 'nowrap' }}>
            <span style={{ fontSize: 16, color: '#0074ff', marginRight: 10 }}>核验任务:{data.taskNo}</span>
            <Tag style={{ marginRight: 10, color: 'rgb(0, 116, 255)', background: 'white', border: '1px solid' }} className="no-edit">{findLabel(data.status, taskStatusEnum)}</Tag>
            <span style={{}}>
                <span style={{ fontSize: 16, marginRight: 10 }}>采集任务:{caijiInfo.taskNo}</span>
                <Tag className="no-edit">{findLabel(caijiInfo.taskStatus, taskStatusEnum)}</Tag>
                <CloseOutlined style={{ cursor: 'pointer' }} onClick={this.onRemoveConnect} />
            </span>
        </span>
    }
    render() {
        const { didModal, didCheck, data, loading } = this.state;
        const disabledDate = current => {
            return current && current < moment().subtract(1, 'day');
        };
        const verifiedParty = this.formRef?.current?.getFieldValue('verifiedParty');
        return (
            <div>
                <PageHeaderTop
                    title="数字资产核验方"
                />
                <PageHeaderFoot
                    title={data && this.titleDom()}
                    expandRight={
                        [<Space key="0">
                            <Button key="3" type="primary" onClick={this.autoSave}>保存</Button>
                            {data && data.status === 1 && <Button key="1" type="primary" loading={loading} onClick={this.autoSend}>发送</Button>}
                            {data && data.status === 1 && <Button key="4" type="primary" onClick={this.onCloseTask}>删除</Button>}
                            <Button key="2" onClick={this.goback}>取消</Button>
                        </Space>]
                    }
                />
                <div style={{ padding: '10px 20px 0' }}>
                    {data && <Form
                        initialValues={data}
                        ref={this.formRef}
                        // onFinish={this.onFinish}
                        layout="vertical"
                    >
                        <Form.Item
                            name='verifiedPartyId'
                            label='采集方did'
                            style={{ display: 'none' }}
                        >
                            <Input />
                        </Form.Item>
                        <Row gutter={24}>
                            <Col span={8}>
                                <Form.Item
                                    name='verifiedParty'
                                    label='采集方'
                                    rules={[
                                        {
                                            required: true,
                                            whitespace: true
                                        },
                                    ]}
                                >
                                    <Input maxLength={80} addonAfter={<a style={{ color: 'inherit' }} onClick={this.showDidModal}><PlusCircleOutlined /></a>} />
                                </Form.Item>
                            </Col>
                            <Col span={8}>
                                <Form.Item
                                    name='taskEndDate'
                                    label='任务截止日期'
                                    rules={[
                                        {
                                            required: true,
                                        },
                                    ]}
                                >
                                    <DatePicker disabledDate={disabledDate} style={{ width: '100%' }} />
                                </Form.Item>
                            </Col>
                            <Col span={8}>
                                <Form.Item
                                    name='creator'
                                    label='任务创建人'
                                    rules={[
                                        {
                                            required: true,
                                        },
                                    ]}
                                >
                                    <Input disabled />
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row gutter={24}>
                            <Col span={8}>
                                <Form.List
                                    name="originalDocList"
                                >
                                    {(fields, { add, remove }) => (
                                        <>
                                            {fields.map((field, index) => (
                                                <Form.Item
                                                    name={[field.name, 'originalDocument']}
                                                    tooltip="请准确的输入单据名称,多个单据请添加多行,最多20行"
                                                    label={index === 0 ? '关联单据' : ''}
                                                    rules={[
                                                        {
                                                            whitespace: true
                                                        },
                                                    ]}
                                                >
                                                    <Input maxLength={50} addonAfter={fields.length > 1 ? (
                                                        <MinusCircleOutlined
                                                            className="dynamic-delete-button"
                                                            onClick={() => remove(field.name)}
                                                        />
                                                    ) : null} />

                                                </Form.Item>
                                            ))}
                                            <Form.Item>
                                                {fields.length < 20 ? <a onClick={() => add()} >
                                                    添加一行
                                                </a> : null}
                                            </Form.Item>
                                        </>
                                    )}

                                </Form.List>
                            </Col>
                            <Col span={8}>
                                <Form.Item
                                    name='remark'
                                    label='备注'
                                >
                                    <Input maxLength={200} />
                                </Form.Item>
                            </Col>
                        </Row>

                    </Form>
                    }
                </div>
                {didModal && <DidModal onClose={this.closeDid} onSuccess={this.onSelectDid} />}
                {didCheck === true && <DIDSelect verifierParty={verifiedParty} onClose={this.onCloseDid} onSuccess={this.send} />}

            </div>
        );
    }
}
export default withRouter(UIComponents as any)