<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="realName">
        <el-input v-model="dataForm.realName"
                  placeholder="姓名"></el-input>
      </el-form-item>
      <el-form-item label="性别"
                    prop="sex">
        <el-select v-model="dataForm.sex"
                   placeholder="性别">
          <el-option v-for="item in sexFlagArr"
                     :key="item.dictValue"
                     :label="item.dictName"
                     :value="item.dictValue">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="身份证号"
                    prop="identityNo">
        <el-input v-model="dataForm.identityNo"
                  placeholder="身份证号"></el-input>
      </el-form-item>
      <el-form-item label="联系电话"
                    prop="mobile">
        <el-input v-model="dataForm.mobile"
                  placeholder="联系电话"></el-input>
      </el-form-item>
      <el-form-item label="所属网格"
                    prop="allDeptIds">
        <el-cascader v-model="dataForm.allDeptIds"
                     :options="options"
                     filterable
                     clearable></el-cascader>
      </el-form-item>
      <el-form-item label="网络职责"
                    prop="dutyCategoryId">
        <el-select v-model="dataForm.dutyCategoryId"
                   @change="changeCaterory"
                   placeholder="请选择网络职责">
          <el-option v-for="item in dutyCategorys"
                     :key="item.id"
                     :label="item.dutyCategoryName"
                     :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="sort"
                    :label="$t('dict.sort')">
        <el-input-number v-model="dataForm.sort"
                         controls-position="right"
                         :min="0"
                         :label="$t('dict.sort')"></el-input-number>
      </el-form-item>
      <el-form-item label="工作单位"
                    prop="workUnit">
        <el-input v-model="dataForm.workUnit"
                  maxlength="20"
                  show-word-limit
                  placeholder="工作单位"></el-input>
      </el-form-item>
      <el-form-item label="备注"
                    prop="remark">
        <el-input v-model="dataForm.remark"
                  maxlength="50"
                  show-word-limit
                  placeholder="备注"></el-input>
      </el-form-item>
      <el-form-item label="上传相片"
                    v-loading="loading"
                    prop="faceImg">
        <el-upload class="avatar-uploader"
                   :action="this.uploadUrl"
                   :show-file-list="false"
                   :on-success="handleAvatarSuccess"
                   :on-error="handelError"
                   :before-upload="beforeAvatarUpload">
          <img v-if="dataForm.faceImg"
               :src="dataForm.faceImg"
               class="avatar">
          <i v-else
             class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
      <el-button type="primary"
                 @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import Cookies from 'js-cookie'
import debounce from 'lodash/debounce'
export default {
  data () {
    return {
      visible: false,
      dataForm: {
        realName: '',
        sex: '',
        sort: '',
        mobile: '',
        identityNo: '',
        faceImg: '',
        workUnit: '',
        dutyCategoryId: '',
        showFlag: '',
        remark: '',
        allDeptIds: ''
      },
      sexFlagArr: [
        { dictValue: '1', dictName: '男' },
        { dictValue: '0', dictName: '女' }
      ],
      loading: false,
      uploadUrl: '',
      options: [],
      dutyCategorys: []
    }
  },
  computed: {
    dataRule () {
      return {
        realName: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        sex: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        dutyCategoryId: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        allDeptIds: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        faceImg: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getListCategory()
  },
  methods: {
    init () {
      this.getByLoginUser()
      this.getListCategory()
      this.uploadUrl = `${window.SITE_CONFIG['apiURL']}/oss/file/upload?token=${Cookies.get('token')}`
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.getInfo()
        } else {
          this.dataForm.allDeptIds = []
        }
      })
    },
    // 获取信息
    getInfo () {
      this.$http.get(`/custom/gridoperatorinfo/${this.dataForm.id}`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }
      }).catch(() => { })
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.$http[!this.dataForm.id ? 'post' : 'put']('/custom/gridoperatorinfo/', this.dataForm).then(({ data: res }) => {
          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(() => { })
      })
    }, 1000, { 'leading': true, 'trailing': false }),
    // 上传图片
    handleAvatarSuccess (res, file) {
      this.dataForm.faceImg = res.data.url
      this.loading = false
    },
    beforeAvatarUpload (file) {
      this.loading = true
    },
    handelError () {
      this.loading = false
    },
    getByLoginUser () {
      this.$http
        .get(`/sys/user/deptOptions/getByLoginUser`)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.options = res.data.options
        })
        .catch(() => { })
    },
    changeCaterory () {
      let choosenItem = this.dutyCategorys.filter(item => item.id === this.dataForm.dutyCategoryId)[0]
      this.dataForm.dutyCategoryId = choosenItem.id
    },
    getListCategory () {
      this.$http.get(`/custom/gridoperatordutycategory/getAllDutyCat`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.dutyCategorys = res.data
      })
        .catch(() => { })
    }
  }
}
</script>
<style>
.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: 378px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 300px;
  height: 178px;
  display: block;
}
</style>
