import React, {useState, useEffect} from 'react';
import { createForm } from 'rc-form';
import axiosRequest from "../../../utils/request";
import {DatePicker, List, WhiteSpace, WingBlank, Picker, InputItem, Toast} from "antd-mobile";
import MailA from '../../../components/Adjunct/MailA'
import Upload from 'rc-upload';
import './index.less'
import moment from 'moment'
import fileRequest from "../../../utils/fileRequest";
import MeetInfo from './MeetInfo'
import PeopleInfo from './PeopleInfo'
import Skeleton from '../../../components/Skeleton'

const Send = (props) => {
    const {name} = props.match.params;
    const {getFieldProps} = props.form;

    const [UUID, setUUID] = useState();

    const onSubmit = () => {
        props.form.validateFields({ force: true }, (error) => {
            if (!error) {
                const values = props.form.getFieldsValue();
                const keys = Object.keys(values);
                keys.map(item => {
                    !values[item] && (delete values[item]);
                    Array.isArray(values[item]) && values[item].length === 1 && (values[item] = values[item][0]);
                    values[item] instanceof Date && ( values[item] = moment(values[item]).format("YYYY-MM-DD HH:mm:ss"))
                    return null;
                });
                values['会议地点'] = HYSDD;
                !UUID && axiosRequest({
                    method: 'post',
                    url: '/idtAppServiceV6/oApp/save',
                    body: {
                        params: JSON.stringify(values),
                        dealInfo:JSON.stringify({flowTbId: submitData.flowTbId}),
                        tableId: submitData.tableId,
                        operateId: submitData.operateId,
                        templateId: submitData.templateId
                    },
                }).then(res => {
                    res.uuid && setUUID(res.uuid);
                });
                UUID && new Promise((resolve => {
                    upload.length > 0 && uploadFile(upload, 'zw', UUID);
                    upload2.length > 0 && uploadFile(upload2, 'fj', UUID);
                    resolve()
                })).then(() => {
                    Toast.success('新增成功');
                    props.history.goBack()
                })
            }
        });
    };

    const [upload, setUpload] = useState([]);
    const [upload2, setUpload2] = useState([]);
    const uploaderProps = {
        multiple: true,
        beforeUpload(file) {
            const newUpload = [...upload, file];
            setUpload(newUpload);
            return false
        }
    };
    const uploadDelete = uid => {
        const newData = [...upload];
        const Index = newData.findIndex(item => item.uid === uid);
        Index > -1 && newData.splice(Index, 1);
        setUpload(newData)
    };
    const uploaderProps2 = {
        multiple: true,
        beforeUpload(file) {
            const newUpload = [...upload2, file];
            setUpload2(newUpload);
            return false
        }
    };
    const uploadDelete2 = uid => {
        const newData = [...upload2];
        const Index = newData.findIndex(item => item.uid === uid);
        Index > -1 && newData.splice(Index, 1);
        setUpload2(newData)
    };

    const uploadFile = (upload, name, attachId) => {
        const formData = new FormData();
        upload.length > 0 && upload.forEach(file => {
            formData.append('file', file);
        });
        upload.length > 0 && fileRequest({
            method: 'post',
            url: '/idtAppServiceV6/oApp/balanceUploadFileAdapt',
            body: {
                tableId: submitData.tableId,
                ATTACH_ID: attachId,
                FIELDNAME: name,
                FILENAME: 'base64'
            },
            payload: formData
        }).then(res => {
            console.log(res)
            // Toast.success('发送成功');
        });
    }


    const [formData, setFormData] = useState([]);
    const [submitData, setSubmitData] = useState({});
    const [loading2, setLoading2] = useState(false)
    useEffect(() => {
        const menuParams = localStorage.getItem('menu');
        const menu = JSON.parse(menuParams);
        const menuIndex = menu.findIndex(item => item.text === name);
        menuIndex > -1 && menu[menuIndex].children.length > 0 && axiosRequest({
            method: 'post',
            url: `/idtAppServiceV6/oApp/dispatcher`,
            body: {operateId: menu[menuIndex].children[0].id, formType: 'form'}
        }).then(res => {
            setLoading2(true);
            const dataSource = res.elementList.map((item, index) => {
                const group = {};
                group.type = item.colType;
                group.type === 'DATE' && (group.dateType = item.dateType);
                group.label = item.showName.replace(/\s+/g,"");
                item.dict && item.dict.data && item.dict.data.length > 0 && (group.data = item.dict.data.map(item => ({label: item.DISP_VALUE, value: item.REAL_VALUE})));
                return group;
            });
            setSubmitData(res.property)
            setFormData(dataSource)
        });
    }, []);

    const getMode = val => {
        const date = /^(\w{4})-(\w{2})-(\w{2})$/;
        const time = /^(\w{2}):(\w{2}):(\w{2})$/;
        return date.test(val) ? 'date' : (time.test(val) ? 'time' : 'datetime')
    };


    const [placeVisible, setPlaceVisible] = useState(false);
    const [personVisible, setPersonVisible] = useState(false);
    const getPlace = () => {
        setPlaceVisible(true)
    };
    const getPerson = () => {
        onSubmit();
        setPersonVisible(true)
    };
    const [HYSDD, setHYSDD] = useState();
    const selectRoom = HYSDD => {
        setHYSDD(HYSDD);
    };
    const [sP, setSP] = useState([]);

    return (
        <div>
            <MeetInfo
                visible={placeVisible}
                onClose={setPlaceVisible}
                selectR={selectRoom}
            />
            <PeopleInfo
                UUID={UUID}
                visible={personVisible}
                onClose={setPersonVisible}
                peopleData={sP}
                onSelect={setSP}
            />
            {loading2 ? (
                <form>
                    <List className="send-content">
                        {formData.length > 0 && (
                            <div>
                                {formData.map((item, index) => {
                                    if (item.type === 'DATE') {
                                        return (
                                            <DatePicker key={index} mode={getMode(item.dateType)} className="send-date-style"{...getFieldProps(item.label)}>
                                                <List.Item arrow="horizontal">{item.label}</List.Item>
                                            </DatePicker>
                                        )
                                    }else if (item.data) {
                                        return (
                                            <Picker key={index} data={item.data} cols={1} {...getFieldProps(item.label)}>
                                                <List.Item arrow="horizontal">{item.label}</List.Item>
                                            </Picker>
                                        )
                                    }else if (item.label === '会议地点') {
                                        return (
                                            <List.Item className="auto-flex" key={index} extra={
                                                <div className="pos-aline">
                                                    <div className="meet-select-btn" onClick={getPlace}>选择会议地点</div>
                                                    <div className="ml-40 room-num">{HYSDD}</div>
                                                </div>
                                            }>会议地点</List.Item>
                                        )
                                    } else if (item.label === '参会人员') {
                                        return (
                                            <List.Item className="auto-flex" key={index} extra={
                                                <div className="pos-aline">
                                                    <div className="meet-select-btn" onClick={getPerson}>选择参会人员</div>
                                                    <div className="ml-40 room-num">{sP.length}人</div>
                                                </div>
                                            }>参会人员</List.Item>
                                        )
                                    } else {
                                        return <InputItem key={index}{...getFieldProps(item.label)}>{item.label}</InputItem>
                                    }
                                })}

                                {/*正文*/}
                                <div className="am-textarea-label upload-title">正文：</div>
                                <WingBlank>
                                    {upload.length > 0 && upload.map((item, index) => (
                                        <MailA key={index} data={item} onDelete={uploadDelete}/>
                                    ))}
                                </WingBlank>

                                <Upload className="auto-upload" {...uploaderProps}>
                                    <a className="auto-upload">上传正文 +</a>
                                </Upload>
                                <WhiteSpace/>

                                <div className="am-textarea-label upload-title">附件：</div>
                                <WingBlank>
                                    {upload2.length > 0 && upload2.map((item, index) => (
                                        <MailA key={index} data={item} onDelete={uploadDelete2}/>
                                    ))}
                                </WingBlank>
                                <Upload className="auto-upload" {...uploaderProps2}>
                                    <a className="auto-upload">上传附件 +</a>
                                </Upload>
                                <WhiteSpace/>
                            </div>
                        )}
                    </List>
                    {formData.length > 0 && (
                        <div className="event-footer">
                            {/*<Button type="primary">保存</Button>*/}
                            <div className={`footer-button ${sP.length > 0 ? '' : 'btn-disabled'}`} onClick={sP.length > 0 ? onSubmit : null}>保存</div>
                        </div>
                    )}

                </form>
            ) : <Skeleton/>}

        </div>
    );
};

export default createForm()(Send);
