<template>
  <div class="inputs">
    <el-checkbox-group
      v-if="inputWriteable"
      v-validate="inputValidate"
      :name="inputName"
      :min="min"
      :max="max"
      v-model="inputVal"
      :disabled="disabled || readonly"
    >
      <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>
    <ht-field-tail
      v-if="permission!='n'"
      :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,
    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 => {
              optionVals.push(this.options.find(opt => opt.key === m).value);
            });
            return optionVals;
          }
        }
      },
      set: function(val) {}
    },
    inputWriteable: function() {
      return this.writeable ? utils.getWriteable(this.permission):this.writeable;
    },
    inputValidate: function() {
      return utils.addRequiredOrNot(this.permission, this.validate, this);
    }
  },
  mounted() {
    const _me = this;
    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;
                }
              });
            });
          }
        }
        service.linkageHandler(this, exp);
      }
    },
    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>
