// import Axios from "axios";
//const DOMAIN = "http://dotest.kfems.kr:9997/";
const DOMAIN = '';
// const DOMAIN = "http://localhost:9999/";
// const DOMAIN = "/";
const INIT_URL_STATE = {
   // apiUrl:
   selectBlocMstrCodeList: 'comm/base/CommCtr/selectBlocMstrCodeList', // 사업장 목록
   selectEnergy: 'ems/base/EmsCommCtr/selectEnergy', // 에너지원 목록
   selectCommCdSelect: 'comm/base/CommCdMngCtr/selectCodeList', // 시스템관리 공통셀렉트 목록
   selectCodeList: 'comm/base/CommCdMngCtr/selectCodeList', // 시스템관리 공통셀렉트 목록
   selectMonthWeekendList: 'comm/base/CalendarMngCtr/selectMonthWeekendList', // 공휴일 목록 조회 => 최초 1회만 실행
   selectFactoryList: 'ems/base/seasonReadCtr/selectFactoryList', //공장 목록
   selectMtt: 'ems/base/EmsCommCtr/selectMtt',
   selectMttCd: 'ems/base/ReadResultCloseMngCtr/selectMttCd', // 개소종류
   selectStandard: 'ems/base/EmsCommCtr/selectStandard', //기준 목록
   // 기준 정보 (신규)
   selectAddGrpInfo: 'ems/base/AddInfoMngCtr/selectAddGrpInfo',
   selectAddInfo: 'ems/base/AddInfoMngCtr/selectAddInfo', // 공휴일 목록 조회 => 최초 1회만 실행
   selectReadObjInfo: 'ems/base/ReadObjMngCtr/selectReadObjInfo',
   selectEqpmGrp: 'ems/base/EqpmGrpMngCtr/selectEqpmGrp',
   selectErc: 'ems/base/EnrgResourceCenterMngCtr/selectErcInfo',
};

export const state = () => Object.assign({}, INIT_URL_STATE);

