<template>
  <div class="app-container">

     <el-form :model="queryParams" ref="queryForm" class="search-form" :inline="true" >

         <el-form-item label="所属部门">
             <treeselect style="width:205.4px" v-model="deptId" :options="deptOptions" :show-count="true" placeholder="请选择所属部门" />
         </el-form-item>

          <el-form-item  prop="companyUserId">
              <el-select filterable v-model="queryParams.companyUserId" @change="companyUserChange" placeholder="请选择员工" clearable size="small">
                <el-option
                  v-for="item in users"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId">
                </el-option>
              </el-select>
          </el-form-item>

         <el-form-item  prop="qwUserId">
              <el-select filterable v-model="queryParams.qwUserId"  @change="qwUserChange" placeholder="请选择企微账号" clearable size="small">
                <el-option
                  v-for="item in accountList"
                  :key="item.qwUserId"
                  :label="item.account"
                  :value="item.qwUserId">
                </el-option>
              </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
     </el-form>


      <div class="imui-center qq-lemon-imui" v-show="showQW">
        <lemon-chatui  class="lemon-slot"
          :width="windowWidth"
          :height="windowHeight"
          :user="UserData"
          ref="IMUI"  
          :theme="theme"
          :hide-menu="hideMenu"
          :hide-menu-avatar="hideMenuAvatar"
          :hide-message-name="hideMessageName"
          :hide-message-time="hideMessageTime"
          :messageTimeFormat="messageTimeFormat"
          @change-menu="handleChangeMenu"
          @pull-messages="handlePullMessages"
          @change-contact="handleChangeContact"
          @change-conversation="handleChangeConversation"
          @message-click="handleMessageClick"
          @menu-avatar-click="handleMenuAvatarClick"
          @pick-image="handleImageClick"
          @pick-msg-records="handleMsgRecordsClick"
          @pick-export-msg="handleExportMsgClick"
          >
          <template #cover>
                <div class="cover">
                    <!-- <i class="lemon-icon-message"></i>
                    <p>
                        <b>自定义封面 Lemon</b>IMUI
                    </p> -->
                </div>
          </template>

        </lemon-chatui>
      </div>
   
       <el-dialog :visible.sync="dialogVisible" append-to-body width="35%">
         <img style="width:100%;height:auto" :src="dialogImageUrl" alt="" />
      </el-dialog>

       <el-dialog :visible.sync="dialogVideoVisible"
               :close-on-click-modal="false"
               :destroy-on-close="true"
               :width="aplayer.pWidth"
               :height="aplayer.height" 
               @close="dialogVideoVisible=false"
               ref="player">
              <videoPlayer  :width="aplayer.width" :height="aplayer.height"  :videoWidth="aplayer.videoWidth"  :videoHeight="aplayer.videoHeight"   :vid="aplayer.vid"  :autoplay="true" 
                :source="dialogVideoUrl" :cover="dialogVideoCover" ref="player">
              </videoPlayer>
       </el-dialog>

       <Material ref="material" @pickImageData="handlePickImageDone"  v-model="imageArr" type="image" :num="1" :width="150" :height="150" />

       <ChatRecords ref="chatRecords" :qwUser="qwUser" />

       
  </div>
</template>

<script>

import store from "@/store";
import { getQrCode } from '@/api/qw/login';
import { getDeviceId,listAccount,getAccount} from '@/api/qw/account';
import LemonMessageVoice from "@/components/LemonUI/components/message/voice";
import { getContactsByUser,getConversations,getHistoryList,getRoomInfo,exportMessage} from '@/api/qw/im';
import Conversations from "@/components/LemonUI/database/conversations";
import EmojiData from "@/components/LemonUI/database/emoji";
import '@/components/LemonUI/index.css';
import Material from '@/components/Material/index'
import VideoPlayer from '@/components/VideoPlayer/VueAliplayer'
import ChatRecords from '@/components/LemonUI/components/chatrecords/basic'

import { getUserListByDeptId} from "@/api/company/companyUser";
import { treeselect } from "@/api/company/companyDept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getCompanyList } from "@/api/company/company";

