<template>
  <div class="group-assistant-send">
    <el-row type="flex" align="middle" style="margin-bottom: 10px">
      <!-- 群发对象 -->
      <el-radio-group v-model="sendType">
        <el-radio-button label="customers">我的客户</el-radio-button>
        <el-radio-button label="friends">企业联系人</el-radio-button>
        <el-radio-button label="rooms">群聊</el-radio-button>
      </el-radio-group>
      <el-input
        style="width: 300px; margin-left: 10px"
        placeholder="请输入昵称"
        prefix-icon="el-icon-search"
        clearable
        maxlength="20"
        show-word-limit
        v-model.trim.lazy="searchName"
      ></el-input>
    </el-row>

    <!-- 数据展示 -->
    <el-table
      ref="multipleTable"
      :data="tableData"
      stripe
      border
      style="width: 100%"
      highlight-current-row
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="index" :index="indexMethod" label="序号" width="100px"></el-table-column>
      <el-table-column label="昵称" prop="Name"></el-table-column>
      <el-table-column label="备注名" prop="Alias"></el-table-column>
      <el-table-column label="性别" prop="Gender"></el-table-column>
      <el-table-column label="群成员人数">
        <template slot-scope="{ row }">
          <span v-if="row.Members" v-text="row.Members.length"></span>
        </template>
      </el-table-column>
      <el-table-column type="selection" label="全选" align="center"></el-table-column>
    </el-table>

    <!-- 下一步 -->
    <div class="group-send-operation">
      <el-button type="primary" @click="sendNext">下一步</el-button>
    </div>

    <!-- 编辑内容 -->
    <el-dialog class="group-send-dialog" title="设置群发消息" :close-on-click-modal="false" :visible.sync="editDialg">
      <!-- 添加 -->
      <div>
        <!-- 展示 -->
        <div class="msg-list">
          <div class="no-msg" v-if="msgList.length === 0">
            <img src="@/assets/images/group/noMsgBg.png" alt="" />
            <p style="margin-top: 21px; color: rgba(0, 0, 0, 0.25)">您还未设置群发消息，请在下方设置</p>
          </div>

          <div class="msg-item" v-for="(msg, index) in msgList" :key="index">
            <el-row type="flex" align="middle">
              <div style="margin-right: 10px; color: rgba(0, 0, 0, 0.45)">[{{ contentTypeMap[msg.ContentType] }}]</div>
              <el-image
                v-if="msg.thumbUrl"
                style="width: 30px; height: 30px; margin-right: 10px; border-radius: 15px"
                :src="msg.thumbUrl"
              >
                <div slot="error" class="image-slot">
                  <img src="@/assets/images/group/link.png" alt="" />
                </div>
              </el-image>
              <p style="width: 320px; color: rgba(0, 0, 0, 0.65)" class="ellipsis" v-text="msg.desc"></p>
            </el-row>

            <div>
              <el-button
                style="color: #a8a8a8"
                type="text"
                icon="el-icon-delete-solid"
                @click="deleteMsg(index)"
              ></el-button>
              <i
                draggable
                style="margin-left: 10px; cursor: pointer; color: #a8a8a8"
                class="fa fa-bars"
                @dragover="msgDragOver($event, index)"
                @dragend="msgDragEnd($event, index)"
              ></i>
            </div>
          </div>
        </div>

        <!-- 添加 -->
        <div class="add-msg">
          <el-tabs style="height: 150px" v-model="msgType" @tab-click="setMsgType">
            <el-tab-pane label="文本" name="Text">
              <el-input
                v-model="textContent"
                type="textarea"
                placeholder="请输入内容"
                maxlength="500"
                show-word-limit
                resize="none"
              ></el-input>
            </el-tab-pane>

            <el-tab-pane label="图片" name="Picture" class="tab-pane-picture">
              <label v-if="!pictureUrl" style="cursor: pointer; padding: 5px" for="addPicture">
                <i style="color: #bfbfbf" class="el-icon-circle-plus"></i>
                <span style="color: #bfbfbf; font-size: 14px; margin-left: 5px">上传图片</span>
              </label>
              <input
                v-show="false"
                id="addPicture"
                ref="pictureInputRef"
                type="file"
                accept=".jpg, .png, .jpeg"
                @change="chosePicture"
              />
              <img style="max-height: 82px; max-width: 100px" v-if="pictureUrl" :src="pictureUrl" alt="" />
              <div v-if="pictureUrl" class="pic-btn">
                <p style="max-width: 400px" class="ellipsis" v-text="pictureName"></p>
                <p style="color: #5a9cf8; cursor: pointer" @click="resetContent('Picture')">
                  <i class="el-icon-delete"></i>
                  删除
                </p>
              </div>
            </el-tab-pane>

            <el-tab-pane label="链接" name="Link" class="link-list">
              <div
                v-for="(link, index) in linkList"
                :key="index"
                class="we-app-item"
                :class="{ 'we-app-item-checked': linkContent.id === link.id }"
                :title="link.content.title"
                @click="linkContent = 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>
              </div>
            </el-tab-pane>

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

          <el-row
            style="height: 42px; padding: 0 5px; border-top: 1px solid rgba(0, 0, 0, 0.08)"
            type="flex"
            align="middle"
            justify="space-between"
          >
            <div style="margin-left: 20px">
              <Expression v-if="msgType === 'Text'" @expressionContent="modifyContent" />
            </div>
            <div>
              <el-button size="small" @click="resetContent(msgType)">重 置</el-button>
              <el-button size="small" type="primary" @click="addMsgToList">添 加</el-button>
            </div>
          </el-row>
        </div>
      </div>
      <!-- 预览 -->
      <div class="preview-box">
        <div class="preview-list">
          <div class="preview-item" v-for="(msg, index) in msgList" :key="index">
            <img style="height: 28px; margin-right: 5px" src="@/assets/images/group/prevideAvatar.png" alt="" />

            <p v-if="msg.ContentType === 'Text'" class="preview-item-bg" style="line-height: 30px">
              {{ msg.Content }}
            </p>
            <img
              v-if="msg.ContentType === 'Picture'"
              :src="msg.Content"
              style="max-width: 100px; max-height: 100px"
              alt=""
            />
            <div v-if="msg.ContentType === 'Link'" class="preview-item-bg preview-item-link">
              <p
                style="width: 160px; font-weight: 600; font-size: 14px; line-height: 30px"
                class="ellipsis"
                v-text="msg.jContent.title"
              ></p>
              <el-row type="flex" align="middle" justify="space-between">
                <p style="font-size: 12px" class="ellipsis-3" v-text="msg.jContent.desc"></p>
                <el-image style="width: 60px; min-width: 60px; height: 60px" :src="msg.thumbUrl">
                  <div slot="error" class="image-slot">
                    <img src="@/assets/images/group/link2.png" alt="" />
                  </div>
                </el-image>
              </el-row>
            </div>
            <div v-if="msg.ContentType === 'WeApp'" class="preview-item-bg" style="width: 170px">
              <p
                style="width: 160px; font-weight: 600; font-size: 14px; line-height: 30px"
                class="ellipsis"
                v-text="msg.jContent.appName"
              ></p>
              <el-image style="width: 160px; min-width: 160px" :src="msg.jContent.thumbUrl">
                <div slot="error" class="image-slot">
                  <img style="margin-left: 16px" src="@/assets/images/group/weApp.png" alt="" />
                </div>
              </el-image>
              <el-row type="flex" align="middle" style="height: 30px">
                <img
                  style="widht: 18px; height: 18px; margin-right: 5px; border-radius: 50%"
                  :src="msg.jContent.iconUrl"
                  alt=""
                />
                <p style="font-size: 10px; color: #a8a8a8">小程序</p>
              </el-row>
            </div>
          </div>
        </div>
      </div>

      <!-- footer -->
      <div class="group-send-footer" slot="footer">
        <el-radio-group v-model="timeRadio">
          <el-radio style="margin-right: 20px" :label="'rightNow'">立即发送</el-radio>
          <el-radio :label="'timing'">定时发送</el-radio>
          <el-date-picker
            v-model="refTime"
            style="width: 200px"
            type="datetime"
            placeholder="选择日期时间"
            clearable
            :disabled="timeRadio === 'rightNow'"
          ></el-date-picker>
        </el-radio-group>

        <!-- 发时间隔 -->
        <div>
          <span style="color: #606266">群发间隔时间</span>
          <el-input-number
            v-model="betweenTime"
            style="width: 100px; margin: 0 5px"
            controls-position="right"
            :min="0"
            :max="30"
          ></el-input-number>
          秒
        </div>

        <div>
          <el-button @click="resetData">取 消</el-button>
          <el-button type="primary" @click="sureSend">发 送</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { fileUpload } from '@/utils/upload'
