import Vue from "vue";
import Vuex from "vuex";
import { EPCC_DOMAIN, CUG_DOMAIN } from "@/constants/constants";

Vue.use(Vuex);

const examHomeModule = {
  namespaced: true,
  state: { faceCheckModalOpen: false },
  mutations: {
    toggleFaceCheckModal(state, open) {
      if (open === undefined) {
        state.faceCheckModalOpen = !state.faceCheckModalOpen;
      } else {
        state.faceCheckModalOpen = open;
      }
    },
  },
  actions: {},
  getters: {},
};

const examingHomeModule = {
  namespaced: true,
  state: {
    exam: null,
    paperStruct: null,
    examQuestionList: null,
    questionFilterType: "ALL",
    snapNow: false,
    remainTime: null,
    snapProcessingCount: 0,
    shouldSubmitPaper: false,
    allAudioPlayTimes: [],
    questionQrCode: null,
    questionQrCodeScanned: null,
    questionAnswerFileUrl: [],
    pictureAnswer: {},
    uploadModalVisible: false,
    isDoingFaceLiveness: false,
  },
  mutations: {
    updateRemainTime(state, remainTime) {
      state = Object.assign(state, { remainTime });
    },
    toggleSnapNow(state) {
      // FIXME: 这里对多次调用不够严谨，比如，下次调用时本意是要抓拍，但别处的watch不知道是否已经执行。最好改成event的形式。
      state.snapNow = !state.snapNow;
      if (state.snapNow) {
        state.snapProcessingCount = state.snapProcessingCount + 1;
      }
    },
    decreaseSnapCount(state) {
      state.snapProcessingCount = state.snapProcessingCount - 1;
    },
    updateExamState(state, payload) {
      state = Object.assign(state, payload);
    },
    updateExamResult(state, payload) {
      state = Object.assign(state, { examResult: payload });
    },
    updateQuestionFilter(state, type) {
      window._hmt.push(["_trackEvent", "正在考试页面", "筛选问题"]);
      state.questionFilterType = type;
    },
    updateQuestionAudioPlayTimes(state, payload) {
      // const cAudio = state.allAudioPlayTimes.find(
      //   audio => audio.name === payload
      // ) || { name: payload, times: 1 };

      // console.log(cAudio);
      // console.log(
      //   state.allAudioPlayTimes.find(audio => audio.name === payload)
      // );

      let alreayHas = false;
      let allAudioPlayTimes = state.allAudioPlayTimes.map(audio => {
        if (audio.name === payload) {
          alreayHas = true;
          const times = audio.times + 1;
          return { name: payload, times: times };
        }
        return audio;
      });
      // console.log(allAudioPlayTimes);
      if (!alreayHas) {
        // let o = {};
        // o.name = payload;
        // o.times = 1;
        allAudioPlayTimes.push({ name: payload, times: 1 });
        // allAudioPlayTimes.push(o);
      }
      // console.log(allAudioPlayTimes);

      const examQuestionList = state.examQuestionList.map(eq => {
        // console.log(eq.order, order);
        if (eq.order == 1) {
          return Object.assign(
            {},
            eq,
            { dirty: true },
            { getQuestionContent: true }, // 第一题总是获取
            { audioPlayTimes: JSON.stringify(allAudioPlayTimes) }
          );
        }
        return eq;
      });

      state = Object.assign(state, { allAudioPlayTimes, examQuestionList });
    },
    updateExamQuestion(
      state,
      { order, studentAnswer, isSign, audioPlayTimes, getQuestionContent }
    ) {
      const examQuestionList = state.examQuestionList.map(eq => {
        // console.log(eq.order, order);
        if (eq.order == order) {
          return Object.assign(
            {},
            eq,
            getQuestionContent === undefined && { dirty: true }, // 仅设置getQuestionContent时，不更新dirty
            studentAnswer !== undefined && { studentAnswer },
            audioPlayTimes !== undefined && { audioPlayTimes },
            isSign !== undefined && { isSign },
            getQuestionContent !== undefined && { getQuestionContent }
          );
        }
        return eq;
      });
      // if (audioPlayTimes) {
      //   const cq = state.examQuestionList[order - 1];
      //   examQuestionList = examQuestionList.map(eq => {
      //     if (cq.questionId == eq.questionId) {
      //       // 保存套题的音频播放次数
      //       return Object.assign(
      //         {},
      //         eq,
      //         { dirty: true },
      //         audioPlayTimes !== undefined && { audioPlayTimes }
      //       );
      //     }
      //     return eq;
      //   });
      // }
      state = Object.assign(state, { examQuestionList });
    },
    resetExamQuestionDirty(state) {
      const examQuestionList = state.examQuestionList.map(eq => {
        return Object.assign({}, eq, { dirty: false });
      });
      state = Object.assign(state, { examQuestionList });
    },
    setShouldSubmitPaper(state) {
      state.shouldSubmitPaper = !state.shouldSubmitPaper;
    },
    setQuestionQrCode(state, payload) {
      state.questionQrCode = payload;
    },
    setQuestionQrCodeScanned(state, payload) {
      state.questionQrCodeScanned = payload;
    },
    setQuestionFileAnswerUrl(state, payload) {
      // 先清理之前保存过的记录
      state.questionAnswerFileUrl = state.questionAnswerFileUrl.filter(
        v => !v.saved
      );
      let ary = state.questionAnswerFileUrl;
      let found = false;
      for (const i of ary) {
        if (i.order === payload.order) {
          // 同一道题可能更新
          i.fileUrl = payload.fileUrl;
          found = true;
          break;
        }
      }
      if (found) {
        state.questionAnswerFileUrl = [...ary];
      } else {
        state.questionAnswerFileUrl.push(payload);
      }
    },
    updatePicture(state, payload) {
      state.pictureAnswer = payload;
    },
    updateUploadModalVisible(state, payload) {
      state.uploadModalVisible = payload;
    },
    updateIsDoingFaceLiveness(state, payload) {
      state.isDoingFaceLiveness = payload;
    },
  },
  actions: {},
  getters: {
    examShouldShowAnswer(state) {
      if (state.exam && state.exam.practiceType === "IN_PRACTICE") {
        return true;
      }
      return false;
    },
  },
};

