<template>
  <view class="answer-page">
    <template v-if="hasAuth">
      <view class="answer-bar">
        <view
          class="bar-item"
          :class="{ active: item.key === selectKey }"
          @click="changeBar(item)"
          v-for="item in barList"
          :key="item.key"
          >{{ item.label + "(" + item.num + ")" }}</view
        >
      </view>
      <view class="answer-list">
        <view class="report-empty-box" v-if="questionList.length == 0">
          <image :src="globalImgUrls.activityNoAuth" mode="widthFix" style="width:100%;"/>
          <view>暂无数据</view>
        </view>
        <view
          class="question-item"
          v-for="item in questionList"
          :key="item.community_question_id"
          @click="toDetail(item)"
        >
          <view class="question-info">
            <view style="flex: 1" class="question-title">
              <text
                class="item-label"
                v-if="(item.reply_status === 3 || item.replier_user_id == userInfo.user_id) && questionStatus!=2"
                >{{ item.variety_tag_name }}</text
              >
              {{ item.question_content }}
            </view>
            <view class="item-answer" v-if="item.reply_status === 3">
              <view class="answer" @click.stop="handlePlayAudioByBg(item)">
                <!-- 改为背景音频播放 -->
                <image class="music-img" :src="item.community_question_id==curVoiceId&&!curAudioPaused?playImgSrc:pauseImgSrc" mode="widthFix"/>
                <text>{{ moment(item.answer.audioTime).format('mm:ss') }}</text>

                <!-- <template v-if="!item.loading">
                  <image
                    class="music-img"
                    :src="item.answer.isplay ? playImgSrc : pauseImgSrc"
                    mode="widthFix"
                  />
                  <template v-if="item.answer.isplay || item.answer.ispause">
                    <text>{{
                      item.answer.audioTime - currentAudioMsg.audioCurrentTime>0?
                      moment(item.answer.audioTime - currentAudioMsg.audioCurrentTime).format('mm:ss')
                      :'00:00'}}
                    </text>
                  </template>
                  <template v-else>
                    <text>{{
                      moment(item.answer.audioTime).format("mm:ss")
                    }}</text>
                  </template>
                </template>
                <template v-else>
                  <image
                    class="load-img"
                    src="../static/loading.png"
                    mode="aspectFill"
                  />
                  <text>{{ moment(item.answer.audioTime).format("mm:ss") }}</text>
                </template> -->
              </view>
            </view>
          </view>
          <text class="item-time">提问时间:{{ item.create_time }}</text>
        </view>
      </view>
    </template>
    <!-- 没有权限 -->
    <template v-else>
      <view class="noAuth-wrap">
				<image class="img" :src="globalImgUrls.activityNoAuth" mode="widthFix"></image>
				<view class="auth-text">您暂无权限查看问答社区</view>
				<view class="auth-text" v-if="noAuthInfo.type==='contact'">若想查看可以联系对口销售</view>
				<view class="auth-text" v-else>若想查看可以申请开通</view>
				<view class="auth-text" v-if="noAuthInfo.type==='contact'">
				{{noAuthInfo.name||''}}:<text @click="handleCallPhone(noAuthInfo.mobile+'')">{{noAuthInfo.mobile||''}}</text>
				</view>
				<view class="apply" @click="handleGoApply" v-else>立即申请</view>
			</view>
    </template>
    <!-- 弹窗 -->
    <van-popup
      :show="pupData.show"
      round
      @close="pupData.show = false"
      closeable
      :close-on-click-overlay="false"
    >
      <view class="global-pup">
        <view class="content">
          <rich-text
            style="flex: none; margin-bottom: 20rpx"
            :nodes="pupData.content"
          ></rich-text>
          <view class="contact" v-if="pupData.type === 'contact'">
            {{ pupData.saleName || "梁娜" }}:<text
              @click="handleCallPhone(pupData.mobile)"
              >{{ pupData.mobile || "123456" }}</text
            >
          </view>
          <view class="apply" v-else-if="pupData.type === 'apply'">
            <view @click="handleApply">立即申请</view>
          </view>
        </view>
      </view>
    </van-popup>

    <!-- 音频悬浮 -->
    <audioBox v-if="showAudioPop"/>
  </view>
