<script setup lang="ts">
import { ElScrollbar, ElCheckbox, ElCheckboxGroup } from 'element-plus';
import { ref, watchEffect, watchPostEffect, defineEmits } from 'vue'
/**
 * @desc: 复选框选择器组件主要用于表单场景下 支持全选
 * @author: changjun
 */

interface CheckChangerProps {
  options: any[],
  modelValue: []
}

const { options = [], modelValue = [] } = defineProps<CheckChangerProps>()
const emit = defineEmits(['update:modelValue', 'change']);


const treeCheckAll = ref(false) // 全选
const isIndeterminate = ref(false) // 半选
const checkList = ref([]) as any // 当前选中列表

// 全选/清空 回调
const handleCheckAllChange = (val: boolean) => {
  const _allList = unref(options).map(item => item.id)
  checkList.value = val ? _allList : []
  handleCheckChange(checkList.value)
}

watchEffect(() => {
  checkList.value = modelValue;
});

watchPostEffect(() => {
  const _currentCheck = checkList.value
  const _allIds = options.map(item => item.id)
  treeCheckAll.value = _currentCheck.length === _allIds.length
  isIndeterminate.value = _currentCheck.length > 0 && _currentCheck.length < _allIds.length
})

// 选中值改变修改父
function handleCheckChange(list) {
  console.log('选中值改变', list)
  emit('update:modelValue', list)
  emit('change', list)
}


</script>

<template>
  <div class="check-changer-card">
    <div class="check-changer-card-header">
      <ElCheckbox v-model="treeCheckAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</ElCheckbox>
    </div>
    <div class="check-changer-card-content">
      <ElScrollbar>
        <ElCheckboxGroup v-model="checkList" @change="handleCheckChange">
          <ElCheckbox v-for="checkitem in options" :key="checkitem.id" :label="checkitem.id">{{ checkitem.roleName }}
          </ElCheckbox>
        </ElCheckboxGroup>
      </ElScrollbar>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.check-changer-card {
  width: 100%;
  display: flex;
  height: 275px;
  background: rgba(0, 0, 0, 0.01);
  border-radius: 2px;
  border: 1px solid rgba(0, 0, 0, 0.2);
  flex-direction: column;

  .el-checkbox {
    width: 152px;
    height: 32px;
    padding: 0 0 0 9px;
    box-sizing: border-box;
    border-radius: 2px;
    display: flex;
    align-items: center;
    margin-right: 0;
    --el-checkbox-text-color: #666666;
    --el-checkbox-font-weight: 400;
  }


  .check-changer-card-header {
    width: 100%;
    height: 40px;
    display: flex;
    align-items: center;
    padding: 0 16px;
    box-sizing: border-box;
    border-bottom: 1px solid rgba(0, 0, 0, 0.2);

  }

  .check-changer-card-content {
    width: 100%;
    height: 235px;
    padding: 16px;
    box-sizing: border-box;

    .el-checkbox-group {
      display: flex;
      flex-wrap: wrap;
      gap: 0 16px;
    }

    .el-checkbox:hover {
      background: #F4F4F4;
    }

    :deep(.el-checkbox:hover .el-checkbox__inner) {
      border-color: var(--el-checkbox-input-border-color-hover);
    }

  }
}
</style>
