<template>
  <div>
    <div class="head-container">
      <el-button class="iconfont icon-fabu-fanbai" size="mini" @click="handleSend">发布</el-button>
      <el-button icon="el-icon-edit" size="mini" :disabled="!(selections.length === 1)" @click="handleEdit">修改</el-button>
      <el-button icon="el-icon-delete" size="mini" :disabled="!selections.length" @click="handleDel">删除</el-button>
    </div>
    <div class="app-container container-wrap">
      <span class="right-top-line" />
      <span class="left-bottom-line" />
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="isLoading"
        :default-sort="{prop: 'create_time', order: 'descending'}"
        :data="tableData"
        style="width: 100%;"
        height="calc(100vh - 294px)"
        @row-click="clickRowHandler"
        @selection-change="selectionChangeHandler"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="100" align="center" />
        <el-table-column prop="noticeContent" :show-overflow-tooltip="true" label="通知内容" min-width="200" align="center" />
        <el-table-column prop="noticeType" label="消息类型" align="center" min-width="150">
          <!-- <span v-if="scope.row.noticeType===1">系统消息</span> -->
          <span>系统消息</span>
        </el-table-column>
        <el-table-column prop="pushTo" :show-overflow-tooltip="true" label="推送对象" align="center" min-width="150">
          <template slot-scope="scope">
            <span v-if="typeof(scope.row.pushTo)==='string'">{{ scope.row.pushTo }}</span>
            <div v-if="!(typeof(scope.row.pushTo)==='string')" class="tag-hidden">
              <!-- <el-tag v-for="(item,i) in scope.row.pushTo" :key="i" style="margin-left:3px;color: #fff">{{ item }}</el-tag> -->
              {{ scope.row.pushTo.join('，') }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="update_by" label="推送人" align="center" min-width="150" />
        <el-table-column prop="create_time" :sortable="true" label="推送时间" align="center" min-width="180">
          <template slot-scope="scope">
            <div>{{ scope.row.create_time | parseTime }}</div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :page-size.sync="page.size"
        :total="page.total"
        :current-page.sync="page.page"
        style="margin-top: 8px;"
        layout="total, prev, pager, next, sizes"
        @size-change="sizeChangeHandler($event)"
        @current-change="pageChangeHandler"
      />
      <!-- 发布 -->
      <el-dialog append-to-body :close-on-click-modal="false" :visible.sync="sendVisible" title="发布通知" @close="handleClose">
        <span class="dialog-right-top" />
        <span class="dialog-left-bottom" />
        <div class="setting-dialog">
          <el-form ref="formDom" :rules="rules" :model="sendForm" size="small" label-width="80px" style="margin-left:85px">
            <el-form-item label="消息类型" prop="msgType" class="down-select">
              <el-select v-model="noticeType" placeholder="请选择" style="width:315px">
                <el-option
                  v-for="item in msgTypeOptions"
                  :key="item.name"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="发布内容" prop="notification" style="margin-bottom:8px">
              <textarea v-model="sendForm.notification" cols="38" rows="6" />
            </el-form-item>
            <el-form-item label="推送对象" prop="">
              <el-radio-group v-model="pushObj" @change="pushObjChange">
                <el-radio label="用户">用户</el-radio>
                <el-radio label="设备">设备</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="选择对象" prop="paramName">
              <el-select ref="selectBox" v-model="selectOptions" multiple :collapse-tags="showTags" clearable placeholder="请选择" style="width:315px" @change="changeSelect">
                <!-- <el-option key="全选" label="全选" value="全选" /> -->
                <el-option v-for="item in sendObjOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button v-loading="btnloading" type="primary" @click="handleSave">保存</el-button>
          </div>
        </div>
      </el-dialog>
      <!-- 删除 -->
      <el-dialog :visible.sync="delVisible" title="提示">
        <span class="dialog-right-top" />
        <span class="dialog-left-bottom" />
        <div class="setting-dialog">
          <p class="delMsg">确定删除所选消息吗？</p>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="handleDelConfirm">确定</el-button>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { noticeCreate, getAllDev, getAllUser, getNoticeList, noticeDel } from '@/api/system/logs'
export default {
  name: 'NotifyManage',
  inject: ['reload'],
  data() {
    return {
      isLoading: false,
      tableData: [],
      selections: [],
      sendVisible: false,
      delVisible: false,
      sendForm: {
        // msgType: 1,
        notification: '',
        // pushObj: '用户',
        sendObj: ['全选']
      },
      pushObj: '用户',
      checked: '',
      noticeType: 1,
      msgTypeOptions: [
        { value: 1, label: '系统通知' }
        // { value: 2, label: '报警消息', disabled: true },
        // { value: 3, label: '借还消息', disabled: true },
        // { value: 4, label: '下载消息', disabled: true }
      ],
      userOptions: [],
      devOptions: [],
      selectOptions: [],
      oldSelect: null,
      showTags: true,
      rules: {
        // msgType: [
        //   { required: true, message: '请选择类型', trigger: 'blur' }
        // ],
        notification: [
          { required: true, message: '请填写内容', trigger: 'blur' }
        ],
        pushObj: [
          { required: true, message: '请选择推送对象', trigger: 'blur' }
        ]
      },
      allUser: null,
      allDev: null,
      page: {
        total: 0,
        size: 10,
        page: 1
      },
      btnloading: false,
      isEdit: null
    }
  },
  computed: {
    sendObjOptions() {
      if (this.pushObj === '用户') {
        return this.userOptions
      } else {
        return this.devOptions
      }
    }
  },
  async created() {
    await this.getUser()
    await this.getDev()
    this.getTableData()
  },
  methods: {
    getParams() {
      const params = {
        page: null,
        size: null,
        sort: 'createTime,desc'
      }
      params.page = this.page.page - 1
      params.size = this.page.size
      return params
    },
    getTableData() {
      this.isLoading = true
      getNoticeList(this.getParams()).then(res => { // 获取列表
        console.log(res, 'res')
        const table = res.content
        this.page.total = res.totalElements
        table.forEach(item => {
          item.pushTo = null
          item.pushVal = null
          if (item.pushType === 2) { // 推送对象为设备
            item.pushVal = item.noticeDevices.map(i => { return i.deviceInfoId })
            item.pushTo = item.noticeDevices.map(i => {
              let dev = null
              this.devOptions.forEach(val => {
                if (val.value === i.deviceInfoId) {
                  dev = val.label
                }
              })
              return dev
            })
          } else if (item.pushType === 1) { // 推送对象为用户
            item.pushVal = item.noticeUsers.map(i => { return i.userId })
            item.pushTo = item.noticeUsers.map(i => {
              let user = null
              this.userOptions.forEach(val => {
                if (val.value === i.userId) {
                  user = val.label
                }
              })
              return user
            })
          }
          // 去重
          const arrTo = []
          const arrVal = []
          item.pushTo.forEach(i => {
            if (arrTo.indexOf(i) === -1 && i !== null) {
              arrTo.push(i)
            }
          })
          item.pushVal.forEach(i => {
            if (arrVal.indexOf(i) === -1 && i !== null) {
              arrVal.push(i)
            }
          })
          item.pushVal = arrVal
          if (item.pushType === 1) { // 用户
            item.pushTo = arrVal.length === this.userOptions.length - 1 ? '全部用户' : arrTo
          } else {
            item.pushTo = arrVal.length === this.devOptions.length - 1 ? '全部设备' : arrTo
          }
        })
        this.tableData = table
        this.isLoading = false
      })
    },
    // 获取用户
    async getUser() {
      await getAllUser().then(res => {
        const arr0 = [{ value: 0, label: '全部用户' }]
        const arr = res.map(item => {
          const val = item.id
          const lab = item.dept.name + '-' + item.username
          const obj = {
            value: val,
            label: lab
          }
          return obj
        })
        this.userOptions = arr0.concat(arr)
      })
    },
    // 获取设备
    async getDev() {
      await getAllDev().then(res => {
        const arr0 = [{ value: 0, label: '全部设备' }]
        const arr = res.map(item => {
          const val = item.id
          const lab = item.deviceName
          const obj = {
            value: val,
            label: lab
          }
          return obj
        })
        this.devOptions = arr0.concat(arr)
      })
    },
    // 每页条数改变
    sizeChangeHandler(e) {
      this.loading = true
      this.page.size = e
      this.page.page = 1
      this.getTableData()
      this.loading = false
    },
    // 当前页改变
    pageChangeHandler(e) {
      this.loading = true
      this.page.page = e
      this.getTableData()
      this.loading = false
    },
    clickRowHandler(row) {
      // this.$refs.table.clearSelection()
      this.$refs.table.toggleRowSelection(row) // 单选选中
    },
    selectionChangeHandler(val) {
      this.selections = val
      console.log(val)
    },
    // 发布
    handleSend() {
      this.defaultSelAll()
      this.isEdit = false
      this.sendVisible = true
    },
    // 修改
    handleEdit() {
      this.isEdit = true
      this.sendForm.notification = this.selections[0].noticeContent
      const temp = this.selections[0].pushVal
      if (this.selections[0].pushType === 1) {
        this.pushObj = '用户'
        this.selectOptions = temp.length === this.userOptions.length - 1 ? [0, ...temp] : temp
      } else {
        this.pushObj = '设备'
        this.selectOptions = temp.length === this.devOptions.length - 1 ? [0, ...temp] : temp
      }
      this.sendVisible = true
    },
    // 保存
    handleSave() {
      this.$refs.formDom.validate((valid) => {
        if (valid) {
          this.noticeSend(this.getPushParams())
        } else {
          return false
        }
      })
    },
    getPushParams() { // 发布消息参数
      const params = {}
      params.noticeType = this.noticeType
      params.noticeContent = this.sendForm.notification
      //* ************** */
      if (this.pushObj === '用户') { // 选择用户
        params.pushType = 1
        params.userId = this.selectOptions.filter(item => item !== 0)
      } else { // 选择设备
        params.pushType = 2
        params.deviceInfoId = this.selectOptions.filter(item => item !== 0)
      }
      if (this.isEdit) {
        params.id = this.selections[0].id
      }
      console.log(params, '参数')
      return params
    },
    // 调用发布接口
    noticeSend(params) {
      noticeCreate(params).then(res => {
        if (res === 'SUCCESS') {
          this.btnloading = false
          this.sendVisible = false
          // this.getTableData()
          this.reload()
          this.$message({
            message: '发布成功',
            type: 'success'
          })
          this.$refs.formDom.resetFields()
          this.$refs.formDom.clearValidate()
        } else {
          this.btnloading = false
          this.$message.error('发布失败')
        }
      })
    },
    handleClose() {
      this.$refs.formDom.resetFields()
      this.$refs.formDom.clearValidate()
      this.sendForm.notification = ''
      this.pushObj = '用户'
      this.noticeType = 1
    },
    // 删除
    handleDel() {
      this.delVisible = true
    },
    // 删除确认
    handleDelConfirm() {
      const params = this.selections.map(item => { return item.id })
      noticeDel(params).then(res => {
        if (res === 'SUCCESS') {
          // this.getTableData()
          this.delVisible = false
          this.reload()
          this.$message({
            message: '删除成功',
            type: 'success'
          })
        } else {
          this.$message.error('删除失败')
        }
      })
    },
    // 选择器 推送对象
    handelChange(val) {
      if (val.length === this.sendObjOptions.length) {
        this.checked = true
      } else {
        this.checked = false
      }
    },
    // 默认全选
    defaultSelAll() {
      this.selectOptions = this.sendObjOptions.map(item => { return item.value })
      this.oldSelect = this.selectOptions
      this.showTags = true
    },
    changeSelect(val) {
      if (val[val.length - 1] === 0) { // 选中全选
        this.defaultSelAll()
        this.$refs.selectBox.$el.querySelector('.el-input__inner').style.height = '34px'
      } else {
        const arr1 = this.oldSelect.filter(item => item !== 0)
        const arr2 = val.filter(item => item !== 0)
        if (arr1.length === arr2.length) { // 取消全选
          this.selectOptions = []
        } else if (arr1.length < arr2.length && arr2.length === this.sendObjOptions.length - 1) {
          this.defaultSelAll() // 除全选时都选中 此时加入全选
          this.$refs.selectBox.$el.querySelector('.el-input__inner').style.height = '34px'
        } else {
          this.selectOptions = this.selectOptions.filter(item => item !== 0) // 取消其他选项时 去除全选
          this.showTags = false
        }
        this.oldSelect = this.selectOptions
      }
    },
    pushObjChange(val) {
      if (val) {
        this.defaultSelAll()
        this.showTags = true
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/styles/lend-manage.scss';
.head-container{
  padding-bottom: 0;
}
.container-wrap{
  min-height: calc(100vh - 242px)
}
textarea{
  background-color: #021941;
  border: 1px solid #339CFF;
  border-radius: 3px;
  &:focus{
    outline: none;
  }
  caret-color: #fff;
  color: #fff;
  padding: 10px 12px;
  font-size: 14px;
}
::v-deep .el-radio-group{
  width: 315px;
  height: 32px;
  border: 1px solid #339CFF;
  border-radius: 3px;
  padding-left: 14px;
  display: flex;
  label{
    display: flex;
    align-items: center;
    margin-right: 50px;
    span{
      color: #3A99FD;
      margin-left: 10px;
    }
  }
}
.el-checkbox{
  display: flex;
  justify-content: right;
  align-items: center;
  padding-right: 20px;
}
::v-deep .el-form-item__error{
  top: 93%;
}
.tag-hidden{
  width: 100%;
  overflow: hidden;
  text-overflow:ellipsis;
  white-space: nowrap;
}
</style>