</template>
<script>
import mixin from "../mixin/questionMixin";
import { apiBarTotal ,apiSetRead} from "@/api/question.js";
import audioBox from '@/components/audioBox/audioBox.vue'
export default {
  mixins: [mixin],
  components:{
    audioBox
  },
  computed:{
		showAudioPop(){//是否显示音频弹窗
      return this.$store.state.audio.show
    },
    showAudioBigPop(){
      return this.$store.state.audio.showBig
    },
    curVoiceId(){//当前正在播放的音频id
      return this.$store.state.audio.questionId
    },
    curAudioPaused(){//当前音频是否暂停状态
      return this.$store.state.audio.paused
    },
	},
  data() {
    return {
      questionList: [],
      barList: [],
      selectKey: "Wait",
      pauseImgSrc: "../static/question/recordplay.png",
      playImgSrc: "../static/question/recordpause.png",
	  // 列表的状态 0-全部 2-未回答 3-已回答 4-待回答
	  questionStatus:0,
      /* userInfo:{
				is_inner:1,//0:外部客户;1内部员工
				status:'试用',
				is_suspend:0,
				is_researcher:0
			},//mock用户信息 */
    };
  },
  onLoad() {
    /* this.getVisitor();
    this.getBarList();
    this.getQuestionData(); */
  },
  onShow() {
    this.getSelectKey();
    this.getBarList();
    this.getQuestionData();
  },
  onReachBottom() {
    if (this.finished) return;
    this.page++;
    this.getQuestionData();
  },
  onPullDownRefresh() {
    this.resetAudio()
		this.refreshPage()
		setTimeout(() => {
			uni.stopPullDownRefresh()
		}, 1500);
	},
  methods: {
    toDetail(item) {
		// 未回答的不进行操作
		if(this.questionStatus == 2) return 
      //reply_status:1-待分配 2-待回答 3-已回答
      if (this.isUserResearcher && item.reply_status === 2 && item.replier_user_id == this.userInfo.user_id) {
		  // 是研究员 && 问题是待回答 && 回答者是我
        uni.navigateTo({ url: "/pages-question/answerDetail?id=" + item.id });
      }
    },
    //点击bar
    changeBar({ key }) {
		if (key === this.selectKey) return;
		this.selectKey = key;
		this.questionList = [];
		this.page = 1;
		// 重新获取数量
		apiBarTotal().then(res=>{
		  if(res.code == 200){
			  const { replied, wait, total,distribute } = res.data;
			  for (const bar of this.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
				}
			  }
		  }
		});
      this.resetAudio();
      this.getQuestionData();
    },
    getSelectKey() {
      if(this.userInfo.is_inner === 1){
        this.selectKey = 'Distribute'
      }else{
        this.selectKey = 'Replied'
      }
    },
    async getBarList() {
      const res = await apiBarTotal();
      if (res.code !== 200) return;
      const { replied, wait, total,distribute } = 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: "Total",
          num: total,
        },
      ];
      this.barList = this.isUserResearcher ? researBar : customBar;
    },
    async getQuestionData() {
      const reply_status = { Wait: 2, Replied: 3, Total: 0 ,Distribute:4};
	  this.questionStatus = reply_status[this.selectKey]
      await this.getQuestionList(reply_status[this.selectKey],1);
      this.setQuestionsRead()
    },
    async setQuestionsRead(){
      //获取未读的数据,请求未读接口变为已读
      let unReadArr = []
      this.questionList.forEach(item=>{
        /* let isReadKey = this.isUserResearcher?'replier_is_read':'is_read' */
        let isReadKey = item.user_id===this.userInfo.user_id?'replier_is_read':'is_read'
        if(item[isReadKey]===0){
          unReadArr.push(item.community_question_id)
        }
      })
      if(unReadArr.length===0) return
      await apiSetRead({
        question_ids:unReadArr.join(',')
      })
    },
    refreshPage() {
			this.page = 1
			this.selectId = -1
			this.questionList = []
			this.finished = false
			this.getQuestionData()
    },
  },
};
</script>
<style lang="scss" scoped>
.answer-page {
  padding: 30rpx;
  .answer-bar {
    display: flex;
    /* justify-content: space-between; */
    overflow-x: scroll;
    &::-webkit-scrollbar{
        width: 0;
        display: none;
    }
    .bar-item {
      width: 206rpx;
      min-width: 206rpx;
      color: #666666;
      background-color: #f5f5f5;
      height: 70rpx;
      line-height: 70rpx;
      text-align: center;
      margin-right: 20rpx;
      &.active {
        background-color: #fdf8f2;
        color: #e3b377;
      }
    }
  }
  .answer-list {
    margin-top: 20rpx;
  }
  .global-pup {
    .content {
      padding: 90rpx 34rpx;
      flex-direction: column;
      .contact {
        text {
          margin-left: 15rpx;
          color: #e6b77d;
        }
      }
      .apply {
        margin-top: 40rpx;
        width: 390rpx;
        height: 80rpx;
        background-color: #e6b77d;
        color: #ffffff;
        text-align: center;
        line-height: 80rpx;
        border-radius: 40rpx;
      }
    }
  }
}
</style>