import axios from 'axios'

export default {
  namespaced: true,
  state: {
    Conference: {},
    ConferenceList: [],
    fileList: [],
    issues: {
      _id: '62f5d6fc6c21410d3339538e',
      staffName: '林詳淯',
      respondTime: '2022/08/12',
      detail: '測試'
    }
  },
  mutations: {
    setConference (state, Conference) {
      state.Conference = Conference
    },
    setConferenceList (state, ConferenceList) {
      state.ConferenceList = ConferenceList
    },
    setFileList (state, fileList) {
      state.fileList = fileList
    },
    setIssues (state, issues) {
      state.issues = issues
    }
  },
  actions: {
    // 會議
    async post ({state, dispatch}) { // 建立會議
      let time = new Date(state.Conference.conference_date)
      if (String(time.getDate()).padStart(2, '0') === '31') {
        let firstDate = new Date(time.getFullYear(), time.getMonth() + 1, 1)
        let endTime = firstDate.getFullYear() + '-' + String(firstDate.getMonth() + 1).padStart(2, '0') + '-' + String(firstDate.getDate()).padStart(2, '0')
        let endDate = endTime.slice(0, 8) + String(Number(endTime.slice(-2)))
        await dispatch('postSchedule', endDate)
      } else {
        let endTime = time.getFullYear() + '-' + String(time.getMonth() + 1).padStart(2, '0') + '-' + String(time.getDate()).padStart(2, '0')
        let endDate = endTime.slice(0, 8) + String(Number(endTime.slice(-2)) + 1)
        await dispatch('postSchedule', endDate)
      }
    },
    async postSchedule ({state, commit, dispatch}, endDate) { // 會議行事曆
      let result = await axios.post('/conference', state.Conference)
      commit('setConference', result.data)
      await dispatch('schedule/conferencePostSchedule', {
        title: state.Conference.conference_name,
        start: state.Conference.conference_date,
        end: endDate,
        color: '#f56161',
        scheduleType: '會議',
        thing: state.Conference.description,
        id: state.Conference._id
      }, { root: true })
    },
    async initConference ({commit, rootState}) { // 初始會議
      const currentToday = new Date()
      // const time = new Date().getTime()
      let currentUser = rootState.user.current
      let init = {
        conference_date: currentToday, // 會議日期
        conference_time: '', // 會議時間
        conference_name: '', // 會議名稱
        end_time: '', // 會議結束時間
        venue: '', // 會議地點
        host: '', // 會議主持人
        recorder: currentUser._id, // 會議記錄人
        description: '', // 相關說明
        conference_classification: '', // 會議類別
        officialDocId: null // 公文Id
      }
      commit('setConference', init)
    },
    async getConferenceList ({commit}, data) { // 會議總攬
      let result = await axios.get('/conference/list', {
        params: data
      })
      commit('setConferenceList', result.data)
    },
    async lookupConference ({commit}, id) { // 檢視會議
      let result = await axios.get(`/conference/lookup/${id}`)
      commit('setConference', result.data)
    },
    async patch ({state}) { // 編輯會議
      // let conference = state.Conference.issueId.forEach((element, index, array) => {
      //   array[index] = element._id
      // })
      // console.log(conference)
      await axios.patch(`/conference/${state.Conference.id}`, state.Conference)
    },
    async patchSchedule ({state, dispatch}, id) { // 編輯會議 | 修改行事曆
      await axios.patch(`/conference/${state.Conference.id}`, state.Conference)
      let time = new Date(state.Conference.conference_date)
      let endDate
      if (String(time.getDate()).padStart(2, '0') === '31') {
        let firstDate = new Date(time.getFullYear(), time.getMonth() + 1, 1)
        let endDateDay = String(firstDate.getDate()).padStart(2, '0')
        endDate = `${firstDate.getFullYear()}-${String(firstDate.getMonth() + 1).padStart(2, '0')}-${endDateDay}`
      } else {
        let nextDay = new Date(time)
        nextDay.setDate(nextDay.getDate() + 1)
        let endDateMonth = String(nextDay.getMonth() + 1).padStart(2, '0')
        let endDateDate = String(nextDay.getDate()).padStart(2, '0')
        endDate = `${nextDay.getFullYear()}-${endDateMonth}-${endDateDate}`
      }

      await dispatch('schedule/patchConferenceSchedule', {
        scheduleId: id,
        obj: {
          title: state.Conference.conference_name,
          start: state.Conference.conference_date,
          end: endDate,
          thing: state.Conference.description
        }
      }, { root: true })
    },
    async deleteConference ({state}, ConferenceId) { // 刪除會議
      await axios.delete(`/conference/${ConferenceId}`, state.Conference)
    },
    // 檔案
    async addFiles ({state}, {file}) { // 新增檔案
      try {
        let result = await axios.post(`/conference/${state.Conference._id}/fileTokens`, {
          name: file.name,
          mime: file.type,
          size: file.size
        })
        await axios.put(result.headers['location'].replace("/post-webapi", ""), file, {
          headers: {
            'Content-Type': file.type
          }
        })
      } catch (err) {
        throw err
      }
    },
    async getFileList ({state, commit}) { // 查看檔案
      let result = await axios.get(`/conference/${state.Conference._id}/file`)
      commit('setFileList', result.data)
    },
    async deleteFiles ({state}, fileId) { // 刪除檔案
      await axios.delete(`/conference/${state.Conference._id}/fileTokens/${fileId}`)
    }
  },
  getters: {
    conferenceMemberName (state) { // 檢視會議參與人員
      if (!state.Conference.member) return
      let member = []
      for (let i = 0; i < state.Conference.member.length; i++) {
        const element = state.Conference.member[i].name
        member.push(element)
      }
      return member.join('、')
    },
    conferenceContent (state) { // 會議議題
      if (!state.Conference.issueId) return
      let description = []
      for (let i = 0; i < state.Conference.issueId.length; i++) {
        const element = state.Conference.issueId[i].description
        description.push(element)
      }
      return description.join('、')
    }
  }
}
