<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
  <div>
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      v-dialogDrag
      width="1400px"
      height="500px"
      @close="close"
      append-to-body
      @keyup.enter.native=""
      :visible.sync="visible">
      <el-form size="small" :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view' || method === 'read'?'readonly':''" :disabled="method==='view' || method === 'read'"
             label-width="80px" @submit.native.prevent>
      <el-row  :gutter="15">
        <el-col :span="12">
          <el-form-item label="通告状态" prop="notifyType"
                        :rules="[
                  {required: true, message:'通告状态不能为空', trigger:'blur'}
                 ]">
            <el-select size="medium" @change="changeNotifyType" v-model="inputForm.notifyType" placeholder="请选择"  style="width: 100%;">
              <el-option
                v-for="item in $dictUtils.getDictList('oa_notify_status')"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="inputForm.notifyType === '0'">
          <el-form-item label="通告时间" prop="dates"
                        :rules="[
                                {required: true, message:'通告时间不能为空', trigger:'blur'}
                   ]">
            <el-date-picker
              size="medium"
              style="width: 100%"
              placement="bottom-start"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              v-model="inputForm.dates"
              type="datetimerange"
              range-separator="至"
              @input="daterangeChange"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="类型" prop="type"
                        :rules="[
                  {required: true, message:'类型不能为空', trigger:'blur'}
                 ]">
            <el-select size="medium" v-model="inputForm.type" placeholder="请选择"  style="width: 100%;">
              <el-option
                v-for="item in $dictUtils.getDictList('oa_notify_type')"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="标题" prop="title"
                        :rules="[
                  {required: true, message:'标题不能为空', trigger:'blur'}
                 ]">
            <el-input size="medium" v-model="inputForm.title" placeholder="请填写标题"     ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="文号" prop="no"
                        :rules="[
                 ]">
            <el-input size="medium" v-model="inputForm.no" placeholder="请填写文号"     ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="创建人" prop="createBy.name"
                        :rules="[
                   ]">
            <el-input size="medium" :disabled="true" v-model="inputForm.createBy.name" placeholder="请填写创建人" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属部门" prop="officeId"
                        :rules="[
                   ]">
            <SelectTree
              ref="officeTree"
              :props="{
                          value: 'id',             // ID字段名
                          label: 'name',         // 显示名称
                          children: 'children'    // 子级字段名
                        }"
              :url="`/sys/office/treeData?type=2`"
              :value="inputForm.officeId"
              :accordion="true"
              :disabled="true"
              size="medium"
              @getValue="(value) => {inputForm.officeId=value}"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="内容" prop="content"
                        :rules="[
                   ]">
            <WangEditor ref="contentEditor" v-model="inputForm.content" @getUrl="(url, lsUrl) => {
                        inputForm.editorFilesDTOList.push({temporaryUrl: lsUrl, url: url})
                        }" @change="changeEditor"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider content-position="left">
        <div style="float:left;"><i class="el-icon-document"></i> 通告范围-部门</div>
        <div style="float:left;">
          <el-button style="margin-left: 20px" :disabled="true" type="primary"  size="mini" @click="openOfficeChoose" plain>
            选择
          </el-button>
        </div>
      </el-divider>
      <el-row  :gutter="15" >
        <el-form :disabled="true">
          <vxe-table
            border
            :column-config="{resizable: true}"
            show-overflow
            show-footer
            :key="tableKeyOffice"
            ref="officeTable"
            class="vxe-table-element"
            :data="inputForm.pluginNotifyOfficesDTOList"
            style=""
            @cell-click=""
            @edit-closed=""
            highlight-current-row
          >
            <vxe-table-column align="center" field="officeName" title="部门"></vxe-table-column>
            <vxe-table-column align="center" title="操作" width="100">
              <template v-slot="scope">
                <el-button size="mini" type="danger" @click="removeEvent(scope.row,scope.$rowIndex,'office')">删除</el-button>
              </template>
            </vxe-table-column>
          </vxe-table>
        </el-form>
      </el-row>

      <div style="margin-top: 30px">
        <el-divider content-position="left" >
          <div style="float: left"><i class="el-icon-document"></i> 通告范围-成员</div>
          <UserSelectButton ref="userSelectButton" :disabled="true" @getValue="(value) => {openUserChoose(value)}"></UserSelectButton>
        </el-divider>
      </div>
      <el-row  :gutter="15">
        <el-form :disabled="true">
          <vxe-table
            border
            :column-config="{resizable: true}"
            show-overflow
            show-footer
            :key="tableKeyUser"
            ref="userTable"
            class="vxe-table-element"
            :data="inputForm.pluginNotifyUserDTOList"
            style=""
            @cell-click=""
            @edit-closed=""
            highlight-current-row
          >
            <vxe-table-column align="center" field="userName" title="姓名"></vxe-table-column>
            <vxe-table-column align="center" field="officeName" title="部门"></vxe-table-column>
            <vxe-table-column align="center" title="操作" width="100">
              <template v-slot="scope">
                <el-button size="mini" type="danger" @click="removeEvent(scope.row,scope.$rowIndex,'user')">删除</el-button>
              </template>
            </vxe-table-column>
          </vxe-table>
        </el-form>
      </el-row>
    </el-form>
