<template>
  <div class="interact-bar">
    <div v-show="theme==2" class="bottom-btn">
      <el-button class="btn fen-xiang" @click="addShare()"><img src="@/assets/images/icon/fenxiang@2x.png" alt="" srcset="">{{data.shares}}</el-button>
      <el-button class="btn dian-zan" @click="addPraise()"><img src="@/assets/images/icon/dianzan@2x.png" alt="" srcset="">{{data.praises}}</el-button>
      <el-button class="btn shou-cang" @click="addFavorite()"><img src="@/assets/images/icon/shoucang@2x.png" alt="" srcset="">{{data.favorites}}</el-button>
    </div>
    <div v-show="theme==1" class="interact-bar-btns" :style="{'justify-content':showAlign}">
      <div v-if="answers" @click="addAnswers()" :style="`min-width: ${nodeWidth};`" class="interact-bar-btn" :class="{cursor:!readonly || clickAnswer}">
        <el-tooltip  effect="light" content="回答" placement="left">
          <!-- <svg-icon style="margin-right: 0;"  icon-class="comment"></svg-icon> -->
         <img style="width:16px;height:16px;vertical-align: middle;" :src="require('@/assets/images/icon/answers.png')">
        </el-tooltip>
        <span class="interact-bar-value"> {{ data.answers}}</span>
      </div>
      <div v-if="comments" class="interact-bar-btn" :style="`min-width: ${nodeWidth};`" :class="{cursor:!readonly}">
        <el-tooltip  effect="light" content="评论" placement="left">
          <svg-icon style="margin-right: 0;font-size: 16px;" icon-class="comment"></svg-icon>
        </el-tooltip>
        <span class="interact-bar-value"> {{data.comments}}</span>
      </div>
      <div v-if="shares" @click="addShare()" :style="`min-width: ${nodeWidth};`" class="interact-bar-btn" :class="{cursor:!readonly}">
        <el-tooltip effect="light" content="分享" placement="top">
          <svg-icon icon-class="share" style="margin-right: 0;font-size: 16px;"></svg-icon>
        </el-tooltip>
        <span class="interact-bar-value"> {{data.shares}}</span>
      </div>
      <div v-if="praises" @click="addPraise()" :style="`min-width: ${nodeWidth};`" class="interact-bar-btn" :class="{cursor:!readonly}">
        <el-tooltip effect="light" content="点赞" placement="top">
          <svg-icon style="margin-right: 0;font-size: 20px;" :icon-class="isPraise?'praised':'like'"></svg-icon>
        </el-tooltip>
        <span class="interact-bar-value"> {{ data.praises}}</span>
      </div>

      <div v-if="favorites"  @click="addFavorite()" :style="`min-width: ${nodeWidth};`" class="interact-bar-btn" :class="{cursor:!readonly}">
        <el-tooltip effect="light" content="收藏" placement="top">
          <svg-icon style="font-size: 16px;margin-right: 0;" :icon-class="isFavorite?'collected':'collection'"></svg-icon>
          <!-- <svg-icon :icon-class="isFavorite?'collected':'dropdown_collected'"></svg-icon> -->
          <!-- dropdown_collected -->
        </el-tooltip>
        <span class="interact-bar-value"> {{ data.favorites}}</span>
      </div>

      <div v-if="views" style="cursor: default;" :style="`min-width: ${nodeWidth};`" class="interact-bar-btn" :class="{cursor:!readonly}">
        <el-tooltip effect="light" content="浏览量" placement="top">
          <svg-icon style="margin-right: 0;font-size: 16px;" icon-class="browse"></svg-icon>
        </el-tooltip>
        <span class="interact-bar-value"> {{ data.views}}</span>
      </div>
    </div>
    <el-dialog title="分享" :visible.sync="shareShow" :close-on-click-modal="false" width="500px" custom-class="g-dialog">
        <div style="height: 200px;padding-right: 30px;">
            <el-form  label-width="100px"  @submit.native.prevent >
              <el-form-item label="姓名或工号">
                <el-input v-model="shareInfo.name" maxlength="10" placeholder="您要分享的人的姓名查询" @keyup.enter.native="keyupEnter">
                  <el-button @click="findUser" slot="append" icon="el-icon-search">搜索</el-button>
                </el-input>
              </el-form-item>
            </el-form>
            <div style="padding: 0px 20px;">
                <el-checkbox-group v-model="shareUsers">
                   <el-checkbox v-for="(u,uidx) in shareInfo.list" :key="uidx" :label="u.aid">{{u.name+'('+u.code+')'}}</el-checkbox>
                </el-checkbox-group>
            </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="shareShow= false">取 消</el-button>
          <el-button @click="submitShare" type="primary" >提交分享</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
  import apiPraises from '@/api/modules/praises.js'
  import apiShares from '@/api/modules/shares.js'
  import apiFavorites from '@/api/modules/favorites.js'
  import apiUser from '@/api/system/user.js'
  import apiMessage from '@/api/system/message.js'
  import { mapGetters } from 'vuex';
