import { getApp, getNum } from '@/app';
import { base64ToBlob, convertBlob2File } from '@/utils/file';
export default {
  namespaced: true,
  state() {
    return {
      // showPath: false,
      // showFrame: false,
      toursList: [],
      sourceList: null,
      frameId: 0,
      partId: 0,
      tours: [],
      musicList: [],
      delList: [],
      isPlay: false,
      showTours: false,
      isHome: true,
    };
  },
  getters: {
    tours: (state) => {
      return state.tours;
    },

    partId: (state) => {
      return state.partId;
    },
    frameId: (state) => {
      return state.frameId;
    },
    isPlay: (state) => {
      return state.isPlay;
    },
    isHome: (state) => {
      return state.isHome;
    },
    showTours: (state) => {
      return state.showTours;
    },
  },
  mutations: {
    setData(state, payload) {
      if (payload) {
        for (let key in payload) {
          state[key] = payload[key];
        }
      }
    },
    loaded(state, payload) {
      state.tours = payload;
    },
    setBackUp(state) {
      state.toursList = JSON.parse(JSON.stringify(state.tours));
    },
    update(state, tours) {
      this.commit('enterEdit');
      //如果删除片段和备份数据一样则退出编辑模式
      let t = setTimeout(() => {
        clearTimeout(t);
        if (state.tours.length == 0 && state.toursList.length == 0) {
          this.commit('leaveEdit');
        }
      }, 0);
    },
    async setFrame(state, payload) {
      const recordr = await getApp().TourManager.recorder;
      recordr.setFrame(state.frameId, payload);
      this.commit('tour/update');
    },
    async setPart(state, payload) {
      const recordr = await getApp().TourManager.recorder;
      let data = JSON.parse(JSON.stringify(payload));
      for (let key in data) {
        if (key === 'file') {
          delete data[key];
        }
      }
      recordr.setPart(state.partId, data);

      for (let key in payload) {
        state.tours[state.partId][key] = payload[key];
      }

      this.commit('tour/update');
    },
    getUploadMuscis(state, payload) {
      let musics = state.tours.filter((item) => {
        console.log(item.file);
        if (item.file) {
          return item;
        }
      });
      console.log(musics);
      return musics;
    },
    // setTime(state, time) {
    //     // state.tours[state.partId].list[state.frameId].time = time * 1000
    //     this.commit('tour/setFrame', { time: time * 1000 })
    // },
    delList(state, payload) {
      let frameId = payload.frameId || 0;
      let list = state.tours[state.partId].list;
      let music = state.tours[state.partId].music;
      let name = state.tours[state.partId].list[frameId].enter.cove;
      switch (payload.type) {
        case 'part':
          // if (music.indexOf('blob:') == -1 && music != '') {
          if (music != '') {
            let file = state.tours[state.partId].musicUrl ? state.tours[state.partId].musicUrl.split('/').pop().split('?').shift() : music.split('/').pop().split('?').shift();
            state.delList.push(file);
          }
          if (list.length > 0) {
            list.forEach((i, index) => {
              // if (i.enter.coverUrl || i.enter.cover.indexOf('data:image') == -1) {
              //     state.delList.push(i.enter.cover.split('/').pop().split('?').shift())
              // }
              let cover = i.enter.coverUrl ? i.enter.coverUrl.split('/').pop().split('?').shift() : i.enter.cover.split('/').pop().split('?').shift();
              state.delList.push(cover);
            });
          }
          console.log(state.delList);
          break;
        case 'frame':
          // if (name.indexOf('data:image') == -1) {
          //     state.delList.push(name.split('/').pop().split('?').shift())
          // }
          let cover = state.tours[state.partId].list[frameId].enter.coverUrl
            ? state.tours[state.partId].list[frameId].enter.coverUrl.split('/').pop().split('?').shift()
            : state.tours[state.partId].list[frameId].enter.cover.split('/').pop().split('?').shift();
          state.delList.push(cover);
          break;
        case 'music':
          // if (music.indexOf('blob:') == -1 && music != '') {
          //     state.delList.push(name.split('/').pop().split('?').shift())
          // }
          if (music != '') {
            let file = state.tours[state.partId].musicUrl ? state.tours[state.partId].musicUrl.split('/').pop().split('?').shift() : music.split('/').pop().split('?').shift();
            state.delList.push(file);
          }
          break;
        // case 'all':
        //     for (var i = 0; i < state.tours.length; i++) {
        //         let music = state.tours[i].music
        //         if (music.indexOf('blob:') == -1 && music != '') {
        //             state.delList.push(music.split('/').pop().split('?').shift())
        //         }
        //         state.tours[i].list.forEach((frame, index) => {
        //             if (frame.enter.cover.indexOf('data:image') == -1) {
        //                 state.delList.push(frame.enter.cover.split('/').pop().split('?').shift())
        //             }
        //         })
        //     }
        //     break
      }
      console.log(state.delList);
    },

    cancel(state) {
      state.tours = JSON.parse(JSON.stringify(state.toursList));
      getApp().TourManager.load(JSON.parse(JSON.stringify(state.toursList))); //通知回滚
      state.toursList = JSON.parse(JSON.stringify(state.tours));
      this.commit('leaveEdit');
    },
    save(state, newdData) {
      state.toursList = JSON.parse(JSON.stringify(newdData));

      for (let i = 0; i < state.tours.length; i++) {
        state.tours[i].musicUrl = newdData[i].music;
        for (let j = 0; j < newdData[i].list.length; j++) {
          state.tours[i].list[j].coverUrl = newdData[i].list[j].cover;
        }
      }
      console.log(state.tours);
      // state.tours = JSON.parse(JSON.stringify(newdData))
      this.commit('leaveEdit');
    },

    // filterFiles(state,list){
    //   for()
    // }
  },
  actions: {
    delTours({ commit, state }, payload) {
      // tour/delete
      return getApp()
        .remote_editor.tour_delete({ num: getNum() })
        .then((res) => {
          if (res.success) {
            state.tours = [];
            commit('save', []);
            getApp().TourManager.load([]);
          }
          return res;
        })
        .catch((err) => {
          console.log(err);
          return err;
        });
    },
    async delFile({ commit, state }, payload) {
      let params = {
        num: getNum(),
        bizType: 'tour',
        fileNames: state.delList,
      };
      let res = await this.dispatch('delFiles', params);
      console.log(res);
      if (res.success) {
        state.delList = [];
      }
    },
    async save({ commit, dispatch, state }, payload) {
      if (state.delList.length > 0) {
        dispatch('delFile');
      }
      let recorder = await getApp().TourManager.recorder;
      let exportFiles = recorder.exportFiles();
      let files = [];
      console.log(exportFiles);
      exportFiles.map((item) => {
        let obj = {};
        if (item.type == 'base64') {
          obj.file = convertBlob2File(base64ToBlob(item.file), item.name);
          obj.filename = item.name;
        } else if (item.type == 'file') {
          state.tours.filter((i) => {
            let fileId = item.name.split('.')[0].split('-')[2];
            if (fileId == i.sid) {
              obj.file = i.file;
              obj.filename = item.name;
            }
          });
        }
        files.push(obj);
      });
      console.log(files);

      let res = await this.dispatch('scene/upload_files', { bizType: 'tour', num: getNum(), type: 0, files: files });
      if (res.success) {
      }
      let data = recorder.exportData();
      // let audioFiles = files.filter(i => {
      //     return i.type === 'file'
      // })
      // let imageFiles = files.filter(i => {
      //     return i.type === 'base64'
      // })

      // if (audioFiles.length > 0) {
      //     for (let i = 0; i < audioFiles.length; i++) {
      //         for (let j = 0; j < state.tours.length; j++) {
      //             let fileId = audioFiles[i].name.split('.')[0].split('-')[2]
      //             console.log(fileId)
      //             if (fileId == state.tours[j].sid) {
      //                 let res = await this.dispatch('scene/upload_files', { files: state.tours[j].file, bizType: 'tour', num: getNum(), type: 0, fileName: audioFiles[i].name })
      //                 if (res.success) {
      //                 }
      //             }
      //         }
      //     }
      // }
      // if (imageFiles.length > 0) {
      //     for (let i = 0; i < imageFiles.length; i++) {
      //         let res = await this.dispatch('scene/upload_files', { base64: imageFiles[i].file, bizType: 'tour', num: getNum(), type: 0, fileName: imageFiles[i].name })
      //         if (res.success) {
      //         }
      //     }
      // }

      console.log('data', data);
      console.log('tours', state.tours);
      let params = {
        num: getNum(),
        data: JSON.stringify(data),
      };
      return getApp()
        .remote_editor.tour_save(params)
        .then((res) => {
          if (res.success) {
            commit('save', data);
          }
          return res;
        })
        .catch((err) => {
          console.log(err);
          return err;
        });
    },
  },
};
