import { createStore } from "vuex";
import {ElMessage} from 'element-plus'
import {apiUserInfo} from '@/api/user.js'
import {apiActivityAudioPlayRecordAdd,apiActivityAudioPlayRecordUpate} from '@/api/activity'
import {apiViewLogUpdate} from  '@/api/common'
import{apiCountAudioClick}from '@/api/question'
import {apiVoicePlayRecord} from '@/api/voice'

let lastActivityAudioRecordId=0//上次新曾活动音频记录时的id
let lastAudioRecordId=0//上次问答社区\语音播报 音频记录id

const token=localStorage.getItem('token')||''
let platform='web'
if(window.__wxjs_environment === 'miniprogram'){
  platform='xcx'
}
const agent = navigator.userAgent.toLowerCase();
const isMac = /macintosh|mac os x/i.test(navigator.userAgent);

const breadcrumb=sessionStorage.getItem('breadcrumb')?JSON.parse(sessionStorage.getItem('breadcrumb')):[{name:'',path:location.pathname||''}]
export default createStore({
  state: {
    isMac:isMac,
    platform:platform,//所处平台 web/xcx
    globalImgUrls:{//图片配置资源
      chartWait:'https://hzstatic.hzinsights.com/static/icon/hzyb/chart_wait.png',
      chartEmpty:'https://hzstatic.hzinsights.com/static/icon/hzyb/chart_empty.png',
      activityNoAuth:'https://hzstatic.hzinsights.com/static/icon/hzyb/activity_no_auth.png',
      imgSuccess:'https://hzstatic.hzinsights.com/static/icon/hzyb/success_icon.png',
      loginTop:'https://hzstatic.hzinsights.com/static/icon/hzyb/login_top_img.png',
      idCardExp:'https://hzstatic.hzinsights.com/static/icon/hzyb/idcard_exp.jpg',
      defaultAvatar:'https://hzstatic.hzinsights.com/static/icon/hzyb/default_avatar.png',
      ficcServiceImg:'https://hzstatic.hzinsights.com/static/icon/hzyb/ficc_service_pc.png',
      specialColumnBanner:'https://hzstatic.hzinsights.com/static/icon/hzyb/special_column_banner_pc.png'
    },
    showLogin:false,//是否显示微信扫码弹窗
    showBind:false,//是否显示绑定手机号\邮箱弹窗
    token:token,
    userInfo:null,
    audioData:{
      INS:null,//音频实例
      list:[],//音频数据{time:音频时长,url:音频地址,name:音频名称}
      index:0,//当前播放第几个
      activityId:0,//活动的id
      reportId:0,//报告的id
      voiceId:0,//语音播报列表id
      questionId:0,//问答社区的id
      paused:true,//当前音频播放状态
      show:false,//是否显示音频弹窗
      audioCurrentTime:0,//音频当前播放的时间
    },

    activityItemStatus:{//活动详情中某个活动点击了会议提醒\报名 更新列表状态
      activityId:0,
      type:'',// 会议、报名
    },

    breadCrumbList:breadcrumb,//面包屑数据
  },
  mutations: {
    //显示微信扫码登陆
    showLogin(state,e){
      state.showLogin=e
    },
    //显示绑定手机号
    showBindAccount(state,e){
      state.showBind=e
    },
      
    // 获取token
    getToken(state,e){
      console.log(e);
      state.token=e
      localStorage.setItem('token',e)
    },
    // 获取个人信息
    setUserInfo(state,e){
      state.userInfo=e
    },

    // 设置音频播放
    addAudio(state,e){
      // 更新活动音频播放时长
      if(state.audioData.activityId!=0&&lastActivityAudioRecordId!=0){
        handleActivityAudioRecordUpdate(state.audioData)
      }
      // 更新问答\语音播报 音频播放时长
      if(lastAudioRecordId!=0){
        if(state.audioData.voiceId!=0){
          handleAudioRecordUpdate({audioCurrentTime:state.audioData.audioCurrentTime,source:2})
        }
        if(state.audioData.questionId!=0){
          handleAudioRecordUpdate({audioCurrentTime:state.audioData.audioCurrentTime,source:1})
        }
      }
      state.audioData.index=e.index
      state.audioData.list=e.list
      state.audioData.activityId=e.activityId||0
      state.audioData.reportId=e.reportId||0
      state.audioData.voiceId=e.voiceId||0
      state.audioData.questionId=e.questionId||0
      state.audioData.show=true
      state.audioData.INS.play()
      if(state.audioData.activityId!=0){
        handleActivityAudioRecordAdd(state.audioData)
      }
      if(state.audioData.voiceId!=0){
        handleVoiceAudioRecordAdd(state.audioData)
      }
      if(state.audioData.questionId!=0){
        handleQuestionAudioRecordAdd(state.audioData)
      }
    },
    //切换音频
    changeAudio(state,e){
      if(e==='before'){//点击按钮切换上一首
        if(state.audioData.index===0){
          ElMessage('当前为第一首')
        }else{
          if(state.audioData.activityId!=0){
            handleActivityAudioRecordUpdate(state.audioData)
          }
          if(state.audioData.voiceId!=0){
            handleAudioRecordUpdate({audioCurrentTime:state.audioData.audioCurrentTime,source:2})
          }
          if(state.audioData.questionId!=0){
            handleAudioRecordUpdate({audioCurrentTime:state.audioData.audioCurrentTime,source:1})
          }

          state.audioData.index--

          if(state.audioData.activityId!=0){
            handleActivityAudioRecordAdd(state.audioData)
          }
          if(state.audioData.voiceId!=0){
            handleVoiceAudioRecordAdd(state.audioData)
          }
          if(state.audioData.questionId!=0){
            handleQuestionAudioRecordAdd(state.audioData)
          }
          
        }
      }else if(e==='next'){//点击按钮切换下一首
        if(state.audioData.index==state.audioData.list.length-1){
          ElMessage('当前为最后一首')
        }else{
          if(state.audioData.activityId!=0){
            handleActivityAudioRecordUpdate(state.audioData)
          }
          if(state.audioData.voiceId!=0){
            handleAudioRecordUpdate({audioCurrentTime:state.audioData.audioCurrentTime,source:2})
          }
          if(state.audioData.questionId!=0){
            handleAudioRecordUpdate({audioCurrentTime:state.audioData.audioCurrentTime,source:1})
          }
          
          state.audioData.index++
          if(state.audioData.activityId!=0){
            handleActivityAudioRecordAdd(state.audioData)
          }
          if(state.audioData.voiceId!=0){
            handleVoiceAudioRecordAdd(state.audioData)
          }
          if(state.audioData.questionId!=0){
            handleQuestionAudioRecordAdd(state.audioData)
          }
        }
      }else if(e==='auto'){//自动播放切换下一首
        if(state.audioData.index==state.audioData.list.length-1){
          // ElMessage('当前为最后一首')
          if(state.audioData.activityId!=0){
            handleActivityAudioRecordUpdate(state.audioData)
          }
          if(state.audioData.voiceId!=0){
            handleAudioRecordUpdate({audioCurrentTime:state.audioData.audioCurrentTime,source:2})
          }
          if(state.audioData.questionId!=0){
            handleAudioRecordUpdate({audioCurrentTime:state.audioData.audioCurrentTime,source:1})
          }
          
          state.audioData.list=[]
          state.audioData.index=0
          state.audioData.activityId=0
          state.audioData.reportId=0
          state.audioData.voiceId=0
          state.audioData.questionId=0
          state.audioData.INS=null
          state.audioData.show=false
          state.audioData.paused=false
        }else{
          if(state.audioData.activityId!=0){
            handleActivityAudioRecordUpdate(state.audioData)
          }
          if(state.audioData.voiceId!=0){
            handleAudioRecordUpdate({audioCurrentTime:state.audioData.audioCurrentTime,source:2})
          }
          if(state.audioData.questionId!=0){
            handleAudioRecordUpdate({audioCurrentTime:state.audioData.audioCurrentTime,source:1})
          }
          
          state.audioData.index++
          if(state.audioData.activityId!=0){
            handleActivityAudioRecordAdd(state.audioData)
          }
          if(state.audioData.voiceId!=0){
            handleVoiceAudioRecordAdd(state.audioData)
          }
          if(state.audioData.questionId!=0){
            handleQuestionAudioRecordAdd(state.audioData)
          }
        }
      }
    },
    // 关闭音频
    closeAudio(state,e){
      if(state.audioData.activityId!=0){
        handleActivityAudioRecordUpdate(state.audioData)
      }
      if(state.audioData.voiceId!=0){
        handleAudioRecordUpdate({audioCurrentTime:state.audioData.audioCurrentTime,source:2})
      }
      if(state.audioData.questionId!=0){
        handleAudioRecordUpdate({audioCurrentTime:state.audioData.audioCurrentTime,source:1})
      }
      
      state.audioData.list=[]
      state.audioData.index=0
      state.audioData.activityId=0
      state.audioData.reportId=0
      state.audioData.voiceId=0
      state.audioData.questionId=0
      state.audioData.INS=null
      state.audioData.show=false
      state.audioData.paused=false
      
    },
    //音频状态切换
    audioStatusChange(state,e){
      if(e=='paused'){
        state.audioData.paused=true
      }else{
        state.audioData.paused=false
        state.audioData.show=true
      }
    },
    //关闭音频弹窗
    closeAudioPop(state){
      if(state.audioData.activityId!=0){
        handleActivityAudioRecordUpdate(state.audioData)
      }
      if(state.audioData.voiceId!=0){
        handleAudioRecordUpdate({audioCurrentTime:state.audioData.audioCurrentTime,source:2})
      }
      if(state.audioData.questionId!=0){
        handleAudioRecordUpdate({audioCurrentTime:state.audioData.audioCurrentTime,source:1})
      }
      
      state.audioData.show=false
    },
    //更新音频当前播放时间
    updateAudioTime(state,e){
      state.audioData.audioCurrentTime=e
    },

    // 更新活动列表某项状态
    updateActivityStatus(state,e){
      state.activityItemStatus.activityId=e.activityId
      state.activityItemStatus.type=e.type
    },

    // 设置面包屑数据
    // 在全局路由钩子中和自定义路由函数中调用
    setBreadCrumb(state,data){
      // console.log('store中设置面包屑',data);
      // 如果是侧边栏 清除路由栈
      if (data.meta.isRoot) {
        let obj = {
          name: data.meta.title,
          path:data.path
        }
        state.breadCrumbList=[obj]
      }else{
        //判断路由栈中是否包含当前路由
        let index = -1
        state.breadCrumbList.forEach((item,e) => {
          if(item.path === data.path){
            index=e
          }
        });
        if (index==-1) {//不存在
          state.breadCrumbList.push({name:data.meta.title,path:data.path})
        }else{
          const arr=state.breadCrumbList.slice(0,index+1)
          state.breadCrumbList=arr
        }
      }

      sessionStorage.setItem('breadcrumb',JSON.stringify(state.breadCrumbList))
    },

    // 修改面包屑
    modifyBreadCrumb(state,data){
      console.log('修改面包屑',data);
      let temarr=state.breadCrumbList
      temarr[temarr.length-1].name=data
      state.breadCrumbList=temarr
      sessionStorage.setItem('breadcrumb',JSON.stringify(state.breadCrumbList))
    }

  },
  actions: {
    // 获取个人信息
    async getUserInfo(context){
      const res=await apiUserInfo()
      if(res.code===200){
        context.commit('setUserInfo',res.data)
      }
    }
  },
  modules: {},
});



