<template>
  <el-dialog title="选择分类" v-model="dialogVisible">
    <div class="list" v-loading="loading">
      <div class="row" v-for="(item, index) in categorys" :key="item.id">
        <div class="list_title">{{ item.name }}</div>
        <div class="item_wrap">
          <el-button
            :type="item.active ? 'primary' : ''"
            @click="selectHandle(item)"
            >全部</el-button
          >
          <el-button
            :type="val.active ? 'primary' : ''"
            v-for="val in item.childrenList"
            :key="val.id"
            @click="selectHandle(val, index)"
            >{{ val.name }}</el-button
          >
        </div>
      </div>
    </div>
    <span slot="footer" style="display: flex; justify-content: flex-end">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="onSubmitHandle">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script setup>
import { tbShopCategoryGet } from "@/api/device";
import { onMounted, ref } from "vue";
import { useUser } from "@/store/user.js";

const store = useUser();
const emit = defineEmits(["success"]);

const dialogVisible = ref(false);
const loading = ref(false);
const categorys = ref([]);

function onSubmitHandle() {
  let categorysArr = [];
  for (let item of categorys.value) {
    if (item.active) {
      categorysArr.push({
        name: `${item.name}`,
        id: item.id,
      });
    }
    if (item.childrenList.length) {
      for (let val of item.childrenList) {
        if (val.active) {
          categorysArr.push({
            name: `${val.name}`,
            id: val.id,
          });
        }
      }
    }
  }
  emit("success", categorysArr);
  dialogVisible.value = false;
}

// 选择分类
function selectHandle(item, index = -1) {
  if (index != -1) {
    categorys.value[index].active = false;
  } else {
    item.childrenList.map((item) => {
      item.active = false;
    });
  }
  item.active = !item.active;
}

// 获取分类
async function tbShopCategoryGetAjax() {
  try {
    loading.value = true;
    const res = await tbShopCategoryGet({
      shopId: store.userInfo.shopId,
      sort: "sort,desc",
      page: 0,
      size: 500,
    });
    res.map((item) => {
      item.active = false;
      item.childrenList.map((item) => {
        item.active = false;
      });
    });
    categorys.value = res;

    setTimeout(() => {
      loading.value = false;
    }, 300);
  } catch (error) {
    console.log(error);
    loading.value = false;
  }
}

function show() {
  dialogVisible.value = true;
  tbShopCategoryGetAjax();
}

defineExpose({
  show,
});

onMounted(() => {
  tbShopCategoryGetAjax();
});
</script>

<style scoped lang="scss">
.list {
  min-height: 200px;

  .row {
    padding-bottom: 20px;

    .list_title {
      color: #999;
      padding-bottom: 10px;
    }

    .item_wrap {
      display: flex;
    }
  }
}
</style>
