<template>
  <el-collapse-item :name="keyName">
    <template slot="title">
      <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange" class="check-title">
        <span class="check-title">{{title}}</span>
      </el-checkbox>
    </template>
    <el-checkbox-group v-if="options.length > 0" v-model="value" @change="handleCheckedItemChange">
      <template v-for="dataItem in options">
        <br :key="'s'+dataItem.value"/>
        <el-checkbox :label="dataItem.value || dataItem.value === 0?dataItem.value:dataItem.label" :key="dataItem.value">{{dataItem.label}}</el-checkbox>
        <slot v-if="dataItem.slot" :name='dataItem.slotName' :item='dataItem'></slot>
      </template>
    </el-checkbox-group>
  </el-collapse-item>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from "vue-property-decorator";
@Component
export default class OrderCheckbox extends Vue {
  value:Array<any>=[]
  activeNames:Array<any>=[1]
  checkAll= false
  isIndeterminate= false

  @Prop()
  title:string|undefined

  @Prop()
  options!:Array<any>

  @Prop()
  keyName:any

  @Prop()
  retType?:string

  clear(){
    this.value = [];
    this.checkAll = false;
    this.isIndeterminate = false;
  }

  getValue(){
    if(this.retType == 'string'){
      let n='';
      for(const item of this.value){
        if(!n){
          n = n + ',' + item
        }else{
          n = item
        }
      }
      return n;
    }else{
      return this.value;
    }
  }

  emitFun(a?:boolean){
    let v:any = this.getValue();
    if(a){
      this.$emit('checkboxChange',[]);
    }else{
      this.$emit('checkboxChange',v);
    }
    
  }

  handleCheckAllChange(val:any){
    this.value = []
    if(val && this.options){
      for(const item of this.options){
        this.value.push(item.value)
      }
    }
    this.isIndeterminate = false;
    this.emitFun(true);
  }

  handleCheckedItemChange(value:any,config:any){
    let checkedCount = value.length;
    this.checkAll = checkedCount === this.options.length;
    this.isIndeterminate = checkedCount > 0 && checkedCount < this.options.length;
    this.emitFun();
  }

}
</script>

<style lang="scss" scoped>
.check-title{
  font-weight: 700;
}
.slot-box{
  padding-left: 8px;
}
</style>