<!--      附件-->
      <UpLoadComponent ref="uploadComponent"></UpLoadComponent>
<!--      评论-->
      <div v-if="method === 'view' || method === 'read'" style="margin-top: 30px">
        <el-divider content-position="left"><i class="el-icon-document"></i>发表评论</el-divider>
        <el-row>
          <el-col style="margin-bottom: 20px">
            <el-input v-model="inputForm.comment"
                      type="textarea"
                      :rows="5"
                      maxlength="500"
                      placeholder="请输入评论信息"
                      show-word-limit>
            </el-input>
          </el-col>
          <el-button style="float: right" type="primary" size="mini" @click="pushComment()" plain>
            发表
          </el-button>
          <el-button style="float: right; margin-right: 20px" type="primary" size="mini" @click="cleanComment()" plain>
            清空
          </el-button>
        </el-row>

        <el-divider  content-position="left"><i class="el-icon-document"></i>全部评论({{inputForm.comments.length}}条)</el-divider>
        <div v-for="(item, index) in inputForm.comments">
          <el-divider></el-divider>
          <div class="font_div" style="width: 100%; height:30px;"><span>{{item.userName}}</span></div>
          <div style="margin-left: 20px; height:45px;"><span>{{item.comments}}</span></div>
          <div style="width: 100%; height:30px;">
            <span>{{item.deff}}</span>
            <el-link v-if="$store.state.user.id === item.createId || isAdmin" style="float: right" type="text" size="mini" @click="delComment(item.id)">删除</el-link>
          </div>
        </div>
      </div>


      <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="close()" icon="el-icon-circle-close">关闭</el-button>
      <el-button size="small" v-if="method === 'edit'" type="primary" icon="el-icon-circle-check" @click="doSubmitBefore()">确定</el-button>
    </span>
    </el-dialog>

    <OfficeTreeSelect ref="officeTreeSelect" @getOfficeChoose="getOfficeChoose"></OfficeTreeSelect>
  </div>
</template>

