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

    <div class="btn-group">
      <div class="pull-right">
        <el-button type="primary" @click="save">{{ $t('ec.notice.draft') }}</el-button>
        <el-button type="success" @click="sent">{{ $t('ec.notice.send') }}</el-button>
        <el-button type="default" @click="returnBack">{{ $t('ec.dialog.close') }}</el-button>
      </div>
    </div>
    <el-form ref="form" :model="formItem" :rules="rules" :loading="loading" :label-width="'100px'">
      <el-form-item
        :label="$t('ec.notice.receiver')"
        prop="user.id"
      >
        <ec-user-modal ref="userModal" v-model="formItem.user.id" :dept-id="formItem.deptId || ''" :show-tree-checkbox="showTreeCheckbox" multiple @change="findUser" />
        <!--        <el-input v-model="formItem.user.username" type="text" readonly placeholder="用户" @focus="userSelect(formItem.user, true)">-->
        <!--          <el-button-->
        <!--            slot="append"-->
        <!--            icon="el-icon-search"-->
        <!--            @click="userSelect(formItem.user, true)"-->
        <!--          />-->
        <!--        </el-input>-->
      </el-form-item>
      <el-form-item
        :label="$t('ec.notice.title')"
        prop="title"
        :rules="[
          {required: true, message: $t('ec.notice.titleEmpty'), trigger:'blur'}
        ]"
      >
        <el-input v-model="formItem.title" type="text" :placeholder="$t('ec.notice.title')" />
      </el-form-item>
      <el-form-item
        v-if="parseInt(sendWay) !== 5"
        :label="$t('ec.notice.type')"
        prop="type"
        :rules="[
          {required: true, message: $t('ec.notice.typeEmpty'), trigger:'blur'}
        ]"
      >
        <ec-select v-model="formItem.type" :placeholder="$t('ec.notice.type')" dict-type="noticeType" />
      </el-form-item>
      <el-form-item
        v-if="parseInt(sendWay) !== 5"
        :label="$t('ec.notice.sendWay')"
        prop="sendWays"
        :rules="[
          {required: true, message: $t('ec.notice.sendWay'), trigger:'blur'}
        ]"
      >
        <ec-checkbox-group v-model="formItem.sendWays" :ec-data="sendWays" :str-result="false" />
      </el-form-item>
      <el-form-item
        :label="$t('ec.notice.content')"
        prop="content"
        :rules="[
          {required: true, message: $t('ec.notice.contentEmpty'), trigger:'blur'}
        ]"
      >
        <el-input
          v-model="formItem.content"
          type="textarea"
          :rows="10"
          :placeholder="$t('ec.notice.content')"
        />
      </el-form-item>
      <!--      <el-form-item
        :label="$t('ec.notice.status')"
        prop="editStatus"
        :rules="[
          {required: true, message: $t('ec.notice.statusEmpty'), trigger:'blur'}
        ]"
      >
        <ec-radio-group v-model="formItem.editStatus" dict-type="editStatus" />
      </el-form-item>-->
    </el-form>
  </div>
</template>

