import axios from 'axios'

export default {
  namespaced: true,
  state: {
    tenders: {},
    contract: {},
    changeContract: {},
    mileStone: {},
    extendRecord: {},
    checkPoint: {},
    projectStatus: {},
    tenderList: [],
    contractList: [],
    changeList: [],
    extendList: [],
    fileList: [],
    qualityList: [],
    graphicList: [],
    relatedList: [],
    mileStoneList: [],
    checkPointList: [],
    checkPointList: [],
    postFileManagementList: [],
    postFileManagement: {},
    receiveFileManagementList: [],
    receiveFileManagement: {}
  },
  mutations: {
    setTenders (state, tenders) {
      state.tenders = tenders
    },
    setContract (state, contract) {
      state.contract = contract
    },
    setChangeContract (state, changeContract) {
      state.changeContract = changeContract
    },
    setMileStone (state, mileStone) {
      state.mileStone = mileStone
    },
    setExtendRecord (state, extendRecord) {
      state.extendRecord = extendRecord
    },
    setCheckPoint (state, checkPoint) {
      state.checkPoint = checkPoint
    },
    setTendersList (state, tenderList) {
      state.tenderList = tenderList
    },
    setContractList (state, contractList) {
      state.contractList = contractList
    },
    setChangeList (state, changeList) {
      state.changeList = changeList
    },
    setExtendList (state, extendList) {
      state.extendList = extendList
    },
    setFileList (state, fileList) {
      state.fileList = fileList
    },
    setQualityList (state, qualityList) {
      state.qualityList = qualityList
    },
    setProjectStatus (state, projectStatus) {
      state.projectStatus = projectStatus
    },
    setGraphicList (state, graphicList) {
      state.graphicList = graphicList
    },
    setRelatedList (state, relatedList) {
      state.relatedList = relatedList
    },
    setPostFileManagementList (state, postFileManagementList) {
      state.postFileManagementList = postFileManagementList
    },
    setPostFileManagement (state, postFileManagement) {
      state.postFileManagement = postFileManagement
    },
    setReceiveFileManagementList (state, receiveFileManagementList) {
      state.receiveFileManagementList = receiveFileManagementList
    },
    setReceiveFileManagement (state, receiveFileManagement) {
      state.receiveFileManagement = receiveFileManagement
    },
    resetList (state) {
      state.mileStoneList = []
      state.checkPointList = []
    },
    resetObject (state) {
      state.mileStone = {}
      state.checkPoint = {}
    }
  },
  actions: {
    async post ({state, commit}) { // 新增標案
      let result = await axios.post('/tenders', state.tenders)
      commit('setTenders', result.data)
    },
    async initAddTender ({state, commit, rootState}) { // 初始標案
      let initTender = {
        projectId: rootState.project.current._id, // 專案Id
        tender: '', // 標別
        tenderNumber: '', // 標案編號
        project_name: '', // 工程名稱
        owner: '', // 負責單位(承攬廠商)
        start_date: '', // 開工日期
        contactNumber: '', // 聯絡電話
        scheduled_complete: '', // 原契約預定完工日期
        actual_complete: '', // 實際完工日期
        contract_day: '', // 原契約工程天數
        contract_amount: '', // 契約金額
        introduction: '', // 工程概述
        hostControl: [{ // 主辦單位
          organizer: '',
          address: '',
          contactPerson: '',
          contactNumber: '',
          email: ''
        }],
        design_unit: [{ // 設計單位
          organizer: '',
          address: '',
          contactPerson: '',
          contactNumber: '',
          email: ''
        }],
        PCMControl: [{ // 專案管理
          organizer: '',
          address: '',
          contactPerson: '',
          contactNumber: '',
          email: ''
        }],
        CSControl: [{ // 監造工務管理
          organizer: '',
          address: '',
          contactPerson: '',
          contactNumber: '',
          email: ''
        }],
        OtherControl: [{
          organizer: '',
          address: '',
          contactPerson: '',
          contactNumber: '',
          email: ''
        }],
        ManagementControl: [{ // 施工管理
          organizer: '',
          address: '',
          contactPerson: '',
          contactNumber: '',
          email: ''
        }]
      }
      commit('setTenders', initTender)
    },
    async addChangeContract ({state, commit}, id) { // 變更契約
      let result = await axios.post(`/tenders/${id}/changeContract`, state.changeContract)
      commit('setChangeContract', result.data)
    },
    async initChangeContract ({state, commit, dispatch, rootState}) { // 初始變更契約
      dispatch('lookupTender', rootState.user.current.defaultTender)
      let currentAmount
      if (state.tenders.changeContract.length < 1) {
        currentAmount = state.tenders.contract_amount
      } else {
        currentAmount = state.tenders.changeContract[state.tenders.changeContract.length - 1].change_amount
      }
      let initChange = {
        contractNumber: '', // 編號名稱
        changeNumber: '', // 變更次數
        approval_number: '', // 核准文號
        approvalDate: '', // 核准日期
        detail: '', // 變更內容
        addBill: '', // 加帳
        reduceBill: '', // 減帳
        change_amount: Number(currentAmount), // 變更後契約金額
        change_day: '' // 變更天數
      }
      commit('setChangeContract', initChange)
    },
    async addMileStone ({state, commit}, id) { // 新增里程碑
      let result = await axios.post(`/tenders/${id}/mileStone`, state.mileStone)
      commit('setMileStone', result.data)
    },
    async initMileStone ({commit}) { // 初始里程碑
      let initMile = {
        number: '', // 里程碑編號
        contract_date: '', // 原契約工期
        start_date: '', // 開工日期
        final_date: '', // 完工日期
        extension_date: '', // 最新展延日期
        extension_day: '', // 累積展延天數
        contract_totalDay: '', // 契約總工期
        extension_finalDate: '', // 展延完工日期
        directions: '' // 說明
      }
      commit('setMileStone', initMile)
    },
    async addExtendRecord ({state, dispatch, rootState}, id) { // 新增展延
      await axios.post(`/tenders/${id}/extendRecord`, state.extendRecord)
      await dispatch('getOtherList', id)
      for (let one of state.tenderList.extendRecord) {
        if (
          one.explain === state.extendRecord.explain &&
          one.extend_name === state.extendRecord.extend_name
        ) {
          // 新增里程碑及專案查核點展延紀錄
          await dispatch('addMileStoneRecord', one._id)
          await dispatch('addCheckPointRecord', one._id)
        }
      }
    },
    async initExtendRecord ({commit}) { // 初始展延
      let initExtend = {
        extend_name: '', // 展延名稱
        approval_number: '', // 核准文號
        approvalDate: '', // 核准日期
        explain: '' // 說明
      }
      commit('setExtendRecord', initExtend)
    },
    async addCheckPoint ({state, commit}, id) { // 新增專案查核點
      let result = await axios.post(`/tenders/${id}/checkPoint`, state.checkPoint)
      commit('setCheckPoint', result.data)
    },
    async initCheckPoint ({commit}) { // 初始專案查核點
      let initCheck = {
        number: '', // 專案編碼
        contract_date: '', // 原契約工期
        start_date: '', // 開工日期
        final_date: '', // 完工日期
        extension_date: '', // 最新展延日期
        extension_day: '', // 累積展延天數
        contract_totalDay: '', // 契約總工期
        extension_finalDate: '', // 展延完工日期
        directions: '' // 說明
      }
      commit('setCheckPoint', initCheck)
    },
    async addImage ({state, rootState}, {projectStatusId, file, description}) {
      try {
        let result = await axios.post(`/tenders/${rootState.user.current.defaultTender}/imageFile/${projectStatusId}`, {
          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 addProjectStatus ({state, commit, dispatch}, id) { // 新增工程現況
      const data = { // 先不存照片
        title: state.projectStatus.title,
        date: state.projectStatus.date,
        description: state.projectStatus.description
      }
      let result = await axios.post(`/tenders/${id}/projectStatus`, data)
      await dispatch('getOtherList', id)
      for (let one of state.tenderList.projectStatus) {
        if (
          one.title === state.projectStatus.title &&
          one.description === state.projectStatus.description
        ) {
          for (const obj of state.projectStatus.imageFile) {
            await dispatch('addImage', {
              projectStatusId: one._id,
              file: obj.file,
              description: obj.description
            })
          }
        }
      }
      commit('setProjectStatus', result.data)
    },
    async initProjectStatus ({commit}) { // 初始工程現況
      let initStatus = {
        title: '', // 標題
        date: '', // 日期
        imageFile: [], // 圖檔
        description: '' // 說明
      }
      commit('setProjectStatus', initStatus)
    },
    async addContractFile ({state}, {id, file}) { // 新增契約文件
      try {
        let result = await axios.post(`/tenders/${id}/contractFile`, {
          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 deleteContractFile ({state}, contractFileId) { // 刪除契約文件
      await axios.delete(`/tenders/${state.tenderList._id}/contractFile/${contractFileId}`)
    },
    async addQualityDoc ({state}, {id, file}) { // 新增品保文件
      try {
        let result = await axios.post(`/tenders/${id}/qualityDoc`, {
          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 deleteQualityDoc ({state}, qualityDocId) { // 刪除品保文件
      await axios.delete(`/tenders/${state.tenderList._id}/qualityDoc/${qualityDocId}`)
    },
    async addGraphicManagement ({state}, {id, file}) { // 新增圖說管理
      try {
        let result = await axios.post(`/tenders/${id}/graphicManagement`, {
          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 addRelatedManagement ({state}, {id, file}) { // 新增相關資料管理
      try {
        let result = await axios.post(`/tenders/${id}/relatedManagement`, {
          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 addPostFile ({state, rootState}, {fileId, file}) { // 新增發文文件
      try {
        let result = await axios.post(`/tenders/${rootState.user.current.defaultTender}/postFileManagementList/${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) {
        throw err
      }
    },
    async addPostFileManagement ({state}, id) { // 新增發文文件
      await axios.post(`/tenders/${id}/postFileManagement`, state.postFileManagement)
    },
    async addReceiveFile ({state, rootState}, {fileId, file}) { // 新增收文文件
      try {
        let result = await axios.post(`/tenders/${rootState.user.current.defaultTender}/receiveFileManagementList/${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) {
        throw err
      }
    },
    async addReceiveFileManagement ({state}, id) { // 新增收文文件
      await axios.post(`/tenders/${id}/receiveFileManagement`, state.receiveFileManagement)
    },
    async initPostFileManagement ({commit}) { // 初始發文文件
      let initPostFile = {
        postDay: '', // 日期
        docFile: [] // 文檔
      }
      commit('setPostFileManagement', initPostFile)
    },
    async initReceiveFileManagement ({commit}) { // 初始收文文件
      let initReceiveFile = {
        receiveDay: '', // 日期
        docFile: [] // 圖檔
      }
      commit('setReceiveFileManagement', initReceiveFile)
    },
    async deletePostFile ({ state }, postFileManagementId) { // 刪除發文文件
      await axios.delete(`/tenders/${state.tenderList._id}/postFileManagement/${postFileManagementId}`)
    },
    async deleteReceiveFile ({state}, receiveFileManagementId) { // 刪除收文文件
      await axios.delete(`/tenders/${state.tenderList._id}/receiveFileManagement/${receiveFileManagementId}`)
    },
    async addMileStoneRecord ({rootState, state}, id) {
      await axios.post(`/tenders/${rootState.user.current.defaultTender}/mileStone/${id}`, state.mileStoneList)
    },
    async addCheckPointRecord ({rootState, state}, id) {
      await axios.post(`/tenders/${rootState.user.current.defaultTender}/checkPoint/${id}`, state.checkPointList)
    },
    async getTenderList ({ commit }, data) { // 標案列表
      let result = await axios.get('/tenders/list', {
        params: data
      })
      commit('setTendersList', result.data)
    },
    async getOtherList ({commit}, id) { // 其餘列表
      let result = await axios.get(`/tenders/lookup/${id}/tender`)
      commit('setTendersList', result.data)
    },
    async lookupTender ({ commit }, id) { // 標案詳情
      let result = await axios.get(`/tenders/lookup/${id}`)
      commit('setTenders', result.data)
    },
    async lookupSearch ({state}, {operator, keyword}) { // 契約搜尋
      let result = await axios.post('/tenders/search', {
        tenderName: state.tenders.tender,
        operator,
        keyword
      })
      if (result.data.length === 0) alert('查無資料')
      return result.data
    },
    async lookupChange ({ state, commit }, {tenderId, changeContractId}) { // 查看變更契約
      let result = await axios.get(`/tenders/lookup/${tenderId}/changeContract/${changeContractId}`)
      commit('setChangeContract', result.data)
    },
    async lookupMileStone ({ state, commit }, {tenderId, mileStoneId}) { // 查看里程碑
      let result = await axios.get(`/tenders/lookup/${tenderId}/mileStone/${mileStoneId}`)
      commit('setMileStone', result.data)
    },
    async lookupCheckPoint ({ state, commit }, {tenderId, checkPointId}) { // 查看專案查核點
      let result = await axios.get(`/tenders/lookup/${tenderId}/checkPoint/${checkPointId}`)
      commit('setCheckPoint', result.data)
    },
    async lookupExtendRecord ({ state, commit }, {tenderId, extendRecordId}) { // 查看展延紀錄
      let result = await axios.get(`/tenders/lookup/${tenderId}/extendRecord/${extendRecordId}`)
      commit('setExtendRecord', result.data)
    },
    async lookupProjectStatus ({ state, commit }, {tenderId, projectStatusId}) { // 查看工程現況
      let result = await axios.get(`/tenders/lookup/${tenderId}/projectStatus/${projectStatusId}`)
      commit('setProjectStatus', result.data)
    },
    async getContractFile ({state, commit}, id) { // 查看契約文件
      let result = await axios.get(`/tenders/${id}/tender/contractFile`)
      commit('setFileList', result.data)
    },
    async getQualityDoc ({state, commit}, id) { // 查看品保文件
      let result = await axios.get(`/tenders/${id}/tender/qualityDoc`)
      commit('setQualityList', result.data)
    },
    async getGraphicManagement ({state, commit}, id) { // 查看圖說管理
      let result = await axios.get(`/tenders/${id}/tender/graphicManagement`)
      commit('setGraphicList', result.data)
    },
    async getRelatedManagement ({state, commit}, id) { // 查看相關資料管理
      let result = await axios.get(`/tenders/${id}/tender/relatedManagement`)
      commit('setRelatedList', result.data)
    },
    async lookupPostFileSearch ({state}, {operator, keyword}) { // 發文文件搜尋
      let result = await axios.post('/tenders/postFileSearch', {
        tenderName: state.tenders.tender,
        operator,
        keyword
      })
      if (result.data.length === 0) alert('查無資料')
      return result.data
    },
    async getPostFileManagement ({state, commit}, id) { // 查看發文文件檔案
      let result = await axios.get(`/tenders/${id}/tender/postFileManagement`)
      commit('setPostFileManagementList', result.data)
    },
    async lookupReceiveFileSearch ({state}, {operator, keyword}) { // 收文文件搜尋
      let result = await axios.post('/tenders/receiveFileSearch', {
        tenderName: state.tenders.tender,
        operator,
        keyword
      })
      if (result.data.length === 0) alert('查無資料')
      return result.data
    },
    async getReceiveFileManagement ({state, commit}, id) { // 查看收文文件檔案
      let result = await axios.get(`/tenders/${id}/tender/receiveFileManagement`)
      commit('setReceiveFileManagementList', result.data)
    },
    async patch ({state}, {tenderId}) { // 修改標案資料
      await axios.patch(`/tenders/${tenderId}/tender`, state.tenders)
    },
    async patchMileStone ({ state }, {tenderId, mileStoneId}) { // 修改里程碑
      await axios.patch(`/tenders/${tenderId}/mileStone/${mileStoneId}`, state.mileStone)
    },
    async patchCheckPoint ({ state }, {tenderId, checkPointId}) { // 修改專案查核點
      await axios.patch(`/tenders/${tenderId}/checkPoint/${checkPointId}`, state.checkPoint)
    },
    async patchExtendRecord ({ state }, {tenderId, extendRecordId}) { // 修改展延紀錄
      await axios.patch(`/tenders/${tenderId}/extendRecord/${extendRecordId}`, state.extendRecord)
    },
    async patchProjectStatus ({ state, rootState, dispatch }, {projectStatusId}) { // 修改工程現況
      let old = []
      for (const image of state.projectStatus.imageFile) {
        if (image.mime !== undefined && image.name !== undefined) old.push(image)
      }
      const data = {
        title: state.projectStatus.title,
        date: state.projectStatus.date,
        imageFile: old,
        description: state.projectStatus.description
      }
      await axios.patch(`/tenders/${rootState.user.current.defaultTender}/projectStatus/${projectStatusId}`, data)
      for (const image of state.projectStatus.imageFile) {
        if (image.mime === undefined && image.name === undefined) {
          await dispatch('addImage', {
            projectStatusId: projectStatusId,
            file: image.file,
            description: image.description
          })
        }
      }
    }
  },
  getters: {
  }
}
