import axios from 'axios'
import PizZip from 'pizzip'
import fetch from 'node-fetch'
import mime from 'mime-types'

export default {
  namespaced: true,
  state: {
    Schedule: {},
    ScheduleList: []
  },
  mutations: {
    setSchedule (state, Schedule) {
      state.Schedule = Schedule
    },
    setScheduleList (state, ScheduleList) {
      state.ScheduleList = ScheduleList
    },
    resetSchedule (state) {
      state.Schedule = []
    }
  },
  actions: {
    async post ({ state, commit, dispatch }) { // 新增行程
      if (Number(state.Schedule.end.slice(-2)) === 31 || Number(state.Schedule.end.slice(-2)) === 30) {
        let day = new Date(state.Schedule.end.slice(0, 4), String(Number(state.Schedule.end.slice(5, 7)) - 1).padStart(2, '0'))
        let end = new Date(day.getFullYear(), day.getMonth() + 1, 1)
        let endToday = end.getFullYear() + '-' + String(end.getMonth() + 1).padStart(2, '0') + '-' + String(end.getDate()).padStart(2, '0')
        state.Schedule.end = endToday
      } else {
        if (state.Schedule.end.length === 9) {
          state.Schedule.end = state.Schedule.end.slice(0, 8) + String(Number(state.Schedule.end.slice(-1))).padStart(2, '0')
        } else {
          state.Schedule.end = state.Schedule.end.slice(0, 8) + String(Number(state.Schedule.end.slice(-2)))
        }
      }
      const event = { // 先不存照片
        title: state.Schedule.title,
        thing: state.Schedule.thing,
        start: state.Schedule.start,
        end: state.Schedule.end,
        color: state.Schedule.color,
        scheduleType: state.Schedule.scheduleType,
        chronology: state.Schedule.chronology
      }
      // console.log(state.Schedule)
      let result = await axios.post('/schedule', event)
      await dispatch('getScheduleList')
      for (let one of state.ScheduleList) {
        if (
          one.title === state.Schedule.title &&
          one.scheduleType === state.Schedule.scheduleType
        ) {
          for (const obj of state.Schedule.imageFile) {
            await dispatch('addImage', {
              eventId: one._id,
              file: obj.file,
              description: obj.description
            })
          }
        }
      }
      commit('setSchedule', result.data)
    },
    async conferencePostSchedule ({commit}, {title, start, end, color, scheduleType, thing, id}) { // 新增會議行程
      let result = await axios.post('/schedule', {
        title: title,
        start: start,
        end: end,
        color: color,
        scheduleType: scheduleType,
        thing: thing,
        conferenceId: id
      })
      commit('setSchedule', result.data)
    },
    async initSchedule ({commit}) { // 初始行程
      let currentToday = new Date().getFullYear() + '-' + String(new Date().getMonth() + 1).padStart(2, '0') + '-' + String(new Date().getDate()).padStart(2, '0')
      let init = {
        title: '', // 事件名稱
        thing: '', // 事件內容
        start: currentToday, // 開始日期
        end: currentToday, // 結束日期
        color: '', // 事件類別
        chronology: false, // 大事記
        imageFile: []
      }
      commit('setSchedule', init)
    },
    async handleDateSelect ({commit}, {startDate, endDate}) {
      let endTime
      endDate.slice(8, 9) === '0'
        ? endTime = endDate.slice(0, 8) + '0' + String(Number(endDate.slice(-2)) - 1)
        : endTime = endDate.slice(0, 8) + String(Number(endDate.slice(-2)) - 1)
      let handleSelect = { start: startDate, end: endTime, chronology: false }
      commit('setSchedule', handleSelect)
    },
    async addImage ({ state }, { eventId, file, description }) { // 新增圖片
      try {
        let result = await axios.post(`/schedule/${eventId}/imageFile`, {
          name: file.name,
          mime: file.type,
          size: file.size,
          description: description
        })
        await axios.put(result.headers['location'].replace("/post-webapi", ""), file, {
          headers: {
            'Content-Type': file.type
          }
        })
      } catch (err) {
        throw err
      }
    },
    async lookupSchedule ({commit}, {
      id, title, start, end, scheduleType, color, thing, chronology, imageFile
    }) {
      let lookup = {
        id: id,
        title: title,
        start: start,
        end: end,
        scheduleType: scheduleType,
        color: color,
        thing: thing,
        chronology: chronology,
        imageFile: imageFile
      }
      commit('setSchedule', lookup)
    },
    async getScheduleList ({commit}, data) { // 行程列表
      let result = await axios.get('/schedule/list', {
        params: data
      })
      commit('setScheduleList', result.data)
    },
    async patch ({ state, dispatch }, scheduleId) { // 修改行程 (與類別無關)
      if (Number(state.Schedule.end.slice(-2)) === 31 || Number(state.Schedule.end.slice(-2)) === 30) {
        let day = new Date(state.Schedule.end.slice(0, 4), String(Number(state.Schedule.end.slice(5, 7)) - 1).padStart(2, '0'))
        let end = new Date(day.getFullYear(), day.getMonth() + 1, 1)
        let endToday = end.getFullYear() + '-' + String(end.getMonth() + 1).padStart(2, '0') + '-' + String(end.getDate()).padStart(2, '0')
        state.Schedule.end = endToday
      } else {
        if (state.Schedule.end.length === 9) {
          state.Schedule.end = state.Schedule.end.slice(0, 8) + String(Number(state.Schedule.end.slice(-1))).padStart(2, '0')
        } else {
          state.Schedule.end = state.Schedule.end.slice(0, 8) + String(Number(state.Schedule.end.slice(-2)))
        }
      }
      let old = []
      for (const image of state.Schedule.imageFile) {
        if (image.mime !== undefined && image.name !== undefined) old.push(image)
      }
      const event = {
        title: state.Schedule.title,
        thing: state.Schedule.thing,
        start: state.Schedule.start,
        end: state.Schedule.end,
        color: state.Schedule.color,
        scheduleType: state.Schedule.scheduleType,
        chronology: state.Schedule.chronology,
        imageFile: old
      }
      await axios.patch(`/schedule/${scheduleId}`, event)
      for (const image of state.Schedule.imageFile) {
        if (image.mime === undefined && image.name === undefined) {
          await dispatch('addImage', {
            eventId: scheduleId,
            file: image.file,
            description: image.description
          })
        }
      }
    },
    async patchConferenceSchedule ({state}, {scheduleId, obj}) { // 修改會議行程 (與類別無關)
      state.Schedule.title = obj.title
      state.Schedule.start = obj.start
      state.Schedule.end = obj.end
      state.Schedule.thing = obj.thing
      await axios.patch(`/schedule/${scheduleId}`, state.Schedule)
    },
    async deleteSchedule ({state}, scheduleId) { // 刪除事件
      await axios.delete(`/schedule/${scheduleId}`, state.Schedule)
    },
    async getScheduleContent ({commit}, id) { // 行程檢視
      let result = await axios.get(`/schedule/lookup/${id}`)
      commit('setSchedule', result.data)
    },
    async printChronologyZip ({ state }, {year, fileName, blobData}) { // 大事記匯出打包
      try {
        const imageList = state.ScheduleList
          .filter(val => new Date(val.start).getFullYear() === year.getFullYear())
          .map((event) => { return event.imageFile })
          .flatMap(num => num)
        var zip = new PizZip()
        if (imageList.length !== 0) {
          var img = zip.folder('大事記照片')
          for (let i = 0; i < imageList.length; i++) {
            const element = imageList[i]
            const response = await (await fetch(element.src)).arrayBuffer()
            img.file(String(element._id) + '.' + mime.extension(element.mime), response)
          }
        }
        const xlsx = await blobData.arrayBuffer()
        zip.file(fileName, xlsx, { binary: true })
        var content = zip.generate({ type: 'blob' })
        require('downloadjs')(content, '大事記匯出.zip', 'application/zip')
      } catch (err) {
        alert('大事紀匯出列表失敗！')
        console.log(err)
      }
    }
  }
}
