import fetch from 'isomorphic-fetch';
import actionTypes from '../actiontype/trouble'
import userActionTypes from "../actiontype/user";
import {saveHeaderInfo} from './initHeader'
import {saveCommonInfo,getTaskList} from "./common";

const domain = ENV.domain;

const saveTroubleList = (data) => {
    return {
        type: actionTypes.SAVETROUBLELIST,
        data
    }
};


const saveUserInfo = (data) => {
    return {
        type: userActionTypes.SAVEUSERINFO,
        data
    }
}

var myHeaders = new Headers({
    'Access-Control-Allow-Origin': '*',
    'Content-Type': 'application/json; charset=UTF-8',
});


const getTroubleList = (info) => {
    let {storeInfo={},userInfo={},taskInfo={}} = info;
    return (dispatch) => {
        let bodyData = Object.assign({}, {
            employeeId: userInfo.employeeId,
            storeId: storeInfo.id
        });
        UTILPATH.myLogger.info("getTroubleList request ",bodyData);
        fetch(domain + 'machine_pad/list_fault.action', {
            credentials: 'include',
            method: 'POST',
            mode: 'cors',
            headers: myHeaders,
            body: JSON.stringify(bodyData)
        }).then((response) => response.json())
            .then(json => {
                if (json.meta.success && json.data) {
                    dispatch(saveCommonInfo({taskInfo : {taskId: json.data.taskId, sellOrderId: json.data.sellOrderId}}))
                    dispatch(saveTroubleList(json.data))
                }
            }).catch(e => {
            UTILPATH.myLogger.error("getTroubleList error ",e);
        })
    }
};

const updateTroubleList = (info, headerInfo) => {
    let {taskInfo={},userInfo={},storeInfo={}} = headerInfo;
    let bodyData = Object.assign({}, {details: info}, {taskId:taskInfo.taskId,employeeId:userInfo.employeeId,storeId:storeInfo.id});
    UTILPATH.myLogger.info("save_all_error request ",bodyData);
    //todo 更新故障处理，并且获取新的工单
    return (dispatch) => {
        fetch(domain + 'machine_pad/save_all_error.action', {
            credentials: 'include',
            method: 'POST',
            mode: 'cors',
            headers: myHeaders,
            body: JSON.stringify(bodyData)
        }).then((response) => response.json())
            .then(json => {
                dispatch(getTaskList(headerInfo))
            }).catch(e => {
            UTILPATH.myLogger.error("save_all_error error ",e);
        })
    }
};

export {getTroubleList, updateTroubleList}