export const actions = {
   addInx({}, payload) {
      return payload.map((item, i) => ({ ...item, idx: i }));
   },

   // 휴일 목록 조회 selectBlocMstrCodeList
   getHolidayList({ state, rootState, commit }) {
      if (!rootState.holidayList) {
         const params = { params: {} }; // as-is 에서는 파람을 넘겨 토,일 요일정보도 가져왔으나  to-be 는 전체 휴일정보만 한번에 가져와 진행할 예정
         const res = this.$axios.post(
            DOMAIN + state.selectMonthWeekendList,
            params,
         );
         res
            .then(value => {
               commit('setHolidayList', value.data.dataset.workcaldData, {
                  root: true,
               });
            })
            .catch(error => console.log(error));
         // .finally(() => console.log("end"));
      } else {
         // console.log("휴일 정보가 이미 있음 ", rootState.holidayList);
      }
   },

   // 사업장 목록 조회 selectBlocMstrCodeList
   getBlocMstrList({ rootState, state, dispatch, commit }, payload) {
      const headers = {
         headers: {
            'X-Fems-MenuId': this.state.activeMenuInfo.menuId,
         },
      };
      const dataKey = payload.dataKey || '';
      const params = { params: payload.params || {} };
      const res = this.$axios.post(
         DOMAIN + state.selectBlocMstrCodeList,
         params,
         headers,
      );
      res
         .then(value => {
            let newList = value.data.dataset.blocCodeLists;
            if (payload.addAll) newList.unshift({ blocId: '', blocNm: '전체' });

            dispatch('addInx', newList).then(list => {
               let defaultValue = '';
               if (!dataKey) {
                  defaultValue =
                     rootState.pageData[rootState.activeMenuInfo.prgmId].blocId ||
                     list[0].blocId;
               } else {
                  defaultValue =
                     rootState.pageData[rootState.activeMenuInfo.prgmId][dataKey] ||
                     list[0].blocId;
               }
               if (!dataKey) {
                  commit(
                     'setPageData',
                     { blocMstrList: list, blocId: 0 },
                     { root: true },
                  );
               } else {
                  commit(
                     'setPageData',
                     { [dataKey + 'List']: list, [dataKey]: defaultValue },
                     { root: true },
                  );
               }
            });
         })
         .catch(error => console.log(error));
      // .finally(() => console.log("end"));
   },

   // 사업장 목록 조회 selectBlocMstrCodeList - localstorage 추가
   getBlocMstrListForPop({ state, dispatch, commit }, payload) {
      const headers = {
         headers: {
            'X-Fems-MenuId': this.state.activeMenuInfo.menuId,
         },
      };
      const params = { params: payload || {} };
      const res = this.$axios.post(
         DOMAIN + state.selectBlocMstrCodeList,
         params,
         headers,
      );
      res
         .then(value => {
            dispatch('addInx', value.data.dataset.blocCodeLists).then(list => {
               commit(
                  'setPageData',
                  {
                     blocMstrList: list,
                     blocId:
                        localStorage.getItem(
                           this.state.activeMenuInfo.id + 'SelectedBlocCd',
                        ) === null
                           ? 0
                           : parseInt(
                                 localStorage.getItem(
                                    this.state.activeMenuInfo.id + 'SelectedBlocCd',
                                 ),
                             ),
                  },
                  { root: true },
               );
            });
         })
         .catch(error => console.log(error));
      // .finally(() => console.log("end"));
   },

   // 에너지원 목록 조회 selectErc
   getErcList({ state, dispatch, commit }, payload) {
      const headers = {
         headers: {
            'X-Fems-MenuId': this.state.activeMenuInfo.menuId,
         },
      };
      const params = { params: payload || {} };
      const res = this.$axios.post(DOMAIN + state.selectErc, params, headers);
      res
         .then(value => {
            dispatch('addInx', value.data.dataset.ercInfoData).then(list => {
               commit('setPageData', { ercList: list, ercId: 0 }, { root: true });
            });
         })
         .catch(error => console.log(error));
      // .finally(() => console.log("end"));
   },

   // 에너지원 목록 조회 selectEnergy
   getEnergyList({ state, dispatch, commit }, payload) {
      const headers = {
         headers: {
            'X-Fems-MenuId': this.state.activeMenuInfo.menuId,
         },
      };
      const params = { params: payload || {} };
      const res = this.$axios.post(DOMAIN + state.selectEnergy, params, headers);
      res
         .then(value => {
            dispatch('addInx', value.data.dataset.energyData).then(list => {
               commit(
                  'setPageData',
                  { energyList: list, energyCd: 0 },
                  { root: true },
               );
            });
         })
         .catch(error => console.log(error));
      // .finally(() => console.log("end"));
   },

   // 에너지원 목록 조회 selectEnergy - localstorage 추가
   getEnergyListForPop({ state, dispatch, commit }, payload) {
      const headers = {
         headers: {
            'X-Fems-MenuId': this.state.activeMenuInfo.menuId,
         },
      };
      const params = { params: payload || {} };
      const res = this.$axios.post(DOMAIN + state.selectEnergy, params, headers);
      res
         .then(value => {
            dispatch('addInx', value.data.dataset.energyData).then(list => {
               commit(
                  'setPageData',
                  {
                     energyList: list,
                     energyCd:
                        localStorage.getItem(
                           this.state.activeMenuInfo.id + 'SelectedEnergyCd',
                        ) === null
                           ? 0
                           : parseInt(
                                 localStorage.getItem(
                                    this.state.activeMenuInfo.id + 'SelectedEnergyCd',
                                 ),
                             ),
                  },
                  { root: true },
               );
            });
         })
         .catch(error => console.log(error));
      // .finally(() => console.log("end"));
   },

   // 공통코드 사용여부 목록 조회 selectUseFg
   getUseFgList({ state, dispatch, commit }, payload) {
      const headers = {
         headers: {
            'X-Fems-MenuId': this.state.activeMenuInfo.menuId,
         },
      };
      const params = { params: payload || {} };
      const res = this.$axios.post(
         DOMAIN + state.selectCommCdSelect,
         params,
         headers,
      );
      res
         .then(value => {
            dispatch('addInx', value.data.dataset.codeLists).then(list => {
               commit('setPageData', { useFgList: list }, { root: true });
            });
         })
         .catch(error => console.log(error));
      // .finally(() => console.log("end"));
   },
   // 공통코드 목록 조회 selectCodeList
   getCodeList({ rootState, state, dispatch, commit }, payload) {
      const headers = {
         headers: {
            'X-Fems-MenuId': this.state.activeMenuInfo.menuId,
         },
      };
      const dataKey = payload.dataKey || '';
      const params = { params: payload.params || {} };
      const res = this.$axios.post(
         DOMAIN + state.selectCodeList,
         params,
         headers,
      );
      res
         .then(value => {
            let newList = value.data.dataset.codeLists;
            if (payload.addAll) newList.unshift({ commCd: '', commCdNm: '전체' });
            if (payload.addBlank) newList.unshift({ commCd: '', commCdNm: '' });

            dispatch('addInx', newList).then(list => {
               const defaultValue =
                  rootState.pageData[rootState.activeMenuInfo.prgmId][dataKey] ||
                  list[0].commCd;
               // { [dataKey + "List"]: list, [dataKey]: 0 },
               commit(
                  'setPageData',
                  { [dataKey + 'List']: list, [dataKey]: defaultValue },
                  { root: true },
               );
            });
         })
         .catch(error => console.log(error));
      // .finally(() => console.log("end"));
   },
   getMttList({ rootState, state, dispatch, commit }, payload) {
      const headers = {
         headers: {
            'X-Fems-MenuId': this.state.activeMenuInfo.menuId,
         },
      };
      const dataKey = payload.dataKey || '';
      const params = { params: payload.params || {} };
      const res = this.$axios.post(DOMAIN + state.selectMtt, params, headers);
      res
         .then(value => {
            let newList = value.data.dataset.mttData;
            dispatch('addInx', newList).then(list => {
               const defaultValue =
                  list[0].mttCd ||
                  rootState.pageData[rootState.activeMenuInfo.prgmId][dataKey];
               // { [dataKey + "List"]: list, [dataKey]: 0 },
               commit(
                  'setPageData',
                  { [dataKey + 'List']: list, [dataKey]: defaultValue },
                  { root: true },
               );
            });
         })
         .catch(error => console.log(error));
      // .finally(() => console.log("end"));
   },

   // 측정 대상 유형 목록 조회 selectReadObjInfo
   getReadObjInfoList({ rootState, state, dispatch, commit }, payload) {
      const headers = {
         headers: {
            'X-Fems-MenuId': this.state.activeMenuInfo.menuId,
         },
      };
      const dataKey = payload.dataKey || '';
      const params = { params: payload.params || {} };
      const res = this.$axios.post(
         DOMAIN + state.selectReadObjInfo,
         params,
         headers,
      );
      res
         .then(value => {
            let newList = value.data.dataset.readObjInfoData;
            if (payload.addAll)
               newList.unshift({ readObjId: '', readObjNm: '전체' });

            dispatch('addInx', newList).then(list => {
               const defaultValue =
                  rootState.pageData[rootState.activeMenuInfo.prgmId][dataKey] ||
                  list[0].readObjId;
               // { [dataKey + "List"]: list, [dataKey]: 0 },
               commit(
                  'setPageData',
                  { [dataKey + 'List']: list, [dataKey]: defaultValue },
                  { root: true },
               );
            });
         })
         .catch(error => console.log(error));
   },
   // 측정 대상 유형 목록 조회 selectEqpmGrp
   getEqpmGrpList({ rootState, state, dispatch, commit }, payload) {
      const headers = {
         headers: {
            'X-Fems-MenuId': this.state.activeMenuInfo.menuId,
         },
      };
      const dataKey = payload.dataKey || '';
      const params = { params: payload.params || {} };
      const res = this.$axios.post(DOMAIN + state.selectEqpmGrp, params, headers);
      res
         .then(value => {
            let newList = value.data.dataset.eqpmGrpData;
            if (payload.addAll)
               newList.unshift({ eqpmGrpId: '', eqpmGrpNm: '전체' });

            dispatch('addInx', newList).then(list => {
               const defaultValue =
                  rootState.pageData[rootState.activeMenuInfo.prgmId][dataKey] ||
                  list[0].eqpmGrpId;
               // { [dataKey + "List"]: list, [dataKey]: 0 },
               commit(
                  'setPageData',
                  { [dataKey + 'List']: list, [dataKey]: defaultValue },
                  { root: true },
               );
            });
         })
         .catch(error => console.log(error));
   },
   // 추가 정보 그룹 목록 조회 selectAddGrpInfo
   getAddGrpInfoList({ rootState, state, dispatch, commit }, payload) {
      const headers = {
         headers: {
            'X-Fems-MenuId': this.state.activeMenuInfo.menuId,
         },
      };
      const dataKey = payload.dataKey || '';
      const params = { params: payload.params || {} };
      const res = this.$axios.post(
         DOMAIN + state.selectAddGrpInfo,
         params,
         headers,
      );
      res
         .then(value => {
            let newList = value.data.dataset.addGrpInfoData;
            if (payload.addAll) newList.unshift({ addGrpId: '', addGrpNm: '전체' });

            dispatch('addInx', newList).then(list => {
               if (list.length > 0) {
                  const defaultValue =
                     rootState.pageData[rootState.activeMenuInfo.prgmId][dataKey] ||
                     list[0].addGrpId;
                  // { [dataKey + "List"]: list, [dataKey]: 0 },
                  commit(
                     'setPageData',
                     { [dataKey + 'List']: list, [dataKey]: defaultValue },
                     { root: true },
                  );
               }
            });
         })
         .catch(error => console.log(error));
   },
   // 추가 정보 목록 조회 selectAddInfo
   getAddInfoList({ rootState, state, dispatch, commit }, payload) {
      const headers = {
         headers: {
            'X-Fems-MenuId': this.state.activeMenuInfo.menuId,
         },
      };
      const dataKey = payload.dataKey || '';
      const params = { params: payload.params || {} };
      const res = this.$axios.post(DOMAIN + state.selectAddInfo, params, headers);
      res
         .then(value => {
            let newList = value.data.dataset.addInfoData;
            if (payload.addAll)
               newList.unshift({ addInfoId: '', addInfoNm: '전체' });

            dispatch('addInx', newList).then(list => {
               if (list.length > 0) {
                  const defaultValue =
                     rootState.pageData[rootState.activeMenuInfo.prgmId][dataKey] ||
                     list[0].addInfoId;
                  // { [dataKey + "List"]: list, [dataKey]: 0 },
                  commit(
                     'setPageData',
                     { [dataKey + 'List']: list, [dataKey]: defaultValue },
                     { root: true },
                  );
               }
            });
         })
         .catch(error => console.log(error));
   },
   // 공장 목록 조회 selectFactoryList
   getFactoryList({ state, dispatch, commit }, payload) {
      const headers = {
         headers: {
            'X-Fems-MenuId': this.state.activeMenuInfo.menuId,
         },
      };
      const params = { params: payload || {} };
      const res = this.$axios.post(
         DOMAIN + state.selectFactoryList,
         params,
         headers,
      );
      res
         .then(value => {
            dispatch('addInx', value.data.dataset.seasonReadData).then(list => {
               commit(
                  'setPageData',
                  { factoryList: list, plcCd: 0 },
                  { root: true },
               );
            });
         })
         .catch(error => console.log(error));
      // .finally(() => console.log("end"));
   },
   // 공통 search
   getSearchList({ rootState, state, commit }, payload) {
      // console.log(payload);
      const headers = {
         headers: {
            'X-Fems-MenuId': this.state.activeMenuInfo.menuId,
         },
      };
      const params = { params: payload.params };
      const res = this.$axios.post(
         DOMAIN + state[payload.apiKey],
         params,
         headers,
      );
      res
         .then(value => {
            const list = value.data.dataset[payload.resKey];
            let returnList = [];
            let defaultValue = '';
            if (list.length > 0) {
               returnList = list.map(item => ({
                  ...item,
                  text: item.value || item[payload.dataNm],
                  code: item.code || item[payload.dataCd],
               }));
               if (payload.addAll) returnList.unshift({ code: '', text: '전체' });
               defaultValue =
                  rootState.pageData[rootState.activeMenuInfo.prgmId][
                     payload.resKey + 'Default' // 기본 지정값이 있다면 모화면 defaultData 에 [resKey + "Default"] 값으로 세팅
                  ] || returnList[0].code;
            }
            commit(
               'setPageData',
               {
                  [payload.resKey + 'List']: returnList,
                  [payload.resKey]: defaultValue,
               },
               { root: true },
            );
         })
         .catch(error => console.log(error));
      // .finally(() => console.log("end"));
   },
   getStandardList({ rootState, state, dispatch, commit }, payload) {
      const headers = {
         headers: {
            'X-Fems-MenuId': this.state.activeMenuInfo.menuId,
         },
      };
      const dataKey = payload.dataKey || '';
      const params = { params: payload.params || {} };
      const res = this.$axios.post(
         DOMAIN + state.selectStandard,
         params,
         headers,
      );

      res
         .then(value => {
            let newList = value.data.dataset.standardData;

            dispatch('addInx', newList).then(list => {
               const defaultValue =
                  list[0].readObjId ||
                  rootState.pageData[rootState.activeMenuInfo.prgmId][dataKey];
               // { [dataKey + "List"]: list, [dataKey]: 0 },
               commit(
                  'setPageData',
                  { [dataKey + 'List']: list, [dataKey]: defaultValue },
                  { root: true },
               );
            });
         })
         .catch(error => console.log(error));
      // .finally(() => console.log("end"));
   },
};