import axios from 'axios'

export default {
  namespaced: true,
  state: {
    selected: {},
    todo: {},
    list: [],
    todoList: [],
    permission: []
  },
  mutations: {
    setSelected (state, selected) {
      state.selected = selected
    },
    setTodo (state, content) {
      state.todo = content
    },
    setList (state, staffList) {
      state.list = staffList
    },
    setPermission (state, permission) {
      state.permission = permission
    },
    setTodoList (state, list) {
      state.todoList = list
    },
    resetTodo (state) {
      state.todo = {}
    }
  },
  actions: {
    async initStaff ({commit}) { // 初始化人員資料
      let init = {
        name: '',
        staffID: '',
        unit: '',
        account: '',
        password: '',
        tender: '',
        email: '@gmail.com',
        emailPass: '',
        contactNumber: '09',
        substitute: '',
        group: '',
        projectTitle: '',
        projectRole: '6266b118556a4a09a1f5e0bf',
        permissions: []
      }
      commit('setSelected', init)
    },
    async addStaff ({state, rootState, dispatch}) { // 新增人員與專案內人員
      try {
        state.selected.defaultTender = state.selected.tender[0]._id
        let init = []
        for (const tender of rootState.tenders.tenderList) {
          let tenderInfo = {}
          tenderInfo.tenderId = tender._id
          tenderInfo.permission = [
            {
              name: 'basicSetting',
              title: '基本設定',
              functionItem: [
                {
                  name: '通訊錄',
                  permission: 1,
                  permissionType: 0,
                  englishName: 'directory'
                },
                {
                  name: '工程現況',
                  permission: 1,
                  permissionType: 0,
                  englishName: 'projectStatus'
                }
              ]
            },
            {
              name: 'officialDocumentManagement',
              title: '公文管理',
              functionItem: [
                {
                  name: '收發文',
                  permission: 1,
                  permissionType: 0,
                  englishName: 'receivePostDocument'
                },
                {
                  name: '結案',
                  permission: 1,
                  permissionType: 1,
                  englishName: 'caseEnd'
                },
                {
                  name: '參數設置',
                  permission: 1,
                  permissionType: 1,
                  englishName: 'paramSetting'
                },
                {
                  name: '收發文資料管理',
                  permission: 1,
                  permissionType: 0,
                  englishName: 'receivePostManagement'
                }
              ]
            },
            {
              name: 'workCollaboration',
              title: '工作協同',
              functionItem: [
                {
                  name: '會議管理',
                  permission: 1,
                  permissionType: 0,
                  englishName: 'conferenceManagement'
                },
                {
                  name: '解除列管',
                  permission: 1,
                  permissionType: 1,
                  englishName: 'postCaseClosed'
                },
                {
                  name: '文件提審',
                  permission: 1,
                  permissionType: 0,
                  englishName: 'fileManagement'
                },
                {
                  name: '結束提審',
                  permission: 1,
                  permissionType: 1,
                  englishName: 'finishDeliver'
                },
                {
                  name: '刪除文件',
                  permission: 1,
                  permissionType: 1,
                  englishName: 'deleteFile'
                }
              ]
            },
            {
              name: 'documentCollaboration',
              title: '文件管理',
              functionItem: [
                {
                  name: '刪除契約',
                  permission: 1,
                  permissionType: 1,
                  englishName: 'deleteContract'
                },
                {
                  name: '品保文件',
                  permission: 1,
                  permissionType: 0,
                  englishName: 'qualityAssurance'
                },
                {
                  name: '變更契約',
                  permission: 1,
                  permissionType: 0,
                  englishName: 'contractChanging'
                },
                {
                  name: '展延紀錄',
                  permission: 1,
                  permissionType: 0,
                  englishName: 'extendedRecord'
                }
              ]
            },
            {
              name: 'calendar',
              title: '行事曆',
              functionItem: [
                {
                  name: '事件管理',
                  permission: 1,
                  permissionType: 0,
                  englishName: 'eventManagement'
                },
                {
                  name: '參數設置',
                  permission: 1,
                  permissionType: 1,
                  englishName: 'eventType'
                }
              ]
            }
          ]
          tenderInfo.isOpen = true
          init.push(tenderInfo)
        }
        state.selected.tenderPermissions = init
        await axios.post('/staff', state.selected)
        await dispatch('getAllStaff')
        for (let oneStaff of state.list) {
          if (oneStaff.name === state.selected.name && oneStaff.staffID === state.selected.staffID) {
            await axios.post(`/project/${rootState.project.current._id}/staffs`, {_id: oneStaff._id})
          }
        }
      } catch (err) {
        console.log(err)
      }
    },
    async initTodo ({commit}) { // 初始化待辦事項
      let init = {
        title: '',
        endingTime: '',
        description: '',
        src: ''
      }
      commit('setTodo', init)
    },
    async addTodo ({rootState, state, commit}) { // 新增待辦事項
      let result = await axios.post(`/staff/${rootState.user.current._id}/todo`, state.todo)
      commit('setTodo', result.data)
    },
    async deleteStaff ({rootState, dispatch}, staffId) { // 刪除人員與專案內人員
      try {
        await axios.delete(`/project/${rootState.project.current._id}/staff/${staffId}`)
        await axios.delete(`/staff/${staffId}`)
      } catch (err) {
        console.log(err)
      }
    },
    // async lookupUndertaker () { // 承辦人使用
    //   return (await axios.get('/staff/undertaker')).data
    // },
    async getAllStaff ({commit}) { // 拿取全部人員
      let result = await axios.get('/staff/list')
      commit('setList', result.data)
    },
    async getTodoList ({rootState, commit}) {
      let result = await axios.get(`/staff/${rootState.user.current._id}/todoList`)
      commit('setTodoList', result.data)
    },
    async lookUp ({commit, rootState, dispatch}, id) { // 查詢人員資料 (需在優化，隨時都會當機)
      // let currentUser = rootState.user.current
      // for (let i = 0; i < currentUser.tender.length; i++) {
      //   const element = currentUser.tender[i]
      //   await dispatch('project/getTender', element, {root: true})
      // }
      // let tender = rootState.project.tenders
      let result = await axios.get(`/staff/${id}`)
      // result.data.tender = []
      // result.data.tender.push(tender.tender)
      commit('setSelected', result.data)
    },
    async lookUpTodo ({rootState, commit}, id) { // id檢視待辦事項
      let result = await axios.get(`/staff/${rootState.user.current._id}/lookup/${id}`)
      commit('setTodo', result.data)
    },
    async updateStaffData ({state, commit, dispatch}) { // 人員切換標案
      await axios.patch(`/staff/${state.selected._id}`, state.selected)
      await dispatch('tenders/lookupTender', state.selected.defaultTender, { root: true })
      await dispatch('tenders/getOtherList', state.selected.defaultTender, { root: true })
    },
    async patchStaff ({state}, staffId) { // 修改人員資料
      await axios.patch(`/staff/${staffId}`, state.selected)
    },
    async patchPermission ({state}, {staff, tender}) { // 修改權限
      for (const a of state.selected.tenderPermissions) {
        if (a.tenderId._id === tender) {
          state.permission[0].isOpen = a.isOpen
          await axios.patch(`/staff/${staff}/permission/${tender}`, state.permission)
        }
      }
    },
    async patchStaffTodo ({ rootState, state }, id) { // 編輯待辦事項 (modal專用)
      await axios.patch(`/staff/${rootState.user.current._id}/todo/${id}`, state.todo)
    },
    async patchFinishTodo ({rootState}, {id, data}) { // 完成待辦事項 (勾選用)
      await axios.patch(`/staff/${rootState.user.current._id}/todo/${id}`, data)
    },
    async sendEmail ({state}, data) { // 發送email
      try {
        await axios.post('/staff/email', data)
      } catch (err) {
        alert('傳送失敗！')
        throw new Error('傳送失敗！')
      }
    },
    async selectTenderToLook ({state, commit}, tenderId) { // 檢視該標案設定之權限
      try {
        let result = await axios.get(`/staff/${state.selected._id}/permission/${tenderId}`)
        commit('setPermission', result.data)
      } catch (err) {
        console.log(err)
      }
    },
    async deleteTodo ({rootState}, id) { // 刪除待辦事項
      await axios.delete(`/staff/${rootState.user.current._id}/todo/${id}`)
    }
  },
  getters: {
    permissions (state) {
      return (permissionsTemplate) => {
        let permissions = (state.selected.permissions.length !== 0) ? state.selected.permissions : permissionsTemplate
        return permissions.reduce((map, obj) => ({
          ...map,
          [obj.name]: obj.functionItem
        }), {})
      }
    },
    tenderName (state) { // 使用者資料使用
      if (!state.selected.tender) return
      let tenderName = []
      for (let i = 0; i < state.selected.tender.length; i++) {
        const element = state.selected.tender[i].tender
        tenderName.push(element)
      }
      return tenderName.join('、')
    }
  }
}
