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 Skeleton from '../../../components/Skeleton'

import AddGood from "./AddGood";

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;
                });
                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);
                    if (res.uuid){
                        setGoodSubmit(true);
                        getChildColumns(res.uuid);
                        upload2.length > 0 && new Promise((resolve => {
                            res.uuid && uploadFile(upload2, 'fj', res.uuid);
                            resolve()
                        })).then(() => {
                            Toast.success('新增成功');
                        })
                    }

                });
            }
        });
    };

    const [childData, setChildData] = useState([])
    const getChildColumns = (uuid) => {
        axiosRequest({
            method: 'post',
            url: '/idtAppServiceV6/oApp/childDispatcher',
            body: {
                uuid,
                returnJson: true,
                templateId: submitData.templateId,
                templatePath: 'cgwpxx_list'
            },
        }).then(res => {
            const dataSource = res && res.elementList && 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;
            });
            setChildData(dataSource)
        })
    }

    const [upload2, setUpload2] = useState([]);

    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 && res.elementList && 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 [goods, setGoods] = useState([]);
    const [visible, setVisible] = useState(false);
    const [sGood, setSGood] = useState([]);
    const checkGood = (id, checked) => {
        const newData = JSON.parse(JSON.stringify(sGood));
        const Index = sGood.findIndex(item => item.id === id);
        const lIndex = goods.findIndex(item => item.id === id);
        checked ? newData.push(goods[lIndex]) : newData.splice(Index, 1);
        setSGood(newData)
    };
    const addGoods = (values) => {
        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;
        });
        axiosRequest({
            method: 'post',
            url: `/idtAppServiceV6/oApp/singleSave`,
            body: {
                params: JSON.stringify(values),
                tableId: submitData.tableId,
            }
        }).then(res => {
            if (res.uuid) {
                const newGood = [...goods, {...values, id: res.uuid, checked: false}];
                setGoods(newGood)
            }
        })

    };

    // const saveGoods = () => {
    //     const subData = JSON.parse(JSON.stringify(goods));
    //     subData.map(item => {delete item.id; delete item.checked});
    //
    // }
    const selectAll = (checked) => {
        setSGood(checked ? goods : [])
    };
    const deleteGood = () => {
        alert('删除记录', '确定删除选中的记录', [
            { text: '取消'},
            { text: '确认',
                onPress: () =>{
                    const ids = sGood.map(item => item.id);

                    axiosRequest({
                        method: 'post',
                        url: `/idtAppServiceV6/oApp/delete`,
                        body: {
                            uuids: JSON.stringify(ids),
                            tableId: submitData.tableId,
                        }
                    }).then(res => {
                        // console.log(res)
                    })

                    // 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)
    };

    return (
        <div>
            <AddGood
                columns={childData}
                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 {
                                        return <InputItem key={index}{...getFieldProps(item.label)}>{item.label}</InputItem>
                                    }
                                })}

                                <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/>
                                {!goodSubmit && (
                                    <WingBlank>
                                        <Button onClick={onSubmit} loading={loading} type="primary">保存并添加办公用品</Button>
                                    </WingBlank>
                                )}

                                {goodSubmit && (
                                    <div>
                                        <WhiteSpace/>
                                        <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(child => child.id === item.id) > -1} onChange={(val) => checkGood(item.id, val.target.checked)}>
                                                <div className="good-item-box" onClick={(e) => getGoodInfo(index, e)}>
                                                    <div className="good-item-content">
                                                        {childData[0].label}：{item[childData[0].label] || ''}
                                                        <img src="/img/rarrow.png" alt="" className={`icon18 ${item.checked ? 'icon-checked' : 'icon-unchecked'}`}/>
                                                    </div>
                                                    {item.checked && childData.map((item3, index3) => index3 !== 0 && (
                                                        <div key={index3} className="good-item-content">{item3.label}：{item[item3.label] || ''}</div>
                                                    ))}
                                                </div>
                                            </AgreeItem>
                                        ))}
                                        <WhiteSpace/>
                                    </div>
                                )}

                                <WhiteSpace/>
                            </div>
                        )}
                    </List>
                </form>
            ) : <Skeleton/>}

        </div>
    );
};

export default createForm()(Send);
