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

import QuestionComment from '@/components/QuestionComment.vue'

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

moment.locale('zh-cn');

const askForm = ref(null)

let question = reactive({
  // 问题列表
  list:[],
  page_index:1,
  page_size:20,
  //分组列表
  optionList:[],
  // 二级分组列表数据
  secondGroupList:[],
  // 一级分组Id
  selectedGroupId_first :-1,
  // 二级分组Id
  selectedGroupId_second:-1,
  // 现在点击的Id 为了正确增加点击数
  currentClickId:0,
  // 是否加载完成
  isFinish:false,
  // 数据是否全部加载完成
  isTotalData:false,
  // 是否在加载中
  isLoading:false,
  noAuthorData:{},
  // 权限状态 0 无权限 1 无权限
  isAuthor:1,
  // 显示/隐藏 提问弹窗
  showAskDia:false,
  askForm:{
    problemDescription:'',
    varietyId:''
  }
})  

// 获取分组列表
const getOptionList =async ()=>{
  const res = await apiGetTagTree()
  if(res.code===200){
    // 默认显示全部
    const arr=res.data||[]
    question.optionList = arr.map(item=>{
      return {
        tag_id:item.classify_id,
        tag_name:item.classify_name,
        ...item
      }
    })
    question.optionList.unshift({
      classify_id: -1,
      classify_name: "全部",
      tag_id:-1,
      tag_name:"全部",
      sort: 0,
      tags:[]
    })
  //  console.log(question.optionList);
    // 默认第一个一级分组
    // question.selectedGroupId_first = question.optionList[0].classify_id
    // 默认第一个一级分组的第一个二级分组
    // if(!question.optionList[0].tags[0]){
      // question.selectedGroupId_second=-1
    // }else{
    //   question.selectedGroupId_second = question.optionList[0].tags[0].tag_id
    // }
    // question.secondGroupList = []
    // getQuestionList()
  }
}

// 请求已回答列表
const getQuestionList=()=>{
  question.isLoading = true
  let params = {
    variety_tag_id:question.selectedGroupId_second,
    reply_status:3,
    page_index:question.page_index,
    page_size:question.page_size,
  }
  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.audio_status={
            // 总共的时长
            audioTime:item.audio_list[0].audio_play_seconds*1000,
          }
        } 
      }
    }else 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
    }
  })
  .finally(()=>{
    question.isLoading = false
  })
}

getOptionList()
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 onLoad = ()=>{
  question.page_index++
  getQuestionList()
}

// 切换一级分类
const ChangeFirstGroup = (item)=>{
  question.secondGroupList = item.tags
  question.selectedGroupId_first = item.classify_id
  ChangeSecGroup(question.secondGroupList[0])
}
// 切换二级分类
const ChangeSecGroup = (item)=>{
  question.list=[]
  question.page_index=1
  question.isTotalData = false
  question.isLoading = false
  if(!item){
    // 没有二级分类
    question.selectedGroupId_second = -1
  }else{
    question.selectedGroupId_second = item.tag_id
  }
  getQuestionList()
}
// 提问问题
const askQuestion = ()=>{
  if(askForm.value){
    // 重置表单
   askForm.value.resetFields()
  }
  question.showAskDia = true
}


// 提交问题
const submit = (formEl)=>{
  formEl.validate((valid)=>{
    if(valid){
      apipubAsk({
        question_content:question.askForm.problemDescription,
        variety_classify_id:question.askForm.varietyId[0]||0,
        variety_tag_id:question.askForm.varietyId[1]||0,
      }).then(res=>{
        ElMessage({
          type:'success',
          message:'问题提交成功'
        })
        question.showAskDia = false
      })
    }
  })
}

//播放音频
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')  
    //     }  
    // })
}



/* 设置昵称弹窗 */
const showNicklog = ref(false);
const openNickDialog = () => {
  showNicklog.value = true;
}
/* 跳转我的设置 */
const goSettingHandle = () => {
  showNicklog.value = false;
  router.push('/user/setinfo')
}
/* 不在提醒弹窗 */
const setCancelNickHandle = async() => {
  showNicklog.value = false;
  await apiCanelNickTip()
}


