<template>
   <view class="question-detail-page">
      <van-sticky v-if="!id">
         <view class="" @click="goSearch">
            <van-search :value="key_word" shape="round" :placeholder="type==='question' ? '提问内容' : '评论内容'" disabled />
  
         </view>
         <van-tabs id="tabs" :active="status" title-active-color="#3385FF" color="#3385FF" @change="typeChange" >
            <template v-if="tabs.length">
               <van-tab :title="item.label" :name="item.key" v-for="item in tabs" :key="item.key"></van-tab>
            </template>
         </van-tabs>
      </van-sticky>
      
      <!-- list -->
      <view class="list-cont">
        <question-item 
            v-for="item in list"
            :key="item.CommunityQuestionId"
            :item="item"
            :status="status"
            :type="type"
            :select_users="select_users"
            @open_picker="openPicker"
            @del="delHandle"
            @edit="editHandle"
            @hot="setHotHandle"
         />
      </view>
      
      <van-empty description="暂无数据" :image="require('@/static/empty.png')" v-if="finished&&list.length===0"/>
      
      <!-- 研究员选择弹窗 -->
      <pickerThreeColumn 
         :data="researcherList" 
         v-if="researcherList.length" 
         :visible="isShowrsPicker"
         :default_picker_val="default_picker_val"
         @cancel="cancelPicker"
         @ensure="confirmPicker"
      />
      
      <!-- 编辑框 -->
      <van-popup :show="showEditPicker" bind:close="onClose">
         <view class="edit-cont">
            <view class="editor-wrapper">
               <textarea
                  v-model="edit_item.QuestionContent" 
                  placeholder="请输入提问内容"
                  :show-confirm-bar="false"
                  :cursor-spacing="20"
                  class="editor"
               />
            </view>
            <view style="height:40rpx;padding:10rpx 34rpx;font-size:24rpx;color:#999">
               <text style="float:left">注：限制28个字</text>
               <text style="float:right">超出字数：<text style="color:#ff0000">{{edit_item.QuestionContent.length>28?edit_item.QuestionContent.length-28:0}}</text>字</text>
            </view>
            <view class="edit-bottom">
               <view class="cancel-color" @click="showEditPicker=false">取消</view>
               <view class="blue-color" @click="editQuestionHandle">确定</view>
            </view>
         </view>
      </van-popup>
   </view>
</template>

