<template>
  <div
    v-if="permission != 'n'"
    :class="[
      'inputs',
      formInputsDisplay == 'block'
        ? 'ht-form-inputs__block'
        : 'ht-form-inputs__inline',
      isMobile && optionsVal && optionsVal.length > 2
        ? 'has-margin-checkbox-box'
        : 'mobile-checkbox-box',
    ]"
  >
    <div v-if="inputWriteable && permission_sub != 'n'">
      <input
        v-if="disabled && isValidate && !isSubCellReadOnly"
        v-model="inputVal"
        v-validate="inputValidate"
        type="hidden"
        :name="inputName"
        :data-vv-as="name"
      />
      <template v-if="isSubCellReadOnly">
        <input
          v-model="inputVal"
          v-validate="inputValidate"
          type="hidden"
          :name="inputName"
          :data-vv-as="name"
        />
        <div class="sub-table-cell-readonly" @click="handleCellClick">
          <span>
            {{
              formatValue && formatValue.length > 0
                ? formatValue.join(',')
                : inputVal.join(',')
            }}
          </span>
        </div>
      </template>
      <template v-else>
        <el-checkbox-group
          v-if="!isMobile"
          v-model="inputVal"
          v-validate="inputValidate"
          :size="inputSize"
          :name="inputName"
          :data-vv-as="name"
          :min="min"
          :max="max"
          :disabled="
            disabled ||
            readonly ||
            !inputWriteable ||
            (permission && permission === 'd') || (permission_sub && permission_sub === 'd')
          "
        >
          <el-checkbox
            v-for="item in optionsVal"
            :key="item.key"
            :class="{
              'el-checkbox-vertical': optionLayout == 'vertical',
              'el-checkbox-horizontal': optionLayout == 'horizontal',
            }"
            :label="item.key"
            :disabled="
              item.disabled ||
              !inputWriteable ||
              (permission && permission === 'd') || (permission_sub && permission_sub === 'd')
            "
            @change="handleCheckboxChange"
          >
            {{ $td(item.i18nKey, item.value) }}
          </el-checkbox>
        </el-checkbox-group>
        <div v-else>
          <van-checkbox-group
            v-model="inputVal"
            v-validate="validateRules"
            :disabled="
              disabled ||
              readonly ||
              !inputWriteable ||
              (permission && permission === 'd') || (permission_sub && permission_sub === 'd')
            "
            :max="max"
            :min="min"
            :direction="optionLayout == 'horizontal' ? 'horizontal' : ''"
            :name="inputName"
            :data-vv-as="name"
            :icon-size="18"
            @change="handleMobileCheckboxChange"
          >
            <van-checkbox
              v-for="item in optionsVal"
              :key="item.key"
              :name="item.key"
              shape="square"
              :disabled="limitDisabled(item)"
              checked-color="#409EFF"
            >
              {{ $td(item.i18nKey, item.value) }}
            </van-checkbox>
          </van-checkbox-group>
        </div>
      </template>
    </div>
    <ht-field-tail
      v-if="permission != 'n'"
      :field-name="inputName"
      :readonly="!inputWriteable"
      input-value
      :tag-format-value="formatValue || inputVal"
    />
  </div>
