/* 问答社区 公共逻辑 */
import {
    apiQuestionList
} from '@/api/question'
import { apiApplyPermission, apiUserInfo } from '@/api/user'
import {apiCountAudioClick} from '@/api/question'
const moment = require('@/utils/moment-with-locales.min')
moment.locale('zh-cn');
export default {
    data() {
        return {
            moment: moment,
            innerAudio: null, //该页面的音频
            currentAudioMsg: {
                id: '',
                audioCurrentTime: 0, //音频播放实时时间
                audioTime: 0, //当前音频时间
                audioCurrentUrl: '', //当前音频地址
            }, //当前正在播放音频的一些信息
            pupData: {
                show: false,
                content: '', //弹窗html字符串
                type: '',
                mobile: "",
                customer_info: {}
            },
            page: 1,
            pageSize: 20,
            finished: false,
            selectId: -1,
            noAuth:['潜在','流失','冻结'],
            hasAuth:true,//是否有该页面权限
            noAuthInfo:null,/* {
                name:'梁娜',
                mobile:123456,
                type:'apply',//apply||contact||''
                customer_info:{
                    company_name:'',
                    name:'客户a',
                    mobile:'',
                    status:'冻结',
                    is_suspend:0,
                    has_apply:false
                }
            }, *///无权限用户信息
		    updateHasApply:false
        }
    },
    computed:{
        userAuth(){
			//暂停试用
			if(this.userInfo.status==='试用'&&this.userInfo.is_suspend===1){
				return false
			}
			//潜在流失冻结
			if(this.noAuth.includes(this.userInfo.status)){
				return false
			}
			//有权限的
			return true
		},
        isUserResearcher(){
			//内部人员+研究员
			if(this.userInfo.is_inner===1&&this.userInfo.is_researcher===1){
				return true	
			}
			return false
		}
    },
    onLoad() {
        //this.initAudio()
    },
    onShow(){
        this.initAudio()
    },
    onHide(){
        this.resetAudio()
        this.destroyAudio()
    },
    onUnload() {
        //this.destroyAudio()
    },
    methods: {
        //初始化audio
        initAudio() {
            this.innerAudio = uni.createInnerAudioContext()
            this.handleAudioFun()
        },
        //销毁audio
        destroyAudio() {
            if (this.innerAudio) {
                this.innerAudio.destroy()
            }
        },
        //重置音频播放信息
        resetAudio(){
            this.innerAudio.pause();
            this.questionList.map((i) => {
                if(i.id===this.currentAudioMsg.id){
                    i.answer.isplay = false
                    i.answer.ispause = false
                }
            })
            this.changeCurrentAudio({
                id: '',
                answer: {
                    source: '',
                    audioTime: 0
                }
            })
        },
        //audio事件
        handleAudioFun() {
            this.innerAudio.onPlay(() => {
                console.log('开始了')
                this.questionList.map(i => {
                    if (i.id === this.currentAudioMsg.id) {
                        i.loading = false
                    }
                })
            })
            this.innerAudio.onTimeUpdate(() => {
                //console.log('时间更新')
                this.currentAudioMsg.audioCurrentTime = this.innerAudio.currentTime * 1000
            })
            this.innerAudio.onPause(() => {
                console.log("暂停");
            })
            this.innerAudio.onEnded(() => {
                console.log('音频播放完毕')
                const {
                    id
                } = this.currentAudioMsg
                this.questionList.map(i => {
                    if (i.id === id) {
                        i.answer.isplay = false
                        i.answer.ispause = false
                    }
                })
                this.changeCurrentAudio({
                    id: '',
                    answer: {
                        source: '',
                        audioTime: 0
                    }
                })
            })
        },
        //播放音频
        handleAudioPlay() {
            this.innerAudio.onCanplay(() => {
                this.innerAudio.play()
            })
        },
        //切换当前播放音频
        changeCurrentAudio(item) {
            const {
                id
            } = item
            const {
                source,
                audioTime
            } = item.answer
            this.currentAudioMsg = {
                id: id,
                audioCurrentTime: 0 * 1000,
                audioTime: audioTime,
                audioCurrentUrl: source
            }
            this.questionList.map(i => {
                if (i.id === item.id) {
                    i.loading = true
                }
            })
        },
        //获取问答列表:status(问题状态) only_mine(只看我的)
        async getQuestionList(status,onlyMine=0) {
            let questionData = []
            const res = await apiQuestionList({
                page_index: this.page,
                page_size: this.pageSize,
                /* chart_permission_id: this.selectId === -1 ? '' : this.selectId, */
                variety_tag_id: this.selectId === -1 ? '' : this.selectId,
                reply_status: status,
                only_mine:onlyMine
            })
            if (res.code === 200) {
                if (res.data) {
                    questionData = res.data
                } else {
                    this.finished = true
                }
            }
            //没权限
            if(res.code ===403){
                this.hasAuth = false
                this.noAuthInfo = res.data
            }
            let tempArr = []
            questionData.forEach(item => {
                let temp = item
                let audio_url = '',
                    audio_play_seconds = 0;
                //问题状态为已回答,取audio_list第一项为音频
                if (item.reply_status === 3) {
                    audio_url = item.audio_list[0].audio_url
                    audio_play_seconds = item.audio_list[0].audio_play_seconds
                }
                //问题状态不为已回答,取默认值
                temp.answer = {
                    source: audio_url,
                    audioTime: parseInt(audio_play_seconds) * 1000,
                    isplay: false,
                    ispause: false
                }
                temp.id = item.community_question_id
                temp.loading = false
                tempArr.push(temp)
            })
            if (this.page > 1) {
                this.questionList = this.questionList.concat(tempArr)
            } else {
                this.questionList = tempArr
            }

        },
        //点击某条音频
        handleAudio(item) {
            //如果没有权限,弹窗并return
           /*  if (!item.auth_ok) {
            	this.initPupData(item)
            	return
            } */
            const {
                source,
                isplay
            } = item.answer
            if (isplay) {
                //说明是播放->暂停
                this.innerAudio.pause()
            } else if (item.id === this.currentAudioMsg.id) {
                //说明是暂停->播放
                this.innerAudio.play()
            } else {
                //console.log('aaa', source, this.innerAudio.src)
                if(!source) return
                //说明是第一次播放或点击其他播放项
                this.changeCurrentAudio(item)
                this.innerAudio.stop()
                this.innerAudio.src = source
                /* this.innerAudio.play() */
                this.handleAudioPlay()
                //音频点击次数+1
                const audio_id = item.audio_list[0].community_question_audio_id
                apiCountAudioClick({
                    community_question_audio_id:audio_id,
                    source_agent:1
                }).then((res)=>{
                    if(res.code===200){
                      console.log('音频id为'+audio_id+'点击次数+1')  
                    }
                    
                })
            }
            this.questionList.map((i) => {
                if (i.id === item.id) {
                    if (i.answer.isplay) {
                        i.answer.ispause = true
                    }
                    i.answer.isplay = !i.answer.isplay
                } else {
                    i.answer.isplay = false
                    i.answer.ispause = false
                    i.loading = false
                }
            })
        },
        //初始化无权限弹窗
        initPupData(item) {
            let str = '<p>您暂无权限查看语音回复</p>'
            const {
                type,
                mobile,
                name,
                customer_info
            } = item.permission_info
            if (type === 'apply') {
                this.pupData.type = 'apply'
                str += '<p>若想查看可以申请开通</p>'
            }
            if (type === 'contact') {
                this.pupData.mobile = mobile + ''
                this.pupData.saleName = name
                this.pupData.type = 'contact'
                str += `<p>若想查看可以联系对口销售</p>`
            }
            this.pupData.customer_info = customer_info
            this.pupData.content = str
            this.pupData.show = true
        },
        //拨号
        async handleCallPhone(tel) {
            uni.makePhoneCall({
                phoneNumber: tel ? tel : ' ',
                success: () => {
                    this.pupData.show = false
                }
            });
            if(!this.noAuthInfo.customer_info.has_apply && !this.updateHasApply){
                // 请求申请
                const res = await apiApplyPermission({
                    company_name: this.noAuthInfo.customer_info.company_name,
                    real_name: this.noAuthInfo.customer_info.name,
                    source: 5,
                    from_page: '问答社区'
                })
                if (res.code === 200) {
                    this.updateHasApply = true
                    console.log('自动申请成功');
                }
            }
        },
        //弹窗申请权限
        async handleApply() {
            if (this.pupData.customer_info.has_apply) { //已经申请过
                this.pupData.content = `<p>您已提交过申请，请耐心等待</p>`
                this.pupData.type = ''
            } else {
                if (!this.pupData.customer_info.status || this.pupData.customer_info.status != '流失') {
                    uni.navigateTo({
                        url: "/pages-applyPermission/applyPermission?source=5&form_page=问答社区"
                    })
                } else { //主动调一次申请权限接口 
                    const res = await apiApplyPermission({
                        company_name: this.pupData.customer_info.company_name,
                        real_name: this.pupData.customer_info.name,
                        source: 5,
                        from_page: '问答社区'
                    })
                    if (res.code === 200) {
                        //重新获取页面数据
                        const pages = getCurrentPages();
                        const page = pages[pages.length - 1];
                     /*    page.onLoad(); */
                        page.onShow();
                    }
                    this.pupData.content = `<p>申请已提交</p><p>请等待销售人员与您联系</p>`
                    this.pupData.type = ''

                }
            }
        },
        //申请权限
        async handleGoApply(){
            await this.checkUserIsBind()
            const {customer_info} = this.noAuthInfo
            if (customer_info.has_apply) { //已经申请过
                uni.showToast({
                  title:'您已提交过申请，请耐心等待',
                  icon:'none'
                })
            } else {
                if (!customer_info.status || customer_info.status != '流失') {
                    uni.navigateTo({
                        url: "/pages-applyPermission/applyPermission?source=5&form_page=问答社区"
                    })
                } else { //主动调一次申请权限接口 
                    const res = await apiApplyPermission({
                        company_name: customer_info.company_name,
                        real_name: customer_info.name,
                        source: 5,
                        from_page: '问答社区'
                    })
                    if (res.code === 200) {
                        uni.showToast({
                            title:'您已提交过申请，请耐心等待',
                            icon:'none'
                        })
                        const pages = getCurrentPages();
                        const page = pages[pages.length - 1];
                        page.onShow();
                    }
                }
            }
        },

        //点击播放音频
		handlePlayAudioByBg(item){
			const audioItem=item.audio_list[0]
			if(this.$store.state.audio.questionId==item.community_question_id){
                if(this.globalBgMusic.paused){
                    this.globalBgMusic.play()
                }else{
                    this.globalBgMusic.pause()
                }
            }else{
                const list=[{url:audioItem.audio_url,time:audioItem.audio_play_seconds,title:item.question_content}]
                this.$store.commit('audio/addAudio',{
                    list:list,
                    questionId:item.community_question_id
                })
                apiCountAudioClick({
                    community_question_audio_id:audioItem.community_question_audio_id,
                    source_agent:1
                }).then((res)=>{
                    if(res.code===200){
                      console.log('音频id为'+audioItem.community_question_audio_id+'点击次数+1')  
                      this.$store.commit('audio/addAudioRecordId',{recordId:res.data,source:1})
                    }
                })
            }
		}
    }
}