<template>
  <div class="tool-bar can-not-select">
    <div class="tool-start">
      <!-- qq表情 -->
      <el-popover placement="top-start" width="400" trigger="hover">
        <div class="scroll" style="height: 210px; overflow-y: scroll">
          <img class="qq-face" src="expression/qqface.png" usemap="#qqMap" />
          <map name="qqMap">
            <area
              v-for="(expression, index) in 105"
              :key="index"
              shape="rect"
              :coords="
                (index % 15) * 25 +
                ', ' +
                parseInt(index / 15) * 25 +
                ', ' +
                ((index % 15) + 1) * 25 +
                ', ' +
                (parseInt(index / 15) + 1) * 25
              "
              :title="qqFaceMap[index]"
              @click="selectExpression(index)"
            />
          </map>
          <img src="expression/emoji.png" usemap="#emojiMap" />
          <map name="emojiMap">
            <area
              v-for="(emoji, index) in 177"
              :key="index"
              shape="rect"
              :coords="
                (index % 15) * 25 +
                ', ' +
                parseInt(index / 15) * 25 +
                ', ' +
                ((index % 15) + 1) * 25 +
                ', ' +
                (parseInt(index / 15) + 1) * 25
              "
              :title="qqFaceMap[105 + index]"
              @click="selectExpression(105 + index)"
            />
          </map>
        </div>
        <div slot="reference" class="tool" title="表情">
          <img class="icon" src="../../../../assets/svg/tool-bar-expression.svg" alt />
        </div>
      </el-popover>
      <!-- 发图片|视频|文件 -->
      <div class="tool" title="发送文件">
        <label class="label" for="sendFiles">
          <img class="icon" src="../../../../assets/svg/tool-bar-files.svg" alt />
        </label>
        <input
          v-show="false"
          type="file"
          id="sendFiles"
          accept=".txt, .doc, .xls, .ppt, .docx, .xlsx, .pptx, .rar, .zip, .exe, .text, .apk, .mp3, .jpg, .png, .gif, .jpeg, .mp4"
          ref="toolsFile"
          @change="choseMedia('File')"
        />
      </div>
      <!-- 剪切 -->
      <div v-if="currentMode === 'electron'" class="tool" title="截图" @click="shearScreen()">
        <img class="icon" src="../../../../assets/svg/tool-bar-shear.svg" alt />
      </div>
      <!-- 发语音 -->
      <div class="tool" title="发语音">
        <label class="label" for="sendVoiceId">
          <img class="icon" src="../../../../assets/svg/tool-bar-voice.svg" alt />
        </label>
        <input
          v-show="false"
          type="file"
          id="sendVoiceId"
          accept=".amr, .mp3"
          ref="toolsVoice"
          @change="choseMedia('Voice')"
        />
      </div>
      <!-- 发名片 -->
      <div class="tool" title="发名片" @click="showSendNameCard">
        <img class="icon" src="../../../../assets/svg/tool-bar-name-card.svg" alt />
      </div>
      <!-- 我的收藏 -->
      <div class="tool" title="我的收藏" @click="showResours">
        <img class="icon" src="../../../../assets/svg/tool-bar-shoucang.svg" alt />
      </div>
    </div>

    <div class="tool-end">
      <!-- 创建群聊 -->
      <div class="tool" @click="createChatRoom()" title="创建群">
        <img class="icon" src="../../../../assets/svg/tool-bar-create-room.svg" alt />
      </div>
    </div>

    <!-- 创建群聊弹框 -->
    <SlotFriends
      v-if="friendsDialogVisible"
      :dialogTilte="dialogTilte"
      :action="action"
      :dialogData="dialogData"
      :currentFriend="currentFriend"
      :friends="dialogData"
      :friendsDialogVisible="friendsDialogVisible"
      @closeSlotFriends="friendsDialogVisible = false"
    />

    <!-- 我的收藏弹框 -->
    <el-dialog append-to-body class="my-collection-dialog" title="我的收藏" :visible.sync="resourcesDialog">
      <el-tabs style="width: 100%" v-model="resourcesType" @tab-click="setResourcesType">
        <el-tab-pane label="文本" name="Text">
          <el-table
            :data="myCollections"
            border
            style="width: 100%"
            height="354px"
            @selection-change="handleSelectionChange"
          >
            <el-table-column prop="content" label="内容"></el-table-column>
            <el-table-column type="selection" width="55" align="center"></el-table-column>
            <el-table-column fixed="right" label="操作" width="100">
              <template slot-scope="{ row }">
                <el-button @click="deleteResource(row.id)" type="text" size="small">删除</el-button>
                <el-button @click="sendResource(row)" type="text" size="small">发送</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="图片" name="Picture" class="picture-list">
          <div
            class="picture-item"
            :class="{ 'picture-item-checked': currentItem.id === ri.id }"
            v-for="(ri, index2) in myCollections"
            :key="index2"
            @click="checkItem(ri)"
          >
            <img style="object-fit: 'conver'" :src="ri.content.url" alt="" />
            <i class="el-icon-delete delete-icon" @click="deleteResource(ri.id)"></i>
          </div>
        </el-tab-pane>

        <el-tab-pane label="链接" name="Link" class="link-list">
          <div
            v-for="(link, index3) in myCollections"
            :key="index3"
            class="we-app-item"
            :class="{ 'we-app-item-checked': currentItem.id === link.id }"
            :title="link.title"
            @click="checkItem(link)"
          >
            <img
              v-if="link.content.thumbUrl && link.content.thumbUrl.startsWith('http://www')"
              class="we-app-img"
              :src="link.content.thumbUrl"
              alt=""
            />
            <div v-else class="we-app-img-no">
              <i style="font-size: 20px" class="el-icon-picture-outline"></i>
            </div>
            <p class="we-app-name ellipsis" v-text="link.content.title"></p>
            <i class="el-icon-delete delete-icon" @click="deleteResource(link.id)"></i>
          </div>
        </el-tab-pane>

        <el-tab-pane label="小程序" name="WeApp" class="link-list">
          <div
            v-for="(weApp, index4) in myCollections"
            :key="index4"
            class="we-app-item"
            :class="{ 'we-app-item-checked': currentItem.id === weApp.id }"
            @click="checkItem(weApp)"
          >
            <img class="we-app-img" :src="weApp.content.iconUrl" alt="" />
            <p class="we-app-name ellipsis" v-text="weApp.content.appName"></p>
            <i class="el-icon-delete delete-icon" @click="deleteResource(weApp.id)"></i>
          </div>
        </el-tab-pane>
      </el-tabs>

      <span slot="footer">
        <el-button size="small" @click="resetResource">取 消</el-button>
        <el-button size="small" type="primary" @click="sendResources(resource2send, currentItem)">发 送</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import SlotFriends from '../SlotFriends'

