<template>
  <el-container class="category-select-view">
    <el-header class="sa-header">
      <div class="sa-title sa-flex sa-row-between">
        <div class="label sa-flex">选择分类</div>
        <div>
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确定</el-button>
        </div>
      </div>
    </el-header>
    <el-main class="sa-p-0">
      <div class="category-list">
        <el-tree
          ref="treeRef"
          :data="categoryList"
          :props="treeProps"
          node-key="id"
          :default-checked-keys="selectedIds"
          show-checkbox
          :check-strictly="checkStrictly"
          @check="handleCheck"
        />
      </div>
    </el-main>
  </el-container>
</template>

<script>
  export default {
    name: 'CategorySelect',
  };
</script>

<script setup>
  import { ref, reactive, onMounted } from 'vue';
  import { api } from '../goods.service';

  const emit = defineEmits(['modalCallBack']);
  const props = defineProps({
    modal: {
      type: Object,
      default: () => ({}),
    },
    multiple: {
      type: Boolean,
      default: true,
    },
    checkStrictly: {
      type: Boolean,
      default: false,
    },
  });

  const treeRef = ref();
  const categoryList = ref([]);
  const selectedIds = ref([]);

  const treeProps = {
    children: 'children',
    label: 'name',
    value: 'id',
  };

  // 获取分类数据
  async function getData() {
    try {
      const { data, code } = await api.category.list();
      if (code == 200) {
        categoryList.value = data || [];
      }
    } catch (error) {
      console.error('获取分类数据失败:', error);
    }
  }

  // 处理选择
  function handleCheck(data, checked) {
    if (props.multiple) {
      selectedIds.value = checked.checkedKeys;
    } else {
      selectedIds.value = [data.id];
      // 单选模式下，取消其他选择
      treeRef.value.setCheckedKeys([data.id]);
    }
  }

  // 确认选择
  function handleConfirm() {
    const checkedNodes = treeRef.value.getCheckedNodes();
    const selectedCategories = checkedNodes.map((node) => ({
      id: node.id,
      name: node.name,
    }));

    emit('modalCallBack', {
      type: 'confirm',
      data: props.multiple ? selectedCategories : selectedCategories[0] || null,
    });
  }

  // 取消选择
  function handleCancel() {
    emit('modalCallBack', {
      type: 'cancel',
    });
  }

  onMounted(() => {
    getData();

    // 设置默认选中
    if (props.modal.selectedIds) {
      selectedIds.value = Array.isArray(props.modal.selectedIds)
        ? props.modal.selectedIds
        : [props.modal.selectedIds];
    }
  });
</script>

<style lang="scss" scoped>
  .category-select-view {
    .category-list {
      padding: 20px;
      height: 400px;
      overflow-y: auto;
    }
  }
</style>
