import React, {useState, useEffect} from 'react';
import { createForm } from 'rc-form';
import axiosRequest from "../../../utils/request";
import {DatePicker, List, WhiteSpace, WingBlank, Picker, InputItem, Toast, Modal, Checkbox, Button} 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 AddGood from "./AddGood";
import Skeleton from '../../../components/Skeleton'

const alert = Modal.alert;
const Item = Checkbox.CheckboxItem;
const AgreeItem = Checkbox.AgreeItem;


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

    const [loading, setLoading] = useState(false);
    const [goodSubmit, setGoodSubmit] = useState(false)
    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;
                });
                name === '会议申请' && (values['会议地点'] = HYSDD);
                // name === '收文管理' && (values['文号'] = HYSDD);
                // name === '发文管理' && (values['编号'] = HYSDD);
                setLoading(true);
                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 => {
                    setLoading(false);
                    new Promise((resolve => {
                        res.uuid && uploadFile(upload, 'zw', res.uuid);
                        res.uuid && uploadFile(upload2, 'fj', res.uuid);
                        resolve()
                    })).then((res) => {
                        if (name !== '办公用品采购') {
                            res && res.uuid && Toast.success('新增成功');
                            res && res.uuid && props.history.goBack()
                        }else {
                            setGoodSubmit(true)
                        }

                    })
                });
            }
        });
    };

    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('blob', file);
        });
        upload.length > 0 && fileRequest({
            method: 'post',
            url: '/idtAppServiceV6/oApp/balanceUploadFile',
            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 [numberData, setNumberData] = useState([]);
    const [numberList, setNumberList] = 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;
            });
            const numberIndex = dataSource.findIndex(item =>
                name === '收文管理' ? (item.label === '来文机关或部门') : (item.label === '发文机关代字')
            );
            const list =  numberIndex > -1 && (dataSource[numberIndex].data.map(item => ({label: item.label, value: item.label,})));
            setNumberData(list || []);
            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 = () => {
        setPersonVisible(true)
    };
    const [HYSDD, setHYSDD] = useState();
    const selectRoom = HYSDD => {
        setHYSDD(HYSDD);
    }

    const [goods, setGoods] = useState([]);
    const [visible, setVisible] = useState(false);
    const [sGood, setSGood] = useState([]);
    const checkGood = (index, checked) => {
        const newData = [...sGood];
        const Index = sGood.findIndex(item => item.id === index);
        checked ? newData.push(goods[index]) : newData.splice(Index, 1);
        setSGood(newData)
    };
    const addGoods = (values) => {
        const newGood = [...goods, values];
        const newGoods = newGood.map((item, index) => ({...item, id: index, checked: false}));
        setGoods(newGoods)
    };
    const selectAll = (checked) => {
        setSGood(checked ? goods : [])
    };
    const deleteGood = () => {
        alert('删除记录', '确定删除选中的记录', [
            { text: '取消'},
            { text: '确认',
                onPress: () =>{
                    const ids = sGood.map(item => item.id);
                    const result = goods.filter(item => ids.indexOf(item.id) < 0);
                    setGoods(result);
                    setSGood([]);
                }
            },
        ])


    };
    const getGoodInfo = (index, e) => {
        e.preventDefault();
        const newGoods =  [...goods];
        newGoods[index].checked = !newGoods[index].checked;
        setGoods(newGoods)
    };
    // const checkTitle = () => {
    //     fileRequest({
    //         method: 'post',
    //         url: '/idtAppServiceV6/control/getList',
    //         body: {
    //             script: 'oa_fwgl_jyFwwhbh',
    //             args: JSON.stringify([numberList[0], numberList[1]]),
    //             keys: JSON.stringify([numberList[2]])
    //         }
    //     }).then((res) => {
    //         Toast.success('校验成功');
    //     });
    // };
    const saveNumber = (number1, number2, number3) => {
        const result = [...numberList];
        number1 && (result[0] = number1);
        number2 && (result[1] = number2);
        number3 && (result[2] = number3);
        setNumberList(result);
        const developer = localStorage.getItem('developer');

        name.indexOf('发文') > -1 && result[0] && result[1] && axiosRequest({
            method: 'post',
            url: '/idtAppServiceV6/control/getMap',
            body: {
                script: 'oa_fwgl_setFwwhbh',
                args: JSON.stringify([result[1], result[0]]),
                replaceMap: JSON.stringify({developer})
            }
        }).then((res) => {
            res && res.MAXFWWHBH && props.form.setFieldsValue({编号: res.MAXFWWHBH});
        });
    };

    return (
        <div>
            <MeetInfo
                visible={placeVisible}
                onClose={setPlaceVisible}
                selectR={selectRoom}
            />
            <PeopleInfo
                visible={personVisible}
                onClose={setPersonVisible}
            />
            <AddGood
                visible={visible}
                onClose={() => setVisible(false)}
                addGoods={addGoods}
            />
            {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 key={index} className="auto-flex" 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 key={index} className="auto-flex" extra={
                                                <div>
                                                    <div className="meet-select-btn" onClick={getPerson}>选择参会人员</div>
                                                </div>
                                            }>参会人员</List.Item>
                                        )
                                    } else if (name=== '收文管理' && item.label.indexOf('文号') > -1) {
                                        return (
                                            <List.Item key={index}>
                                                文号
                                                <div className="pos-aline">
                                                    <Picker value={[numberList[0]]} data={numberData} cols={1} onChange={val => saveNumber(val[0])}>
                                                        <List.Item className="room-num-2"/>
                                                    </Picker>
                                                    <div className="pos-aline">[ <input className="room-num-2" onBlur={val => saveNumber(null, val.target.value)}/> ]</div>
                                                    <input {...getFieldProps('文号')} className="room-num-2"/> 号
                                                    {/*<Button className="org-btn" size="small" onClick={checkTitle}>校验</Button>*/}
                                                </div>
                                            </List.Item>
                                        )
                                    } else if (name=== '发文管理' && item.label.indexOf('编号') > -1) {
                                        return (
                                            <List.Item key={index}>
                                                编号
                                                <div className="pos-aline">
                                                    <Picker value={[numberList[0]]} data={numberData} cols={1} onChange={val => saveNumber(val[0])}>
                                                        <List.Item className="room-num-2"/>
                                                    </Picker>
                                                    <div className="pos-aline">[ <input className="room-num-2" onBlur={val => saveNumber(null, val.target.value)}/> ]</div>
                                                    <input className="room-num-2" {...getFieldProps('编号')}/> 号
                                                </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/>
                                {name === '办公用品采购' && (
                                    <div>
                                        {!goodSubmit && (
                                            <WingBlank>
                                                <Button onClick={onSubmit} loading={loading} type="primary">添加办公用品</Button>
                                            </WingBlank>
                                        )}
                                        <List.Item extra={
                                            <div className="good-btn-content">
                                                <div className="good-btn mr-12 c-primary" onClick={() => setVisible(true)}>添加</div>
                                                <div className={`good-btn ${sGood.length > 0 ? 'c-orange' : 'c-gray'}`} onClick={setGoods.length > 0 && deleteGood}>删除</div>
                                            </div>
                                        }>申请物品</List.Item>
                                        <WhiteSpace/>
                                        {goods.length > 0 && (<Item onChange={(val) => selectAll(val.target.checked)}>全选</Item>)}
                                        {goods.length > 0 && goods.map((item, index) => (
                                            <AgreeItem className="mt-10" key={index} checked={sGood.findIndex(item => item.id === index) > -1} onChange={(val) => checkGood(index, val.target.checked)}>
                                                <div className="good-item-box" onClick={(e) => getGoodInfo(index, e)}>
                                                    <div className="good-item-content">
                                                        品名：{item.name || ''}
                                                        <img src="/img/rarrow.png" alt="" className={`icon18 ${item.checked ? 'icon-checked' : 'icon-unchecked'}`}/>
                                                    </div>
                                                    {item.checked && (
                                                        <div>
                                                            <div className="good-item-content">领取人：{item.name || ''}</div>
                                                            <div className="good-item-content">申请数量：{item.name || ''}</div>
                                                            <div className="good-item-content">实际发放数量：{item.name || ''}</div>
                                                        </div>
                                                    )}
                                                </div>
                                            </AgreeItem>
                                        ))}
                                        <WhiteSpace/>
                                    </div>
                                )}
                            </div>
                        )}
                    </List>
                    {formData.length > 0 && name !== '办公用品采购' && (
                        <div className="event-footer">
                            <div className="event-footer-button" onClick={onSubmit}>发送</div>
                        </div>
                    )}

                </form>
            ) : (<Skeleton/>)}

        </div>
    );
};

export default createForm()(Send);
