<template>
  <div class="xd-checkbox">
    <el-checkbox
      v-if="isAll"
      class="xd-checkbox__all"
      :indeterminate="isIndeterminate"
      v-model="checkAll"
      @change="handleCheckAllChange"
    >全选</el-checkbox>
    <el-checkbox-group
      class="xd-checkbox__group"
      v-model="checkedList"
      @change="handleCheckedCitiesChange"
    >
      <div
        class="xd-checkbox__group-item"
        :style="{
          border: border ? '1px solid #f4f4f4': '0',
          width: itemWidth,
          margin: itemMargin
        }"
        v-for="(item,index) in checkDataList"
        :key="index"
        :class="{'is-one-line': isOneLine}"
      >
        <div class="xd-checkbox__group-item-self">
          <el-checkbox
            class="app-checkbox"
            :label="item[labelKey]"
            :key="index"
          >{{item[labelName]}}</el-checkbox>
        </div>
        <div class="xd-checkbox__group-item-slot">
          <slot :item="item" :index="index">
            {{item[labelName]}}
          </slot>
        </div>
      </div>
    </el-checkbox-group>
  </div>
</template>

<script>
  /**
   * @description 自定义全选组
   * 依赖于 element-ui
   * 参考网站如下：
   * https://element.eleme.io/#/zh-CN/component/checkbox
   * 文档：https://www.npmjs.com/package/gxd-helper
   *
   * @property {Array} value 已经选中数据 （选填） 默认：[116.404, 39.915]天安门
   * @property {Boolean} isAll 是否全选中按钮 （选填） 默认：true
   * @property {Array} list 列表显示数据 （选填） 默认：15
   * @property {String} itemWidth 选项宽度 （选填） 默认：300px
   * @property {String} itemMargin 选项边距宽度 （选填） 默认：0 20px 20px 0
   * @property {Boolean} isOneLine 是否单行显示 （选填） 默认：false
   * @property {Number} border 是否选项边框 （选填） 默认：false
   * @property {String} labelKey 指定label key值 （选填） 默认：id
   * @property {String} labelName 指定label name值,  （选填） 默认：name
   *
   * @event {Function} change 选中改变事件 参数：this.checkedList
   *
   * @slot 默认插槽  参数：（item, index）
   *
   * @v-model this.checkedList
   */

  export default {
    name: "XdCheckBoxList",
    props: {
      value:{
        type: Array,
        default(){
          return [];
        }
      },
      isAll: {
        type: Boolean,
        default: true
      },
      list: {
        type: Array,
        required: true
      },
      itemWidth: {
        type: String,
        default: '300px'
      },
      itemMargin: {
        type: String,
        default: '0 20px 20px 0'
      },
      isOneLine: {
        type: Boolean,
        default: false
      },
      border: {
        type: Boolean,
        default: false
      },
      labelKey: {
        type: String,
        default: 'id'
      },
      labelName: {
        type: String,
        default: 'name'
      }
    },
    data(){
      return {
        checkAll: false, //是否全选 true=>全选 false=>不选
        checkedList: [], //选中itemID列表
        checkDataList: [], //当前数据项列表
        checkSourceDataList: [],//当前原始数据项列表
        isIndeterminate: false, //是否全选状态 true=>半选 false 不选（提前是非全选时候生效）
      }
    },
    created() {
      this.init();
      this.updateSelect()
    },
    watch:{
      list(){
        this.init();
        this.updateSelect();
      },
    },

    methods:{

      init(){
        //检查数据项
        if (this.$xdHelper.checkVarType(this.list) === 'array' &&
          this.list.length > 0
        ) {
          this.checkDataList = this.$xdHelper.cloneDeep(this.list);
          this.checkSourceDataList = this.$xdHelper.cloneDeep(this.list);
        }

        //检查选中数据项
        if (this.$xdHelper.checkVarType(this.value) === 'array' &&
          this.value.length > 0
        ) {
          this.checkedList = this.$xdHelper.cloneDeep(this.value);
          this.isIndeterminate = true;

          if (this.value.length === this.checkDataList.length){
            this.checkAll = true;
            this.isIndeterminate = false;
          }
          else{
            this.checkAll = false;
            this.isIndeterminate = true;
          }
        }
      },

      /**
       * @description 选中事件操作
       */
      updateSelect() {
        this.$emit('input', this.checkedList);
        this.$emit('change', this.getCheckedItem());
      },

      /**
       * @description 设置返回参数方法
       */
      getCheckedItem() {
        let temp = {
          value: this.$xdHelper.cloneDeep(this.checkedList),
          list: []
        };
        this.checkedList.map((id) => {
          let item = this.$xdHelper.isKeyInLists(this.checkSourceDataList, id, this.labelKey);
          if (item) temp.list.push(item);
        });
        return temp;
      },

      /**
       * @description 全选/取消操作按钮
       * @param val
       */
      handleCheckAllChange(val) {
        let getIds = (list) => {
          let temp = [];
          list.map((item) => {
            temp.push(item[this.labelKey]);
          });
          return temp;
        };
        this.checkedList = val ? this.$xdHelper.cloneDeep(getIds(this.checkSourceDataList)) : [];
        this.isIndeterminate = false;
        this.updateSelect();

      },

      /**
       * @description 选中插件项目对象操作
       * @param value
       */
      handleCheckedCitiesChange(value) {
        let checkedCount = value.length;
        this.checkAll = checkedCount === this.checkDataList.length;
        this.isIndeterminate = checkedCount > 0 && checkedCount !== this.checkDataList.length;
        this.updateSelect();
      },
    }
  }
</script>

<style scoped lang="scss">
  .xd-checkbox {
    &__all {
      height: 20px;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      padding-bottom: 5px;
    }

    &__group {
      width: 100%;
      display: flex;
      justify-content: flex-start;
      align-content: center;
      flex-direction: row;
      flex-wrap: wrap;

      &-item {
        position: relative;

        &.is-one-line {
          display: flex;
          justify-content: flex-start;
          align-items: center;
          flex-wrap: wrap;
          min-height: 20px;
          line-height: 20px;
          padding:3px 0;
          font-size: 14px;
        }

        &.is-one-line &-slot {
          margin-left: 6px;
        }

        &-slot {
          font-size: 14px;
          flex: 1;
        }

        &-self {
          margin-top: 1px;
          height: 100%;
          flex-shrink: 0;
         & ::v-deep .el-checkbox__label {
            display: none;
          }
        }
      }
    }
  }

  @media screen and (max-width: 768px) and  (orientation: portrait)  {
    .xd-check-group {
      width: 100%;
    }
    .xd-checkbox-item {
      margin: 0!important;
      width: 100%!important;
    }

    .xd-checkbox-item ::v-deep .el-card__body {
      margin: 2vw;
    }

  }

  @media screen and (max-width: 850px) and (orientation: landscape) {
    .xd-check-group {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      align-content: center;
      flex-wrap: wrap;
    }

    .xd-checkbox-item {
      margin: 0 0 2vw!important;
      width: 42vw!important;
    }

    .xd-checkbox-item ::v-deep.el-card__body {
      margin: 2vw;
    }
  }


</style>