</template>
<script>
  import utils from '@/utils.js'
  import HtFieldTail from '../../FieldTail/index'
  import permission from '@/mixins/permission.js'
  import linkage from '@/mixins/linkage.js'
  import inputName from '@/mixins/inputName.js'
  import ganged from '@/mixins/ganged.js'
  import form from '@/mixins/form.js'
  import formDataUpdate from '@/mixins/formDataUpdate.js'
  import mobileMode from '@/mixins/mobileMode.js'
  import tableFieldReadOnly from '@/mixins/tableFieldReadOnly.js'

  export default {
    name: 'HtCheckbox',
    components: {
      HtFieldTail,
    },
    mixins: [
      permission,
      inputName,
      linkage,
      ganged,
      form,
      formDataUpdate,
      mobileMode,
      tableFieldReadOnly,
    ],
    props: {
      value: String,
      optionLayout: {
        type: String,
        default: 'horizontal',
        validator: function (value) {
          return ['horizontal', 'vertical'].some((i) => i == value)
        },
      },
      options: Array,
      cklist: String,
      readonly: {
        type: Boolean,
        default: false,
      },
      disabled: {
        type: Boolean,
        default: false,
      },
      min: Number,
      max: Number,
      isValidate: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        optionsVal: [],
        mobileChecked: [],
        formatValue: '',
      }
    },
    computed: {
      inputVal: {
        get: function () {
          if (
            utils.isEmpty(this.value) ||
            !this.optionsVal ||
            this.optionsVal.length == 0
          ) {
            return []
          }
          if (this.value.constructor == String) {
            const ary = this.value.split(',')
            if (!this.inputWriteable || this.isSubCellReadOnly) {
              let opts = []
              ary.forEach((m) => {
                const currentObj = this.optionsVal.find((opt) => opt.key === m)
                currentObj && opts.push(currentObj.value)
              })
              // eslint-disable-next-line
              this.formatValue = opts
            }
            return ary
          }
          return []
        },
        set: function (val) {
          if (this.isMobile) {
            this.$emit('input', val.join(','))
          }
        },
      },
      limitDisabled() {
        return function (item) {
          let check = this.inputVal.includes(item.key)
          return (
            !check && (this.inputVal || []).length >= this.max && this.max > 0
          )
        }
      },
      validateRules() {
        return this.disabled && !this.isValidate ? '' : this.inputValidate
      },
    },
    watch: {
      options: function () {
        this.loadOption()
      },
      optionsVal() {
        if (this.isMobile) {
          this.addMobileCenterStyle()
        }
      },
    },
    created() {
      this.$on('formDataUpdate', () => {
        this.loadOption()
      })
    },
    mounted() {
      this.$isCheckbox = true
      this.loadOption()
    },
    methods: {
      //加载选项
      loadOption: function () {
        // 动态选项
        if (this.ganged && this.ganged.alias) {
          this.dynamicLoadOption()
        } else {
          // 静态选项
          this.optionsVal = this.cklist
            ? JSON.parse(this.cklist)
            : this.options
            ? this.options
            : []
        }
      },
      // 动态加载选项
      dynamicLoadOption() {
        this.doCustomQuery(null, true).then(({ data }) => {
          if (data != null || data != undefined) {
            this.optionsVal = data
          }
        })
      },
      // 通过选项值数组 获取 选项key数组
      getOptionKeyByValue: function (valueAry) {
        const keyAry = []
        if (
          !valueAry ||
          valueAry.constructor !== Array ||
          valueAry.length == 0
        ) {
          return keyAry
        }
        valueAry.forEach((m) => {
          const _option = this.optionsVal.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)
      },
      handleMobileCheckboxChange(val) {
        this.$emit('change', val.join(','))
      },
    },
  }
</script>
<style lang="scss" scoped>
  label.el-checkbox-horizontal {
    margin-right: 30px;
  }

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

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

  .el-checkbox-group {
    line-height: 14px;
  }

  div.el-checkbox-group[aria-invalid='true'] {
    outline: 1px solid #f56c6c;
  }
  div.van-checkbox-group[aria-invalid='true'] {
    border: none;
  }
  .van-checkbox {
    margin: 5px 0 5px 24px;
    justify-content: flex-end;
  }
  ::v-deep .van-checkbox__icon--disabled .van-icon {
    background-color: #f9f9f9;
    border-color: #e6e6e6;
  }
  ::v-deep .van-checkbox__icon--checked.van-checkbox__icon--disabled .van-icon {
    color: #fff;
    background-color: #a0cfff !important;
    border-color: #a0cfff;
  }
  ::v-deep .van-checkbox-group--horizontal {
    justify-content: flex-end;
  }
</style>
