<template>
  <div class="inputs ht-component">
    <!-- 只读也要显示多选框 -->
    <!-- v-if="inputWriteable" -->
    <el-checkbox-group
      v-if="permission != 'n'"
      v-validate="inputValidate"
      :name="inputName"
      :min="min"
      :max="max"
      v-model="inputVal"
      :disabled="disabled || readonly || permission == 'r'"
    >
      <el-checkbox
        :class="{
          'el-checkbox-vertical': optionLayout == 'vertical',
          'el-checkbox-horizontal': optionLayout == 'horizontal'
        }"
        @change="handleCheckboxChange"
        v-for="item in options"
        :key="item.key"
        :label="item.key"
      >
        {{ item.value }}
      </el-checkbox>
    </el-checkbox-group>

    <!-- v-if="permission != 'n'" -->
    <ht-field-tail
      v-if="!['r', 'n'].includes(permission)"
      :writeable.sync="writeable"
      :fieldName="inputName"
      :readonly="!inputWriteable"
      inputValue
      :tag-format-value="inputVal"
    />
  </div>
</template>
<script>
import utils from '@/utils.js'
import service from '@/service.js'
import HtFieldTail from '@/components/HtFieldTail.vue'

export default {
  name: 'ht-checkbox',
  props: {
    validate: [String, Object],
    value: [String, Number, Boolean],
    name: String,
    permission: {
      type: String,
      default: 'w',
      validator: function(value) {
        return ['b', 'w', 'r', 'n'].indexOf(value) !== -1
      }
    },
    optionLayout: {
      type: String,
      default: 'horizontal',
      validator: function(value) {
        return ['horizontal', 'vertical'].some(i => i == value)
      }
    },
    options: Array,
    readonly: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    min: Number,
    max: Number,
    linkage: [Object, Array],
    ganged: Object
  },
  components: {
    HtFieldTail
  },
  data() {
    return {
      inputName: null,
      writeable: true
    }
  },
  computed: {
    inputVal: {
      get: function() {
        if (
          utils.isEmpty(this.value) ||
          !this.options ||
          this.options.length == 0
        ) {
          return []
        }
        if (this.value.constructor == String) {
          const ary = this.value.split(',')
          if (this.inputWriteable) {
            return ary
          } else {
            let optionVals = []
            ary.forEach(m => {
              let _option = this.options.find(opt => opt.key === m)
              if (_option) {
                optionVals.push(_option.key)
              }
            })
            return optionVals
          }
        }
        return []
      },
      set: function() {}
    },
    inputWriteable: function() {
      return this.writeable
        ? utils.getWriteable(this.permission)
        : this.writeable
    },
    inputValidate: function() {
      if (this.permission == 'r') return
      return utils.addRequiredOrNot(this.permission, this.validate, this)
    }
  },
  mounted() {
    this.mountedLinkage()
  },
  created() {
    this.inputName = this.name ? this.name : utils.getName()
    this.$validator = this.$root.$validator
  },
  methods: {
    mountedLinkage() {
      if (this.linkage) {
        const exp = this.linkage
        // 如果要联动的字段权限是只读“r”,则把联动配置里面要联动的字段权限“w”改为只读“r”
        if (exp && exp.length > 0) {
          const frmInst = utils.getOnlineFormInstance(this)
          // 表单所有字段的初始权限
          if (frmInst && frmInst.permission) {
            exp.forEach(item => {
              let effect = item.effect
              effect.forEach(effectItem => {
                let initPermission = utils.getValueByPath(
                  frmInst,
                  effectItem.target
                )
                if (
                  effectItem.target &&
                  effectItem.target.indexOf('permission') != -1 &&
                  effectItem.value != 'n' &&
                  initPermission == 'r'
                ) {
                  effectItem.value = initPermission
                }
              })
            })
          }
        }
        this.$isCheckbox = true
        setTimeout(() => {
          service.linkageHandler(this, exp)
        }, 0)
      }
    },
    // 通过选项值数组 获取 选项key数组
    getOptionKeyByValue: function(valueAry) {
      const keyAry = []
      if (!valueAry || valueAry.constructor !== Array || valueAry.length == 0) {
        return keyAry
      }
      valueAry.forEach(m => {
        const _option = this.options.find(opt => opt.value === m)
        if (_option) {
          keyAry.push(_option.key)
        }
      })
      return keyAry
    },
    handleCheckboxChange: function(m, n) {
      let vals = [...this.inputVal]
      const currentVal = n.currentTarget.value
      if (m) {
        vals.push(currentVal)
      } else {
        vals.remove(currentVal)
      }
      vals = vals.filter(i => i !== '')
      this.$emit('input', vals.join(','))
      this.$emit('change', m, n)
    }
  }
}
</script>
<style lang="scss" scoped>
label.el-checkbox-horizontal {
  margin: 0px 30px 0 0;
}

label.el-checkbox-vertical {
  display: block;
}

label.el-checkbox-vertical ~ label.el-checkbox-vertical {
  margin-top: 10px;
  margin-left: 0px;
}

div.el-checkbox-group[aria-invalid="true"] {
  border: 1px solid #f56c6c;
  padding: 0 0 10px 10px;
}
</style>
