<script setup lang="ts">
import { ref, shallowRef, watch } from "vue";
import OrganizeTree from "./cpns/organize-tree.vue";
import Modal from "./cpns/modal.vue"
import { usePermission } from "/@/hooks/core/usePermission";


const pageName = "sort";

const data = ref<any>({})
const breadcrumb = ref<any[]>([]);
const visible = shallowRef(false)
const params = ref<Record<string, string>>({ status: "", cat_name: "", company_name: '' });

const organizeTreeRef = ref<InstanceType<typeof OrganizeTree> | null>(null);

function handleBreadcrumbChange(depart: any) { breadcrumb.value.push(depart); }

function handleOrganizeTreeSearch(index?: number) {
  if (index === breadcrumb.value.length - 1) return;
  const item = breadcrumb.value[index];
  const id = item ? item.id : "";
  organizeTreeRef.value.changePid(id);
  organizeTreeRef.value.onSearch();
  breadcrumb.value.splice(index + 1);
}

watch(() => breadcrumb.value, () => {
  const business = breadcrumb.value[breadcrumb.value.length - 1]
  data.value.companyNo = business ? business.companyNo : ''
  data.value.pid = business ? business.id : '0'
}, {
  immediate: true,
  deep: true
})
const { hasPermissionWithCode } = usePermission(pageName)
</script>

<template>
  <PageAuth class="px-[10px] h-[calc(100vh-60px)] bg-white" :pageName="pageName" :margin="false">
    <ul class="flex cursor-pointer">
      <li @click="() => handleOrganizeTreeSearch()">
        全部一级分类
        <span v-if="breadcrumb.length > 0" class="mx-[5px]">/</span>
      </li>

      <li :class="{ 'cursor-pointer': true, 'text-[#ccc]': index === breadcrumb.length - 1 }"
        v-for="(item, index) in breadcrumb" :key="item.id" @click="() => handleOrganizeTreeSearch(index)">
        {{ item.cat_name }}
        <span class="mx-[5px]" v-if="index !== breadcrumb.length - 1">/</span>
      </li>
    </ul>

    <div class="flex justify-between pt-[20px]">
      <div class="flex gap-1">
        <ElInput 
          v-model="params.cat_name" 
          placeholder="分类名称" 
          clearable 
          size="small"
          @change="() => organizeTreeRef.onSearch()" 
        />
      </div>

      <div class="flex">
        <ElButton 
          size="small" 
          type="primary" 
          @click="visible = true;data = {}"
          v-if="hasPermissionWithCode('003')"
        >添加</ElButton>
        
        <ElButton size="small" @click="() => organizeTreeRef.onSearch()">刷新</ElButton>
      </div>
    </div>

    <!-- 树节点 -->
    <div class="flex-1">
      <OrganizeTree ref="organizeTreeRef" :otherParms="params" :breadcrumb="breadcrumb"
        @breadcrumb-change="handleBreadcrumbChange" />
    </div>

    <Modal 
      v-model:data="data" 
      v-model:visible="visible" 
      @refresh="organizeTreeRef.onSearch()" 
      :breadcrumb="breadcrumb"
      :type="'create'"
      :pid="breadcrumb.length === 0 ? '0' : breadcrumb[breadcrumb.length -1].id" 
    />
  </PageAuth>
</template>
