<template>
  <div class="app-container">


    <div class = "search-bx"  >
        <div class="search">
          <el-row :gutter="0">


              <el-select v-model="tableObj.getdataListParm.parammaps.noticetype" placeholder="公告类型" class="filter-item" style="width: 120px;" clearable>
                  <el-option v-for="item in noticetypeList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>


               <el-input v-model="tableObj.getdataListParm.parammaps.noticetitle" placeholder="消息名词" style="width: 180px;" class="filter-item" clearable />


                <el-button class="successBorder" @click="form_search">查询</el-button>
                <el-button class="successBorder" @click="form_clear">重置</el-button>
                <el-button  class="success" icon="el-icon-plus" @click="form_add">新增</el-button>

          </el-row>
        </div>


    </div>


    <div class="table"   >
      <el-table :key="tableObj.tableKey" v-loading="tableObj.listLoading" element-loading-text="给我一点时间" :data="tableObj.list" border fit highlight-current-row style="width: 100%;" :row-style="rowStyle" :cell-style="cellStyle" class="elTable table-fixed">

        <el-table-column label="序号" align="center" type="index" width="50px">
          <template slot-scope="scope">
            <span>{{ scope.$index + (tableObj.pageNum-1) * tableObj.pageSize + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="公告标题" min-width="150px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.noticetitle }}</span>
          </template>
        </el-table-column>
        <el-table-column label="公告类型" min-width="150px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.noticetype }}</span>
          </template>
        </el-table-column>
        <el-table-column label="公告对象" min-width="150px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.roleName }}</span>
          </template>
        </el-table-column>


        <el-table-column label="公告内容" min-width="200px" align="center">
          <!-- <template slot-scope="scope">
            <span v-html="scope.row.content"> </span>
          </template> -->
          <!-- <template slot-scope="scope">
            <span style = "color:#409EFF; cursor: pointer;" @click="form_see_nums(scope.row)">查看</span>
          </template> -->
         <template slot-scope="scope">
            <el-popover
              placement="left"
              width="700"
              trigger="hover">

              <span v-html="scope.row.content" style="height:500px"> </span>
              <span slot="reference" style = "color:#409EFF; cursor: pointer;">查看</span>
            </el-popover>
          </template>
        </el-table-column>

        <el-table-column label="更新时间" min-width="150px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.updatedate }}</span>
          </template>
        </el-table-column>


        <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="{row}">
            <el-button  class="miniSuccess" @click="form_edit(row)">编辑</el-button>
            <el-button class="miniDanger" @click="form_delete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="tableObj.total>=0" :total="tableObj.total" :page.sync="tableObj.getdataListParm.offset" :limit.sync="tableObj.getdataListParm.pagecount" @pagination="get_table_data" />
    </div>

    <!-- 新增/编辑 -->
    <el-dialog :title="textMap[create.dialogStatus]" :visible.sync="create.dialogFormVisible" :close-on-click-modal="false" width="90%">
      <div class="app-add">
        <el-form ref="temp" :rules="create.rules" :model="create.temp" label-position="right" label-width="150px" style="width: 80%;margin:0 auto 50px">

          <el-form-item label="公告标题：" prop="noticetitle">
            <el-input ref="noticetitle" v-model="create.temp.noticetitle" />
          </el-form-item>


          <el-form-item label="公告类型：" prop="noticetype">
            <el-select v-model="create.temp.noticetype" placeholder="公告类型"  class="filter-item" style="width: 100%;"clearable>
              <el-option v-for="item in noticetypeList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>

          <el-form-item label="公告对象：" prop="roleNameArr">
            <el-select v-model="create.temp.roleNameArr" placeholder="公告对象"  class="filter-item" style="width: 100%;"clearable multiple>
              <el-option v-for="item in roleNameList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>


          <el-form-item label="公告内容：" prop="content">

           <div style="border: 1px solid #ccc;">
              <Toolbar
                  style="border-bottom: 1px solid #ccc"
                  :editor="editor"
                  :defaultConfig="toolbarConfig"
                  :mode="mode"
              />
              <Editor
                  style="height: 500px; overflow-y: hidden;"
                  v-model="create.temp.content"
                  :defaultConfig="editorConfig"
                  :mode="mode"
                  @onCreated="onCreated"
              />
          </div>


          </el-form-item>


          <el-form-item  label="上传附件：" prop="" v-show="false">

                <el-upload
                  ref = "upLoadBx"
                  class="avatar-uploader"
                  :headers="headers2"
                  :auto-upload="true"
                  :show-file-list="true"
                  :limit="1"
                  :action="uploadFileUrl"
                  :on-exceed="handleExceed"
                  :on-success="handlefileSuccess"
                  :file-list="uploadfileList1"
                  >
                   <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
            </el-form-item>


        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button v-if="create.dialogStatus==='create' || create.dialogStatus==='update'" class="success" @click="create.dialogStatus==='create'?add_dialog_save():form_edit_save()">确认</el-button>
          <el-button class="cancelClose" @click="create.dialogFormVisible = false;get_table_data()">关闭</el-button>

        </div>
      </div>
    </el-dialog>


  </div>
</template>
 <style src="@wangeditor/editor/dist/css/style.css"></style>
<script>
import { GetDataByName, PostDataByName, failproccess, ExecDataByConfig, GetDataByNames, checkButtons, calculativeWidth } from '@/api/common'
import { isIntegerZero } from '@/utils/validate'
import Cookies from 'js-cookie'
import { parseTime } from '@/utils/index.js'
import Pagination from '@/components/Pagination'
import { MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'


import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { DomEditor } from '@wangeditor/editor'


export default {
  name: 'PublicNotice',
  components: { Pagination, Editor, Toolbar},


  data() {
    return {


      headers2: {
        optname: 'insertcustompic',
        id: 1,
        token: getToken() // 从cookie里获取token，并赋值token
      },

      //图片文件请求地址
      uploadFileUrl: process.env.VUE_APP_BASE_API + 'uploadfileCRM',
      uploadfileList1: [],

      editor: null,

            toolbarConfig: {
               excludeKeys :[  // 排除菜单组，写菜单组 key 的值即可
                   'group-image',
                    'group-video',
                    'codeBlock',
                    'todo',
                    'undo',
                    'redo',
                    'fullScreen',
                    'emotion',
                    'blockquote',
                ]
            },
            editorConfig: { placeholder: '请输入内容...' },
            mode: 'default', // or 'simple'

      isRoleEdit: [],

      // 下拉框 - 出差单
      noticetypeList: [
        { "name": "重要通知", "id": "重要通知" },
        { "name": "规章制度", "id": "规章制度" },
        { "name": "指定周期", "id": "指定周期" }
      ],


      roleNameList: [
        // { "name": "全部", "id": "重要通知" },
        // { "name": "角色1", "id": "角色1" },
        // { "name": "角色2", "id": "角色2" },
        // { "name": "角色3", "id": "角色3" },
        // { "name": "角色4", "id": "角色4" },
      ],


      //表格请求参数~
      tableObj: {
        getdataListParm: {
          name: 'getNotice',
          page: 1,
          offset: 1,
          pagecount: parseInt(Cookies.get('pagecount')),
          returntype: 'Map',
          parammaps: {
            noticetype: '',
            noticetitle: '',
          }
        },
        tableKey: 0,
        list: [],
        total: 0,
        listLoading: true,
        temp: {}
      },

      // 新增/编辑
      create: {
        dialogFormVisible: false,
        dialogStatus: '',
        temp: {
          noticetitle: '',
          noticetype: '',
          roles: '',
          roleNameArr:[],
          content: '',
          id: '',
          fileId: 0,
          fileName: ''
        },
        rules: {
          // cname: [{ type: 'string', required: true, message: '必填', trigger: 'blur' }],
          // sort: [{ validator: isIntegerZero, trigger: 'blur' }]

        },
      },
      textMap: {
        create: '添加',
        update: '编辑'
      },

      requestParam: {},

      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' }
    }
  },

  created() {
    this.get_table_data()
    this.get_select_list()
    this.get_auto_buttons()
  },

  methods: {
    onCreated(editor) {
            this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错


        },
    //获取按钮权限
    get_auto_buttons() {
      const Edit = 'PublicNotice'


      const isRoleEdit = checkButtons(this.$store.state.user.buttons, 'PublicNotice')
      this.isRoleEdit = isRoleEdit


      // const isRoleEdit = checkButtons(JSON.parse(sessionStorage.getItem('buttons')), Edit)

      console.log("this.isRoleEdit",this.isRoleEdit)
      this.isRoleEdit = isRoleEdit
    },

    //获取所有下拉框的内容
    get_select_list() {
      // 下拉框请求
      var send_select_list = [
        { name: 'getRoleAll', offset: 0, pagecount: 0, parammaps: {} },

      ]
      GetDataByNames(send_select_list).then(response => {

        this.roleNameList = response.data.getRoleAll.list
        console.log("角色下拉框", this.roleNameList)

      })


    },


    //加载表格
    get_table_data() {
      this.tableObj.listLoading = true
      console.log("this.tableObj.getdataListParm======>", this.tableObj.getdataListParm)
      GetDataByName(this.tableObj.getdataListParm).then(response => {
        console.log('table数据======>', response.data.list)
        if (response.data.list !== null) {
          for (var i = 0; i < response.data.list.length; i++) {
              if(response.data.list[i].roles.length == 0 || response.data.list[i].roles == null || response.data.list[i].roles == undefined){
                  var roleNameArr = []
                  this.$set(response.data.list[i], 'roleNameArr', roleNameArr)
                } else {
                  var roleNameArr = response.data.list[i].roles.split(",")
                  this.$set(response.data.list[i], 'roleNameArr', roleNameArr)
              }
              }

          this.tableObj.list = response.data.list
          this.tableObj.pageNum = response.data.pageNum
          this.tableObj.pageSize = response.data.pageSize
          this.tableObj.total = response.data.total
        } else {
          this.tableObj.list = []
        }
        setTimeout(() => {
          this.tableObj.listLoading = false
        }, 100)
      })
    },
    form_search() {
      console.log('点击了查询')

      this.tableObj.getdataListParm.offset = 1
      this.get_table_data()
    },
    form_clear() {
      console.log('点击了重置')
      this.tableObj.getdataListParm.parammaps.noticetype = ''
      this.tableObj.getdataListParm.parammaps.noticetitle = ''
      this.tableObj.getdataListParm.offset = 1
      this.get_table_data()
    },

    // 添加
    form_reset() {
      this.create.temp = { noticetitle: '', noticetype: '', roles: '', content: '',  fileId: 0, id:'',roleNameArr:[],
          fileName: ''}

      if(this.$refs['upLoadBx']){
        this.$refs['upLoadBx'].clearFiles()
      }

    },


    // 删除
    form_delete(row) {
      MessageBox.confirm('是否确认删除此信息?', {
        confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        this.requestParam.name = 'delNotice'
        this.requestParam.parammaps = {}
        this.requestParam.parammaps.id = row.id
        PostDataByName(this.requestParam).then(response => {
          if (response.msg === 'fail') {
            this.$notify({ title: '删除失败', message: response.data, type: 'warning', duration: 2000 })
          } else {
            this.$notify({ title: '成功', message: '删除成功', type: 'success', duration: 2000 })
            this.get_table_data()
          }
        })
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消删除' })
      })
    },


    handleExceed(files, fileList) {
        this.$message.warning(`限制只能上传一个文件，请删除原文件后再上传新的原件`);
    },
    handlefileSuccess(response, file, fileList) {
        console.log(response, file, fileList)
        this.create.temp.fileId = response.data.LastInsertId
        this.create.temp.fileName = file.name
        this.$refs.temp.resetFields()

        console.log(file.name)
        console.log(response.data.LastInsertId)

        console.log(this.uploadfileList1)
    },


    //监听 - 弹窗 - 新增
    form_add() {
      console.log('点击了新增')
      this.form_reset()
      this.create.dialogStatus = 'create'
      this.create.dialogFormVisible = true
    },
    //监听 - 弹窗 - 新增保存
    add_dialog_save() {
      console.log('点击了新增保存',this.create.temp)


      // const toolbar = DomEditor.getToolbar(this.editor)

      // const curToolbarConfig = toolbar.getConfig()
      // console.log( curToolbarConfig.toolbarKeys )

      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      this.$refs['temp'].validate(valid => {
        if (valid) {
          this.isokDisable = true
          setTimeout(() => {
            this.isokDisable = false
          }, 1000)


            var roleNameArr = this.create.temp.roleNameArr
            if(roleNameArr.length == 0){
              var roles = ""
            } else {
              var roles =  roleNameArr.join()
            }

             this.create.temp.roles = roles

                var send_data = {
                  "name": "insertNotice",
                   "parammaps": this.create.temp
                }

                PostDataByName(send_data).then(response => {
                  console.log('新增保存发送参数', send_data)
                  if (response.msg !== 'fail') {
                    this.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })
                    this.create.dialogFormVisible = false
                    this.get_table_data()
                  } else {
                    this.$notify({ title: '失败', message: '保存失败', type: 'error', duration: 2000 })
                  }
                })


        }
      })
    },


    // 编辑
    form_edit(row) {
      console.log('点击了编辑', row)
      row.barid = String(row.barid)

      this.create.temp = Object.assign({}, row)
      this.create.temp.id = row.id
      this.create.dialogStatus = 'update'
      this.create.dialogFormVisible = true
      this.uploadfileList1 = [{ "name": this.create.temp.fileName,"url": "", "response": { "execresult": { "LastInsertId": process.env.VUE_APP_BASE_API + this.create.temp.fileId } } }]
    },

    // 编辑保存
    form_edit_save() {
      this.$refs['temp'].validate(valid => {
        if (valid) {
            var roleNameArr = this.create.temp.roleNameArr
            if(roleNameArr.length == 0){
              var roles = ""
            } else {
              var roles =  roleNameArr.join()
            }

             this.create.temp.roles = roles

                var send_data = {
                  "name": "updateNotice",
                   "parammaps": this.create.temp
                }

                PostDataByName(send_data).then(response => {
                  console.log('编辑保存发送参数', send_data)
                  if (response.msg !== 'fail') {
                    this.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })
                    this.create.dialogFormVisible = false
                    this.get_table_data()
                  } else {
                    this.$notify({ title: '失败', message: '保存失败', type: 'error', duration: 2000 })
                  }
                })


        }
      })
    },


    // 导出
    form_export(item) {
      if (item == 1) {
        console.log('点击了导出模板')
      } else {
        console.log('点击了导出数据')
      }
    },

    // 导入
    form_inport() {
      console.log('点击了导入')
    }

  },
    mounted() {
        // 模拟 ajax 请求，异步渲染编辑器
        // setTimeout(() => {
        //     this.html = '<p>模拟 Ajax 异步设置内容 HTML</p>'
        // }, 1500)
    },
    beforeDestroy() {
        const editor = this.editor
        if (editor == null) return
        editor.destroy() // 组件销毁时，及时销毁编辑器
    }
}
</script>
<style lang="scss" scoped>
.search {
  padding-top: 10px;
  clear: both;
}
.table {
  margin-top: 10px;
}
</style>