<script>
import mixin from 'ecip-web/utils/common-mixin'
import { getById, save, update } from 'ecip-web/api/vue/notice/noticeApi'
export default {
  name: 'ModulesSystemSysrNoticeForm',
  components: {},
  mixins: [...mixin],
  props: {
    isEdit: {
      type: Boolean,
      default: false
    },
    sendWay: {
      type: String,
      default: '1'
    }
  },
  data() {
    return {
      showTreeCheckbox: true,
      id: this.$route.params.id,
      loading: false,
      sendWays: [],
      formItem: {
        user: {},
        editStatus: 'sent'
      },
      rules: {}
    }
  },
  created() {
    this.initSendWay()
    this.getData()
  },
  methods: {
    initSendWay() {
      if (parseInt(this.sendWay) === 1) {
        // 发送通知
        this.sendWays = [
          { value: '1', label: this.$t('ec.notice.system') },
          { value: '2', label: this.$t('ec.notice.email') },
          { value: '4', label: this.$t('ec.notice.sms') },
          { value: '3', label: this.$t('ec.notice.wechat') },
          { value: '6', label: this.$t('ec.notice.app') }
        ]
      }
    },
    getData() {
      if (this.id) { //  编辑
        getById(this.id).then(res => {
          this.formItem = Object.assign({ user: {}}, res.data)
          this.sendWay = this.formItem.sendWay
          const userValues = []
          const userAttrNames = []
          this.formItem.sysrNoticeDetailList.forEach(item => {
            userValues.push(item.userId)
            userAttrNames.push(item.userName)
          })
          this.$refs.userModal.handleVueValues(userValues, userAttrNames)
          this.formItem.user.id = userValues.join(',')
        })
      } else {
        this.formItem = {
          user: {},
          editStatus: 'draft',
          sendWays: ['1']
        }
      }
    },
    findUser(userArray, deptArray) {
      this.formItem.deptId = deptArray.map(value => value.id).join()
      this.$refs.userModal.setDeptId(this.formItem.deptId)
    },
    save() {
      let validFlag
      this.$refs.form.validate(valid => { validFlag = valid })
      if (!validFlag) {
        return
      }
      let data = Object.assign(this.formItem)
      if (parseInt(this.sendWay) === 1) {
        const sendWays = this.formItem.sendWays.map(item => Number.parseInt(item))
        sendWays.push('1')
        data = Object.assign(this.formItem, { sendWays })
      } else {
        data.sendWays = ['5']
      }
      data.editStatus = 'draft'
      if (this.isEdit) {
        this.loading = true
        if (this.formItem.user.id) {
          data.userId = this.formItem.user.id
        }
        update(this.id, data).then(res => {
          this.loading = false
          this.returnBack()
          this.$notify.success(this.$t('ec.message.saveSuccess'))
        })
      } else {
        let validFlag
        this.$refs.form.validate(valid => { validFlag = valid })
        if (!validFlag) {
          return
        }
        if (this.formItem.user.id) {
          data.userId = this.formItem.user.id

          this.loading = true
          save(data).then(res => {
            this.loading = false
            this.returnBack()
            this.$notify.success(this.$t('ec.message.saveSuccess'))
          })
        } else {
          if (this.formItem.editStatus === 'sent') {
            this.$confirm(this.$t('ec.notice.sendAllConfirm'), this.$t('ec.message.prompt'), {
              confirmButtonText: this.$t('ec.message.confirm'),
              cancelButtonText: this.$t('ec.message.cancel'),
              type: 'warning'
            }).then(() => {
              this.loading = true
              save(data).then(res => {
                this.loading = false
                this.returnBack()
                this.$notify.success(this.$t('ec.notice.sendSuccess'))
              })
            }
            )
          } else {
            this.loading = true
            save(data).then(res => {
              this.loading = false
              this.returnBack()
              this.$notify.success(this.$t('ec.message.saveSuccess'))
            })
          }
        }
      }
    },
    sent() {
      let validFlag
      this.$refs.form.validate(valid => { validFlag = valid })
      if (!validFlag) {
        return
      }
      let data = Object.assign(this.formItem)
      if (parseInt(this.sendWay) === 1) {
        const sendWays = this.formItem.sendWays.map(item => Number.parseInt(item))
        if (!sendWays.includes(1)) {
          sendWays.push(1)
        }
        data = Object.assign(this.formItem, { sendWays })
      } else {
        data.sendWays = ['5']
      }

      data.userId = this.formItem.user.id
      data.editStatus = 'sent'

      let message = this.$t('ec.notice.sendConfirm')
      if (!data.userId) {
        message = this.$t('ec.notice.sendAllConfirm')
      }
      this.$confirm(message, this.$t('ec.message.prompt'), {
        confirmButtonText: this.$t('ec.message.confirm'),
        cancelButtonText: this.$t('ec.message.cancel'),
        type: 'warning'
      }).then(() => {
        this.loading = true
        save(data).then(res => {
          this.loading = false
          this.returnBack()
          this.$notify.success(this.$t('ec.notice.sendSuccess'))
        })
      })
    },
    returnBack() {
      this.formItem.sendWay = this.sendWays.join(',')
      this.$store.dispatch('tagsView/delView', this.$route).then(({ visitedViews }) => {
        if (this.formItem.sendWay.indexOf('5') > -1) {
          this.$router.push(`/sysrInboxView`)
        } else {
          this.$router.push(`/sysrNoticeView`)
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
