import React, {useState, useEffect} from 'react';
import Document from 'react-document-title'
import {WingBlank, WhiteSpace, ActionSheet, Toast} from 'antd-mobile'
import axiosRequest from '../../utils/request';
import downloadFile from '../../utils/downloadFile'
import TopTabs from '../../components/Tabs/BlankTabs'
import Skeleton from '../../components/Skeleton'
import Basic from './commponents/Basic'
import Adjunct from './commponents/Adjunct'
import Flow from './commponents/Flow';
import Option from './commponents/Option';

import './index.less'

const Process = (props) => {
    const {uuid, FLOWTBID} = props.match.params;

    const [templateId, setTemplateId] = useState();
    const [tableId, setTableId] = useState();
    const [nodeId, setNodeId] = useState();
    // const [operateId, setOperateId] = useState();
    const [flowTbId, setFlowTbId] = useState();

    //回到顶部
    useEffect(() => {
        window.scrollTo(0, 0)
    }, []);

    useEffect(() => {
        const {id} = props.match.params;
        setFlowTbId(FLOWTBID);
        axiosRequest({
            method: 'post',
            url: `/idtAppServiceV6/oApp/dispatcher`,
            body: {
                operateId: id,
                formType: 'form',
                uuid,
                mobileSign: 1
            }
        }).then(res => {
            // console.log(res.elementList && res.elementList.length > 0)
            // const keys = res.elementList ? Object.keys(res.elementList) : [];
            // console.log(keys);
            setBasic(res.elementList && res.elementList.length > 0  ? res.elementList.map(item => ({title: item.showName})) : []);
            setTableId(res.table && res.table.tableId);
            setTemplateId(res.property && res.property.templateId);
            setNodeId(res.property && res.property.curNodeId);
            // setOperateId(res.property && res.property.operateId);
        });

    }, []);
    //获取basic数据
    const [basic, setBasic] = useState([]);
    const [basicLoading, setBasicLoading] = useState(false)
    const getBasic = uuid => {
        axiosRequest({
            method: 'post',
            url: `/idtAppServiceV6/oApp/getData`,
            body: {uuid, tableId, templateId}
        }).then(res => {
            setBasicLoading(true)
            const result = [...basic];
            result.map(item => {
                item.content = res[item.title]
                return null;
            });
            setBasic(result)
        });
    }
    //获取Flow数据
    const [flowData, setFlowData] = useState([]);
    const [flowLoading, setFlowLoading] = useState(false)
    const getFlow = uuid => {
        axiosRequest({
            method: 'post',
            url: `/idtAppServiceV6/oApp/getFlowList`,
            body: {uuid, tableId}
        }).then(res => {
            setFlowLoading(true)
            setFlowData(res)
        });
    };

    const [adjunctData, setAdjunctData] = useState([]);
    const [adjunctLoading, setAdjunctLoading] = useState(false)
    const getAdjunct= uuid => {
        axiosRequest({
            method: 'post',
            url: `/idtAppServiceV6/oApp/getFiles`,
            body: {uuid, fieldName: 'fj', tableId}
        }).then(res => {
            setAdjunctLoading(true)
            setAdjunctData(res)
        });
    };
    const [button, setButton] = useState([])
    const getButton= uuid => {
        axiosRequest({
            method: 'post',
            url: `/idtAppServiceV6/oApp/nextNodeList`,
            body: {curNodeId: nodeId}
        }).then(res => {
            const result = res ? res.map(item => ({button: item.name, target: item.special, nodetype: item.nodetype})) : []
            setButton(result)
        });
    };
    useEffect(() => {
        const {uuid} = props.match.params;
        templateId && tableId && getBasic(uuid)
        templateId && tableId && getFlow(uuid);
        templateId && tableId && getAdjunct(uuid)
        getButton()
    }, [nodeId]);

    //提交按钮状态
    const [disabled, setDisabled] = useState(true);
    //提交按钮文字
    const [footButton, setFootButton] = useState('处理');
    //聚焦
    const optionBlur = () => {
        setFootButton('确认发送');
        setFootStatus(true)
    };
    useEffect(() => {
        const option = document.getElementsByClassName("option-text")[0];
        if (option) {
            option.addEventListener('focus', optionBlur, true);
            return () => option.removeEventListener('focus', optionBlur, true);
        }
    }, [basic]);

    const [blyj, setBlyj] = useState();
    const optionChange = val => {
        setBlyj(val);
        optionBlur()
        setDisabled(!(val != null && val !== ''))
    };

    const [current, setCurrent] = useState('basic');
    const [footStatus, setFootStatus] = useState(false);

    //点击输入框， 聚焦移动
    const textClick = () => {
        document.getElementsByClassName("option-text")[0].focus();
        window.scrollTo(0, document.body.scrollHeight);
        optionBlur()
    };
    const download = (uuid, callback) => {
        const developer = localStorage.getItem('developer');
        downloadFile({
            method: 'post',
            url: `/idtAppServiceV6/oApp/downloadLargeFileForword`,
            body: {uuid, tableId, developer},
        }).then(res => {
            var downloadElement = document.createElement('a');
            downloadElement.href = res.request.responseURL;
            document.body.appendChild(downloadElement);
            downloadElement.click(); //点击下载
            document.body.removeChild(downloadElement); //下载完成移除元素
        })
    }

    //tab切换
    const tabClick = (name) => {
        setCurrent(name)
        name === 'option' && document.getElementsByClassName("option-text")[0].focus();
        name === 'option' && optionBlur()
        const top = document.getElementById(`event-${name}`).offsetTop - document.getElementById(`event-basic`).offsetTop;
        window.scrollTo(0,top);
    };


    //antd-mobile 提交选项
    const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
    let wrapProps;
    if (isIPhone) {
        wrapProps = {
            onTouchStart: e => e.preventDefault(),
        };
    };

    const blyjSubmit = () => {
        axiosRequest({
            method: 'post',
            url: `/idtAppServiceV6/oApp/save`,
            body: {
                tableId,
                dealInfo: JSON.stringify({BLYJ: blyj, flowTbId}),
                params: JSON.stringify({UUID: uuid})}
        }).then(res => {
            console.log(res)
        });
    }

    const showActionSheet = () => {
        blyjSubmit()
        const BUTTON = [];
        button.map(item => BUTTON.push(item.button));
        const BUTTONS = BUTTON.concat(['取消']);
        ActionSheet.showActionSheetWithOptions({
                options: BUTTONS,
                cancelButtonIndex: BUTTONS.length - 1,
                maskClosable: true,
                wrapProps,
            },
            (buttonIndex) => {
                buttonIndex > -1 && (buttonIndex < BUTTONS.length - 1) && subUrl(buttonIndex)
            });
    };
    const subUrl = key => {
        button[key].nodetype === 'bakup' ? end() :
        props.history.push(`/blank/submit/${nodeId}/${uuid}/${flowTbId ? flowTbId : 'null'}`)
    };
    const end = () => {
        axiosRequest({
            method: 'post',
            url: `/idtAppServiceV6/application/interfaces/flow/saveWorkFlowModel.jsp`,
            body: {
                flowNodeId: nodeId,
                attachId: uuid,
                flowTbId: flowTbId === 'null' ? '' : flowTbId,
                userListMap: JSON.stringify([{}])
            }
        }).then(res => {
            if (res.success === 'success') {
                Toast.success("操作成功", 1, () => {
                    props.history.push('/bord/backlog')
                });

            }
        });
    };

    const resultLoading = basicLoading && adjunctLoading && flowLoading;
    return (
        <Document title="待办详情">
            <div>
                <TopTabs page={current} onClick={tabClick}/>
                <div id="event">
                    <WingBlank>
                        <div id="event-basic"/>
                        <WhiteSpace/>
                        {resultLoading ?  <Basic data={basic} attachId={uuid} {...props}/> : <Skeleton/>}
                        <div id="event-adjunct"/>
                        <WhiteSpace/>
                        {resultLoading ? <Adjunct download={download} data={adjunctData} tableId={tableId}/> : <Skeleton/>}
                        <div id="event-flow"/>
                        <WhiteSpace/>
                        {resultLoading ? <Flow data={flowData}/> : <Skeleton/>}
                        <div id="event-option"/>
                        <WhiteSpace/>
                        {resultLoading ? <Option onChange={optionChange}/> : <Skeleton/>}
                    </WingBlank>
                </div>

                <div className="event-footer">
                    { resultLoading && (
                        <div className={`event-footer-button ${(footStatus && disabled) ? 'button-disabled' : '' }`} onClick={footStatus && !disabled ? showActionSheet: textClick}>
                            {!footStatus && (
                                <img alt="" src="/img/process-edit.png" className="process-edit"/>
                            )}
                            {footButton}
                        </div>
                    )}

                </div>

            </div>
        </Document>
    );
};

export default Process;
