import Vue from 'vue'
// import nedb from '../../db/nedb'
import deepClone from '@/utils/deepClone'

// state
const state = {
  circles: {
    SnsList: [],
    WxId: '',
    NextSeq: '',
    Success: null
  } // 朋友圈
}

// getters
const getters = {
  circles: (state) => state.circles
}

// actions
const actions = {
  // 设置群发助手页面 当前微信的好友列表
  SetCircles({ state, commit }, newCirlces) {
    let currentCircles = state.circles
    if (currentCircles.WxId === newCirlces.WxId) {
      if (currentCircles.NextSeq !== newCirlces.NextSeq) {
        commit('UPDATE_CIRCLES', newCirlces)
      }
    } else {
      commit('SET_CIRCLES', newCirlces)
    }
  }
  //   // 更新朋友圈数据（图片、视频地址）
  //   UpdateCircle({ state, commit }, newCirlce) {
  //     console.log('UpdateCircle', newCirlce)
  //     const currentCircles = state.circles
  //     if (currentCircles.WxId === newCirlce.WxId) {
  //       const { SnsInfo: snsInfo } = newCirlce
  //       const { SnsList } = currentCircles
  //       let snsList = deepClone(SnsList)
  //       for (const sns of snsList) {
  //         if (sns.SnsId === snsInfo.SnsId) {
  //           if (snsInfo.Video) {
  //             sns.Video = snsInfo.Video
  //             break
  //           } else if (snsInfo.Images) {
  //             sns.Images = snsInfo.Images
  //             break
  //           }
  //         }
  //       }
  //       commit('UPDATE_CIRCLES_SNSLIST', snsList)
  //     }
  //   }
}

// mutations
const mutations = {
  // 设置朋友圈
  SET_CIRCLES(state, circlesData) {
    state.circles = circlesData
  },
  // 重置朋友圈数据
  RESET_CIRCLES(state) {
    state.circles = {
      SnsList: [],
      WxId: '',
      NextSeq: '',
      Success: null
    }
  },
  // 添加朋友圈数据
  UPDATE_CIRCLES(state, updateData) {
    Vue.set(state.circles, 'NextSeq', updateData.NextSeq)
    if (updateData.SnsList) {
      Vue.set(state.circles, 'SnsList', state.circles.SnsList.concat(updateData.SnsList))
    }
  },
  //   // 更新朋友圈数据
  //   UPDATE_CIRCLES_SNSLIST(state, snsData) {
  //     Vue.set(state.circles, 'SnsList', snsData)
  //   },
  // 删除朋友圈成功后更新本地数据
  UPDATE_CIRCLES_BY_DELETE(state, delData) {
    let cc = state.circles
    if (cc.WxId === delData.WxId) {
      let delId = 0
      for (const sns of cc.SnsList) {
        if (sns.SnsId === delData.TaskId) {
          cc.SnsList.splice(delId, 1)
          break
        }
        delId++
      }
    }
  },
  // 删除朋友圈成功后更新本地数据
  UPDATE_CIRCLES_BY_ONE(state, oneData) {
    let cc = state.circles
    if (cc.WxId === oneData.WxId) {
      let findId = 0
      for (const sns of cc.SnsList) {
        if (sns.SnsId === findId.TaskId) {
          cc.SnsList.splice(findId, 1, oneData.SnsInfo)
          break
        }
        findId++
      }
    }
  }
}

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