let pages = {};
export default {
  name: "qwChat",
  components: {   
    Material,
    VideoPlayer,
    ChatRecords,
    Treeselect
  },
  watch: {
    // 监听deptId
    'deptId': 'currDeptChange'
  },
  data() {
    return {
      theme: "default",
      IMUI:null,
      hideMenuAvatar: false,
      hideMenu: false,
      hideMessageName: false,
      hideMessageTime: true,
      accountList:[],
      qwUser:{
          //"userId":1688854331463712,"avatar":"https://wework.qpic.cn/wwpic/258414_QSUkkN5rTMGzwIc_1692169272/0","corpId":1970326754004217,"corpName":"重庆润方数字科技","nickName":"秦先觉","deviceId":"aeff5e72448d4d299e03d7291a21c2ea","phone":null,"account":"1261818888"
      },
      showQW:false,
      UserData: {
        id: "1000",
        displayName: "June",
        avatar: "",
      },
      contactData:null,
      conversationData:null,
      isFromLogin:false,
      dialogImageUrl: '',
      dialogVisible: false,
      dialogVideoVisible:false, 
      dialogVideoUrl:'',
      dialogVideoCover:'',
      imageArr:[],
      pickUploadImgData:null,
      aplayer: {
        vid: "bf9b7e4a36d84aea8cee769765fbc28b",
        pWidth:"1040px",
        width:"1000px",
        height:"900px",
        videoWidth:"1000px",
        videoHeight:"900px"
        
      },
      player: null,
      roomMembers:[],
      roomAdmins:[],
      roomInfo:null,
      windowWidth: document.documentElement.clientWidth*0.65,  //实时屏幕宽度
      windowHeight: document.documentElement.clientHeight*0.7,   //实时屏幕高度
      queryParams: {
          pageNum: 1,
          pageSize: 10,
          companyUserId: null,
          qwUserId:null,
      },
       companys:[],
       deptOptions:[],
       companyId:37,
       companyUserId:undefined,
       deptId:undefined,
       userIds:undefined,
       qwUserId:undefined,
       users:[],

    };
  },
  created(){
      this.getTreeselect();
      this.qwListAccount();
  },
  mounted() {

    this.showQW=true;
    //this.setQwUserInfo();
    //this.getContacts();  //获取联系人信息
    //this.getConversation();   //获取会话信息
   
    const IMUI = this.$refs.IMUI;
    IMUI.initMenus([
      {
        name: "messages",
      },
      // {
      //   name: "contacts",
      // },
      // {
      //   name: "custom1",
      //   title: "自定义按钮1",
      //   unread: 0,
      //   render: menu => {
      //     return <i class="lemon-icon-attah" />;
      //   },
      //   renderContainer: () => {
      //     return (
      //       <div class="article">
      //         <ul>
      //           <li class="article-item">
      //             <h2>网红带货：产品真的值得买吗？</h2>
      //           </li>
      //           <li class="article-item">
      //             甘肃夏河县发生5.7级地震 暂未接到人员伤亡报告
      //           </li>
      //           <li class="article-item">
      //             北方多地风力仍强沙尘相伴,东北内蒙古等地迎雨雪
      //           </li>
      //           <li class="article-item">
      //             英货车案：越南警方采集疑死者家属DNA作比对
      //           </li>
      //           <li class="article-item">
      //             知名连锁咖啡店的蛋糕吃出活虫 曝光内幕太震惊
      //           </li>
      //         </ul>
      //         <lemon-contact  props={{ contact: contactData1 }} style="margin:20px"/>
      //         <lemon-contact props={{ contact: contactData3 }} style="margin:20px" />
      //       </div>
      //     );
      //   },
      //   isBottom: true,
      // }
      
      ,
      {
          name: "custom2",
          title: "切换账号",
          unread: 0,
          click: () => {
            alert("拦截导航点击事件");
          },
          render: menu => {
            return <i class="lemon-icon-group" />;
          },
          isBottom: true,
       },
    ]);
    IMUI.initEmoji(EmojiData); 
  
  },

  methods: {

   getTreeselect() {
        treeselect().then((response) => {
           this.deptOptions = response.data;
        });
    },
  
    currDeptChange(val){
      console.log(val)
      this.deptId=val;
      this.queryParams.companyUserId=null;
      this.getUserListByDeptId();
    },
 
    getUserListByDeptId() {
        this.userIds=undefined;
        var data={deptId:this.deptId};
        getUserListByDeptId(data).then(response => {
          this.users = response.data;
        });
    },
    companyUserChange(companyUserId){  
       this.queryParams.companyUserId=companyUserId;
       this.qwListAccount();
    },
    qwListAccount() {

        listAccount(this.queryParams).then(response => {
            this.accountList = response.rows;
            if(this.accountList.length>0){
                this.qwUser=this.accountList[0];
                if(this.qwUser.qwUserId==null){
                    this.msgError("该账号暂未扫码绑定企微");
                    return;
                }
                this.queryParams.qwUserId=this.qwUser.qwUserId;
                this.qwUser.userId=this.queryParams.qwUserId;
                this.setQwUserInfo();
                this.getContacts();  //获取联系人信息
                this.getConversation();   //获取会话信息
            }else{
                 this.qwUser={};
                 this.qwUserId="";
                 this.msgError("暂无企微号!");
            }
        });
    },
    qwUserChange(qwUserId){
        let index= this.accountList.findIndex(item => item.qwUserId == qwUserId);
        this.qwUser=this.accountList[index];
        this.queryParams.qwUserId=this.qwUser.qwUserId;
        this.qwUser.userId=this.queryParams.qwUserId;
        if(this.qwUser.qwUserId==null){
            this.msgError("暂未扫码登录企微号");
            return;
        }
        this.setQwUserInfo();
        this.getContacts();  //获取联系人信息
        this.getConversation();   //获取会话信息 
    },

    setQwUserInfo(){
        this.deviceId=this.qwUser.deviceId;
        this.UserData.id=this.qwUser.userId;
        this.UserData.displayName=this.qwUser.nickName;
        this.UserData.avatar=this.qwUser.avatar;
    },
     /** 搜索按钮操作 */
    handleQuery() {
      this.qwListAccount();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      //this.handleQuery();
    },
  
    getRoomInfo(roomId){
        getRoomInfo(roomId).then(response => {
             this.roomMembers=response.members;
             this.admins=response.members;
             this.roomInfo=response.detail;
        });
    },
    getContacts(){  
      getContactsByUser(this.qwUser.userId).then(response => {
           this.contactData = response.data;
           this.$refs.IMUI.initContacts(this.contactData);
      });
    },
    getConversation(){
      let that=this;
      const IMUI = this.$refs.IMUI;
      getConversations(this.qwUser.userId).then(response => {
           this.conversationData = response.data;
           IMUI.initConversations(response.data);
           var fstConversation=this.conversationData[0];
           if(fstConversation){
              IMUI.changeContact(fstConversation.conversationId);
           }
         
      });
    },
    messageTimeFormat(time) {
      return this.friendlyDate(time);
    },
    changeTheme() {
       this.theme = this.theme == "default" ? "blue" : "default";
    },
    scrollToTop() {
      document.body.scrollIntoView();
    },
  
    handlePullMessages(contact, next,instance) {
       const { IMUI } = this.$refs;
       let isEnd = false;
       getHistoryList(this.queryParams).then(response => {
          if(response.code==200){
               isEnd=response.data.isLastPage;
               next(response.data.list, isEnd);
               if(!isEnd){
                   pages[contact.conversationId]++;
                   this.queryParams.pageNum=pages[contact.conversationId];
               }
          }
      });
    },
    handleChangeConversation(conversation, instance) {
        //console.log("qxj ChangeConversation:"+JSON.stringify(conversation));
        if (!pages[conversation.conversationId]){
            pages[conversation.conversationId] =1;
        }
       this.queryParams.pageNum=pages[conversation.conversationId];
       this.queryParams.conversationId=conversation.conversationId;
       if(conversation.unread>0){
          conversation.unread=0;
          instance.updateContact(conversation);
       }
       instance.closeDrawer();
    },
    handleChangeContact(contact, instance) {
        
    },
    //收到消息后添加消息显示
    appendMessageAction(msgData){
          if(msgData.type=="text" || msgData.type=="image" || msgData.type=="voice"){     //文本   text  image  video  voice 
              const message = {
                    id: msgData.id,
                    status: msgData.status,
                    type: msgData.type,
                    sendTime: msgData.sendTime,
                    content: msgData.content,
                    params1: "1",
                    params2: "2",
                    toContactId: msgData.toContactId,
                    fromUser: msgData.fromUser,
              };
              this.appendRemoteMessage(message);
           }
           else if(msgData.type=="file"){
               const message = {
                    id: msgData.id,
                    status: msgData.status,
                    type: msgData.type,
                    sendTime: msgData.sendTime,
                    content: msgData.content,
                    toContactId: msgData.toContactId,
                    fromUser: msgData.fromUser,
                    fileName:msgData.fileName,
                    fileSize:msgData.fileSize
              };
              this.appendRemoteMessage(message);
           }
           else{
              const message = {
                    id: msgData.id,
                    status: msgData.status,
                    type: msgData.type,
                    sendTime: msgData.sendTime,
                    content: msgData.content,
                    toContactId: msgData.toContactId,
                    fromUser: msgData.fromUser,
              };
              this.appendRemoteMessage(message);
           }
    },
 
    handleMenuAvatarClick() {
      console.log("Event:menu-avatar-click");
    },
    //聊天工具栏点击图片
    handleImageClick() { 
      //this.$refs.material.openMaterial(this.qwUser.deviceId);
    },
    handleMsgRecordsClick() { 
      console.log("qxj handleMsgRecordsClick");
      this.$refs.chatRecords.open(this.qwUser,this.queryParams.conversationId,this.conversationData);
    },
    handleExportMsgClick() { 
      let that=this;
      this.$confirm('是否确认导出消息记录吗?', "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(function() {
            let queryParams={conversationId:that.queryParams.conversationId}
            return exportMessage(queryParams);
          }).then(response => {
            this.download(response.msg);
          }).catch(function() {});
    },
    //选择图片框确定按钮回调
    handlePickImageDone(data){
        console.log("handlePickImageDone:"+JSON.stringify(data));
        this.pickUploadImgData=data;
        const IMUI = this.$refs.IMUI;
        IMUI._handleRemoteImage(data.url);
    },
    tooglePlayVideo(data){
       this.dialogVideoVisible=true;
       this.dialogVideoUrl=data.content;
       this.dialogVideoCover=data.url;
       const player = this.$refs.player.instance
       player && player.play()
    },
    handleMessageClick(e, key, message, instance) {
      console.log("点击了消息", e, key, message);
      //console.log("qxj message:"+JSON.stringify(message));
      if(message.type=="image"){
           var url=!!message.url?message.url:message.content;
           this.handlePicturePreview(url);
      }
      else if(message.type=="video"){  
           this.tooglePlayVideo(message);
      }
      else if(message.type=="file"){  
           
      }
      if (key == "status") {
        instance.updateMessage({
          id: message.id,
          status: "going",
          content: "正在重新发送消息...",
        });
        setTimeout(() => {
          instance.updateMessage({
            id: message.id,
            status: "succeed",
            content: "发送成功",
          });
        }, 2000);
      }
    },

    changeMenuAvatarVisible() {
      this.hideMenuAvatar = !this.hideMenuAvatar;
    },
    changeMenuVisible() {
      this.hideMenu = !this.hideMenu;
    },
    changeMessageNameVisible() {
      this.hideMessageName = !this.hideMessageName;
    },
    changeMessageTimeVisible() {
      this.hideMessageTime = !this.hideMessageTime;
    },
    removeMessage() {
        const { IMUI } = this.$refs;
        const messages = IMUI.getCurrentMessages();
        const id = messages[messages.length - 1].id;
        if (messages.length > 0) {
            IMUI.removeMessage(id);
        }
    },
    updateMessage() {
        const { IMUI } = this.$refs;
        const messages = IMUI.getCurrentMessages();
        const message = messages[messages.length - 1];
        if (messages.length > 0) {
            const update = {
            id: message.id,
            status: "succeed",
            type: "file",
            fileName: "被修改成文件了.txt",
            fileSize: "4200000",
            };
            if (message.type == "event") {
            update.fromUser = this.user;
            }
            IMUI.updateMessage(update);
            IMUI.messageViewToBottom();
      }
    },
    appendCustomMessage() {
        const { IMUI } = this.$refs;
        const message = {
            id: generateRandId(),
            status: "succeed",
            type: "voice",
            sendTime: getTime(),
            content: "语音消息",
            params1: "1",
            params2: "2",
            toContactId: "contact-1",
            fromUser: this.user,
        };
        IMUI.appendMessage(message, true);
    },
    appendMessage() {
        const { IMUI } = this.$refs;
        const contact = IMUI.currentContact;
        const message = generateMessage("contact-3");
        message.fromUser = {
            ...message.fromUser,
            ...this.user,
        };
        IMUI.appendMessage(message, true);
        console.log("🚀 ~ file: App.vue ~ line 1508 ~ appendMessage ~ message", message)
    },
    appendEventMessage() {
      const { IMUI } = this.$refs;
      const message = {
        id: generateRandId(),
        type: "event",
        content: (
          <span>
            邀请你加入群聊{" "}
            <span
              style="color:#333;cursor:pointer"
              on-click={() => alert("OK")}>
              接受
            </span>
          </span>
        ),
        toContactId: "contact-3",
        sendTime: getTime(),
      };
      IMUI.appendMessage(message, true);
    },
    appendRemoteMessage(message) {  //从服务端返回的消息
        const { IMUI } = this.$refs;
        IMUI.appendMessage(message, true);
    },
    updateContact() {
      this.$refs.IMUI.updateContact({
        id: "contact-3",
        unread: 10,
        displayName: generateRandWord(),
        lastSendTime: getTime(),
        lastContent: "修改昵称为随机字母",
      });
    },
    handleChangeMenu() {
      console.log("Event:change-menu");
    },
    openCustomContainer() {

    },
    handlePicturePreview(url) {
        this.dialogImageUrl = url;
        this.dialogVisible = true;
    },
  },
};
</script>