export default {
  props: {
    data:{
      type:Object,
      default(){
        return{
            id:'',
            answers:0,
            favorites:0,
            comments:0,
            shares:0,
            praises:0,
            views:0,
          }
      }
    },
    nodeWidth:{
      type:String,
      default:'40px'
    },
    readonly:{
      type:Boolean,
      default:false
    },
    align:{
      type:String,
      default:'right'
    },
    answers:{
      type:Boolean,
      default:false
    },
    clickAnswer:{
      type:Boolean,
      default:false
    },
    comments:{
      type:Boolean,
      default:true
    },
    favorites:{
      type:Boolean,
      default:true
    },
    shares:{
      type:Boolean,
      default:true
    },
    praises:{
      type:Boolean,
      default:true
    },
    views:{
      type:Boolean,
      default:true
    },
    type:{
      type:Number,
      default:0
    },
    theme:{
      type:Number,
      default:1
    }
  },
  data(){
    return {
      loading:false,
      isPraise:false,
      isFavorite:false,
      shareShow:false,
      shareUsers:[],
      shareInfo:{
        name:'',
        load:false,
        list:[]
      }
    }
  },

  computed:{
      ...mapGetters(['userInfo']),

    showAlign(){
      if(this.align=='left'){
        return 'flex-start';
      }else if(this.align=='right'){
        return 'flex-end';
      }
    }
  },
  watch:{
    data(newVal,oldVal){
      // console.log(newVal,'newVal');
      // if(newVal && newVal.id!=''){
      //    this.checkHas();
      // }
    }
  },
  created(){

  },
  mounted() {
    if(this.data && this.data.id && !this.readonly){
       this.checkHas();
    }
  },
  methods:{
    addAnswers() {
      this.$emit('addAnswers');
    },
    messageSave(refId,title,sendName,acceptName,acceptId,typeText){
        // let typeText
        // if(type=='share'){
        //   typeText='分享给我'
        // }
        // if(type=='favorite'){
        //   typeText='收藏了我发布的'
        // }
        // if(type=='praise'){
        //   typeText='点赞了我的'
        // }

        let content;
        let conType;
        if(this.type==1){
          content='课程';
          conType = this.data.type;
        }
        if(this.type==2){
          content='文章'
        }
        if(this.type==3){
          content='案例'
        }
        if(this.type==4){
          content='问答'
        }
        if(this.type==5){
          content='回答'
        }
      content=sendName+typeText+content+'-'+title
      let message={
        content,
        refId,
        refType:this.type,
        sendName,
        acceptName,
        acceptId,
        title:'系统消息',
        sendType:1,
        conType,
      }
      apiMessage.save(message).then(res=>{
        if(res.status==200){

        }
      })
    },
    checkHas(){
      if(this.type>0 && !this.readonly && this.data.id){
        if(this.favorites){
          apiFavorites.has(this.type,this.data.id).then(rs=>{
            if(rs.status==200 && rs.result){
              this.isFavorite=true;
            }else{
              this.isFavorite=false;
            }
          })
        }
        if(this.praises){
          apiPraises.has(this.type,this.data.id).then(rs=>{
            if(rs.status==200 && rs.result){
              this.isPraise=true;
            }else{
              this.isPraise=false;
            }
          });
        }
      }
    },
    addShare(){
      if(this.readonly){
        return
      }
      this.shareShow=true;
    },
    addPraise(){

     if(this.type==0){
       console.log('未设置type值,1表课程,2表文章，3表案例，4表问答')
       return;
      }
      //需要判断是否已点赞，已点赞的不再加
      if(!this.readonly){
        let postData={
          objType:this.type,
          objId:this.data.id,
          title:'',

        }
        if(this.type==1){
          postData.title=this.data.name;
        }else{
          postData.title=this.data.title;
        }
        if(this.loading) {
          return;
        }
        this.loading=true;
        if(this.isPraise) {// 已经点赞，取消点赞
          apiPraises.remove(this.type,this.data.id).then(res=>{
             this.loading = false;
            if(res.status==200){
              if(res.result){
                this.data.praises--;
              }
              this.isPraise=false;
              this.$message({message:'取消点赞',type:'success'})
            }else{
              console.log('取消失败：'+res.message);
            }
          })
        } else {
          apiPraises.save(postData).then(res=>{
            this.loading = false;
            if(res.status==200){
              if(res.result){
                this.data.praises++;
              }
              if(this.type!=1&&this.type!=5){
                this.messageSave(this.data.id,this.data.title,this.userInfo.name,this.data.sysCreateBy,this.data.sysCreateAid,'点赞了我的');
              }
              // if(this.type==5){
              //   this.messageSave(this.data.id,this.data.content,this.userInfo.name,this.data.sysCreateBy,this.data.sysCreateAid,'评论了我的');
              // }
              this.isPraise=true;
              this.$message({message:'点赞成功',type:'success'})
            }else{
              console.log('点赞失败：'+res.message);
            }
          })
        }

      }
    },
    addFavorite(){

      if(this.readonly){
        return
      }
      if(this.type==0){
        console.log('未设置type值,1表课程,2表文章，3表案例，4表问答')
        return;
       }
      //需要判断是否已点赞，已点赞的不再加
      let postData={
        objType:this.type,
        objId:this.data.id,
        title:'',
      }
      if(this.loading) {
          return;
        }
        this.loading=true;
      if(this.type==1){
        postData.title=this.data.name;
      }else{
        postData.title=this.data.title;
      }
      if(this.isFavorite) {// 已经收藏，再次点击取消收藏
        apiFavorites.remove(this.type,this.data.id).then(res=>{
          this.loading=false;
        if(res.status==200){
          this.isFavorite=false;
          if(res.result){
            this.data.favorites--;
          }
          this.$message({message:'已取消收藏',type:'success'});
          //this.$emit('addFavorite',res.result);//添加收藏,如果是true代表添加成功，false代表已存在
        }else{
          console.log('取消收藏失败：'+res.message);
        }
      })
      } else {
        apiFavorites.save(postData).then(res=>{
          this.loading=false;
        if(res.status==200){
          this.isFavorite=true;
          if(res.result){
            this.data.favorites++;
          }
          if(this.type===2||this.type===4){
            this.messageSave(this.data.id,this.data.title,this.userInfo.name,this.data.sysCreateBy,this.data.sysCreateAid,'收藏了我发布的');
          }
          this.$message({message:'已加入收藏',type:'success'});
          //this.$emit('addFavorite',res.result);//添加收藏,如果是true代表添加成功，false代表已存在
        }else{
          console.log('加入收藏失败：'+res.message);
        }
      })
      }
      //

    },
    jumpRouter(){
      //此跳转不行
      if(this.type==2){
        this.$router.push({path:'/article/detail?id='+this.data.id})
      }
      if(this.type==3){
        this.$router.push({path:'/case/detail?id='+this.data.id})
      }
      if(this.type==1){
        this.$router.push({path:'/course/detail?id='+this.data.id})
      }
      if(this.type==4){
        this.$router.push({path:'/qa/answer?id='+this.data.id})
      }
    },
    keyupEnter(){
       this.findUser();
       return false;
    },
    findUser(){
       this.shareInfo.load=false;
       this.shareInfo.list=[];
       this.shareUsers=[];
       var name=this.shareInfo.name;
       var regPos = /^\d+(\.\d+)?$/; //非负浮点数
       if(regPos.test(name)){
            //console.log("数字");
            apiUser.getByLoginName(name).then(rs=>{
              if(rs.status==200){
                //因为根据工号查询，只会是一个人，所有会有null情况，而json会返回空字符串
                if(rs.result!=''){
                  this.shareInfo.list.push(rs.result);
                }else{
                  this.$message.error("查无此用户")
                }
                this.shareInfo.load=true;
              }else{
                this.$message.error(rs.message);
              }
            })
        }else{
            // console.log("非数字");
            apiUser.findByName(name).then(rs=>{
              if(rs.status==200){
                if(rs.result.length==0){
                  return this.$message.error(rs.message);
                }
                this.shareInfo.list=rs.result;
                this.shareInfo.load=true;
              }else{
                this.$message.error(rs.message);
              }
            })
        }
    },
    submitShare(){

      if(this.shareUsers.length==0){
        this.$message.error('请选择分享人');
        return;
      }
      let conType;
      if(this.type == 1) {
        conType = this.data.type;
      }

      let postData={
        objType:this.type,
        objId:this.data.id,
        content:'',
        isRead:false,
        toAid:'',
        toAname:'',
        conType: conType,
      }
      let $this=this;
      this.shareUsers.forEach(u=>{
        var curUser=null;
         $this.shareInfo.list.some(item=>{
           if(item.aid==u){
             curUser=item;
             return true;
           }else{
             return false;
           }
         });
         if(curUser!=null){
           postData.toAid=curUser.aid;
           postData.toAname=curUser.name;
           if(this.userInfo.aid==postData.toAid){
             return this.$message.warning("不能分享给自己")
           }
           apiShares.save(postData).then(rs=>{
             $this.shareShow=false;
             $this.data.shares++;
             if(rs.status!=200){
               this.$message.error("分享失败")
             }else{
               if(rs.result){
                 this.$message.success("分享成功")
                 if(this.type!=3){
                   if(this.type==1){
                     this.messageSave(this.data.id,this.data.name,this.userInfo.name,curUser.name,curUser.aid,'分享给我的');
                   }else{
                     this.messageSave(this.data.id,this.data.title,this.userInfo.name,curUser.name,curUser.aid,'分享给我的');
                   }
                 }
               }else{
                 this.$message.warning("您已分享给对方，分享失败")
               }
             }
           })
         }
      })

    }
  }

};
</script>

<style lang="scss" scoped>
.interact-bar{
  // height: 30px;
  .interact-bar-btns {
    line-height: 30px;
    display: flex;
    justify-content: flex-end;
    .interact-bar-btn {
      margin: 0 0 0 15px;
    }
    .interact-bar-value{
       color:#8590A6
    }
  }
}
.cursor{
  cursor: pointer;
}
.bottom-btn{
  padding: 10px 50px;
      text-align: center;
      .btn{
        width: 104px;
        height: 42px;
        color: #fff;
         img{
         width: 16px;
         height: 15px;
         vertical-align: bottom;
         margin-right: 5px;
        }
      }
      .fen-xiang{
        background: #2ab28b;

      }
      .dian-zan{
        background: #f56262;

      }
      .shou-cang{
        background: #ff8e00;
      }
}
</style>