// onMounted(()=>{
//   // 自动弹出提问
//   if(route.query.isAutoQuestion){
//     askQuestion()
//   }
// })

onActivated(()=>{
  // 自动弹出提问
  if(route.query.isAutoQuestion){
    askQuestion()
    history.replaceState(null,null,window.location.origin+window.location.pathname)
  }
})

</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="question-list-container">
        <div class="top-nav-box" >
            <div class="first-nav-box">
                <span 
                    v-for="item in question.optionList" 
                    :key="item.classify_id"
                    :class="item.classify_id==question.selectedGroupId_first?'active':''"
                    @click="ChangeFirstGroup(item)"
                >{{item.classify_name}}</span>
                <span class="ask-icon" @click="askQuestion"><img src="@/assets/icon-question-ask.png" /> 我要提问  </span>
            </div>
            <div class="sec-nav-box" v-show="question.secondGroupList.length>0">
                <span
                    :class="['sec-item',item.tag_id==question.selectedGroupId_second?'active':'']"
                    v-for="item in question.secondGroupList"
                    :key="item.tag_id"
                    @click="ChangeSecGroup(item)"
                >{{item.tag_name}}</span>
                <!-- <el-popover
                    :width="560"
                    trigger="click"
                >
                    <template #reference>
                        <img v-if="question.secondGroupList.length>6" style="width:16px;transform: rotate(90deg);cursor: pointer" src="@/assets/icon-more.png" alt="">
                    </template>
                    <template #default>
                        <div class="flex top-nav-filter-box">
                            <div 
                                :class="['item',item.tag_id == question.selectedGroupId_second&&'active']" 
                                v-for="item in question.secondGroupList.slice(6)" 
                                :key="item.tag_id"
                                @click="ChangeSecGroup(item)"
                            >{{item.tag_name}}</div>
                        </div>
                    </template>
                </el-popover> -->
            </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">
              <div class="label">{{item.research_group_second_name}}</div>
              {{item.question_content}}
            </div>
            <div class="question-time">
              提问时间：{{moment(item.create_time).format('YYYY.MM.DD')}}
            </div>
            <div class="question-audio" @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>
            <!-- 点赞/评论 -->
            <QuestionComment :item="item" @open_nick_dia="openNickDialog"/>
          </div>
        </div>
        </SelfList>
        <el-dialog 
          title="提问详情" 
          v-model="question.showAskDia" 
          :close-on-click-modal="false" 
          draggable 
          :width="600" 
        >
          <el-form :model="question.askForm" ref="askForm" class="ask-form">
            <div>
              <div style="margin-bottom:10px">所属品种</div>
              <el-form-item prop="varietyId" :rules="{required:true,message:'请选择所属品种',trigger:'change'}">
                <el-cascader 
                  style="width:100%"
                  v-model="question.askForm.varietyId" 
                  :options="question.optionList.slice(1)"
                  :props="{
                    value:'tag_id',
                    label:'tag_name',
                    children:'tags'
                  }"
                />
              </el-form-item>
            </div>
            <div class="ask-label">
              问题描述
              <el-tooltip content="实际发布的问题会以提炼出的精简内容为准" placement="bottom-start">
                <img src="@/assets/icon-question-askTip.png" alt="提示" />
              </el-tooltip>
            </div>
            <el-form-item prop="problemDescription" :rules="{required:true,message:'提问内容不能为空',trigger:'blur'}">
              <el-input type="textarea" v-model.trim="question.askForm.problemDescription" placeholder="点击输入提问"
              resize="none" maxlength="40" rows="7"></el-input>
            </el-form-item>
            <p>剩余可输入字数：{{40 - question.askForm.problemDescription.length}} 字</p>
            <div class="askForm-button">
              <el-button @click="question.showAskDia = false">取消</el-button>
              <el-button type="warning" @click="submit(askForm)">发布</el-button>
            </div>
          </el-form>
        </el-dialog>
    </div>
  </template>
  
  <div class="nick-dialog-mask" v-if="showNicklog">
    <div class="nick-dialog">
      <div class="header">
        温馨提示
      </div>
      <div class="content">检测到您还未设置头像和昵称，您的留言将发布为匿名，是否立即去设置？</div>
      <div class="bottom">
        <span class="cancel self-elmessage-cancel-btn" @click="setCancelNickHandle">暂时不用</span>
        <span class="confirm self-elmessage-confirm-btn" @click="goSettingHandle">去设置</span>
      </div>
    </div>
  </div>