<style lang="scss" scoped>
    .imui-center{
        margin-bottom:"60px"; 
        display: flex;
        align-items: center;
        justify-content: center;
        height: 80vh;
    }
    .lemon-wrapper{
        border:"1px solid #ddd";
        height: "60%" !important;
    }
    .lemon-drawer{
        border:"1px solid #ddd";
        border-left:"0";
    }
    .more {
        font-size: 12px;
        line-height: 24px;
        height: 24px;
        position: absolute;
        top: 14px;
        right: 14px;
        cursor: pointer;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
        color: #f1f1f1;
        display: inline-block;
        border-radius: 4px;
        background: #111;
        padding: 0 8px;
    }

    /deep/.el-dialog__headerbtn{
         top:10px;
    }

    /deep/.el-dialog:not(.is-fullscreen) {
        margin-top: 0 !important;
    }

    .search-form{
       margin: 20px 30px 0px 30px;
    }

    .el-select{
      margin: 5px 10px;
    }

    .vue-treeselect{
      width: 217px;
      height: 36px;
    }

  .vue-treeselect__control{
    display: block;
   }


   /deep/.el-form-item{
        margin-bottom: 0;
        vertical-align: middle !important;
   }

  

    
</style>


<style lang="stylus">
   .lemon-container__title
     padding-bottom:10px;
   .slot-group
      width:200px;
      .slot-group-title
        padding:0 0 10px 0;
        .slot-group-notice
           padding: 10px 10px;
     
      .slot-search
           width:calc(100% - 20px) ;
           margin:5px 10px;
           padding:3px 0px;

      .slot-group-member
          display: flex;
          padding: 5px 0;
          flex:1;
          font-size: 14px;
          align-items: center;
          .avatar
              width: 30px;
              height: 30px;
              line-height: 30px;
              margin-right:5px;
              img 
                vertical-align: middle;
                border-style: none;
                width: 100%;
                height: 100%;
                line-height: 30px;
                border-radius: 50%;
</style>