<script setup>
import{
  apiCountAudioClick,
  apiQuestionList,
  apiBarTotal
}from '@/api/question'
import{
  apiGetWechatQRCode
} from '@/api/common'
import { apiApplyPermission } from '@/api/user'
import{ref,reactive} from "vue"
import {useStore} from 'vuex'
import {ElMessageBox} from "element-plus"
import SelfList from '@/components/SelfList.vue'
import {onBeforeRouteLeave,useRouter} from "vue-router"
import moment from 'moment';

const store = useStore()
const router = useRouter()

moment.locale('zh-cn');

const askForm = ref(null)

let question = reactive({
  // 问题列表
  list:[],
  // 顶部导航
  barList:[],
  page_index:1,
  page_size:20,
  // 用于 顶部导航栏
  selectKey:'Wait',
  // 研究员 + 内部人员
  isUserResearcher:false,
  // 问题列表状态
  questionStatus:0,
  //分组列表
  optionList:[],
  // 现在点击的Id 为了正确增加点击数
  currentClickId:0,
  // 是否加载完成
  isFinish:false,
  // 数据是否全部加载完成
  isTotalData:false,
  // 是否在加载中
  isLoading:false,
  noAuthorData:{},
  // 权限状态 0 无权限 1 无权限
  isAuthor:1,
  // 回答弹窗控制
  showReplayDia:false,
  // 小程序码地址
  replayCodeUrl:''
})  

// 顶部导航栏
const getBarList = async ()=>{
  await store.dispatch('getUserInfo')
  question.isUserResearcher = store.state.userInfo.is_inner==1&&store.state.userInfo.is_researcher==1 ? true:false
  question.selectKey = question.isUserResearcher?'Distribute':'Replied'
  // console.log(question.selectKey,question.isUserResearcher);
  const res = await apiBarTotal();
  if(res.code == 403){
      question.isAuthor=0
      question.noAuthorData = {
        type:res.data.type,
        salesName:res.data.name,
        salesMobile:res.data.mobile,
        hasApply:res.data.customer_info.has_apply,
        company:res.data.customer_info.company_name,
        name:res.data.customer_info.name,
        status:res.data.customer_info.status
      }
      question.isFinish=true
  }
  if (res.code !== 200) return;
  const { replied, wait, total,distribute ,stop} = res.data;
  //客户: 已回答 未回答 全部
  const customBar = [
    {
      label: "已回答",
      key: "Replied",
      num: replied,
    },
    {
      label: "未回答",
      key: "Wait",
      num: wait,
    },
    {
      label: "全部",
      key: "Total",
      num: total,
    },
  ];
  //研究员: 待回答 未回答 已回答 全部
  const researBar = [
    {
      label: "待回答",
      key: "Distribute",
      num: distribute,
    },
    {
      label:'未回答',
      key:'Wait',
      num:wait,
    },
    {
      label: "已回答",
      key: "Replied",
      num: replied,
    },
    {
      label: "已终止",
      key: "Stop",
      num: stop,
    },
    {
      label: "全部",
      key: "Total",
      num: total,
    },
  ];
  question.barList = question.isUserResearcher ? researBar : customBar;
  getQuestionList()
}
  // 联系销售
