<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
  <div>
      <el-form size="small" :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view' || method === 'read'?'readonly':''" :disabled="method==='view' || method === 'read' || status === 'audit' || status === 'taskFormDetail'"
               label-width="120px" @submit.native.prevent>
        <el-row  :gutter="15">
          <el-col :span="24">
            <el-form-item label="通告状态" prop="notifyType"
                          :rules="[
                  {required: true, message:'通告状态不能为空', trigger:'blur'}
                 ]">
              <el-radio v-model="inputForm.notifyType" v-for="item in $dictUtils.getDictList('oa_notify_status')" :label="item.value" size="small" style="margin-right: 20px">
                {{item.label}}</el-radio>
<!--              <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">
            <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" 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="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})
                        }"/>
            </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" type="primary"  size="mini" @click="openOfficeChoose" plain>
              选择
            </el-button>
          </div>
        </el-divider>
        <el-row  :gutter="15" >
          <el-form :disabled="status === 'audit' || status === 'taskFormDetail'">
            <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="status === 'audit' || status === 'taskFormDetail'" @getValue="(value) => {openUserChoose(value)}"></UserSelectButton>
          </el-divider>
        </div>
        <el-row  :gutter="15">
          <el-form :disabled="status === 'audit' || status === 'taskFormDetail'">
            <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>
    <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: []
        },
        keyWatch: '',
        tableKeyOffice: '',
        tableKeyUser: ''
      }
    },
    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: {
      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: []
        }
        this.inputForm.id = id
        this.loading = false
        this.$nextTick(() => {
          this.$refs.inputForm.resetFields()
          this.loading = true
          this.$refs.contentEditor.clear()
          this.notifyService.query({id: this.inputForm.id, isSelf: false}).then(({data}) => {
            this.$refs.uploadComponent.clearUpload()
            this.inputForm = this.recover(this.inputForm, data)
            this.inputForm = JSON.parse(JSON.stringify(this.inputForm))
            if (this.status === 'audit' || this.status === 'taskFormDetail') {
              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.status === 'audit' || this.status === 'taskFormDetail') {
              this.method = 'view'
              method = 'view'
            }
            if (this.commonJS.isEmpty(this.inputForm.workAttachmentDtoList)) {
              this.inputForm.workAttachmentDtoList = []
            }
            this.$refs.uploadComponent.newUpload(this.method, this.inputForm.workAttachmentDtoList, 'notify')
            this.loading = false
          })
        })
      },
      saveForm (callback) {
        this.doSubmit('save', callback)
      },
      startForm (callback) {
        this.doSubmit('start', callback)
      },
      agreeForm (callback) {
        this.notifyService.query({
          id: this.inputForm.id,
          isSelf: false
        }).then(({data}) => {
          if (data.status !== '2') { // 审核状态不是“待审核”，就弹出提示
            this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
            throw new Error()
          } else {
            this.doSubmit('agree', callback)
          }
        })
      },
      reapplyForm (callback) {
        this.notifyService.query({
          id: this.inputForm.id,
          isSelf: false
        }).then(({data}) => {
          if (data.status !== '4') { // 审核状态不是“驳回”，就弹出提示
            this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
            throw new Error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
          } else {
            this.doSubmit('reapply', callback)
          }
        })
      },
      // 表单提交
      doSubmit (status, callback) {
        if (status === 'save') {
          // 暂存
          this.inputForm.status = '1'
          this.loading = true
          if (this.$refs.uploadComponent.checkProgress()) {
            this.loading = false
            return
          }
          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]
          } else {
            this.inputForm.beginDate = ''
            this.inputForm.endDate = ''
          }
          this.getEditorFilesDTOList()
          this.notifyService.saveForm(this.inputForm).then(({data}) => {
            callback(data.businessTable, data.businessId, this.inputForm)
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
          return
        } else if (status === 'start') {
          // 送审  待审核
          this.inputForm.status = '2'
        } else if (status === 'agree') {
          // 审核同意
          this.inputForm.status = '5'
        } else if (status === 'reapply') {
          this.inputForm.status = '2'
        }
        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
              callback(data.businessTable, data.businessId, this.inputForm)
            }).catch(() => {
              this.loading = false
            })
          }
        })
      },
      updateStatusById (type, callback) {
        if (this.$refs.uploadComponent.checkProgress()) {
          this.loading = false
          throw new Error()
        } else {
          if (type === 'reject' || type === 'reback') {
            this.notifyService.query({
              id: this.inputForm.id,
              isSelf: false
            }).then(({data}) => {
              if (data.status !== '2') { // status的值不等于“审核中”就弹出提示
                this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
                throw new Error()
              } else {
                if (type === 'reject') {
                  // 驳回
                  this.inputForm.status = '4'
                  let param = {status: '4', id: this.inputForm.id}
                  this.notifyService.updateStatusById(param).then(() => {
                    callback()
                  })
                }
                if (type === 'reback') {
                  // 撤回
                  let param = {status: '3', id: this.inputForm.id}
                  this.notifyService.updateStatusById(param).then(() => {
                    callback()
                  })
                }
              }
            })
          } else if (type === 'hold') {
            this.notifyService.query({
              id: this.inputForm.id,
              isSelf: false
            }).then(({data}) => {
              if (data.status !== '4') { // status的值不等于“驳回”就弹出提示
                this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
                throw new Error()
              } else {
                // 终止
                let param = {status: '1', id: this.inputForm.id}
                this.notifyService.updateStatusById(param).then(() => {
                  callback()
                })
              }
            })
          }
        }
      },
      close () {
        this.$refs.uploadComponent.clearUpload()
        this.$refs.contentEditor.enable()
        this.inputForm = {
          createBy: {
            id: '',
            name: ''
          },
          createDate: '',
          id: '',
          type: '',
          title: '',
          content: '',
          files: '',
          status: '',
          remarks: '',
          notifyType: '',
          no: '',
          beginDate: '',
          endDate: '',
          dates: '',
          officeId: '',
          workAttachmentDtoList: [],
          pluginNotifyOfficesDTOList: [],
          pluginNotifyUserDTOList: [],
          editorFilesDTOList: []
        }
      },
      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()
            })
          })
        }
      }
    }
  }
</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>