const userStr = window.localStorage.getItem("user-for-reload");
const initUser = userStr ? JSON.parse(userStr) : {};

export default new Vuex.Store({
  state: {
    user: initUser,
    timeDifference: 0,
    siteMessages: [],
    siteMessagesTimeStamp: Date.now(),
    QECSConfig: {}, // getter/setter 来解决其他页面刷新访问的问题
    menus: [],
  },
  mutations: {
    updateUser(state, payload) {
      state = Object.assign(state, { user: payload });
    },
    updateTimeDifference(state, payload) {
      state = Object.assign(state, { timeDifference: payload });
    },
    updateSiteMessages(state, payload) {
      state = Object.assign(state, { siteMessages: payload });
    },
    updateSiteMessagesTimeStamp(state, payload) {
      state = Object.assign(state, { siteMessagesTimeStamp: payload });
    },
    updateQECSConfig(state, payload) {
      state = Object.assign(state, { QECSConfig: payload });
    },
    updateMenus(state, payload) {
      state = Object.assign(state, { menus: payload });
    },
  },
  actions: {},
  modules: {
    examHomeModule,
    examingHomeModule,
  },
  getters: {
    isEpcc(state) {
      return state.user.schoolDomain === EPCC_DOMAIN;
    },
    isCug(state) {
      const FE_FEATURE_IMAGE_PDF = true;
      return state.user.schoolDomain === CUG_DOMAIN && FE_FEATURE_IMAGE_PDF;
    },
  },
});
