<template>
  <el-form :model="config" inline ref="form" size="medium" v-if="hasPermission">
    <el-form-item :label="config.configName" :label-width="(config.configName.length + 1) + 'em'" prop="configValue">
      <slot :row="config">
        <el-switch v-if="type === 'switch'" v-model="switchValue" @change="handleSubmit" v-loading="loading"/>
        <el-input v-else v-model="config.configValue" :placeholder="`请输入${config.configName}`"/>
      </slot>
    </el-form-item>
    <el-form-item>
      <el-button v-if="type === 'input'" @click="handleSubmit" type="primary" :loading="loading" icon="el-icon-check" size="small">修改</el-button>
      <slot name="remark">
        <span v-if="config.remark" style="font-size: 12px;color: #606060;margin-left: 1em;">{{config.remark}}</span>
      </slot>
    </el-form-item>
  </el-form>
</template>

<script>
import { batchUpdateConfigValue } from '@/api/system/config'
import { checkPermi } from '@/utils/permission'
import { isEmpty } from '@/utils'

export default {
  name: "ConfigItem",
  props: {
    config: {
      type: Object,
      default: () => {}
    },
    rules: {
      type: Object,
      default: () => {}
    },
    type: {
      type: String,
      default: 'input',
      validator(val) {
        return ['input', 'switch'].includes(val);
      }
    }
  },
  computed: {
    // 判断是否有权限
    hasPermission() {
      if (this.config == null || isEmpty(this.config.permission)) {
        return true;
      }
      return checkPermi([this.config.permission]);
    },
    // 开关的值
    switchValue: {
      set(val) {
        this.config.configValue = val ? 'true' : 'false';
      },
      get() {
        return this.config != null && this.config.configValue === 'true';
      }
    }
  },
  data() {
    return {
      loading: false,
    }
  },
  methods: {
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true;
          batchUpdateConfigValue([this.config]).then(res => {
            if (res.code === 200) {
              this.$message.success('修改成功')
              this.$emit('success');
            }
          }).finally(() => {
            this.loading = false;
          })
        }
      })
    }
  }
}
</script>
