import axios from 'axios'

export default {
  namespaced: true,
  state: {
    DocumentColl: {},
    DocumentCollList: [],
    fileList: [],
    recordList: []
  },
  mutatins: {
    setDocumentColl (state, DocumentColl) {
      state.DocumentColl = DocumentColl
    },
    setDocumentCollList (state, DocumentCollList) {
      state.DocumentCollList = DocumentCollList
    },
    setFileList (state, fileList) {
      state.fileList = fileList
    },
    setRecordList (state, recordList) {
      state.recordList = recordList
    }
  },
  actions: {
    // 資料夾
    async post ({commit}, DocumentCollData) { // 新增資料夾
      let result = await axios.post('/documentCollaboration', DocumentCollData)
      commit('setDocumentColl', result.data)
    },
    async getDocumentCollList ({commit}, data) { // 資料夾列表
      let result = await axios.get('/documentCollaboration/list',
        {
          params: data
        })
      commit('setDocumentCollList', result.data)
    },
    async loockupFolder ({commit}, id) { // 檢視資料夾
      let result = await axios.get(`/documentCollaboration/${id}`)
      commit('setDocumentColl', result.data)
    },
    async patch ({state}) { // 修改資料夾
      await axios.patch(`/documentCollaboration/${state.DocumentColl.id}`, state.DocumentColl)
    },
    async deleteFolder ({state}) { // 刪除資料夾
      await axios.delete(`/documentCollaboration/${state.DocumentColl.id}`, state.DocumentColl)
    },
    // 檔案
    async addFiles ({state}, {file}) { // 新增檔案
      try {
        let result = await axios.post(`/documentCollaboration/${state.DocumentColl._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(`/documentCollaboration/${state.DocumentColl._id}/files`)
      commit('setFileList', result.data)
    },
    async deletefiles ({state}, fileId) { // 刪除檔案
      await axios.delete(`/documentCollaboration/${state.DocumentColl._id}/fileTokens/${fileId}`)
    },
    // 紀錄
    async addRecords ({state, dispatch}, recordData) { // 新增紀錄
      await axios.post(`/documentCollaboration/${state.DocumentColl.id}/records`, recordData)
      dispatch('getRecordList')
    },
    async getRecordList ({state, commit}) { // 查看紀錄
      let result = await axios.get(`/documentCollaboration/${state.DocumentColl.id}/records`)
      commit('setRecordList', result.data)
    }
  },
  getters: {}
}
