<template>
  <div class="box box-shadow">
    <div class="left-header">
      <span class="left-header-title">业务分类</span>
      <span>
        <plus-outlined class="header-add" @click="addEdit()" />
      </span>
    </div>
    <!-- 搜索框-->
    <div class="search">
      <a-input
        v-model:value="searchText"
        placeholder="分类名称"
        class="search-input"
        allow-clear
        @pressEnter="getTreeData"
        @change="searchTextChange"
      >
        <template #prefix>
          <icon-font iconClass="icon-opt-search"></icon-font>
        </template>
      </a-input>
    </div>
    <div class="tree-content">
      <a-spin tip="Loading..." :spinning="apiLoading" :delay="100">
        <div v-show="treeData && treeData.length > 0" class="left-tree">
          <a-directory-tree
            :show-icon="true"
            v-model:selectedKeys="currentSelectKeys"
            v-model:expandedKeys="expandedKeys"
            @select="selectNode"
            :tree-data="treeData"
            :fieldNames="{ children: 'children', title: 'categoryName', key: 'businessCategoryId', value: 'businessCategoryId' }"
          >
            <!-- 图标 -->
            <template #icon>
              <icon-font iconClass="icon-tree-wenjianjia" color="#43505e" fontSize="24px"></icon-font>
            </template>
            <!-- 标题 -->
            <template #title="data">
              <!-- 需要显示编辑图标 -->
              <span class="tree-edit">
                <span class="edit-title" :title="data.categoryName"> {{ data.categoryName }}</span>
                <span class="edit-icon">
                  <a-space>
                    <icon-font iconClass="icon-opt-bianji" color="var(--primary-color)" @click.stop="addEdit(data)"></icon-font>
                    <icon-font iconClass="icon-opt-shanchu" color="red" @click.stop="deleteClick(data)"></icon-font>
                  </a-space>
                </span>
              </span>
            </template>
          </a-directory-tree>
        </div>
        <a-empty v-show="treeData && treeData.length == 0" class="empty" />
      </a-spin>
    </div>

    <!-- 模型分类新增编辑弹框 -->
    <ListTypeAddEdit v-model:visible="showEdit" v-if="showEdit" :data="current" @done="getTreeData" />
  </div>
</template>

<script setup name="ListTypeTree">
import { BusinessCategoryApi } from '../../api/BusinessCategoryApi';
import { ref, createVNode, onMounted, computed, watch } from 'vue';
import { message, Modal } from 'ant-design-vue/es';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import ListTypeAddEdit from './list-type-add-edit.vue';

const props = defineProps({
  // 是否初始化选中
  isInitSelect: {
    type: Boolean,
    default: true
  }
});

const emits = defineEmits(['treeSelect', 'defaultSelect', 'selectNull']);

// 搜索名称
const searchText = ref('');
// 加载状态
const apiLoading = ref(false);
// 配置分类树
const treeData = ref([]);
// 当前选中节点
const currentSelectKeys = ref([]);
// 老的选择数据
const oldSelectKeys = ref([]);
// 当前展开的节点
const expandedKeys = ref([]);
// 是否显示分类新增编辑弹框
const showEdit = ref(false);
// 当前行数据
const current = ref(null);

onMounted(() => {
  getTreeData(true);
});

// 获取分类列表
const getTreeData = (flag = false) => {
  apiLoading.value = true;
  BusinessCategoryApi.list({ searchText: searchText.value })
    .then(res => {
      treeData.value = res;
      const businessCategoryId = localStorage.getItem('businessCategoryId');
      if (flag && res && res.length > 0) {
        if (businessCategoryId && res.find(item => item.businessCategoryId == businessCategoryId)) {
          currentSelectKeys.value = [businessCategoryId];
          oldSelectKeys.value = [businessCategoryId];
          emits(
            'defaultSelect',
            res.find(item => item.businessCategoryId == businessCategoryId)
          );
        } else if (props.isInitSelect) {
          currentSelectKeys.value = [res[0].businessCategoryId];
          oldSelectKeys.value = [...currentSelectKeys.value];
          localStorage.setItem('businessCategoryId', res[0].businessCategoryId);
          emits('defaultSelect', res[0]);
        } else {
          emits('defaultSelect', { businessCategoryId: '' });
        }
      } else {
        emits('selectNull');
      }
    })
    .finally(() => (apiLoading.value = false));
};

// 选中节点
const selectNode = (selectedKeys, metadata) => {
  if (JSON.stringify(oldSelectKeys.value) === JSON.stringify(selectedKeys)) {
    currentSelectKeys.value = [];
    oldSelectKeys.value = [];
    localStorage.setItem('businessCategoryId', '');
    emits('treeSelect', false, metadata);
  } else {
    currentSelectKeys.value = selectedKeys;
    oldSelectKeys.value = [...selectedKeys];
    localStorage.setItem('businessCategoryId', selectedKeys[0]);
    emits('treeSelect', true, metadata);
  }
};

// 搜索值变化
const searchTextChange = () => {
  if (!searchText.value) getTreeData();
};

// 新建编辑
const addEdit = data => {
  current.value = data;
  showEdit.value = true;
};

// 删除
const deleteClick = data => {
  Modal.confirm({
    title: '提示',
    content: '确定要删除吗?',
    icon: createVNode(ExclamationCircleOutlined),
    maskClosable: true,
    onOk: () => {
      apiLoading.value = true;
      BusinessCategoryApi.delete({ businessCategoryId: data.businessCategoryId })
        .then(res => {
          message.success(res.message);
          const businessCategoryId = localStorage.getItem('businessCategoryId');
          if (businessCategoryId == data.businessCategoryId) {
            localStorage.setItem('businessCategoryId', '');
          }
          getTreeData();
        })
        .finally(() => (apiLoading.value = false));
    }
  });
};

defineExpose({
  currentSelectKeys,
  getTreeData
});
</script>

<style scoped lang="less">
@import url('@/styles/commonTree.less');
:deep(.ant-tree-switcher) {
  display: none;
}
</style>
