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 Upload from '../../CommonComponents/Upload';
import { DigitalAssetVerification } from '../../..';
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 { Space } from 'kts-components-antd-x4';
import DenyModal from '../UI.DenyModal';
const { RangePicker } = DatePicker;
interface IProps {
    onSuccess: () => void;
    // taskUuid?: string;
}
export default class UIComponents extends React.Component<any, any> {
    formRef:any = React.createRef<FormInstance>();
    constructor(props: IProps) {
        super(props);
        this.state = {
            didModal: false,
            didCheck: false,
            creator: '',
            data: null,
            id: this.props.match.params.id,
            closeModal: false,
            loading: false,
        }
    }

    componentDidMount() {
        if (this.state.id) {
            this.getDetail();
        } else {
            this.getCompany();
        }
    }
    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 = res.res.taskEndDate&&moment(res.res.taskEndDate);
            res.res.heyan = res.res.effectiveStart && [moment(res.res.effectiveStart), moment(res.res.effectiveEnd)];
            if (res.res.originalDocList.length === 0) {
                res.res.originalDocList = [{ originalDocument: undefined }]
            }
            this.setState({
                data: res.res
            })
        }
    }
    //如果新建或者从老数据创建
    getCompany = async () => {
        const { state } = this.props.location;
        if (this.props.location.state) {
            const newDate=state.taskEndDate>moment().format('x')?moment(state.taskEndDate).format('YYYY-MM-DD'):moment().endOf('month').format('YYYY-MM-DD');
            this.setState({
                data: {
                    creator: DigitalAssetVerification.user.userInfo.nickName,
                    taskEndDate: moment(newDate),
                    originalDocList: this.props.location.state.originalDocList.length > 0 ? this.props.location.state.originalDocList : [{ originalDocument: undefined }],
                    status: 0,
                    remark: this.props.location.state.remark,
                    verifiedPartyId: this.props.location.state.verifiedPartyId,
                    verifiedParty: this.props.location.state.verifiedParty,
                    heyan: this.props.location.state.effectiveStart && [moment(this.props.location.state.effectiveStart), moment(this.props.location.state.effectiveEnd)],

                }
            })
        } else {
            this.setState({
                data: {
                    creator: DigitalAssetVerification.user.userInfo.nickName,
                    taskEndDate: moment(moment().endOf('month').format('YYYY-MM-DD')),
                    originalDocList: [{ originalDocument: undefined }],
                    // originParty: res.res.name,
                    status: 0
                }
            })
        }
    }
    /**
     * 
     * @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();
        // formData.originalDocList = this.dirtData(formData.originalDocList);
        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 = () => {
        const { id } = this.state;
        if (id) {
            this.update(true);
        } else {
            this.create(true);
        }
    }
    autoSend = () => {
        const { id } = this.state;
        if (id) {
            this.update(false);
        } else {
            this.create(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) => {
        this.formRef?.current?.validateFields().then(async values => {
            let cloneoriginalDocList = JSON.parse(JSON.stringify(values.originalDocList));
            values = {
                ...values,
                effectiveStart: values['heyan'] && values['heyan'][0].format('YYYY-MM-DD'),
                effectiveEnd: values['heyan'] && values['heyan'][1].format('YYYY-MM-DD'),
                originalDocList: this.dirtData(cloneoriginalDocList),
                taskEndDate: values['taskEndDate']&&moment(values['taskEndDate']).format('YYYY-MM-DD'),
            }
            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 = JSON.parse(JSON.stringify(values.originalDocList));
            // values.originalDocList = this.dirtData(values.originalDocList);
            values = {
                ...data,
                ...values,
                effectiveStart: values['heyan'] && values['heyan'][0].format('YYYY-MM-DD'),
                effectiveEnd: values['heyan'] && values['heyan'][1].format('YYYY-MM-DD'),
                originalDocList: this.dirtData(cloneoriginalDocList),
                taskEndDate: values['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();
        }
    }
    closeModal = () => {
        this.setState({
            closeModal: false,
        })
    }
    onCloseSuccess = () => {
        this.closeModal();
    }
    operationButtons = () => {
        const { data, loading } = this.state;
        if (data) {
            if (data.status === 0) {
                //新建
                return (<>
                    <Button key="3" type="primary" onClick={this.autoSave}>保存</Button>
                    <Button key="1" type="primary" loading={loading} onClick={this.autoSend}>发送</Button>
                </>)
            } else if (data.status === 1) {
                //草稿
                return (<>
                    <Button key="3" type="primary" onClick={this.autoSave}>保存</Button>
                    <Button key="1" type="primary" loading={loading} onClick={this.autoSend}>发送</Button>
                    <Button key="4" type="primary" onClick={this.onCloseTask}>删除</Button>
                </>)
            } else if (data.status === 2) {
                //已完成
                return (<>
                    {/* <Button key="3" type="primary" onClick={this.onCloseTask}>关闭</Button> */}
                </>)
            } else if (data.status === 7) {
                //发送失败
                return (<>
                    <Button key="1" type="primary" loading={loading} onClick={this.autoSend}>重新发送</Button>
                    <Button key="4" type="primary" onClick={this.onCloseTask}>删除</Button>
                </>)
            }
        }
    }
    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={<span style={{ fontSize: 16 }}>基础信息</span>}
                    expandRight={
                        [<Space key="0">
                            {this.operationButtons()}
                            <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='任务截止日期'
                                >
                                    <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
                                                    key={index}
                                                    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='heyan'
                                    label='核验日期范围'
                                >
                                    <RangePicker style={{ width: '100%' }} />
                                </Form.Item>
                            </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} />}
                {
                    this.state.closeModal && <DenyModal id={this.state.processList} onClose={this.closeModal} onSuccess={this.onCloseSuccess} />
                }
            </div>
        );
    }
}
