/* eslint-disable no-empty-pattern */
import axios from 'axios'
import PizZip from 'pizzip'
import fetch from 'node-fetch'

export default {
  namespaced: true,
  state: {
    officialDoc: {},
    list: [],
    relatedList: [],
    isStored: false,
    fileList: [],
    scanFile: [],
    recordList: [],
    workRecordList: []
  },
  mutations: {
    setOfficialDoc (state, officialDoc) {
      state.officialDoc = officialDoc
    },
    setList (state, list) {
      state.list = list
    },
    setDocList (state, relatedList) {
      state.relatedList = relatedList
    },
    setFileList (state, fileList) {
      state.fileList = fileList
    },
    setScanFile (state, scanFile) {
      state.scanFile = scanFile
    },
    setRecordList (state, recordList) {
      state.recordList = recordList
    },
    concatList (state, list) {
      let newList = state.list.concat(list)
      state.list = newList
    },
    setWorkRecordList (state, workRecordList) {
      state.workRecordList = workRecordList
    },
    resetList (state) {
      state.list = []
    }
  },
  actions: {
    async getAmount ({commit}, distinguish) { // 拿取收發文數量
      let today = new Date()
      let yyy = today.getFullYear() - 1911
      let result = await axios.get('/officialDocument/amount', {
        params: {
          distinguish: distinguish,
          year: yyy
        }
      })
      return result.data
    },
    async initOfficialDoc ({commit, rootState, dispatch}, routeName) { // 初始公文尚未存料資料庫
      let currentUser = rootState.user.current
      await dispatch('project/lookupProjectRoleParamSetting', currentUser.projectRole, {root: true})
      let paramSetting = rootState.project.selectedProjectRole
      const currentToday = new Date()
      let today = new Date()
      let afterProcessing
      let init = {
        projectId: rootState.project.current._id, // 計畫Id
        distinguish: '', // 區別
        year: today.getFullYear() - 1911, // 年分
        number: '', // 公文數量
        document_type: '書函', // 書函輸出類型
        issue_number: '', // 發文編號
        issue_date: '', // 來(發)文日期
        issue_text_number: '', // 來(發)文字號
        issuer: '', // 發文單位
        reference_number: [], // 依據文號
        document_classification: '', // 公文類型
        original: [], // 正本
        copy: [], // 副本
        subject: '', // 主旨
        instruction: '', // 說明
        undertaker: currentUser._id, // 承辦人
        handle_period: '', // 辦理期限
        standard: '', // 標別
        urgency_level: '普通件', // 速別
        confidentiality_class: '', // 密等
        release_condition: '', // 解密條件
        confidentiality_period: '', // 保密期限
        received_number: '', // 收文編號
        received_date: '', // 收文日期
        limited_date: '', // 限辦日期
        appendix: '', // 附件說明
        file_number: '', // 檔號
        status: '辦理中', // 狀態
        newDocumentStatus: '未新增', // 提審狀態
        projectRole: '', // 專案角色
        archive_number: '', // 歸檔編號
        conferenceId: null // 會議Id
      }
      switch (routeName) {
        case 'PaperPostCreate':
          today.setDate(today.getDate() + Number(paramSetting.issueHandlingDay))
          afterProcessing = today.getFullYear() + '-' + String(today.getMonth() + 1).padStart(2, '0') + '-' + String(today.getDate()).padStart(2, '0')
          init.distinguish = '發文'
          init.number = (await dispatch('getAmount', init.distinguish)) + 1
          init.issue_number = `${init.year}-${String(init.number).padStart(6, '0')}`
          init.archive_number = `${paramSetting.archive_number}`
          init.issue_date = currentToday
          init.issue_text_number = `${paramSetting.issue_text_number}${String(init.number).padStart(6, '0')}`
          init.issuer = paramSetting.issuer
          init.handle_period = afterProcessing
          commit('setOfficialDoc', init)
          break
        case 'PaperReceiveCreate':
          today.setDate(today.getDate() + Number(paramSetting.receiveHandlingDay))
          afterProcessing = today.getFullYear() + '-' + String(today.getMonth() + 1).padStart(2, '0') + '-' + String(today.getDate()).padStart(2, '0')
          init.distinguish = '來文'
          init.number = (await dispatch('getAmount', init.distinguish)) + 1
          init.received_number = `${init.year}-${String(init.number).padStart(6, '0')}`
          init.archive_number = `${paramSetting.archive_number}`
          init.received_date = currentToday
          init.limited_date = afterProcessing
          commit('setOfficialDoc', init)
          break
      }
    },
    async post ({commit, state}) { // 新增公文
      let result = await axios.post('/officialDocument', state.officialDoc)
      commit('setOfficialDoc', result.data)
    },
    async getList ({rootState, commit, dispatch}, data) { // 公文列表
      let result = await axios.get('/officialDocument/list', {
        params: {
          projectId: rootState.project.current._id,
          ...data
        }
      })
      commit('setList', result.data)
    },
    async lookupList ({state}, data) { // 公文列表
      let result = await axios.get('/officialDocument/list', {
        params: data
      })
      return result.data
    },
    async getDocToRelate ({rootState, commit}, data) { // 相關聯公文
      let result = await axios.get('/officialDocument/list', {
        params: {
          projectId: rootState.project.current._id,
          ...data
        }
      })
      commit('setDocList', result.data)
    },
    async lookupReferenceList ({state, commit, dispatch}, referenceNumbers) { // 依據文號列表查詢
      let result = await axios.post('/officialDocument/referenceSearch', referenceNumbers)
      if (result.data.length === 0) {
        if (state.list.length === 0) alert('查無此相關公文或請填入依據文號！')
      } else {
        commit('concatList', result.data)
        dispatch('forLoop', result.data)
        window.scrollTo(0, document.body.scrollHeight)
      }
    },
    forLoop ({dispatch}, list) {
      for (let i = 0; i < list.length; i++) {
        const element = list[i]
        dispatch('lookupReferenceList', element.reference_number)
      }
    },
    async lookupSearchList ({rootState, dispatch}, {routeName, issueDateStart, issueDateEnd, condition, operator, keyword}) { // 篩選查詢
      await dispatch('project/lookupProject')
      let distinguish
      if (routeName === 'PaperPostList') distinguish = '發文'
      else if (routeName === 'PaperReceiveList') distinguish = '來文'
      let result = await axios.post('/officialDocument/searchList', {
        projectId: rootState.project.current._id,
        distinguish: distinguish,
        issueDateStart: (issueDateStart === undefined) ? '' : issueDateStart,
        issueDateEnd: (issueDateEnd === undefined) ? '' : issueDateEnd,
        condition,
        operator,
        keyword})
      if (result.data.length === 0) alert('查無資料')
      return result.data
    },
    async getOfficialDocument ({commit, dispatch}, id) { // id 拿去可編輯公文
      let result = await axios.get(`/officialDocument/${id}`)
      commit('resetList')
      commit('setOfficialDoc', result.data)
      dispatch('lookupRecords')
      dispatch('getFileList')
      dispatch('getScanFile')
      dispatch('getRecordList')
    },
    async lookupOfficialDoc ({commit, dispatch}, id) { // id 查詢公文
      let result = await axios.get(`/officialDocument/lookup/${id}`)
      commit('resetList')
      commit('setOfficialDoc', result.data)
      dispatch('getFileList')
      dispatch('getScanFile')
      dispatch('getRecordList')
    },
    async patch ({state}) { // 修改公文
      await axios.patch(`/officialDocument/${state.officialDoc._id}`, state.officialDoc)
    },
    async conferencePatch ({state}) {
      await axios.patch(`/officialDocument/${state.officialDoc._id}`, state.officialDoc)
    },
    async addFiles ({state}, {files}) { // 新增檔案到單筆公文
      await axios.post(`/officialDocument/${state.officialDoc._id}/files`, files)
    },
    async addScanFile ({state}, {file}) { // 新增掃描檔案到單筆公文
      try {
        let result = await axios.post(`officialDocument/${state.officialDoc._id}/scanFile`, {
          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(`officialDocument/${state.officialDoc._id}/OfficialDocs-with-files`)
      commit('setFileList', result.data)
    },
    async getScanFile ({state, commit}) { // 拿取公文的掃描檔案
      let result = await axios.get(`officialDocument/${state.officialDoc._id}/scanFile`)
      commit('setScanFile', result.data)
    },
    async deleteOfficialDocFile ({state}, fileId) { // 刪除檔案
      await axios.delete(`/officialDocument/${state.officialDoc._id}/file/${fileId}`)
    },
    async deleteOfficialDocScanFile ({state}, fileId) { // 刪除掃描檔案
      await axios.delete(`/officialDocument/${state.officialDoc._id}/scanFile/${fileId}`)
    },
    async addRecord ({state, dispatch}, recordData) { // 新增紀錄
      await axios.post(`/officialDocument/${state.officialDoc._id}/record`, recordData)
      dispatch('getRecordList')
    },
    async getRecordList ({state, commit}) { // 查詢公文的紀錄
      let result = await axios.get(`/officialDocument/${state.officialDoc._id}/records`)
      commit('setRecordList', result.data)
    },
    async download ({state, dispatch}, isGetWordContent) { // 書函輸出 or email拿檔案的data(isGetWordContent) /// 要用pdf檔
      try {
        let result = await axios.post('officialDocument/download/formal', state.officialDoc, {responseType: 'arraybuffer'})
        require('downloadjs')(result.data, `${state.officialDoc.document_type}.docx`, 'application/vnd.openxmlformats-officedocument.wordprocessingml.document')
      } catch (err) {
        alert('下載失敗！')
        throw new Error('下載失敗！')
      }
    },
    async printBatch ({state}) { // 附件下載
      try {
        if (state.fileList.length !== 0) {
          var zip = new PizZip()
          for (let i = 0; i < state.fileList.length; i++) {
            const element = state.fileList[i]
            const response = await (await fetch(element.src)).arrayBuffer()
            zip.file(element.name, response)
          }
          var content = zip.generate({ type: 'blob' })
          require('downloadjs')(content, '附件包', 'application/zip')
        }
      } catch (err) {
        alert('附件下載失敗！')
        console.log(err)
      }
    },
    async lookupRecords ({state, commit}) { // 查詢提審紀錄列表
      let result = await axios.get(`/officialDocument/${state.officialDoc._id}/recordList`)
      commit('setWorkRecordList', result.data)
    },
    async addWorkRecords ({state}, idData) { // 新增提審紀錄id (測試中)
      await axios.post(`/officialDocument/${state.officialDoc._id}/record`, idData)
    },
    async sendEmail ({state}, data) { // 發送email
      try {
        await axios.post('/officialDocument/sendEmail', data)
      } catch (err) {
        alert('傳送失敗！')
        throw new Error('傳送失敗！')
      }
    }
  },
  getters: {
    originalName (state) {
      if (!state.officialDoc.original) return
      return state.officialDoc.original.join('、')
    },
    copyName (state) {
      if (!state.officialDoc.copy) return
      return state.officialDoc.copy.join('、')
    },
    referenceNumber (state) {
      if (!state.officialDoc.reference_number) return
      return state.officialDoc.reference_number.join('、')
    },
    referenceList (state) {
      let list = state.list.filter((element, index, arr) => {
        return arr.findIndex(ele => element._id === ele._id) === index
      })
      list.sort((a, b) => { return new Date(a.issue_date) - new Date(b.issue_date) })
      return list
    },
    reference_Number (state) {
      if (!state.officialDoc.reference_number) return
      let issueNumber = []
      for (let i = 0; i < state.officialDoc.reference_number.length; i++) {
        const element = state.officialDoc.reference_number[i].issue_text_number
        issueNumber.push(element)
      }
      return issueNumber.join('、')
    }
  }
}