const toContact = ()=>{
  // 请求申请接口
  if(!question.noAuthorData.hasApply){
      toApply('auto')
  }
  window.location.href=`tel:${question.noAuthorData.salesMobile}`
}
// 去申请
const toApply = (type='')=>{
    if(store.state.userInfo.is_bind===0){
        ElMessageBox({
            title:`温馨提示`,
            message:'为了优化您的用户体验，<br>请登录后查看更多信息！',
            dangerouslyUseHTMLString: true,
            center: true,
            confirmButtonText:'去登录',
            confirmButtonClass:'self-elmessage-confirm-btn',
            showCancelButton:true,
            cancelButtonText:'取消',
            cancelButtonClass:'self-elmessage-cancel-btn'
        }).then(res=>{
            wx.miniProgram.reLaunch({url:'/pages/login'})
        }).catch(()=>{})
        return
    }
    if(type=='auto'){
      apiApplyPermission({
        company_name:question.noAuthorData.company,
        real_name:question.noAuthorData.name,
        source:5,
        from_page:'问答社区',
      }).then(res=>{
        question.noAuthorData.hasApply=true
        console.log('自动申请成功');
      })
    }else{
      // 申请成功后将设置 has_apply
      let storeHasApply = store.state.userInfo.has_apply || false
      if(question.noAuthorData.hasApply || storeHasApply){
        const htmlStr = `<p>申请已提交</p><p>请等待销售人员与您联系</p>`;
        ElMessageBox({
            title: "温馨提醒",
            message: htmlStr,
            center: true,
            dangerouslyUseHTMLString: true,
            confirmButtonText: "知道了",
            confirmButtonClass: "self-elmessage-confirm-btn",
        });
        return 
      }
      if(question.noAuthorData.status==='流失'||question.noAuthorData.status==='关闭'){
        apiApplyPermission({
            company_name:question.noAuthorData.company,
            real_name:question.noAuthorData.name,
            source:5,
            from_page:'问答社区',
        }).then(res=>{
            question.noAuthorData.hasApply=true
            const htmlStr = `<p>申请已提交</p><p>请等待销售人员与您联系</p>`;
            ElMessageBox({
                title: "温馨提醒",
                message: htmlStr,
                center: true,
                dangerouslyUseHTMLString: true,
                confirmButtonText: "知道了",
                confirmButtonClass: "self-elmessage-confirm-btn",
            });
        })
      }else{
        // 潜在
        router.push({
            path:'/apply/permission',
            query:{
                source:5,
                fromPage:'问答社区'
            }
        })
      }
  }
}
const changeTopTar = (key)=>{
  question.selectKey = key
  // 重新获取数量
  apiBarTotal().then(res=>{
    if(res.code == 200){
        const { replied, wait, total,distribute,stop } = res.data;
        for (const bar of question.barList) {
          if(bar.label == '已回答'){
            bar.num = replied
          }else if(bar.label == '未回答'){
            bar.num = wait
          }else if(bar.label == '全部'){
            bar.num = total
          }else if(bar.label == '待回答'){
            bar.num = distribute
          }else if(bar.label=='已终止'){
            bar.num=stop
          }
        }
    }
  });
  question.list=[]
  question.page_index=1
  question.isTotalData = false
  question.isLoading = false
  getQuestionList()
}

// 请求回答列表
const getQuestionList=()=>{
  question.isLoading = true
  const reply_status = { Wait: 2, Replied: 3, Total: 0 ,Distribute:4,Stop:5};
  let params = {
    reply_status:reply_status[question.selectKey],
    page_index:question.page_index,
    page_size:question.page_size,
    only_mine:1
  }
  question.questionStatus = params.reply_status
  apiQuestionList(params).then(res=>{
    question.isFinish = true
    if(question.page_index==1){
      document.body.scrollTop=document.documentElement.scrollTop=0
    }
    if(res.code == 200){
      let arr =res.data || []
      question.list = [...question.list,...arr]
      if(arr.length==0 || arr.length<params.page_size){
        question.isTotalData = true
      }
      for (const item of question.list) {
        if(!item.audio_status && item.reply_status==3){
          item.audio_status={
            // 总共的时长
            audioTime:item.audio_list[0].audio_play_seconds*1000,
          }
        }
      }
    }
  })
  .finally(()=>{
    question.isLoading = false
  })
}

const onLoad = ()=>{
  question.page_index++
  getQuestionList()
}

const toDetail = (item)=>{
    // 未回答的不进行操作
  if(question.questionStatus == 2) return 
    //reply_status:1-待分配 2-待回答 3-已回答
    if (question.isUserResearcher && item.reply_status === 2 && item.replier_user_id == store.state.userInfo.user_id) {
    // 是研究员 && 问题是待回答 && 回答者是我
      apiGetWechatQRCode({
        CodePage:'pages-question/answerDetail',
        CodeScene:JSON.stringify({id:item.community_question_id})
        }).then(res=>{
        if(res.code == 200){
          question.showReplayDia = true
          question.replayCodeUrl=res.data
        }
      })
    }
}


