<!--
 * @Author: gaoshoujun gaosj@yueworld.cn
 * @Date: 2022-06-28 11:00:24
 * @LastEditors: 傅豪杰 18516149270@163.com
 * @LastEditTime: 2023-05-12 17:05:08
-->
<template>
  <!-- 全选 -->
  <div>
    <el-checkbox
      v-if="hasCheckAll"
      class="f-checkbox"
      v-model="checkAllData"
      v-bind="$attrs"
      :disabled="isDisabled"
      :indeterminate="currentValue.length>0&&currentValue.length<list.length"
      @change="handleCheckAllChange"
    >
      全选
    </el-checkbox>
    <el-checkbox-group
      v-bind="$attrs"
      v-model="currentValue"
      @change="handleChange"
      :disabled="isDisabled"
    >
      <el-checkbox
        v-for="(item, index) in list"
        class="f-checkbox"
        :key="'checkbox' + index"
        :label="item[listKey]"
      >
        {{ item[listName] }}
      </el-checkbox>
    </el-checkbox-group>
  </div>
</template>
<script>
import formMixins from'../../mixins/formMixins.js'
export default {
  name: 'FCheckbox',
  mixins:[formMixins],
  data() {
    return {
      checkAll: false
    };
  },
  props:{
    value: {}, // 绑定的数据

    // 渲染的options
    list:{
      type:Array,
      default:()=>[]
    },
    // 选项value
    listKey:{
      type:String,
      default:'value'
    },
    // 选项name
    listName:{
      type:String,
      default:'name'
    },
    // 是否有全选
    hasCheckAll:{
      type:Boolean,
      default:false
    }
  },
  computed: {
    currentValue:{
      get(){
        return this.value || []
      },
      set(val){
        this.$emit('input',val)
      }
    },
    checkAllData: {
      get() {
        // 监听是否权限
        if (this.currentValue.length === this.list.length) {
          return true;
        }
        if (this.currentValue.length === 0) {
          return false;
        }
        return this.checkAll;
      },
      set(value) {
        this.checkAll = value;
      }
    }
  },
  methods: {
    handleCheckAllChange(val) {
      const list = this.list.map(item => item[this.listKey]);
      this.$emit('input',val ? list : [])
    },
    // change事件
    handleChange(val){
      this.$emit('change',val)
    }
  }
};
</script>
