import nodeApi from '../api/crawlNodeApi'
const state = {
    nodes: [] // 其他模块会用到这个数据的ipPort字段，请不要修改
}
const mutations = {
    setNodes(state, data) {
        state.nodes = data;
    },
    delNodes(state, ids) {
        for (var i = 0; i < state.nodes.length; i++) {
            for (var j = 0; j < ids.length; j++) {
                if (state.nodes[i].id == ids[j]) {
                    state.nodes.splice(i, 1);
                    i--;
                    break;
                }
            }
        }
    },
    addNode(state, node) {
        state.nodes.push(node);
    },
    updateNode(state, node){
        for (var i = 0; i < state.nodes.length; i++) {
            if (state.nodes[i].id == node.id) {
                state.nodes[i] = {...node};
            }
        }
    }    
}

const actions = {
    queryAllNodes({ commit }) {
        nodeApi.queryAllCrawlNodes((response) => {
            if (response.data.code == 200) {
                commit('setNodes', response.data.content);
            }
        })
    },
    delNodes({ commit }, data) {
        var ids = []
        data.forEach(element => {
            ids.push(element.id);
        });
        nodeApi.delCrawlNodes(ids, (response) => {
            if (response.data.code == 200) {
                commit('delNodes', ids);
            }
        })
    },
    saveNode({ commit }, form) {
        nodeApi.saveCrawlNode(form,(response)=>{
            return new Promise((resolve,reject)=>{                
                if(response.data.code == 200){
                    commit('addNode', form);
                    resolve(response);
                }else{
                    reject();
                }
            })
        })
    },
    updateNode({commit}, form){
        nodeApi.updateCrawlNode(form,(response)=>{
            return new Promise((resolve,reject)=>{                
                if(response.data.code == 200){
                    commit('updateNode', form);
                    resolve(response);
                }else{
                    reject();
                }
            })
        })      
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}

// function formatNumber (n) {
//     n = n.toString()
//     return n[1] ? n : '0' + n;
// }

// function timestampToTime(timestamp) {
//     var date = new Date(timestamp);
//     var Y = date.getFullYear();
//     var M = date.getMonth() + 1;
//     var D = date.getDate();
//     // var h = date.getHours() + ':';
//     // var m = date.getMinutes() + ':';
//     // var s = date.getSeconds();
//     return formatNumber(Y) + '-' + formatNumber(M) + '-' + formatNumber(D);
// }