import fetch from 'isomorphic-fetch';
import actionType from '../actiontype/common'
import {addErrorInfo} from './uploadError'
let domain = ENV.domain;

let myHeaders = new Headers({
    // 'Access-Control-Allow-Origin': '*',
    // 'Content-Type': 'text/plain;charset=UTF-8',
    // 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'Content-Type': 'application/json; charset=UTF-8',
});

//获取店铺信息
const getStoreInfo = (storeId)=>{
    return async (dispatch)=>{
        let bodyData = {storeId};
        UTILPATH.myLogger.info("getMachineData request ",bodyData);

        let success = (json)=>{
            UTILPATH.myLogger.info("getMachineData response ",json);
            let storeInfo = Object.assign({},{id:storeId});
            if(json.meta.success && json.data.warehouse){
                storeInfo = Object.assign({},storeInfo,json.data.warehouse)
            }
            dispatch(saveCommonInfo(Object.assign({},{storeInfo})));
        };

        let fail = (e)=>{
            UTILPATH.myLogger.error(`getMachineData error ${e}`);
            dispatch(getStoreInfo(storeId));
        };

        try{
            let res = await fetch(domain + 'pad_warehouse/getMachineData.action',{
                credentials : 'include',
                method : 'POST',
                mode : 'cors',
                headers:myHeaders,
                body: JSON.stringify(bodyData)
            }).then((response)=>response.json());
            return success(res);
        }catch (e) {
            return fail(e)
        }
    }
};


//获取用户信息
const getUserinfo = (employeeId,storeId)=>{
    let bodyData = Object.assign({},{employeeId,storeId});
    UTILPATH.myLogger.info("get_alowed_task request ",bodyData);
    return(dispatch)=>{
        fetch(domain + 'machine_pad/get_alowed_task.action',{
            credentials : 'include',
            method : 'POST',
            mode : 'cors',
            headers:myHeaders,
            body : JSON.stringify(bodyData)
        }).then((response)=>response.json())
            .then(json=>{
                UTILPATH.myLogger.info("getMachineData get_alowed_task response ",json);
                let userInfo = Object.assign({},{id:employeeId})
                if(json.meta.success && json.data){
                    if(json.data.employee){
                        userInfo = Object.assign({},userInfo,json.data.employee)
                    }
                    if(json.data.type){
                        userInfo = Object.assign({},userInfo,{taskType:json.data.type});
                    }else{
                        dispatch(addErrorInfo('没有任务需要处理'))
                    }
                    dispatch(saveCommonInfo(Object.assign({},{userInfo})));
                }
            }).catch(e=>{
                UTILPATH.myLogger.error(`get_alowed_task error ${e}`);
                dispatch(getUserinfo(employeeId,storeId))
            })
    }
};


//拉取工单
const getTaskList = (data={},callback=null)=>{
        let {storeInfo={},userInfo={},taskInfo={}} = data;
        let taskId=taskInfo.taskId || 0;
        let url =`${domain}machine_pad/work/list/${storeInfo.id}/${taskInfo.area}/${taskId}/${userInfo.employeeId}`;
        UTILPATH.myLogger.info("getTaskList url ",url);
        return (dispatch)=>{
            if(!storeInfo.id){
                dispatch(addErrorInfo('没有门店信息，请耐心等待，看右上角是否有门店信息，如还没有，请重启APP'))
            }else if(!userInfo.id){
                dispatch(addErrorInfo('没有用户信息，请重启APP，等有门店信息了，重新扫描开门码'))
            }else if(!taskInfo.area){
                dispatch(addErrorInfo('没有区域信息，请重启APP，等有门店信息了，重新扫描开门码'))
            }else {
                fetch(url,{
                    credentials : 'include',
                    method : 'GET',
                    mode : 'cors',
                    headers: myHeaders
                }).then(response=>response.json())
                    .then((json)=>{
                        UTILPATH.myLogger.info("getTaskList response ",json);
                        let data =Object.assign({});
                        if(json.meta.success && json.data){
                            data.taskInfo = Object.assign({},json.data.flatCommonVo);
                            data.taskList = Object.assign({},json.data.skuFlatVo);
                            let childNum = 0;
                            let currentTaskType = json.data.flatCommonVo.currentTaskType;
                            let currentTaskNum = json.data.flatCommonVo.currentTaskNum;
                            dispatch(getTaskName(currentTaskType,childNum))
                        }else{
                            dispatch(addErrorInfo(json.meta.message))
                        }
                        dispatch(saveCommonInfo(Object.assign({},data)))
                        if(callback){
                            callback()
                        }
                    }).catch(e=>{
                        UTILPATH.myLogger.error(`getTaskList error ${e}`);
                        if(callback){
                            callback()
                        }
                })
            }
        }
}

//本地存储公共信息
const saveCommonInfo = (data)=>{
    return {
        type : actionType.SAVECOMMONINFO,
        data
    }
};

// 退出时清空用户信息，工单信息
const logout = ()=>{
    let data = Object.assign({},{userInfo:{},taskInfo:{},taskList:{}});
    return {
        type : actionType.EMPTYCOMMONINFO,
        data
    }
};

// 清空门店信息（用于断电断网退出时）
const emptyStoreInfo = ()=>{
    let data = Object.assign({},{storeInfo:{}});
    return {
        type : actionType.EMPTYCOMMONINFO,
        data
    }
}

// 获取页面左边部分展示当前任务名
const getTaskName = (currentTaskType,childTaskNum=0)=>{
    return {
        type : actionType.GETTASKNAME,
        data : {currentTaskType,childTaskNum}
    }
}

export {getStoreInfo,saveCommonInfo,getUserinfo,logout,getTaskList,getTaskName,emptyStoreInfo}