import { addTaskTimeInfo, resourcesList } from '@/api/httpApi'
import Expression from '@/components/Expression'

export default {
  name: 'GroupAssistantSend',
  components: {
    Expression
  },
  data() {
    return {
      searchName: '', // 搜索昵称
      msgTarget: null,
      sendType: 'customers', // 群发的类型
      roomsList: [], // 群聊
      wxid2Send: [], // 群发的wxid
      editDialg: false, // 显示设置内容的dialog
      contentTypeMap: {
        Text: '文本',
        Picture: '图片',
        Link: '链接',
        WeApp: '小程序'
      },
      msgList: [],
      msgType: 'Text', // 正在创建的消息类型
      textContent: '', // 文本内容
      pictureUrl: '', // 图片url
      pictureName: '', // 图片名称
      linkContent: '', // 链接内容
      appContent: '', // 小程序内容
      linkList: [],
      weAppList: [],
      timeRadio: 'rightNow', // 立即发送还是定时发送
      refTime: new Date().getTime(),
      betweenTime: 1 // 群发间隔
    }
  },
  computed: {
    ...mapGetters({
      currentUser: 'currentUser',
      currentWeChatId: 'conversation/currentWeChatId',
      conversations: 'conversation/currentConvs', // 会话
      customers: 'conversation/currentCustomers', // 当前的客户列表
      currentContacts: 'conversation/currentContacts' // 当前的联系人列表
    }),
    // 表格中的数据
    tableData() {
      let td = []
      if (this.sendType === 'customers') {
        td = this.customers
      } else if (this.sendType === 'friends') {
        td = this.currentContacts
      } else {
        td = this.roomsList
      }
      // 搜索
      if (this.searchName) {
        td = td.filter((x) => {
          return x.Name && x.Name.indexOf(this.searchName) >= 0
        })
      }
      return td
    }
  },
  watch: {
    currentWeChatId() {
      // 微信改变 重新计算群聊
      this.roomsList = this.conversations.filter((x) => x.Members)
    }
  },
  created() {
    // 计算群聊
    this.roomsList = this.conversations.filter((x) => x.Members)
  },
  methods: {
    // 切换消息类型
    setMsgType(tab) {
      if (tab.name === 'Link') {
        resourcesList(this.currentUser.SupplierId, 1, 100, 'Link').then((res) => {
          if (res.code === 0 && res.data.rows) {
            if (this.resourcesType === 'Text') {
              this.linkList = res.data.rows
            } else {
              this.linkList = res.data.rows.map((x) => {
                let obj = { ...x }
                try {
                  obj.content = JSON.parse(x.content)
                } catch (error) {
                  console.log(error)
                }
                return obj
              })
            }
            console.log(this.linkList)
          } else {
            this.linkList = []
          }
        })
      } else if (tab.name === 'WeApp') {
        resourcesList(this.currentUser.SupplierId, 1, 100, 'WeApp').then((res) => {
          console.log(res)
          if (res.code === 0 && res.data.rows) {
            if (this.resourcesType === 'Text') {
              this.weAppList = res.data.rows
            } else {
              this.weAppList = res.data.rows.map((x) => {
                let obj = { ...x }
                try {
                  obj.content = JSON.parse(x.content)
                } catch (error) {
                  console.log(error)
                }
                return obj
              })
            }
          } else {
            this.weAppList = []
          }
        })
      }
    },
    // 计算序号
    indexMethod(index) {
      return index + 1
    },
    // 选择row
    handleSelectionChange(val) {
      this.wxid2Send = val
    },
    // 下一步
    sendNext() {
      if (this.wxid2Send.length > 0) {
        this.editDialg = true
      } else {
        this.$message.warning('请先选择要发送的好友！')
      }
    },
    // 添加表情
    modifyContent(rm) {
      this.textContent = this.textContent + rm
    },
    // 重置数据
    resetContent(ct) {
      if (ct === 'Text') {
        this.textContent = ''
      } else if (ct === 'Picture') {
        this.pictureUrl = ''
        this.pictureName = ''
        const fileObj = this.$refs.pictureInputRef // 文件对象
        fileObj.value = ''
      } else if (ct === 'Link') {
        this.linkContent = ''
      } else if (ct === 'WeApp') {
        this.appContent = ''
      }
    },
    setAppContent(weapp) {
      this.appContent = weapp
    },
    // 添加数据到列表
    addMsgToList() {
      let msgContent = {
        ContentType: this.msgType // 发送消息类型 Text Picture Voice Video Link File NameCard
      }
      let errMsg = ''
      if (this.msgType === 'Text') {
        if (this.textContent) {
          msgContent.Content = this.textContent
          msgContent.desc = this.textContent
        } else {
          errMsg = '请填写文本！'
        }
      } else if (this.msgType === 'Picture') {
        if (this.pictureUrl) {
          msgContent.Content = this.pictureUrl
          msgContent.thumbUrl = this.pictureUrl
          msgContent.desc = this.pictureName
        } else {
          errMsg = '请上传图片！'
        }
      } else if (this.msgType === 'Link') {
        if (this.linkContent) {
          msgContent.Content = JSON.stringify(this.linkContent.content)
          msgContent.jContent = this.linkContent.content
          msgContent.thumbUrl = this.linkContent.content.thumbUrl
          msgContent.desc = this.linkContent.content.desc
        } else {
          errMsg = '请选择链接！'
        }
      } else if (this.msgType === 'WeApp') {
        console.log(this.appContent)
        if (this.appContent) {
          msgContent.Content = JSON.stringify(this.appContent.content)
          msgContent.jContent = this.appContent.content
          msgContent.thumbUrl = this.appContent.content.iconUrl
          msgContent.desc =
            this.appContent.content.appName || this.appContent.content.title || this.appContent.content.desc
        } else {
          errMsg = '请选择小程序！'
        }
      }
      if (errMsg) {
        this.$message({
          type: 'warning',
          message: errMsg,
          duration: 1000
        })
      } else {
        this.msgList.push(msgContent)
        this.resetContent(this.msgType)
      }
    },
    // 删除要发的信息
    deleteMsg(deleteIndex) {
      this.msgList.splice(deleteIndex, 1)
    },
    // 拖拽消息
    msgDragOver(e, index) {
      this.msgTarget = index
      e.preventDefault()
    },
    // 释放消息
    msgDragEnd(e, index) {
      [this.msgList[index], this.msgList[this.msgTarget]] = [this.msgList[this.msgTarget], this.msgList[index]]
      this.$forceUpdate()
      e.preventDefault()
    },

    // 取消
    resetData() {
      this.editDialg = false
      this.msgType = 'Text'
      this.textContent = ''
      this.pictureUrl = ''
      this.pictureName = ''
      this.linkContent = ''
      this.appContent = ''
      this.wxid2Send = []
      this.msgList = []
      this.$refs.multipleTable.clearSelection()
    },
    // 选择图片
    chosePicture() {
      // 发送图片|视频|文件
      const fileObj = this.$refs.pictureInputRef.files // 文件对象
      // 如果有选中文件
      if (fileObj[0]) {
        const file = fileObj[0]
        // image/jpeg
        const isImage = file.type.indexOf('image') >= 0
        const isLt2M = file.size > 0 && file.size / 1024 / 1024 < 10

        if (!isImage) {
          this.$alert('图片格式不对！', '提示', { type: 'warning' })
          return
        }
        if (!isLt2M) {
          this.$alert('上传图片大小不能超过 10MB!', '提示', { type: 'warning' })
          return
        }
        // 验证通过
        const formdata = new FormData() // 上传
        formdata.append('myfile', file)
        const loading = this.$loading({
          lock: true,
          text: '文件上传中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        fileUpload(formdata)
          .then((res) => {
            this.pictureName = file.name // 文件名
            this.pictureUrl = res.data.url
            loading.close()
          })
          .catch((err) => {
            this.$alert(`${err}`, '文件上传失败', { type: 'error' })
            loading.close()
          })
      }
    },
    // 确认群发 立即发送和定时任务 都是走的定时发送接口
    sureSend() {
      // 没有内容不能发送
      if (this.msgList.length === 0) {
        this.$message.warning('请设置群发内容！')
        return
      }

      // 发送的起始时间
      let startTime = new Date().getTime()
      if (this.timeRadio === 'timing') {
        startTime = this.refTime
      }

      let message = {
        accountid: this.currentUser.UnionId,
        tasktype: this.sendType === 'customers' ? 1 : this.sendType === 'friends' ? 2 : 3, // 1、群发客户；2、群发联系人；3、群发群聊
        state: 1, // 状态1开启中0已完成
        wechatId: this.currentWeChatId, // 要执行的微信号
        wechatList: this.wxid2Send.map((x) => {
          return x.RemoteId
        }), // 好友的微信号
        execute_time: this.transformTime(startTime), // 执行时间
        // restype: typeMap[this.msgType], // 资源类型
        content: JSON.stringify(this.msgList),
        between_time: this.betweenTime // 发消息间隔时间
      }

      addTaskTimeInfo(message)
        .then((res) => {
          if (res.code === 0) {
            this.$message({
              type: 'success',
              message: '创建定时任务成功！',
              duration: 1000
            })
            this.resetData()
          } else {
            this.$message({
              type: 'error',
              message: '创建定时任务失败！',
              duration: 1000
            })
          }
        })
        .catch((err) => {
          this.$message.error(err.message)
        })
    },

    // 定时群发 时间转换
    transformTime(times) {
      var date = new Date(times)
      let Y = date.getFullYear() + '-'
      let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
      let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
      let m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
      // let s = date.getSeconds()
      let time = Y + M + D + h + m
      return time
    }
  }
}
</script>

<style lang="scss" scoped>
.group-assistant-send {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .group-send-operation {
    padding: 7px 15px 5px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