//新增活动音频播放记录
function handleActivityAudioRecordAdd(params) {
  apiActivityAudioPlayRecordAdd({
    primary_id:Number(params.list[params.index].activity_voice_id),
    extend_id:Number(params.list[params.index].activityId),
    from_page:window.location.pathname=='/activity/list'?'活动列表':'活动详情'
  }).then(res=>{
    if(res.code===200){
      console.log('新增活动音频播放记录成功');
      lastActivityAudioRecordId=res.data.id
    }
  })
}

//更新活动音频播放记录
function handleActivityAudioRecordUpdate(params) {
  apiActivityAudioPlayRecordUpate({
    id:Number(lastActivityAudioRecordId),
    stop_seconds:parseInt(params.audioCurrentTime)
  }).then(res=>{
    if(res.code===200){
      console.log('更新音频记录成功');
    }
  })
}

// 更新问答社区、语音播报模块 音频播放记录
function handleAudioRecordUpdate(params){
  apiViewLogUpdate({
    id:lastAudioRecordId,
    stop_seconds:parseInt(params.audioCurrentTime),
    source:params.source,
  }).then(res=>{
    console.log('更新播放时长成功');
  })
}

//新增语音播报音频播放记录
function handleVoiceAudioRecordAdd(params){
  apiVoicePlayRecord({
    broadcast_id:params.voiceId
  }).then(res=>{
    console.log('上报音频播放记录');
    lastAudioRecordId=res.data
  })
} 

//新增问答社区语音播放记录
function handleQuestionAudioRecordAdd(params){
  apiCountAudioClick({
    community_question_audio_id:params.list[params.index].id
  }).then(res=>{
    console.log('上报问答音频播放记录');
    lastAudioRecordId=res.data
  })
}