</template>


<style scoped lang="scss">
.top-nav-filter-box{
    flex-wrap: wrap;
    .item{
        margin: 5px 10px;
        width: 113px;
        height: 40px;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #f6f6f6;
        border-radius: 4px;
        font-size: 16px;
        cursor: pointer;
        :hover{
            color: #fff;
            background-color: #F3A52F;
        }
    }
    .active{
        color: #fff;
        background-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;
    }
}
.question-list-container{
  // border-left: 1px solid #F2F2F2;
  // border-right: 1px solid #F2F2F2;
  .top-nav-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;
    .first-nav-box{
      display:flex;
      flex-wrap: wrap;
      span{
          display: inline-flex;
          align-items:center;
          justify-content:center;
          width: 140px;
          line-height: 40px;
          text-align: center;
          border-radius: 20px;
          background-color: #F6F6F6;
          font-size: 16px;
          margin-right: 30px;
          cursor: pointer;
          margin-bottom:10px;
          box-sizing: border-box;
      }
      .ask-icon{
        display:inline-flex;
        background: #F3A52F;
        border: 1px solid #F3A52F;
        box-shadow: 0px 6px 7px #FFF7EB;
        border-radius: 20px;
        font-style: normal;
        font-weight: 400;
        font-size: 16px;
        color: #FFFFFF;
        img{
          margin-right:6px;
        }
      }
      .active{
          background-color: #FFFBF5;
          box-shadow: 0px 6px 7px 1px #FFF7EB;
          color: #F3A52F;
          border: 1px solid #F3A52F;
      }
      @media screen and (max-width: 1280px){
        span{
              width: 90px;
              height: 30px;
              line-height: 30px;
              margin-right: 15px;
              font-size: 14px;
          }
        .ask-icon{
          font-size: 14px;
          img{
            height: 12px;
          }
        }
      }
    }
    .sec-nav-box{
        margin-top: 30px;
        margin-left: -30px;
        .sec-item{
            color: #666;
            margin-left: 30px;
            cursor: pointer;
            display: inline-block;
        }
        .active{
            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;
        .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;
        }
    }
  }
  .ask-form{
    .ask-label{
      margin-bottom: 12px;
      display: flex;
      align-items: center;
      img{
        margin-left: 6px;
      }
    }
    p{
      text-align: right;
      margin-top: 10px;
      color: #999999;
      font-style: normal;
      font-weight: 400;
      font-size: 16px;
    }
    .askForm-button{
      display: flex;
      align-items: center;
      justify-content: center;
      margin-top: 48px;
      margin-bottom: 10px;
      button{
        box-sizing: border-box;
        background: #F3A52F;
        border-radius: 41px;
        width: 160px;
        height: 40px;
        color: #FFFFFF;
        font-style: normal;
        font-weight: 500;
        font-size: 16px;
        margin-left: 0;
      }
      button:first-child{
        margin-right: 60px;
        border: 1px solid #CCCCCC;
        background-color: transparent;
        color: #333333;
      }
    }
  }
}
// element 样式重写
:deep(.el-dialog__title){
  color: #303133;
  font-family: 'Noto Sans SC';
  font-style: normal;
  font-weight: 400;
  font-size: 18px;
}

.nick-dialog-mask {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  padding: 16px;
  overflow: hidden;
  background: rgba(0, 0, 0, 0.3);
  z-index: 99999;
  .nick-dialog {
    background: #fff;
    border-radius: 4px;
    width: 420px;
    padding: 20px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
    text-align: center;
    .header {
      text-align: center;
      font-size: 18px;
      margin-bottom: 20px;
    }
    .bottom {
      margin-top: 20px;
      display: flex;
      justify-content: center;
      .cancel {
        margin-right: 20px;
      }
      .cancel,.confirm {
        width: 100px;
        height: 40px;
        line-height: 40px;
        border-radius: 4px;
        text-align: center;
        cursor: pointer;
        border: 1px solid #F3A52F;
      }
    }
  }
}

</style>

