<template>
  <el-dialog :visible.sync="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()" :label-width="$i18n.locale === 'en-US' ? '120px' : '80px'">
          <el-form-item label="社群名称" prop="groupName">
          <el-input v-model="dataForm.groupName" placeholder="社群名称"></el-input>
      </el-form-item>
        <el-form-item label="社群头像"
                      v-loading="loading"
                      prop="groupAvatar">
            <el-upload class="avatar-uploader"
                       :action="uploadUrl"
                       :show-file-list="false"
                       :on-success="handleAvatarActSuccess"
                       :on-error="handelError"
                       :before-upload="beforeAvatarUpload">
                <img v-if="dataForm.groupAvatar"
                     :src="dataForm.groupAvatar"
                     class="avatar">
                <i v-else
                   class="el-icon-plus avatar-uploader-icon"></i>
                <div slot="tip"
                     class="el-upload__tip">只能上传jpg/png文件，且不超过500kb
                </div>
            </el-upload>
        </el-form-item>
        <el-form-item label="所属类别"
                      prop="categoryCode">
            <el-select v-model="dataForm.categoryCode"
                       placeholder="所属类别" style="width: 100%">
                <el-option v-for="item in categoryOptions"
                           :key="item.code"
                           :label="item.name"
                           :value="item.code">
                </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="所属机构"
                      prop="deptId">
            <el-cascader v-model="dataForm.deptId" style="width: 100%"
                         :options="options"
                         :disabled="dataForm.id != null"
                         :props="{ checkStrictly: true }"
                         ref="grid"
                         @change="deptHandleChange"
                         filterable
                         collapse-tags></el-cascader>
        </el-form-item>
      </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
      <el-button :disabled="disabled" type="primary" @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import debounce from 'lodash/debounce'
import Cookies from 'js-cookie'
export default {
  data () {
    return {
      visible: false,
      dataForm: {
        id: '',
        groupName: '',
        groupAvatar: '',
        groupIntroduction: '',
        groupCategory: '',
        propertyProjectId: '',
        deptName: '',
        deptId: '',
        state: '',
        processingOpinions: '',
        delFlag: '',
        revision: '',
        createdBy: '',
        createdTime: '',
        updatedBy: '',
        updatedTime: '',
        allDeptIds: '',
        allDeptNames: '',
        parentDeptIds: '',
        parentDeptNames: '',
        referenceBusinessId: '',
        sectionCode: '',
        categoryCode: '',
        typeKey: ''
      },
      categoryOptions: [],
      options: [],
      loading: false,
      disabled: false,
      uploadUrl: ''
    }
  },
  computed: {
    dataRule () {
      return {
        groupName: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        groupAvatar: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        groupIntroduction: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        groupCategory: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        propertyProjectId: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        deptName: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        deptId: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        state: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        processingOpinions: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        delFlag: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        revision: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        createdBy: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        createdTime: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        updatedBy: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        updatedTime: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        allDeptIds: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        allDeptNames: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        parentDeptIds: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        parentDeptNames: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        referenceBusinessId: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        sectionCode: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        categoryCode: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        typeKey: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.$nextTick(() => {
      this.uploadUrl = `${window.SITE_CONFIG['apiURL']}/oss/file/upload?token=${Cookies.get('token')}`
    })
  },
  methods: {
    init () {
      // 获取下拉菜单
      this.getByLoginUser()
      this.getOptions()
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.getInfo()
        }
      })
    },
    // 获取信息
    getInfo () {
      this.$http.get(`/property/group/${this.dataForm.id}`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }
      }).catch(() => {})
    },
    // 获取部门
    getByLoginUser () {
      this.$http
        .get(`/sys/user/deptOptions/getByLoginUser`)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.loading = false
          this.options = res.data.options
        })
        .catch(() => {
          this.loading = false
        })
    },
    getOptions () {
      this.$http
        .get(`/property/sectioncategory/list`, { params: { sectionCode: 'interest_group' } }).then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.categoryOptions = res.data
          console.log(this.categoryOptions)
        })
        .catch(() => { })
    },
    deptHandleChange (value) {
      this.dataForm.deptId = value.slice(-1).shift()
    },
    handleAvatarActSuccess (res, file) {
      this.loading = false
      this.dataForm.groupAvatar = res.data.url
    },
    beforeAvatarUpload (file) {
      this.loading = true
    },
    handelError () {
      this.loading = false
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
        this.disabled = true
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.$http[!this.dataForm.id ? 'post' : 'put']('/property/group/interest', this.dataForm).then(({ data: res }) => {
            this.disabled = false
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        }).catch(() => {
            this.loading = false
        })
      })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>
<style scoped>
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #409eff;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }

    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>