//播放音频
const handlePlay=(item)=>{
    if(store.state.audioData.questionId==item.community_question_id){
        if(store.state.audioData.paused){
            store.state.audioData.INS.play()
        }else{
            store.state.audioData.INS.pause()
        }
        return
    }
    const audioItem=item.audio_list[0]
    store.commit('addAudio',{
        list:[{name:item.question_content,url:audioItem.audio_url,time:audioItem.audio_play_seconds,id:audioItem.community_question_audio_id}],
        questionId:item.community_question_id,
        index:0
    })
    // apiCountAudioClick({
    //     community_question_audio_id:audioItem.community_question_audio_id
    // }).then((res)=>{
    //     if(res.code===200){
    //       console.log('音频id为'+audioItem.community_question_audio_id+'点击次数+1')  
    //     }  
    // })
}

getBarList()
</script>

<template>
  <!-- 无权限 -->
  <div class="quesiton-noAuthor" v-if="question.isAuthor == 0 && question.isFinish">
    <img :src="$store.state.globalImgUrls.activityNoAuth" alt="无权限图" class="noAuthor">
    <div class="noAuthor-box">
      您暂无权限查看问答社区
      <template v-if="question.noAuthorData.type=='contact'">
        <div class="noAuthor-item">
          若想查看请联系对口销售
          <div class="noAuthor-sales">{{question.noAuthorData.salesName}}：
          <span @click="toContact">{{question.noAuthorData.salesMobile}}</span>
          </div>
        </div>
      </template>
      <template v-else>
        <div class="noAuthor-item">
          若想查看可以申请开通
          <div class="apply-button" @click="toApply">立即申请</div>
        </div>
      </template>
    </div>
  </div>
  <template v-if="question.isAuthor == 1 && question.isFinish"> 
    <div class="my-questionList-contain">
      <div class="top-tabbar-box">
        <div class="top-tabbar-row" >
          <div v-for="item in question.barList" :key="item.key" @click="changeTopTar(item.key)"
          :class="['top-tabbar-item',item.key == question.selectKey?'tabbar-active':'']">
            <span class="top-tabbar-item-title">
              {{item.label}}<span>({{item.num}})</span>
            </span>
          </div>
        </div>
      </div>
      <SelfList 
        :finished="question.isTotalData" 
        :isEmpty="question.list.length===0&&question.isTotalData"
        :loading="question.isLoading"
        :count="question.list.length"
        @listOnload="onLoad"
      >
        <div class="question-list">
          <div class="question-item" v-for="item in question.list" :key="item.community_question_id">
            <div class="question-info" @click="toDetail(item)">
              <div class="label">
              {{item.variety_tag_name}}
              </div>
              {{item.question_content}}
            </div>
            <div class="question-time">
              提问时间：{{moment(item.create_time).format('YYYY.MM.DD')}}
            </div>
            <div class="question-time" v-if="item.reply_status === 4">终止理由：{{item.stop_reason}}</div>
            <div class="question-audio" v-if="item.reply_status === 3" @click="handlePlay(item)">
              <div :class="['audio-icon',($store.state.audioData.questionId==item.community_question_id)&&!$store.state.audioData.paused?'active':'']"></div>
              <div class="audio-pic">
                <img src="@/assets/audio-waveform1.png">
                <img src="@/assets/audio-waveform2.png">
              </div>
              <div class="audio-time">{{moment((item.audio_status.audioTime)).format('mm:ss')}}</div>
            </div>
          </div>
        </div>
      </SelfList>
    </div>
  </template>
  <!-- 回答弹窗 -->
  <el-dialog 
    title="回答提示" 
    v-model="question.showReplayDia" 
    :close-on-click-modal="false" 
    draggable 
    :width="407"
  >
    <div class="replay-dialog-item">
      <p>PC端暂不支持回答问题，请扫码进入小程序回答</p>
      <img :src="question.replayCodeUrl" />
    </div>
  </el-dialog>
</template>