<script>
  import UserSelect from '@/components/userSelect'
  import NotifyService from '@/api/notify/NotifyService'
  import SelectTree from '@/components/treeSelect/treeSelect.vue'
  import WangEditor from '@/components/editor/WangEditor'
  import OfficeTreeSelect from '@/components/officeTreeSelect'
  import UserSelectButton from '@/components/userSelectButton/DividerButton'
  import UserService from '@/api/sys/UserService'
  import UpLoadComponent from '@/views/common/UpLoadComponent'
  export default {
    props: {
      businessId: {
        type: String,
        default: ''
      },
      formReadOnly: {
        type: Boolean,
        default: false
      },
      status: {
        type: String,
        default: ''
      }
    },
    data () {
      return {
        title: '',
        method: '',
        loading: false,
        inputForm: {
          createBy: {
            id: '',
            name: ''
          },
          createDate: '',
          id: '',
          type: '',
          title: '',
          content: '',
          files: '',
          status: '',
          remarks: '',
          notifyType: '',
          no: '',
          beginDate: '',
          endDate: '',
          dates: '',
          officeId: '',
          workAttachmentDtoList: [],
          pluginNotifyOfficesDTOList: [],
          pluginNotifyUserDTOList: [],
          editorFilesDTOList: [],
          comments: [],
          comment: ''
        },
        keyWatch: '',
        tableKeyOffice: '',
        tableKeyUser: '',
        visible: false,
        isAdmin: false
      }
    },
    computed: {
      bus: {
        get () {
          return this.businessId
        },
        set (val) {
          this.businessId = val
        }
      }
    },
    watch: {
      'keyWatch': {
        handler (newVal) {
          if (this.commonJS.isNotEmpty(this.bus)) {
            this.init('', this.bus)
          } else {
            this.$nextTick(() => {
              this.$refs.inputForm.resetFields()
            })
          }
        }
      }
    },
    components: {
      UserSelect,
      SelectTree,
      WangEditor,
      OfficeTreeSelect,
      UserSelectButton,
      UpLoadComponent
    },
    notifyService: null,
    userService: null,
    created () {
      this.notifyService = new NotifyService()
      this.userService = new UserService()
    },
    methods: {
      // 查询当前用户是否是管理员用户
      checkIsAdmin () {
        this.userService.is().then(({data}) => {
          this.isAdmin = data
        })
      },
      getKeyWatch (keyWatch) {
        this.keyWatch = keyWatch
      },
      init (method, id) {
        this.method = method
        this.inputForm = {
          createBy: {
            id: '',
            name: ''
          },
          createDate: '',
          id: '',
          type: '',
          title: '',
          content: '',
          files: '',
          status: '',
          remarks: '',
          notifyType: '',
          no: '',
          beginDate: '',
          endDate: '',
          dates: ['', ''],
          officeId: '',
          workAttachmentDtoList: [],
          pluginNotifyOfficesDTOList: [],
          pluginNotifyUserDTOList: [],
          editorFilesDTOList: [],
          comments: [],
          comment: ''
        }
        this.inputForm.id = id
        if (method === 'add') {
          this.title = '新建通告'
        } else if (method === 'edit') {
          this.title = '修改通告'
        } else if (method === 'view') {
          this.title = '查看通告'
        } else if (method === 'read') {
          this.title = '阅读通告'
        }
        this.visible = true
        this.loading = false
        this.$nextTick(() => {
          this.$refs.inputForm.resetFields()
          this.loading = true
          this.$refs.contentEditor.clear()
          this.notifyService.query({id: this.inputForm.id, isSelf: method === 'read'}).then(({data}) => {
            this.checkIsAdmin()
            this.$refs.uploadComponent.clearUpload()
            this.inputForm = this.recover(this.inputForm, data)
            this.inputForm = JSON.parse(JSON.stringify(this.inputForm))
            if (this.method === 'view' || this.method === 'read') {
              this.$refs.contentEditor.disable()
            } else {
              this.$refs.contentEditor.enable()
            }
            if (this.commonJS.isNotEmpty(this.inputForm.content)) {
              this.$refs.contentEditor.init(this.inputForm.content)
            }
            if (this.commonJS.isEmpty(this.inputForm.editorFilesDTOList)) {
              this.inputForm.editorFilesDTOList = []
            }
            if (this.commonJS.isEmpty(this.inputForm.createBy.id)) {
              this.inputForm.createBy.id = JSON.parse(localStorage.getItem('user')).id
              this.inputForm.createBy.name = JSON.parse(localStorage.getItem('user')).name
            }
            if (this.commonJS.isEmpty(this.inputForm.officeId)) {
              this.inputForm.officeId = JSON.parse(localStorage.getItem('user')).officeDTO.id
            }
            this.inputForm.dates = ['', '']
            if (this.commonJS.isNotEmpty(this.inputForm.beginDate) && this.commonJS.isNotEmpty(this.inputForm.endDate)) {
              this.inputForm.dates[0] = this.inputForm.beginDate
              this.inputForm.dates[1] = this.inputForm.endDate
            }
            if (this.commonJS.isEmpty(this.inputForm.notifyType)) {
              this.inputForm.notifyType = '0'
            }
            if (this.commonJS.isEmpty(this.inputForm.pluginNotifyOfficesDTOList)) {
              this.inputForm.pluginNotifyOfficesDTOList = []
            }
            if (this.commonJS.isEmpty(this.inputForm.pluginNotifyUserDTOList)) {
              this.inputForm.pluginNotifyUserDTOList = []
            }
            if (this.method === 'view' || this.method === 'read') {
              this.$refs.uploadComponent.newUpload('view', this.inputForm.workAttachmentDtoList, 'notify')
            } else {
              this.$refs.uploadComponent.newUpload('edit', this.inputForm.workAttachmentDtoList, 'notify')
            }
            if (this.commonJS.isEmpty(this.inputForm.workAttachmentDtoList)) {
              this.inputForm.workAttachmentDtoList = []
            }
            if (method === 'read') {
              this.$emit('refreshDataList')
            }
            this.loading = false
          })
        })
      },
      doSubmitBefore () {
        if (this.inputForm.status === '5') {
          this.$confirm(`修改后会重新发起通告，确定修改数据吗?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.doSubmit()
          })
        } else {
          this.doSubmit()
        }
      },
      // 表单提交
      doSubmit () {
        this.$refs['inputForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            if (this.$refs.uploadComponent.checkProgress()) {
              this.loading = false
              return
            }
            if (this.commonJS.isEmpty(this.inputForm.pluginNotifyOfficesDTOList) && this.commonJS.isEmpty(this.inputForm.pluginNotifyUserDTOList)) {
              this.$message.error('通告范围(部门或成员)，至少填写一项')
              this.loading = false
              throw new Error('通告范围(部门或成员)，至少填写一项')
            }
            this.inputForm.workAttachmentDtoList = this.$refs.uploadComponent.getDataList()
            if (this.commonJS.isNotEmpty(this.inputForm.dates)) {
              this.inputForm.beginDate = this.inputForm.dates[0]
              this.inputForm.endDate = this.inputForm.dates[1]
              if (this.commonJS.isNotEmpty(this.inputForm.beginDate) && this.commonJS.isNotEmpty(this.inputForm.endDate)) {
                if (this.inputForm.beginDate === this.inputForm.endDate) {
                  if (this.inputForm.notifyType === '0') {
                    this.$message.error('通告起止时间不可以相同')
                    this.loading = false
                    throw new Error('通告起止时间不可以相同')
                  }
                }
              } else {
                if (this.inputForm.notifyType === '0') {
                  this.$message.error('请填写通告时间')
                  this.loading = false
                  throw new Error('请填写通告时间')
                }
              }
            } else {
              this.inputForm.beginDate = ''
              this.inputForm.endDate = ''
              if (this.inputForm.notifyType === '0') {
                this.$message.error('请填写通告时间')
                this.loading = false
                throw new Error('请填写通告时间')
              }
            }
            this.getEditorFilesDTOList()
            this.notifyService.saveForm(this.inputForm).then(({data}) => {
              this.loading = false
              this.close()
            }).catch(() => {
              this.loading = false
            })
          }
        })
      },
      close () {
        this.$refs.uploadComponent.clearUpload()
        this.$refs.contentEditor.enable()
        this.$emit('refreshDataList')
        this.visible = false
        this.inputForm = {
          createBy: {
            id: '',
            name: ''
          },
          createDate: '',
          id: '',
          type: '',
          title: '',
          content: '',
          files: '',
          status: '',
          remarks: '',
          notifyType: '',
          no: '',
          beginDate: '',
          endDate: '',
          dates: '',
          officeId: '',
          workAttachmentDtoList: [],
          pluginNotifyOfficesDTOList: [],
          pluginNotifyUserDTOList: [],
          editorFilesDTOList: [],
          comments: [],
          comment: ''
        }
      },
      changeNotifyType () {
        this.inputForm.beginDate = ''
        this.inputForm.endDate = ''
        this.inputForm.dates = ['', '']
      },
      daterangeChange (e) {
        this.$nextTick(() => {
          this.$forceUpdate()
        })
      },
      getEditorFilesDTOList () {
        let a = []
        if (this.commonJS.isNotEmpty(this.inputForm.editorFilesDTOList)) {
          this.inputForm.content = this.inputForm.content.replace(/&amp;/g, '&')
          this.inputForm.editorFilesDTOList.forEach((item) => {
            if (this.inputForm.content.includes(item.temporaryUrl)) {
              a.push(item)
            }
          })
        }
        this.inputForm.editorFilesDTOList = []
        a.forEach((item) => {
          this.inputForm.editorFilesDTOList.push(item)
        })
      },
      openOfficeChoose () {
        this.$refs.officeTreeSelect.init()
      },
      getOfficeChoose (list) {
        let _this = this
        const wait = () => new Promise((resolve, reject) => {
          if (_this.commonJS.isEmpty(_this.inputForm.pluginNotifyOfficesDTOList)) {
            _this.inputForm.pluginNotifyOfficesDTOList = []
            resolve()
          } else if (_this.commonJS.isEmpty(list)) {
            resolve()
          } else {
            list.forEach((item, index) => {
              _this.inputForm.pluginNotifyOfficesDTOList.forEach((office, rowIndex) => {
                if (item.id === office.officeId || item.name === office.officeName) {
                  this.$refs.officeTable.remove(office)
                  this.inputForm.pluginNotifyOfficesDTOList.splice(rowIndex, 1)
                  this.tableKeyOffice = Math.random()
                }
              })
            })
            resolve()
          }
        })
        wait().then(() => {
          list.forEach((item) => {
            let d = {
              officeName: item.name,
              officeId: item.id
            }
            this.$refs.officeTable.insertAt(d)
            this.inputForm.pluginNotifyOfficesDTOList.push(d)
            this.tableKeyOffice = Math.random()
          })
        })
      },
      removeEvent (row, rowIndex, type) {
        if (type === 'office') {
          this.$refs.officeTable.remove(row)
          this.inputForm.pluginNotifyOfficesDTOList.splice(rowIndex, 1)
          this.tableKeyOffice = Math.random()
        }
        if (type === 'user') {
          this.$refs.userTable.remove(row)
          this.inputForm.pluginNotifyUserDTOList.splice(rowIndex, 1)
          this.tableKeyUser = Math.random()
        }
      },
      openUserChoose (value) {
        if (this.commonJS.isNotEmpty(value)) {
          this.userService.queryDetailList(value).then(({data}) => {
            if (this.commonJS.isEmpty(this.inputForm.pluginNotifyUserDTOList)) {
              this.inputForm.pluginNotifyUserDTOList = []
            }
            data.forEach(item => {
              this.inputForm.pluginNotifyUserDTOList.forEach((user, rowIndex) => {
                if (this.commonJS.isEmpty(item.name) || user.userName === item.name || user.userId === item.id) {
                  this.$refs.userTable.remove(user)
                  this.inputForm.pluginNotifyUserDTOList.splice(rowIndex, 1)
                  this.tableKeyUser = Math.random()
                }
              })
            })
            data.forEach(item => {
              let param = {
                userId: item.id,
                userName: this.commonJS.isEmpty(item.name) ? '' : item.name,
                officeName: this.commonJS.isEmpty(item.officeDTO) ? '' : this.commonJS.isEmpty(item.officeDTO.name) ? '' : item.officeDTO.name
              }
              this.$refs.userTable.insertAt(param)
              this.inputForm.pluginNotifyUserDTOList.push(param)
              this.tableKeyUser = Math.random()
            })
          })
        }
      },
      pushComment () {
        if (this.commonJS.isEmpty(this.inputForm.comment)) {
          this.$message.error('请输入评论内容')
          return
        }
        let param = {
          notifyId: this.inputForm.id,
          comments: this.inputForm.comment,
          userId: this.$store.state.user.id
        }
        this.loading = true
        this.notifyService.addComment(param).then(({data}) => {
          this.init(this.method, this.inputForm.id)
          this.$message.success(data)
          this.loading = false
        })
      },
      cleanComment () {
        this.inputForm.comment = ''
      },
      delComment (id) {
        this.notifyService.delComment(id).then(() => {
          this.init(this.method, this.inputForm.id)
        })
      },
      changeEditor (cont) {
        this.inputForm.content = cont
      }
    }
  }
</script>
<style scoped>
  /deep/ .w-e-text-container {
    z-index: 1 !important;
  }
  /deep/ .w-e-menu {
    z-index: 2 !important;
  }
  /deep/ .wtext {
    height: 400px
  }
</style>