import { fileUpload } from '@/utils/upload'
import { resourcesList, deleteResources } from '@/api/httpApi'
import { expressionMap, emojiMap } from '@/utils/qqFaceMap'
import { TalkToFriendTask } from '@/api/webSocketApi'

export default {
  data() {
    return {
      qrCodeDialog: false, // 显示微信二维码窗口
      chatRoomQrCodeDialog: false, // 显示微信二维码窗口
      redEnvelopeDialog: false, // 显示红包
      transferMoneyDialog: false, // 显示红包
      managerVisiable: false, // 群管理
      circleDrawerVisiable: false, // 好友的朋友圈

      resourcesDialog: false, // 我的收藏弹框
      resourcesType: 'Text', // 资源类型 默认文本
      myCollections: [], // 资源列表
      resource2send: [], // 要发送的资源
      currentItem: {},

      action: 0,
      dialogTilte: '添加群成员',
      dialogData: [],
      friendsDialogVisible: false
    }
  },
  components: {
    SlotFriends
  },
  computed: {
    ...mapGetters({
      currentUser: 'currentUser',
      currentMode: 'currentMode',
      content: 'conversation/content',
      contentType: 'conversation/contentType',
      currentFriend: 'conversation/currentFriend',
      currentFriendId: 'conversation/currentFriendId',
      currentWeChatId: 'conversation/currentWeChatId',
      currentContacts: 'conversation/currentContacts', // 当前的通讯录列表 不分页
      currentCustomers: 'conversation/currentCustomers' // 当前的群聊列表 不分页
    }),
    // qq表情
    qqFaceMap() {
      return expressionMap || {}
    },
    friends() {
      return this.currentContacts.concat(this.currentCustomers)
    }
  },
  methods: {
    // 展示我的收藏
    showResours() {
      this.resourcesDialog = true
      this.queryResources()
    },
    // 设置资源类型
    setResourcesType(rt) {
      this.resourcesType = rt.name
      this.queryResources()
    },
    // 查询我收藏的数据
    queryResources() {
      resourcesList(this.currentUser.SupplierId, 1, 100, this.resourcesType).then((res) => {
        console.log(res)
        if (res.code === 0 && res.data.rows) {
          if (this.resourcesType === 'Text') {
            this.myCollections = res.data.rows
          } else {
            this.myCollections = res.data.rows.map((x) => {
              let obj = { ...x }
              try {
                obj.content = JSON.parse(x.content)
              } catch (error) {
                console.log(error)
              }
              return obj
            })
          }
        } else {
          this.myCollections = []
        }
      })
    },
    handleSelectionChange(val) {
      this.resource2send = val
    },
    // 删除收藏的信息
    deleteResource(resourceId) {
      if (resourceId) {
        deleteResources(resourceId).then((res) => {
          if (res.code === 0) {
            this.queryResources()
          }
        })
      }
    },
    checkItem(item) {
      this.currentItem = item
      //   this.resource2send.push(item)
    },
    // 重置选中的信息
    resetResource() {
      this.resource2send = []
      this.currentItem = {}
      this.resourcesDialog = false
    },
    // 发送消息
    sendResource(resource) {
      const { type, content } = resource
      let rContent = ''
      if (type === 'Text') {
        rContent = content
      } else if (type === 'Picture') {
        rContent = content.url
      } else if (type === 'Link') {
        rContent = JSON.stringify(content)
      } else if (type === 'WeApp') {
        rContent = JSON.stringify(content)
      }

      if (this.currentWeChatId && this.currentFriendId) {
        TalkToFriendTask(this.currentWeChatId, this.currentFriendId, resource.type, rContent)
      } else {
        this.$message.warning('请先选中一个好友！')
      }
      this.resourcesDialog = false
    },
    // 发送多条消息
    sendResources(resource2send, currentItem) {
      if (this.currentWeChatId && this.currentFriendId) {
        console.log(resource2send)
        if (this.resourcesType === 'Text') {
          for (const ri of resource2send) {
            this.sendResource(ri)
          }
        } else {
          console.log(currentItem)
          this.sendResource(currentItem)
        }
        this.resetResource()
      } else {
        this.$alert('请先选中一个好友！', '提示', { type: 'warning' })
      }
    },
    // 选择表情
    selectExpression(val) {
      if (this.contentType !== 'Text') {
        this.$store.commit('conversation/SET_CONTENT', '')
      }
      let rm = expressionMap[val]
      let qqList = [113, 114, 115, 116, 117, 118, 124, 125]
      // qq表情
      if (rm) {
        if (val < 105 || qqList.indexOf(val) >= 0) {
          rm = '[' + expressionMap[val] + ']'
        } else {
          rm = '<' + rm + '>'
          rm = emojiMap[rm]
          // let en = '😁'
          // let encode = en.codePointAt(0)
          let rmencode = parseInt(rm, 16)
          rm = String.fromCodePoint(rmencode)
        }
        let newContent = this.content + rm
        this.$store.commit('conversation/SET_CONTENT_TYPE', 'Text')
        this.$store.commit('conversation/SET_CONTENT', newContent)
      }
      //   else {
      //     this.$message.warning('无效选择')
      //   }
    },
    // 选择图片|视频|语音|文件
    async choseMedia(type) {
      let formdata = new FormData() // 上传

      let fileObj = '' // 文件对象
      let computedType = '' // 文件的type
      if (type === 'Voice') {
        // 发送语音
        fileObj = this.$refs.toolsVoice.files
      } else {
        // 发送图片|视频|文件
        fileObj = this.$refs.toolsFile.files
      }
      // 如果有选中文件
      if (fileObj[0]) {
        let duration = 0 // 语音时长
        // 文件大小
        let fileSize = fileObj[0].size
        let fileName = fileObj[0].name
        // 文件后缀
        let fileType = fileObj[0].name.replace(/.+\./, '').toLowerCase()
        // 文件大于100M不能发送
        if (fileSize > 104857600 || fileSize <= 0) {
          this.$message.warning('文件不能大于100M，文件不能是空文件')
          return
        }
        // 计算要发送的消息类型
        if (type === 'Voice') {
          computedType = 'Voice'
          // 验证文件类型
          if (['amr', 'mp3'].indexOf(fileType) < 0) {
            this.$message.warning('发送语音只能选择MP3或AMR文件')
            return
          }
        } else {
          if (fileType === 'mp4') {
            computedType = 'Video'
          } else if (['jpg', 'png', 'gif', 'jpeg'].indexOf(fileType) >= 0) {
            computedType = 'Picture'
          } else {
            computedType = 'File'
          }
        }
        // 验证通过
        formdata.append('myfile', fileObj[0])

        const loading = this.$loading({
          lock: true,
          text: '文件上传中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        // 如果是发送语音
        if (type === 'Voice') {
          // 如果选择的是mp3文件，文件上传到服务器，转为amr，返回amr的地址
          // 如果选择的是amr文件，直接上传到服务器，返回amr的地址
          if (fileType === 'mp3') {
            formdata.append('isMp3ToAmr', true)
          } else if (fileType === 'amr') {
            formdata.append('isAmrToMp3', false)
          }

          // 计算语音时长
          let formDataMp3 = new FormData()
          formDataMp3.append('myfile', fileObj[0])
          if (fileType === 'mp3') {
            formDataMp3.append('isMp3ToAmr', false)
          } else if (fileType === 'amr') {
            formDataMp3.append('isAmrToMp3', true)
          }

          await new Promise((resolve, reject) => {
            fileUpload(formDataMp3).then((res) => {
              if (res.data && res.data.url) {
                let audioElement = new Audio(res.data.url)
                audioElement.addEventListener('loadedmetadata', function (_event) {
                  duration = audioElement.duration
                  resolve(duration)
                })
              } else {
                reject(false)
              }
            })
          })
        }

        fileUpload(formdata)
          .then((res) => {
            // console.log('文件上传成功', res)
            let content = res.data.url

            // 如果是文件 加上文件名
            if (computedType === 'File') {
              content = JSON.stringify({ name: fileName, url: res.data.url, size: fileSize, Source: 'pc' })
            }

            // 如果是语音 加上时长
            if (computedType === 'Voice') {
              duration = Math.ceil(duration)
              content = content + `?duration=${duration}`
            }

            this.$store.commit('conversation/SET_CONTENT', content)
            this.$store.commit('conversation/SET_CONTENT_TYPE', computedType)
            loading.close()
            type === 'Voice' ? (this.$refs.toolsVoice.value = '') : (this.$refs.toolsFile.value = '')
          })
          .catch((err) => {
            this.$message({
              message: '文件上传失败：' + err,
              type: 'error',
              duration: 0,
              showClose: true
            })
            loading.close()
          })
      }
    },

    // 创建群聊
    createChatRoom() {
      if (!this.currentWeChatId) {
        this.$message.warning('请先选择一个微信！')
        return
      }
      this.dialogTilte = '创建群聊'
      this.action = 8
      this.dialogData = this.friends
      this.friendsDialogVisible = true
    },
    // 显示发名片窗口
    showSendNameCard() {
      this.dialogTilte = '发送名片'
      this.action = 'NameCard'
      this.dialogData = this.friends
      this.friendsDialogVisible = true
    },
    // 截图
    shearScreen() {
      if (process.env.VUE_APP_CURRENTMODE !== 'electron') {
        this.$message.warning('web版不支持截图！')
        return
      } else if (process.env.VUE_APP_CURRENTMODE === 'electron') {
        // 和主进程通讯
        this.$ipcRenderer.send('operations', 'screencap')
        // 监听主进程
        // this.$ipcRenderer.on('screencap', (event, arg) => {
        //   if (arg) {
        //     // document.execCommand("paste")
        //   }
        // })
      }
    },
    // 显示发红包的dialog
    showRedEnvelopeDialog() {
      this.redEnvelopeDialog = true
      this.dialogTilte = '发红包'
    }
  },
  mounted() {
    let _this = this
    document.body.onpaste = function (event) {
      let data = event.clipboardData || window.clipboardData
      let items = data.items
      //   let fileList = []; //存储文件数据
      if (items && items.length) {
        // 检索剪切板items
        // for (let i = 0; i < items.length; i++) {
        //   fileList.push(items[i].getAsFile());
        // }
        let blob = items[0].getAsFile()
        if (blob) {
          // 上传到后台
          let fd = new FormData()
          fd.append('myfile', blob, 'image.png')
          //   fd.append("myfile", blob);
          fileUpload(fd)
            .then((res) => {
              let content = res.url
              _this.$store.commit('conversation/SET_CONTENT', content)
              _this.$store.commit('conversation/SET_CONTENT_TYPE', 'Picture')
            })
            .catch((err) => {})
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.tool-bar {
  height: 40px;
  min-height: 40px;
  width: 100%;
  position: relative;
  display: flex;
  justify-content: space-between;
  border-top: solid $border-color-base 2px;

  .tool-start {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    .tool {
      justify-self: start;
      margin-left: 4px;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;

      .icon,
      .label {
        height: 24px;
        width: 24px;
        min-width: 24px;
        cursor: pointer;
      }
    }

    .remittance-window {
      left: 112px;
    }
  }

  .tool-end {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .tool {
      justify-self: start;
      margin-right: 4px;
      width: 24px;
      min-width: 24px;
      height: 24px;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  ::v-deep .reply-drawer {
    .rtl {
      max-width: 310px;
    }
    .el-drawer__body {
      width: 310px;
      padding: 0 5px;
    }
  }
}
</style>
