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 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 Goods from '../commponents/Goods'

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)
    }, []);

    const [blob, setBlob] = useState(false);
    const [flow, setFlow] = useState(false)
    useEffect(() => {
        setFlowTbId(FLOWTBID);
        axiosRequest({
            method: 'post',
            url: `/idtAppServiceV6/oApp/childDispatcher`,
            body: {
                uuid,
                templatePath: 'cgwpxx_list',
                returnJson: true
            }
        }).then(res => {
            setBlob(Object.keys(res.blob).length > 0);
            setFlow(res.property.showFlow === '1');
            // 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);
        });
        // const {id} = props.match.params;

    }, []);
    //获取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)
        });
    };
    const [applicateData, setapplicateData] = useState([]);
    const [applicateList, setApplicateList] = useState([])
    const getApplication = (uuid) => {
        axiosRequest({
            method: 'post',
            url: `/idtAppServiceV6/oApp/getChildGridDataList`,
            body: {attachId: uuid, templatePath: 'cgwpxx_list'}
        }).then(res => {
            setBasicLoading(true);
            setapplicateData(res.rows);
            setApplicateList(res.elementList)
        });
    };
    const treeClick = (BGYPMC) => {
        const newData = [...applicateData];
        const index = newData.findIndex(item => item.BGYPMC === BGYPMC);
        const checked = newData[index].checked ? newData[index] : false;
        newData[index] = {...newData[index], checked: !checked};
        setapplicateData(newData)
    };
    //获取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 && flow && getFlow(uuid);
        templateId && tableId && blob && getAdjunct(uuid);
        templateId && tableId && getApplication(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();
    // console.log(blyj)
    const optionChange = val => {
        // setBlyj(val)
        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()
    };

    //tab切换
    const tabClick = (name) => {
        setCurrent(name)
        flow && name === 'option' && document.getElementsByClassName("option-text")[0].focus();
        flow && 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 showActionSheet = () => {
        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 < BUTTONS.length - 1 && subUrl(buttonIndex)
                // console.log(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 && (!blob || adjunctLoading) && (!flow || flowLoading);
    return (
        <Document title="待办详情">
            <div>
                <TopTabs page={current} onClick={tabClick}/>
                <div id="event">
                    <WingBlank>
                        <div id="event-basic"/>
                        <WhiteSpace/>
                        {resultLoading ?  (
                            <div>
                                {applicateData.length > 0 && (
                                    <div>
                                        <Basic data={basic}/>
                                        <WhiteSpace/>
                                        <div className="good-title">申领物品信息</div>
                                        <Goods list={applicateList} data={applicateData} onClick={treeClick}/>
                                    </div>
                                )}
                            </div>
                        ) : <Skeleton/>}
                        <div id="event-adjunct"/>
                        <WhiteSpace/>
                        {resultLoading ? (blob && <Adjunct data={adjunctData}/>) : <Skeleton/>}
                        <div id="event-flow"/>
                        <WhiteSpace/>
                        {resultLoading ? (flow && <Flow data={flowData}/>) : <Skeleton/>}
                        <div id="event-option"/>
                        <WhiteSpace/>
                        {resultLoading ? (flow && <Option onChange={optionChange}/>) : <Skeleton/>}
                    </WingBlank>
                </div>

                <div className="event-footer">
                    { resultLoading && flow && (
                        <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;