<script>
   import * as $api from '@/api/question/index.js';
   import questionItem from '../components/questionItem.vue'
   import pickerThreeColumn from '../components/pickerThreeColumn.vue'
   export default {
      data() {
         return {
            id: '',//消息列表进入带的id
            type:'',//页面类型 question  comment
            key_word: '',
            status: 1,
            tabs: [],
            page_no: 1,
            pageSize: 10,
            list:[],
            finished: false,
            researcherList: [],
            
            isShowrsPicker: false,
            select_item: {},
            default_picker_val:[],
            
            showEditPicker: false,//编辑弹窗
            edit_item:{}
         };
      },
      components: { questionItem,pickerThreeColumn },
      onLoad(options) {
         this.initState(options)
         
         // 搜索返回 
         uni.$on('questionListUpdate',({key_word})=>{
            
            this.key_word = key_word;
            this.tabs = [];
            this.status = -1;
            this.page_no = 1;
            this.getList()
           
         })
      },
      onUnload() {
         uni.$off('questionListUpdate')
      },
      onShow() {
         if(!this.id){
            this.$nextTick(()=>{
               this.selectComponent('#tabs').resize();// 解决初始渲染 vant tab 底部条
            })
         }
         
      },
      onPullDownRefresh() {
      	this.page_no=1
      	this.finished=false
      	this.list=[]
      	this.getList()
      	setTimeout(()=>{
      		uni.stopPullDownRefresh()
      	},1500)
      },
      onReachBottom() {
      	if(this.finished) return
      	this.page_no++
      	this.getList()
      },
      methods: {
         /*  待分配研究员列表 */
         async getResearcherList() {
            const { code,data } = await $api.apiRsList();
            if(code !== 200) return
            data && data.forEach(_ => {
               _.children = _.tags || [];
               _.label = _.classify_name;
               _.tags.forEach(_sub => {
                  _sub.children = _sub.researcher_list;
                  _sub.label = _sub.tag_name
                  _sub.researcher_list.forEach(_ths => {
                     _ths.label = _ths.admin_name
                  })
               })
            })
            this.researcherList = data;
         },
         
         async getList() {
            const params = {
               Keyword: this.key_word || '',
               CurrentIndex: this.page_no,
               PageSize: this.pageSize
            }
           const {code,data} = this.type==='question' 
               ? await $api.apiQuestionList({...params,ReplyStatus: this.status,
               CommunityQuestionId: Number(this.id) || '',})
               : await $api.apiCommentList({...params,HotStatus: this.status,CommunityQuestionCommentId: Number(this.id)});
           
           if(code !== 200) return
           this.finished = this.page_no >= data.Paging.Pages;
           
           this.list = this.page_no === 1 ? (data.List || []) : this.list.concat(data.List);
         },
         
         /* 改变类型 */
         typeChange({ detail }) {
            this.status=detail.name
            this.page_no=1
            this.list=[]
            this.getList()
         },
         
          /* 搜索 */
         goSearch() {
            uni.navigateTo({
               url: `/pages-approve/search/index?type=question`,
            })
         },
         
         
         // 删除
         delHandle(id) {
            let index = this.type === 'question' ? this.list.findIndex(_ => _.CommunityQuestionId === id) : this.list.findIndex(_ => _.CommunityQuestionCommentId === id);
            this.list.splice(index,1)
         },
         
         /* 设置精选*/
         setHotHandle(id) {
            let index = this.list.findIndex(_ => _.CommunityQuestionCommentId === id);
            if(this.status === -1) {
               this.list[index].IsHot = this.list[index].IsHot ? 0 : 1
            }else {
               this.list.splice(index,1)
            }
         },
         
         /* 修改问题 */
         editHandle(item) {
            this.edit_item =  JSON.parse(JSON.stringify(item));
            this.showEditPicker = true;
         },
         
         /* 修改问题*/
         async editQuestionHandle() {
            
            const { CommunityQuestionId,QuestionContent } = this.edit_item;
            if(QuestionContent.length > 28)  return uni.showToast({
               title: '字数超限，请修改问题后重试',
               icon: 'none'
            })
            
            const {code,data} = await $api.apiEditQuestion({
               QuestionId: CommunityQuestionId,
               QuestionContent
            })
            
            if( code !== 200) return
            uni.showToast({title: '修改成功'})
            this.showEditPicker = false;
            
            let obj = this.list.find(_ => _.CommunityQuestionId === CommunityQuestionId);
            obj.QuestionContent = QuestionContent;
            console.log(obj)
         },
         
         // 打开弹窗
         openPicker(id) {
            this.select_item =  this.list.find(_ => _.CommunityQuestionId === id);
            this.default_picker_val =  this.select_item.select_users ? this.select_item.select_users.val : [];
            this.isShowrsPicker = true;
         },
         
         cancelPicker() {
            this.isShowrsPicker = false;
         },
         
         /* 确认*/
         confirmPicker(val) {
            console.log(val)
            let data = this.researcherList;
            if(data[val[0]].children.length && data[val[0]].children[val[1]].children.length) {
               let select_users = {
                  val,
                  first_id: data[val[0]].tag_id,
                  second_id: data[val[0]].children[val[1]].tag_id,
                  user_id: data[val[0]].children[val[1]].children[val[2]].admin_id,
                  user_name: data[val[0]].children[val[1]].children[val[2]].admin_name
               }
               
               if(this.select_item.select_users) this.select_item.select_users = select_users
                  else this.$set(this.select_item,'select_users',select_users)
            }
         },
         
         /* init*/
         initState({ type,id }) {
            const titleMap = {
               'question': '分配提问',
               'comment': '评论管理'
            }
            const tabMap = {
               'question': [
                  {
                     label: '待分配',
                     key: 1
                  },
                  {
                     label: '待回答',
                     key: 2
                  },
                  {
                     label: '已回答',
                     key: 3
                  },
                  
               ],
               'comment': [
                  {
                     label: '全部',
                     key: -1
                  },
                  {
                     label: '已精选',
                     key: 1
                  },
                  {
                     label: '未精选',
                     key: 0
                  },
                  
               ]
            }
            
            this.type = type;
            this.id = id;
            this.tabs = id ? [] : tabMap[type];
            this.status = this.tabs.length ? this.tabs[0].key : -1;
            type === 'question' && this.getResearcherList();
            this.getList();
            
            uni.setNavigationBarTitle({
            	title: titleMap[type]
            });
         }
      }
   }
</script>

<style lang="scss" scoped>
.blue-color {
   color: #3385FF;
}
.cancel-color {
   color: #999;
}
.list-cont {
   padding: 40rpx 20rpx;
}
.edit-cont {
   .editor-wrapper {
      padding: 40rpx 34rpx 0;
   }
   .editor {
      height: 300rpx;
      border: 1px solid #EAEAEA;
      border-radius: 4px;
      padding: 20rpx;
      
   }
   .edit-bottom {
      border-top: 1px solid #EAEAEA;
      display: flex;
      align-items: center;
      margin-top: 30rpx;
      view {
         flex: 1;
         padding: 30rpx 0;
         text-align: center;
         font-size: 30rpx;
         border-right: 1px solid #EAEAEA;
         &:last-child {
            border: none;
         }
      }
   }
}
</style>