<style scoped lang="scss">
  .my-questionList-contain{
    // border-left: 1px solid #F2F2F2;
    // border-right: 1px solid #F2F2F2;
    .top-tabbar-box{
      padding: 30px 0 12px;
      background: #FFFFFF;
      // box-shadow: 0px 4px 8px 1px rgba(0, 0, 0, 0.04);
      position: sticky;
      top: 60px;
      width: 100%;
      max-width: 1240px;
      z-index: 10;
      .top-tabbar-row{
        display: flex;
        flex-wrap: wrap;
        .top-tabbar-item{
          min-width: 140px;
          height: 40px;
          box-sizing: border-box;
          background: #F6F6F6;
          border-radius: 20px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 30px;
          cursor: pointer;
          // margin-bottom: 10px;
          .top-tabbar-item-title{
            font-style: normal;
            font-weight: 400;
            font-size: 16px;
            color: #333333;
            span{
              margin-left: 12px;
            }
          }
        }
        @media screen and (max-width: 900px){
            .top-tabbar-item{
                min-width: 90px;
                padding: 0 10px;
                height: 30px;
                line-height: 28px;
                margin-right: 15px;
                font-size: 14px;
                .top-tabbar-item-title{
                    font-size: 14px;
                    span{
                      margin-left: 8px;
                    }
                }
            }
        }
        .tabbar-active{
          border: 1px solid #F3A52F;
          background-color: #FFFBF5;;
          box-shadow: 0px 6px 7px #FFF7EB;
          .top-tabbar-item-title{
            color: #F3A52F;
          }
        }
      }
    }
    .question-noData{
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      margin-top: 50px;
      img{
          height: 360px;
      }
      span{
          margin-top: 30px;
          font-style: normal;
          font-weight: 400;
          font-size: 16px;
          color: #333333;
      }
    }
    .question-list{
      .question-item{
        padding: 32px 30px;
        border: 1px solid #F2F2F2;
        border-top: 1px solid transparent ;
        box-sizing: border-box;
        .question-info{
          display: flex;
          align-items: center;
          font-size: 16px;
          font-weight: 500;
          color: #333333;
          margin-bottom: 16px;
          cursor:pointer;
          .label{
            display: flex;
            align-items: center;
            justify-content: center;
            min-width: 68px;
            background: #333333;
            border-radius: 21px 21px 21px 21px;
            height: 24px;
            padding: 0 12px;
            font-size: 12px;
            font-weight: 500;
            color: #F3A52F;
            margin-right: 14px;
          }
        }
        .question-time{
          font-size: 16px;
          font-weight: 400;
          color: #666666;
          margin-bottom: 24px;
        }
        .question-audio{
          width: 443px;
          height: 46px;
          background-color: #F3A52F;
          border: 1px solid #F3A52F;
          border-radius: 23px;
          display: flex;
          align-items: center;
          padding: 0 54px 0 27px;
          .audio-icon{
            cursor: pointer;
            width: 16px;
            height: 19.5px;
            background-size: cover;
            background-image: url('@/assets/recordplay.png');
            &.active{
              background-image: url('@/assets/recordpause.png');
            }
          }
          .audio-pic{
            margin: 0 27px 0 27px;
          }
          .audio-time{
            font-size: 16px;
            font-weight: 400;
            color: #FFFFFF;
          }
        }
      }
      .bottom-tip-contain{
          .bottom-tip-loadMore{
              margin: 20px auto;
              width: 112px;
              height: 30px;
              background: #FFFFFF;
              border-radius: 20px;
              border: 1px solid #F3A52F;
              color: #F3A52F;
              font-size: 14px;
              text-align: center;
              line-height: 30px;
              cursor: pointer;
          }
          .loading-text{
              margin: 20px auto;
              text-align: center;
              color: #666;
              height: 30px;
          }
          .bottom-tip-noMore{
            text-align: center;
            color: #F3A52F;
          }
      }
    }
  }
  // 无权限
.quesiton-noAuthor{
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 50px;
    img{
        height: 360px;
    }
    .noAuthor-box{
      font-size: 16px;
      font-weight: 400;
      color: #333333;
      text-align: center;
      .noAuthor-item{
        margin-top: 10px;
        .noAuthor-sales{
          margin-top:4px;
          text-align:center;
          span{
            color:#E3B377;
            cursor: pointer;
          }
        }
      }
    }
    .apply-button{
        display: flex;
        align-items: center;
        justify-content: center;
        background: #E6B77D;
        width: 218px;
        border: none;
        height: 40px;
        border-radius: 41px;
        margin-top: 30px;
        font-style: normal;
        font-weight: 500;
        font-size: 16px;
        color: #FFFFFF;
        cursor: pointer;
    }
}
  .replay-dialog-item{
    text-align:center;
    p{
      font-family: 'Noto Sans SC';
      font-style: normal;
      font-weight: 400;
      font-size: 16px;
      color: #000000;
      text-align:center;
    }
    img{
      margin-top:16px;
      margin-bottom:20px;
      height:114px;
    }
  }
</style>
