<style>
#text-box {
  -webkit-app-region: no-drag !important;
}
</style>
<template>
  <div class="user-input-box">
    <ul class="tool">
      <li>
        <i class="iconfont icon-biaoqing1" @click.stop="showEmoji()" style="font-size:19px"></i>
      </li>
      <li>
        <i class="iconfont icon-tupian" @click.stop="showUpload"></i>
      </li>
      <li>
        <i class="iconfont icon-wenjian" @click.stop="showUpload" style="font-size:22px"></i>
      </li>
      <li>
        <i class="iconfont icon-yun" @click="cloudLayer=true;getMyFile()" style="font-size:23px"></i>
      </li>
      <li>
        <i class="iconfont icon-doudong" @click="sendDou" style="font-size:18px"></i>
      </li>
    </ul>
    <div draggable="true" id="text-box" ref="box">
      <input type="file" ref="fileToSent" v-show="false" @change="sendFileMsg">
      <textarea
        v-model="msgToSent"
        id="msgEditorBox"
        ref="msgEditorBox"
        class="input"
        @keyup.13="ctrlEnterPush"
        @keydown.ctrl="ctrlChange(0)"
        @keyup.ctrl="ctrlChange(1)"
      ></textarea>
    </div>
    <div class="foot-Btn-Box">
      <div class="chat-send-box">
        <!-- <el-button type="info" style="margin-right:5px" @click="sendTextMsg">{{$t('pub.closeSel')}}</el-button> -->
        <el-dropdown
          split-button
          type="primary"
          @click="sendTextMsg"
          trigger="click"
          @command="handleCommand"
        >{{$t('op.Send')}}
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="0">
              <i
                class="iconfont icon-zhengque"
                style="color:#5FB878; margin-right:5px"
                :style="{visibility:sendModel==0?'visible':'hidden'}"
              ></i>{{$t('objFill.v101.chat.anjianfsxx')}}
            </el-dropdown-item>
            <el-dropdown-item command="1">
              <i
                class="iconfont icon-zhengque"
                style="color:#5FB878; margin-right:5px"
                :style="{visibility:sendModel==1?'visible':'hidden'}"
              ></i>{{$t('objFill.v101.chat.anctjfsxx')}}
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
    <!-- <div class="tool-box" style="float: right;">
            <span style="display: inline-block; width: 40px; height: 40px; line-height: 40px; text-align: center; border-radius: 20px; background: #E95252!important;">
              <i style="color: #fff;" class="iconfont icon-fasong"  @click="sendTextMsg"></i>
            </span>
    </div>-->
    <chat-emoji
      v-bind:type="type"
      v-bind:scene="scene"
      v-bind:to="to"
      v-show="isEmojiShown"
      v-on:add-emoji="addEmoji"
      v-on:hide-emoji="hideEmoji"
    ></chat-emoji>

    <el-dialog
      custom-class="w800"
      :title="$t('objFill.wodeyunp')"
      :visible.sync="cloudLayer"
      :modal-append-to-body="false"
      center
    >
      <div class="myDocumentsLink" v-if="this.NavigationList.length>0">
        <span @click="getNextLevel(0)">{{$t('advmanager.v_all')}}</span>
        <span v-for="item in NavigationList" @click="getNextLevel(item.Id)">{{item.FolderName}}</span>
      </div>
      <table class="IM_cloudTable" border="0" cellspacing="0" cellpadding="0">
        <tr>
          <th>{{$t('objFill.v101.chat.wenjianming')}}</th>
          <th>{{$t('objFill.v101.chat.daxiao')}}</th>
          <th>{{$t('objFill.v101.chat.xiugairiqi')}}</th>
        </tr>
        <tr v-for="item in myFileList">
          <td v-if="item.DataType==0">
            <div @click="getNextLevel(item.Id)" style="cursor: pointer; display: inline-block;">
              <div :class="['fileIcon', item.icons]"></div>
              {{item.FolderName}}
            </div>
          </td>
          <td v-if="item.DataType==2">
            <input
              type="checkbox"
              :value="item.Id"
              v-model="notFileList"
              @change="ckeckedOne(item)"
            >
            <div style="cursor: pointer;display: inline-block;">
              <div :class="['fileIcon', item.icons]"></div>
              {{item.FolderName}}
            </div>
          </td>
          <td>{{item.FileSize| FileSizeFormat(item.FileSize)}}</td>
          <td>{{item.UpdateTime}}</td>
        </tr>
        <tr v-if="myFileList.length==0">
          <td colspan="3" align="center">{{$t('objFill.v101.chat.zhanwuwenjian')}}</td>
        </tr>
      </table>

      <div slot="footer" class="dialog-footer">
        <input type="button" class="hollowFixedBtn" :value="$t('pub.cancelBtn')" @click="clearFileArr">
        <input type="button" class="normalBtn" :value="$t('op.Send')" @click="sendCustomMessage">
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ChatEmoji from "./ChatEmoji";
import util from "../../utils";
import config from "../../configs";
import pageUtil from "../../utils/page";
export default {
  components: {
    ChatEmoji
  },
  updated() {
    window.document.body.addEventListener("click", () => {
      this.isEmojiShown = false;
    });
  },
  mounted() {
    // 绑定拖拽时间
    this.addDropSupport();
    if (window.localStorage.sendModel && window.localStorage.sendModel != "") {
      this.sendModel = window.localStorage.sendModel;
    }
    this.initClip();
  },
  props: {
    type: String,
    scene: String,
    to: String,
    isRobot: {
      type: Boolean,
      default() {
        return false;
      }
    }
  },
  filters: {
    FileSizeFormat(value) {
      if (value == null) {
        return "-";
      }
      if (value != null) {
        if (value / 1024 < 1) {
          //kb
          return value + "KB";
        }
        if (value / 1024 > 1 && value / (1024 * 1024) < 1) {
          //mb
          return (value / 1024).toFixed(2) + "M";
        }
        if (value / (1024 * 1024) > 1) {
          //G
          return (value / (1024 * 1024)).toFixed(2) + "G";
        }
      }
    }
  },
  watch: {
    continueRobotAccid(curVal, oldVal) {
      if (curVal && this.robotInfos[curVal]) {
        this.msgToSent = `@${this.robotInfos[curVal].nick} `;
      }
      // 重置
      this.$store.dispatch("continueRobotMsg", "");
    },
    msgToSent(curVal, oldVal) {
      if (this.isRobot) {
        return;
      }
      let indexAt = this.msgToSent.indexOf("@");
      if (indexAt >= 0 && indexAt === this.msgToSent.length - 1) {
        if (this.robotslist && this.robotslist.length > 0) {
          this.isRobotListShown = true;
        }
      } else if (this.isRobotListShown === true) {
        this.isRobotListShown = false;
      }
    }
  },
  data() {
    return {
      msg: {
        ParentId: "0",
        FolderName: "",
        EmployeeId: 0
      },
      myFileList: [],
      NavigationList: [],
      notFileList: [],
      notFileListDetail: [],
      cloudLayer: false,
      errorTip: "",
      isEmojiShown: false,
      isRobotListShown: false,
      msgToSent: "",
      icon1: `${config.resourceUrl}/im/chat-editor-1.png`,
      icon2: `${config.resourceUrl}/im/chat-editor-2.png`,
      icon3: `${config.resourceUrl}/im/chat-editor-3.png`,
      isCtrl: false,
      sendModel: 0,
      canSendDou: true
    };
  },
  computed: {
    continueRobotAccid() {
      return this.$store.state.continueRobotAccid;
    },
    robotslist() {
      return this.$store.state.robotslist;
    },
    robotInfos() {
      return this.$store.state.robotInfos;
    },
    robotInfosByNick() {
      return this.$store.state.robotInfosByNick;
    }
  },
  methods: {
    initClip() {
      let _this=this
      document
        .querySelector("#msgEditorBox")
        .addEventListener("paste", function(event) {
          var clipboardData = event.clipboardData;
          var items, item, types;
          if (clipboardData) {
            items = clipboardData.items;
            if (!items) {
              return;
            }
            // 保存在剪贴板中的数据类型
            types = clipboardData.types || [];
            for (var i = 0; i < types.length; i++) {
              if (types[i] === "Files") {
                item = items[i];
                break;
              }
            }
            // 判断是否为图片数据
            if (item && item.kind === "file" && item.type.match(/^image\//i)) {
              // 读取该图片
              var file = item.getAsFile(),
                reader = new FileReader(),
                name='';
              if(item.type.match(/^image\//i))
                name= `截图_${Date.parse(new Date())}.png`
              reader.onload = function(e) {
                _this.$store.dispatch("sendDataUrlMsg", {
                  scene: util.parseSession(window.localStorage.sessionId).scene,
                  to: util.parseSession(window.localStorage.sessionId).to,
                  dataURL: e.target.result,
                  name
                });
                pageUtil.scrollChatListDown();
              };
              reader.readAsDataURL(file);
            }
          }
        });
    },
    handleCommand(command) {
      this.sendModel = command;
      window.localStorage.sendModel = command;
    },
    ctrlChange(type) {
      this.isCtrl = type == 0;
    },
    ctrlEnterPush() {
      if (this.sendModel == 0 && !this.isCtrl) {
        this.sendTextMsg();
      } else if (this.sendModel == 0 && this.isCtrl) {
        this.breakLine();
      } else if (this.sendModel == 1 && this.isCtrl) {
        this.sendTextMsg();
      } else if (this.sendModel == 1 && !this.isCtrl) {
        //this.breakLine()
      }
    },
    breakLine() {
      let index = this.$refs.msgEditorBox.selectionStart;
      if (index == this.msgToSent.length - 1) {
        this.msgToSent += "\n";
      } else {
        this.msgToSent =
          this.msgToSent.substring(0, index) +
          "\n" +
          this.msgToSent.substring(index, this.msgToSent.length);
      }
    },
    sendCustomMessage() {
      if (this.notFileListDetail.length > 0) {
        this.notFileListDetail.forEach(item => {
          this.itemMsg(item);
        });
        this.clearFileArr();
        pageUtil.scrollChatListDown();
      } else {
        this.$message.info(this.$t('objFill.v101.chat.meiyuxzwj'));
      }
    },
    itemMsg(obj) {
      if (this.type === "session") {
        this.$store.dispatch("sendMsg", {
          type: "custom",
          scene: util.parseSession(window.localStorage.sessionId).scene,
          to: util.parseSession(window.localStorage.sessionId).to,
          pushContent: obj.name,
          content: {
            msgtype: "custom_file",
            data: {
              pushContent: obj.name,
              Height: "84",
              content: {
                fileType: obj.type,
                fileUrl: obj.url,
                fileName: obj.name,
                fileSize: obj.size
              },
              recentContent: obj.name,
              Width: "210"
            }
          }
        });
      } else if (this.type === "chatroom") {
        this.$store.dispatch("sendChatroomMsg", {
          type: "custom_file",
          pushContent: obj.name,
          content: {
            msgtype: "custom_file",
            data: {
              pushContent: obj.name,
              Height: "84",
              content: {
                fileType: obj.type,
                fileUrl: obj.url,
                fileName: obj.name,
                fileSize: obj.size
              },
              recentContent: obj.name,
              Width: "210"
            }
          }
        });
      }
    },
    clearFileArr() {
      this.msg.ParentId = 0;
      this.notFileList = [];
      this.notFileListDetail = [];
      this.cloudLayer = false;
    },
    getMyFile() {
      this.msg.EmployeeId = this.getLocalStorage().EmployeeId;
      this.apipost(
        "user_cloud_GetFolderList",
        this.msg,
        res => {
          if (res.data.resultCode == 1) {
            this.myFileList = res.data.data.data;
            this.NavigationList = res.data.data.Navigation;
            res.data.data.data.forEach(item => {
              if (item.DataType == 0) {
                item.icons = this.loadFileICON("");
              }
              if (item.DataType == 2) {
                let fileType = item.FolderName.substring(
                  item.FolderName.lastIndexOf(".") + 1,
                  item.FolderName.length
                ).toLowerCase();
                item.icons = this.loadFileICON(fileType);
              }
            });
          }
        },
        err => {}
      );
    },
    getNextLevel(id) {
      this.msg.ParentId = id;
      this.getMyFile();
    },
    ckeckedOne(obj) {
      let _index = "-1";
      this.notFileList.forEach((item, index) => {
        if (item == obj.Id) {
          _index = index;
        } else {
          _index = "-1";
        }
      });
      if (_index != "-1") {
        //添加
        this.notFileListDetail.push({
          id: obj.Id,
          type: this.typeFormat(obj.FilePath),
          name: obj.FolderName,
          url: obj.FilePath,
          size: this.sizeFormat(obj.FileSize)
        });
      } else {
        //删除
        if (
          this.notFileListDetail.findIndex(item => item.id === obj.Id) != -1
        ) {
          this.notFileListDetail.splice(
            this.notFileListDetail.findIndex(item => item.id === obj.Id),
            1
          );
        }
      }
    },
    dataURLtoBlob(dataurl) {
      var arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },
    addDropSupport() {
      let BOX = this.$refs.box;
      BOX.addEventListener("drop", e => {
        e.preventDefault();
        if (this.readonly) return false;
        let fileList = e.dataTransfer.files;
        if (fileList.length === 0) {
          return false;
        }
        let crt = this;
        for (var i = 0; i < fileList.length; i++) {
          let crtItem = fileList[i];
          this.readBlobAsDataURL(fileList[0], function(dataurl) {
            crt.$store.dispatch("sendDataUrlMsg", {
              scene: util.parseSession(window.localStorage.sessionId).scene,
              to: util.parseSession(window.localStorage.sessionId).to,
              dataURL: dataurl,
              name: crtItem.name
            });
          });
        }
      });
    },
    sizeFormat(value) {
      if (value == null) {
        return "-";
      }
      if (value != null) {
        if (value / 1024 < 1) {
          //kb
          return value + "KB";
        }
        if (value / 1024 > 1 && value / (1024 * 1024) < 1) {
          //mb
          return (value / 1024).toFixed(2) + "M";
        }
        if (value / (1024 * 1024) > 1) {
          //G
          return (value / (1024 * 1024)).toFixed(2) + "G";
        }
      }
    },
    typeFormat(obj) {
      let typeArr = [
        { stringArr: "GIF|JPG|JPEG|PNG|BMP", type: 1 },
        { stringArr: "MP3|OGG|AU|AIFF|VQF", type: 2 },
        {
          stringArr:
            "AVI|WMV|MPEG|MP4|MOV|MKV|FLV|F4V|M4V|RMVB|RM|3GP|DAT|TS|MTS|VOB",
          type: 3
        },
        { stringArr: "DOCX|DOC", type: 4 },
        { stringArr: "XLSX|XLS", type: 5 },
        { stringArr: "PPT|PPTX", type: 6 },
        { stringArr: "PDF", type: 7 },
        { stringArr: "RAR|ZIP", type: 8 },
        { stringArr: "TXT", type: 9 }
      ];
      let fileType = obj
        .substring(obj.lastIndexOf(".") + 1, obj.length)
        .toUpperCase();
      let fileTypeNumber;
      typeArr.forEach(x => {
        if (x.stringArr.indexOf(fileType) != "-1") {
          fileTypeNumber = x.type;
        }
      });
      switch (fileTypeNumber) {
        case 1:
          return "image";
          break;
        case 2:
          return "music";
          break;
        case 3:
          return "video";
          break;
        case 4:
          return "word";
          break;
        case 5:
          return "xls";
          break;
        case 6:
          return "ppt";
          break;
        case 7:
          return "pdf";
          break;
        case 8:
          return "zip";
          break;
        case 9:
          return "txt";
          break;
        default:
          return "others";
      }
    },

    sendTextMsg() {
      this.errorTip = "";
      if (/^\s*$/.test(this.msgToSent)) {
        // this.errorTip='请不要刷屏'
        return;
      } else if (this.msgToSent.length > 800) {
        this.errorTip = this.$t('objFill.v101.chat.qingbucbbz');
        return;
      }
      this.msgToSent = this.msgToSent.trim();
      if (this.type === "session") {
        // 如果是机器人
        if (this.isRobot) {
          this.$store.dispatch("sendRobotMsg", {
            type: "text",
            scene: util.parseSession(window.localStorage.sessionId).scene,
            to: util.parseSession(window.localStorage.sessionId).to,
            robotAccid: this.to,
            // 机器人后台消息
            content: this.msgToSent,
            // 显示的文本消息
            body: this.msgToSent
          });
        } else {
          let robotAccid = "";
          let robotText = "";

          let atUsers = this.msgToSent.match(/@[^\s@$]+/g);
          if (atUsers) {
            for (let i = 0; i < atUsers.length; i++) {
              let item = atUsers[i].replace("@", "");
              if (this.robotInfosByNick[item]) {
                robotAccid = this.robotInfosByNick[item].account;
                robotText = (this.msgToSent + "")
                  .replace(atUsers[i], "")
                  .trim();
                break;
              }
            }
          }
          if (robotAccid) {
            if (robotText) {
              this.$store.dispatch("sendRobotMsg", {
                type: "text",
                scene: util.parseSession(window.localStorage.sessionId).scene,
                to: util.parseSession(window.localStorage.sessionId).to,
                robotAccid,
                // 机器人后台消息
                content: robotText,
                // 显示的文本消息
                body: this.msgToSent
              });
            } else {
              this.$store.dispatch("sendRobotMsg", {
                type: "welcome",
                scene: util.parseSession(window.localStorage.sessionId).scene,
                to: util.parseSession(window.localStorage.sessionId).to,
                robotAccid,
                // 显示的文本消息
                body: this.msgToSent
              });
            }
          } else {
            this.$store.dispatch("sendMsg", {
              type: "text",
              scene: util.parseSession(window.localStorage.sessionId).scene,
              to: util.parseSession(window.localStorage.sessionId).to,
              text: this.msgToSent
            });
          }
        }
      } else if (this.type === "chatroom") {
        let robotAccid = "";
        let robotText = "";

        let atUsers = this.msgToSent.match(/@[^\s@$]+/g);
        if (atUsers) {
          for (let i = 0; i < atUsers.length; i++) {
            let item = atUsers[i].replace("@", "");
            if (this.robotInfosByNick[item]) {
              robotAccid = this.robotInfosByNick[item].account;
              robotText = (this.msgToSent + "").replace(atUsers[i], "").trim();
              break;
            }
          }
        }
        if (robotAccid) {
          if (robotText) {
            this.$store.dispatch("sendChatroomRobotMsg", {
              type: "text",
              robotAccid,
              // 机器人后台消息
              content: robotText,
              // 显示的文本消息
              body: this.msgToSent
            });
          } else {
            this.$store.dispatch("sendChatroomRobotMsg", {
              type: "welcome",
              robotAccid,
              // 显示的文本消息
              body: this.msgToSent
            });
          }
        } else {
          this.$store.dispatch("sendChatroomMsg", {
            type: "text",
            text: this.msgToSent
          });
        }
      }
      this.msgToSent = "";
      pageUtil.scrollChatListDown();
    },
    sendDou() {
      //this.type === 'session'
      if (this.canSendDou) {
        this.canSendDou = false;
        this.$store.dispatch("sendTip", {
          scene: util.parseSession(window.localStorage.sessionId).scene,
          to: util.parseSession(window.localStorage.sessionId).to,
          tip: this.$t('objFill.v101.chat.douleyx')
        });
        this.MsgBus.$emit("doudong");
        setTimeout(() => {
          this.canSendDou = true;
        }, 1000 * 10);
      } else {
        this.Error(this.$t('objFill.v101.chat.diutdxxyx'));
      }
      pageUtil.scrollChatListDown();
    },
    sendFileMsg() {
      let ipt = this.$refs.fileToSent;
      let name = ipt.files[0].name;
      let size = this.sizeFormat((ipt.files[0].size / 1024).toFixed(2));
      let type = this.typeFormat(ipt.files[0].name);
      let that = this;
      let newArr = [];
      let date = new Date();
      let year = date.getFullYear();
      let month = date.getMonth() > 9 ? date.getMonth() : "0" + date.getMonth();
      let day = date.getDate();
      let myTime = year + "/" + month + "/" + day;
      let path = "/Upload/IMFile/" + myTime;
      newArr.push(ipt.files[0]);
      this.UploadSelfFileT(path, newArr, x => {
        if (that.type === "session") {
          this.$store.dispatch("sendMsg", {
            type: "custom",
            scene: util.parseSession(window.localStorage.sessionId).scene,
            to: util.parseSession(window.localStorage.sessionId).to,
            pushContent: name,
            content: {
              msgtype: "custom_file",
              data: {
                pushContent: name,
                Height: "84",
                content: {
                  fileType: type,
                  fileUrl: this.domainManager().ViittoFileUrl + x.data.FilePath,
                  fileName: name,
                  fileSize: size
                },
                recentContent: name,
                Width: "210"
              }
            }
          });
        } else if (that.type === "chatroom") {
          that.$store.dispatch("sendChatroomMsg", {
            type: "custom_file",
            pushContent: name,
            content: {
              msgtype: "custom_file",
              data: {
                pushContent: name,
                Height: "84",
                content: {
                  fileType: type,
                  fileUrl: x.res.requestUrls[0].split("?")[0],
                  fileName: name,
                  fileSize: size
                },
                recentContent: name,
                Width: "210"
              }
            }
          });
        }
        pageUtil.scrollChatListDown();
      });
    },

    showUpload() {
      this.$refs.fileToSent.click();
    },
    showEmoji() {
      this.isEmojiShown = !this.isEmojiShown;
    },
    hideEmoji() {
      this.isEmojiShown = false;
    },
    addEmoji(emojiName) {
      this.msgToSent += emojiName;
      this.hideEmoji();
    },
    chooseRobot(robot) {
      if (robot && robot.account) {
        let len = this.msgToSent.length;
        if (len === 0 || this.msgToSent[len - 1] !== "@") {
          this.msgToSent += "@" + robot.nick + " ";
        }
        {
          this.msgToSent += robot.nick + " ";
        }
      }
    },
    hideRobotList() {
      this.isRobotListShown = false;
    },
    readBlobAsDataURL(blob, callback) {
      var a = new FileReader();
      a.onload = function(e) {
        callback(e.target.result);
      };
      a.readAsDataURL(blob);
    }
  }
};
</script>