import fetch from 'isomorphic-fetch'
import {logout, getTaskList, saveCommonInfo,emptyStoreInfo} from "./common";
import {emit} from "../util/event";
let domain = ENV.domain;
const willCloseDoor=(data,flag=false)=>{
    let url=domain+`machine_pad/finish_task.action`;
    let {userInfo,taskInfo,storeInfo}=data;
    let userId=userInfo.employeeId;
    let machineId=storeInfo.id;
    let {taskId,area,currentTaskType}=taskInfo;
    let bodyData={area,storeId:machineId,taskId,userId,taskType:currentTaskType};
    UTILPATH.myLogger.info("finish_task url ",url);
    UTILPATH.myLogger.info("finish_task flag ",flag);
    UTILPATH.myLogger.info("finish_task request ",bodyData);
    return async (dispatch)=>{
        let success = (json)=>{
            UTILPATH.myLogger.info("finish_task response ",json);
            if(flag){
                //回收箱完成
                dispatch(getTaskList(data))
            }
        };
        let fail = (err)=>{
            UTILPATH.myLogger.error(`finish_task error ${err}`);
        };
        try {
            let result = await fetch(url,{
                credentials : 'include',
                method : 'POST',
                mode : 'cors',
                headers:{
                    'Access-Control-Allow-Origin': '*',
                    'Content-Type': 'application/json; charset=UTF-8'
                },
                body:JSON.stringify(bodyData)
            }).then((response)=>response.json());
            return success(result)
        } catch (err) {
            return fail(err)
        }
    }
}

/**
 *
 * @param data
 * @param stopFlag 断电断网标志，true 断电断网中，
 * @returns {Function}
 */

const closeDoorSuccess=(data,stopFlag=false)=>{
    let {userInfo,taskInfo,storeInfo}=data;
    let userId=userInfo.employeeId;
    let machineId=storeInfo.id;
    let {taskId,area}=taskInfo;
    let bodyData={storeId:machineId,taskId,area,userId}
    let url=domain+'machine_pad/update_door_status.action';
    UTILPATH.myLogger.info("update_door_status url ",url);
    UTILPATH.myLogger.info("update_door_status request ",bodyData);
    UTILPATH.myLogger.info("update_door_status stopFlag ",stopFlag);
    return (dispatch)=>{
        fetch(url,{
            credentials : 'include',
            method : 'POST',
            mode : 'cors',
            headers:{
                'Access-Control-Allow-Origin': '*',
                'Content-Type': 'application/json; charset=UTF-8'
            },
            body:JSON.stringify(bodyData)
        }).then((response)=>response.json())
          .then((json)=>{
              UTILPATH.myLogger.info("update_door_status response ",json);
              if(stopFlag){
                  dispatch(askForNextTask(taskId))
              }else{
                  dispatch(logout());
              }
          }).catch(e=>{
            UTILPATH.myLogger.error(`update_door_status error ${e}`);
            // dispatch(closeDoorSuccess(data));
        })
  }
};


const askForNextTask = (taskId)=>{
    let url = domain+`machine_pad/power_cut_close_door/${taskId}`;
    UTILPATH.myLogger.info("askForNextTask power_cut_close_door url ",url);
    return (dispatch) =>{
        fetch(url,{
            credentials : 'include',
            method : 'POST',
            mode : 'cors',
            headers:{
                'Access-Control-Allow-Origin': '*',
                'Content-Type': 'application/json; charset=UTF-8'
            },
            body:JSON.stringify({})
        }).then((response)=>response.json())
            .then((json)=>{
                let {meta={}} = json;
                UTILPATH.myLogger.info("askForNextTask power_cut_close_door response ",json);
                if(meta.success){
                    let area = meta.message;
                    dispatch(saveCommonInfo(Object.assign({},{taskInfo:{area:area,currentTaskNum:0,currentTaskType:""}})))
                }else{
                    //将门店信息也清空
                    dispatch(emptyStoreInfo());
                    dispatch(logout());
                    emit(CONFIG.socketType.STOPSTOPSERVER,{});
                }
            }).catch(e=>{
            UTILPATH.myLogger.error(`power_cut_close_door error ${e}`);
            // dispatch(askForNextTask(taskId))
        })
    }
}
export {willCloseDoor,closeDoorSuccess}