<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" />
      <!--表格渲染-->
      <!-- :cell-class-name="cell"
        @selection-change="selectionChangeHandler"
         -->
      <el-table
        ref="table"
        :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" />
        <el-table-column prop="pushTo" label="推送对象" align="center" min-width="150" />
        <el-table-column prop="update_by" label="推送人" align="center" min-width="150" />
        <el-table-column prop="create_time" label="推送时间" align="center" min-width="180">
          <template slot-scope="scope">
            <div>{{ scope.row.create_time | parseTime }}</div>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="bindState" label="绑定状态" align="center">
          <template slot-scope="scope">
            <span class="clear" style="width:76px">{{ scope.row.bindState }}</span>
          </template>
        </el-table-column> -->
      </el-table>
      <!-- <pagination /> -->
      <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="sendForm.msgType" 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 type="primary" @click="handleSave">保存</el-button>
          </div>
        </div>
      </el-dialog>
      <!-- 删除 -->
      <el-dialog :visible.sync="delVisible" title="提示" @close="handleClose">
        <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 { presenter, crud } from '@crud/crud'
// import pagination from '@crud/Pagination'
import { getAllDev, getAllUser, getNoticeList } from '@/api/system/logs'

export default {
  name: 'NotifyManage',
  // components: { pagination },
  mixins: [presenter(), crud()],
  // cruds() {
  //   return CRUD({
  //     url: '/api/notice/list'
  //     // optShow: {
  //     //   add: false,
  //     //   edit: false,
  //     //   del: false,
  //     //   download: true
  //     // }
  //   })
  // },
  data() {
    return {
      tableData: [],
      selections: [],
      sendVisible: false,
      delVisible: false,
      sendForm: {
        msgType: 1,
        notification: '',
        pushObj: '用户',
        sendObj: ['全选']
      },
      pushObj: '用户',
      checked: '',
      msgTypeOptions: [
        { value: 1, label: '系统通知' }
        // { value: 2, label: '报警消息', disabled: true },
        // { value: 3, label: '借还消息', disabled: true },
        // { value: 4, label: '下载消息', disabled: true }
      ],
      userOptions: [
        // { value: 0, label: '全部用户' },
        // { value: 1, label: '部门名称 - 张三' },
        // { value: 2, label: '部门名称 - 李四' },
        // { value: 3, label: '部门名称 - 王五' },
        // { value: 4, label: '部门名称 - 张三' },
        // { value: 5, label: '部门名称 - 李四' },
        // { value: 6, label: '部门名称 - 王五' },
        // { value: 7, label: '部门名称 - 王五' }
      ],
      devOptions: [
        // { value: 0, label: '全部设备' },
        // { value: 1, label: '设备1' },
        // { value: 2, label: '设备2' },
        // { value: 3, label: '设备3' }
      ],
      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
      }
    }
  },
  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
      }
      params.page = this.page.page - 1
      params.size = this.page.size
      return params
    },
    getTableData() {
      getNoticeList(this.getParams()).then(res => { // 获取列表
        console.log(res, 'res')
        const table = res.content
        this.page.total = res.totalElements
        table.forEach(item => {
          item.pushTo = null
          if (item.noticeDevices.length > 0) { // 推送对象为设备
            if (item.noticeDevices.length === this.devOptions.length - 1) {
              item.pushTo = '全部设备'
            } else {
              // let push
              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.noticeUsers.length > 0) { // 推送对象为用户
            // pushArr = item.noticeDevices
            if (item.noticeUsers.length === this.devOptions.length - 1) {
              item.pushTo = '全部用户'
            } else {
              // let push
              item.pushTo = item.noticeUsers.map(i => {
                let user = null
                this.userOptions.forEach(val => {
                  if (val.value === i.userId) {
                    user = val.label
                  }
                })
                return user
              })
            }
          }
        })
        console.log(table, 'table')
        this.tableData = table
      })
    },
    // 获取用户
    async getUser() {
      await getAllUser().then(res => {
        console.log(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)
        console.log(this.userOptions, '---用户')
      })
    },
    // 获取设备
    async getDev() {
      await getAllDev().then(res => {
        console.log(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)
        console.log(this.devOptions, '---设备')
      })
    },
    // 每页条数改变
    sizeChangeHandler(e) {
      this.loading = true
      this.page.size = e
      this.page.page = 1
      this.getTableData(this.getParams())
      this.loading = false
    },
    // 当前页改变
    pageChangeHandler(e) {
      this.loading = true
      this.page.page = e
      this.params.page = e - 1
      this.getTableData(this.getParams())

      this.loading = false
    },
    clickRowHandler(row) {
      // this.$refs.table.clearSelection()
      this.$refs.table.toggleRowSelection(row) // 单选选中
    },
    selectionChangeHandler(val) {
      this.selections = val
    },
    // 发布
    handleSend() {
      this.defaultSelAll()
      this.sendVisible = true
    },
    handleEdit() {
      this.sendForm.notification = this.selections[0].notification
      this.sendVisible = true
    },
    // 保存
    handleSave() {
      this.$refs.formDom.validate((valid) => {
        if (valid) {
          // noticeCreate(params).then(res => {
          //   if (res === SUCCESS) {
          //     this.sendVisible = false
          //     this.$refs.formDom.resetFields()
          //     this.$refs.formDom.clearValidate()
          //   }
          // })
          this.sendVisible = false
          this.$refs.formDom.resetFields()
          this.$refs.formDom.clearValidate()
        } else {
          return false
        }
      })
    },
    handleClose() {
      this.$refs.formDom.resetFields()
      this.$refs.formDom.clearValidate()
    },
    // 删除
    handleDel() {
      this.delVisible = true
    },
    // 删除确认
    handleDelConfirm() {
      this.delVisible = false
    },
    // 选择器 推送对象
    handelChange(val) {
      if (val.length === this.sendObjOptions.length) {
        this.checked = true
      } else {
        this.checked = false
      }
    },
    // selectAll(val) {
    //   this.sendForm.sendObj = []
    //   if (val) {
    //     this.sendForm.sendObj = this.sendObjOptions.map(item => item.value)
    //   } else {
    //     this.sendForm.sendObj = []
    //   }
    //   // console.log(this.sendForm.sendObj)
    // },
    // el-select 选中值发生变化时触发，val为目前选中的值
    // 默认全选
    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
      }
      // 最后选中得值
      // var endSelectVal = val[val.length - 1]
      // // showTags配合 collapse-tags 属性来
      // if (!val.includes('全选') && val.length === this.sendObjOptions.length) {
      //   // 当前选中得值不包含“全选”，且其他项全选中
      //   this.showTags = true
      //   val.unshift('全选')
      //   this.$refs.selectBox.$el.querySelector('.el-input__inner').style.height = '34px'
      // } else if (val.includes('全选') && val.length === 1) {
      //   // 当前选中得值是“全选”时
      //   this.showTags = true
      //   this.sendObjOptions.map(item => {
      //     val.push(item.value)
      //   })
      // } else if (val.includes('全选') && val.length - 1 < this.sendObjOptions.length && endSelectVal === '全选') {
      //   // 当前选中得值是其他项，未全部选完，而最后选中得是“全选”时
      //   val = []
      //   this.sendObjOptions.map(item => {
      //     val.push(item.value)
      //   })
      //   val.unshift('全选')
      //   this.showTags = true
      //   this.$refs.selectBox.$el.querySelector('.el-input__inner').style.height = '34px'
      // } else if (val.includes('全选') && val.length - 1 < this.sendObjOptions.length) {
      //   // 当前选中得值是其他项，未全部选完时
      //   this.showTags = false
      //   val = val.filter(item => {
      //     return item !== '全选'
      //   })
      // }
      // this.selectOptions = val // 赋值给select绑定得
    },
    pushObjChange(val) {
      if (val) {
        // this.selectOptions = []
        // this.showTags = false
        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;
}

.delMsg{
  color: #fff;
  font-size: 16px;
}
::v-deep .el-form-item__error{
  top: 93%;
}
</style>
