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

export default {
  namespaced: true,
  state: {
    NewDoc: {},
    NewControl: {},
    Control: {},
    controlWorkFile: [],
    DocList: [],
    allList: [],
    recordList: [],
    FileRecordList: []
  },
  mutations: {
    setNewDoc (state, NewDoc) {
      state.NewDoc = NewDoc
    },
    setDocList (state, DocList) {
      state.DocList = DocList
    },
    setAllList (state, allList) {
      state.allList = allList
    },
    setRecordList (state, recordList) {
      state.recordList = recordList
    },
    setControlWorkFile (state, controlWorkFile) {
      state.controlWorkFile = controlWorkFile
    },
    setNewControl (state, NewControl) {
      state.NewControl = NewControl
    },
    setControl (state, Control) {
      state.Control = Control
    },
    setFileRecordList (state, FileRecordList) {
      state.FileRecordList = FileRecordList
    },
    resetNewDoc (state) {
      state.NewDoc = []
    }
  },
  actions: {
    // 提審文件
    async post ({ commit }, NewDocData) { // 新增送審文件
      let result = await axios.post('/newDocument', NewDocData)
      commit('setNewDoc', result.data)
    },
    async initDoc ({commit, rootState, dispatch}, routeName) { // 初始無文件資料
      let currentUser = rootState.user.current
      await dispatch('project/lookupProjectRoleParamSetting', currentUser.projectRole, {root: true})
      let init = {
        document_distinguish: '', // 提審區別
        document_name: '', // 文件名稱
        project_name: rootState.project.current.name, // 工程名稱
        document_type: '其他', // 文件類別
        authority: currentUser.name, // 承辦人員
        situation: [], // 辦理情況
        document_number: '', // 文件編號
        file_number: '', // 歸檔編號
        description: '', // 文件描述
        version: 'A', // 版次
        records: [] // 紀錄
      }
      switch (routeName) {
        case 'FileReviewCreate':
          init.document_distinguish = '審查文件'
          commit('setNewDoc', init)
          break
        case 'FileSubmitCreate':
          init.document_distinguish = '提送文件'
          commit('setNewDoc', init)
          break
      }
    },
    async getDocList ({ commit }, data) { // 送審文件列表
      let result = await axios.get('/newDocument/list', {
        params: data
      })
      commit('setDocList', result.data)
    },
    async getList ({ commit }, data) { // 送審文件列表
      let result = await axios.get('/newDocument/list', {
        params: data
      })
      commit('setAllList', result.data)
    },
    async getRecordList ({ commit }, data) { // 提審紀錄列表
      let result = await axios.get('/newDocument/recordList', {
        params: data
      })
      commit('setRecordList', result.data)
    },
    async lookupDoc ({ commit }, id) { // 查詢送審文件
      let result = await axios.get(`/newDocument/lookup/${id}`)
      commit('setNewDoc', result.data)
    },
    async patch ({state}) { // 修改送審文件
      // console.log(state.NewDoc)
      await axios.patch(`/newDocument/${state.NewDoc.id}`, state.NewDoc)
    },
    async deleteDoc ({state}) { // 刪除送審文件
      await axios.delete(`/newDocument/${state.NewDoc.id}`, state.NewDoc)
    },
    // 管控作業
    async lookupControlWork ({ commit }, DocListId) { // 查詢管控作業
      let result = await axios.get(`/newDocument/lookup/${DocListId}/Control`)
      commit('setDocList', result.data)
    },
    async addControl ({state, commit}) { // 文件ID新增管控作業
      let result = await axios.post(`/newDocument/${state.NewDoc.id}/controlWork`, state.NewControl)
      commit('setNewControl', result.data)
    },
    async addDeliverWork ({rootState}, DocListId) { // Deliver新增提送作業
      let currentUser = rootState.user.current
      let currentOfficialDoc = rootState.officialDocument.officialDoc
      const currentToday = new Date()
      await axios.post(`/newDocument/${DocListId}/controlWork`, {
        item: '文件提送作業',
        scheduledDate: currentToday, // 預定辦理日期
        unit: '', // 辦理單位
        manager: currentUser.name, // 辦理人員
        version: 'A', // 版次
        documentName: DocListId, // 所屬文件名稱
        officialDocId: currentOfficialDoc._id, // 公文ID
        status: '待編輯' // 辦理狀態
      })
    },
    async addReviewWork ({rootState}, DocListId) { // Deliver新增審查作業
      let currentUser = rootState.user.current
      let currentOfficialDoc = rootState.officialDocument.officialDoc
      const currentToday = new Date()
      await axios.post(`/newDocument/${DocListId}/controlWork`, {
        item: '文件審查作業',
        scheduledDate: currentToday, // 預定辦理日期
        unit: '', // 辦理單位
        manager: currentUser.name, // 辦理人員
        version: 'A', // 版次
        documentName: DocListId, // 所屬文件名稱
        officialDocId: currentOfficialDoc._id, // 公文ID
        status: '待編輯' // 辦理狀態
      })
    },
    async addApproved ({rootState}, DocListId) { // Deliver新增核定作業
      let currentUser = rootState.user.current
      let currentOfficialDoc = rootState.officialDocument.officialDoc
      const currentToday = new Date()
      await axios.post(`/newDocument/${DocListId}/controlWork`, {
        item: '文件核定作業',
        scheduledDate: currentToday, // 預定辦理日期
        unit: '', // 辦理單位
        manager: currentUser.name, // 辦理人員
        version: 'A', // 版次
        documentName: DocListId, // 所屬文件名稱
        officialDocId: currentOfficialDoc._id, // 公文ID
        status: '待編輯' // 辦理狀態
      })
    },
    async addTransfer ({rootState}, DocListId) { // Deliver新增核轉作業
      let currentUser = rootState.user.current
      let currentOfficialDoc = rootState.officialDocument.officialDoc
      const currentToday = new Date()
      await axios.post(`/newDocument/${DocListId}/controlWork`, {
        item: '文件核轉作業',
        scheduledDate: currentToday, // 預定辦理日期
        unit: '', // 辦理單位
        manager: currentUser.name, // 辦理人員
        version: 'A', // 版次
        documentName: DocListId, // 所屬文件名稱
        officialDocId: currentOfficialDoc._id, // 公文ID
        status: '待編輯' // 辦理狀態
      })
    },
    async addResearch ({rootState}, DocListId) { // Deliver新增備查作業
      let currentUser = rootState.user.current
      let currentOfficialDoc = rootState.officialDocument.officialDoc
      const currentToday = new Date()
      await axios.post(`/newDocument/${DocListId}/controlWork`, {
        item: '文件備查作業',
        scheduledDate: currentToday, // 預定辦理日期
        unit: '', // 辦理單位
        manager: currentUser.name, // 辦理人員
        version: 'A', // 版次
        documentName: DocListId, // 所屬文件名稱
        officialDocId: currentOfficialDoc._id, // 公文ID
        status: '待編輯' // 辦理狀態
      })
    },
    async initControl ({commit, rootState, dispatch}) { // 初始無管控作業
      let currentUser = rootState.user.current
      await dispatch('project/lookupProjectRoleParamSetting', currentUser.projectRole, {root: true})
      const currentToday = new Date()
      let init = {
        item: '', // 作業選項 (可再優化自動判斷)
        scheduledDate: currentToday, // 預定辦理日期
        actualDate: '', // 實際辦理日期
        unit: '', // 辦理單位
        manager: currentUser.name, // 辦理人員
        version: 'A', // 版次
        note: '', // 備註
        status: ''
      }
      commit('setNewControl', init)
    },
    async addControlWorkFile ({state}, {docId, file, fileId}) { // 新增檔案到管控作業
      try {
        let result = await axios.post(`/newDocument/${docId}/fileToken/${fileId}`, {
          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) {
        console.log(err)
        throw err
      }
    },
    async addFileRecord ({state, dispatch}, {fid, fileId, recordData}) { // 新增檔案紀錄
      await axios.post(`/newDocument/${fid}/fileRecords/${fileId}`, recordData)
      dispatch('getFileRecord', {fid: fid, fileId: fileId})
    },
    async getFileRecord ({state, commit}, {fid, fileId}) { // 查詢檔案紀錄
      let result = await axios.get(`/newDocument/${fid}/fileRecords/${fileId}`)
      commit('setFileRecordList', result.data)
    },
    async patchDeliverWork ({state}, {docId, controlWorkId, controlWorkData}) { // 修改管控作業的版次
      await axios.patch(`/newDocument/${docId}/controlWork/${controlWorkId}`, controlWorkData)
    },
    async getFileList ({commit}, {DocId, controlWorkId}) { // 查詢管控作業的檔案
      let result = await axios.get(`newDocument/${DocId}/fileToken/${controlWorkId}`)
      commit('setControlWorkFile', result.data)
    },
    async deleteControlWork ({state}, controlWorkId) { // 刪除管控作業
      await axios.delete(`/newDocument/${state.NewDoc.id}/controlWork/${controlWorkId}`, state.NewDoc)
    },
    async deleDeliverWork ({state}, {docId, controlWorkId}) { // 刪除提送紀錄列表管控作業
      await axios.delete(`/newDocument/${docId}/controlWork/${controlWorkId}`, state.NewDoc)
    },
    async deleteFiles ({state}, {docId, controlWorkId, fileId}) { // 刪除檔案
      await axios.delete(`/newDocument/${docId}/controlWork/${controlWorkId}/fileTokens/${fileId}`, state.NewDoc)
    },
    async printZip ({state}, fileList) { // 提審檔案下載
      try {
        if (fileList.length !== 0) {
          var zip = new PizZip()
          for (let i = 0; i < fileList.length; i++) {
            const element = 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)
      }
    }
  },
  getters: {
    getcontrolList (state) {
      let control = Object.values(state.DocList).map(DocList => DocList.controlWork)
      return control
    },
    newDocHasEdit (state) {
      let hasEdit = state.NewDoc.controlWork.map(x => Object.assign(x, {isFix: false}))
      return hasEdit
    },
    deliverHasEdit (state) {
      let hasEdit = state.DocList.map(x => Object.assign(x, {isFix: false}))
      return hasEdit
    }
  }
}
