<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="功能编码"
                    v-if="!dataForm.id"
                    prop="code">
        <el-select v-model="dataForm.code"
                   @change="changeCode"
                   placeholder="请选择">
          <el-option v-for="item in codeList"
                     :key="item.dictValue"
                     :label="item.dictName"
                     :value="item.dictValue">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="功能编码"
                    v-if="dataForm.id"
                    prop="code">
        <el-select v-model="dataForm.code"
                   disabled
                   @change="changeCode"
                   placeholder="请选择">
          <el-option v-for="item in codeList"
                     :key="item.dictValue"
                     :label="item.dictName"
                     :value="item.dictValue">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否可用"
                    prop="availableFlag">
        <template>
          <el-radio v-model="dataForm.availableFlag"
                    label="0">否</el-radio>
          <el-radio v-model="dataForm.availableFlag"
                    label="1">是</el-radio>
        </template>
      </el-form-item>
      <el-form-item label="是否访问外链"
                    prop="externalFlag">
        <template>
          <el-radio v-model="dataForm.externalFlag"
                    label="0">否</el-radio>
          <el-radio v-model="dataForm.externalFlag"
                    label="1">是</el-radio>
        </template>
      </el-form-item>
      <el-form-item label="访问地址"
                    prop="externalUrl">
        <el-input v-model="dataForm.externalUrl"
                  placeholder="访问地址"></el-input>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="dataForm.remark"
                  placeholder="备注"></el-input>
      </el-form-item>
      <el-form-item label="图标"
                    v-loading="loading"
                    prop="imgUrl">
        <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.imgUrl"
               :src="dataForm.imgUrl"
               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: {
        id: '',
        code: '',
        name: '',
        availableFlag: '1',
        externalFlag: '0',
        externalUrl: '',
        remark: '',
        delFlag: '',
        revision: '',
        createdBy: '',
        createdTime: '',
        updatedBy: '',
        updatedTime: '',
        imgUrl: ''
      },
      codeList: [],
      uploadUrl: '',
      loading: false
    }
  },
  computed: {
    dataRule () {
      return {
        code: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        name: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        availableFlag: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        externalFlag: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        externalUrl: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        remark: [
          { 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' }
        ]
      }
    }
  },
  watch: {
    'dataForm.code': function (val) {
      this.codeList.map((res) => {
        if (res.dictValue == this.dataForm.code) {
          this.dataForm.name = res.dictName
          console.log(this.dataForm.name)
        }
      })
    }
  },
  methods: {
    init () {
      this.uploadUrl = `${window.SITE_CONFIG['apiURL']}/oss/file/upload?token=${Cookies.get('token')}`
      this.getListFromDict('custom_home')
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.getInfo()
        }
      })
    },
    // 上传图片
    handleAvatarSuccess (res, file) {
      this.dataForm.imgUrl = res.data.url
      this.loading = false
    },
    beforeAvatarUpload (file) {
      this.loading = true
    },
    handelError () {
      this.loading = false
    },
    // 获取信息
    getInfo () {
      this.$http.get(`/custom/majorfunctionconf/${this.dataForm.id}`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }
      }).catch(() => { })
    },
    getListFromDict (dictType) {
      this.$http.get(`/sys/dict/listSimple/` + dictType).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.codeList = res.data
      }).catch(() => { })
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.$http[!this.dataForm.id ? 'post' : 'put']('/custom/majorfunctionconf/', 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 })
  }
}
</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>
