<template>
  <Layout>
    <div class="flex flex-col w-full h-full">
      <div class="flex items-center">
        <Search
          placeholder="搜索"
          v-model="searchStrOfSys"
          v-show="focusedMenu === 'sys'"
        ></Search>
        <Search
          placeholder="搜索"
          v-model="searchStr"
          v-show="focusedMenu === 'private'"
        ></Search>
        <Avatar class="ml-7"></Avatar>
      </div>
      <div
        class="flex items-center justify-between overflow-hidden flex-shrink-0"
        style="margin-top: 26px"
      >
        <Title>模板管理</Title>
        <div class="flex items-center">
          <syButton
            style="width: 113px"
            mode="elementBtn"
            size="large"
            @click="editCategoryShow = true"
          >
            <Icon icon-name="iconhuazhuanjilu" style="margin-right: 3px"></Icon>
            编辑分类</syButton
          >
          <syMoreOperate
            class="ml-3"
            :list="operateListOfCreate"
            :margin-left="-10"
            teleport
            @click-item="
              ($event) =>
                operateListOfCreate.find((i) => i.value === $event)!.click()
            "
          >
            <syButton
              style="width: 113px"
              mode="elementBtn"
              size="large"
              type="primary"
              >新建</syButton
            >
          </syMoreOperate>
        </div>
      </div>
      <syMenu
        v-model="focusedMenu"
        :menu-list="[
          { label: '系统模板', value: 'sys' },
          { label: '我的模板', value: 'private' },
        ]"
      ></syMenu>
      <HorizontalListWrapper
        v-if="focusedMenu === 'sys'"
        class="flex-shrink-0 mt-[10px]"
        ref="HorizontalListWrapperRef"
      >
        <CategoryList
          v-model:focusedId="focusedSysFolderId"
          :list="
            sysFolderList.map((i) => ({ name: i.folder_name, id: i.folder_id }))
          "
        ></CategoryList>
      </HorizontalListWrapper>
      <HorizontalListWrapper
        v-else-if="focusedMenu === 'private'"
        class="flex-shrink-0 mt-[10px]"
        ref="HorizontalListWrapperRef"
        @to-almost-end="fetchNextPageOfCategory"
      >
        <CategoryList
          :list="categoryList"
          ref="categoryListRef"
          v-model:focusedId="focusedCategoryId"
        ></CategoryList>
      </HorizontalListWrapper>
      <syScrollBar class="flex-grow" style="margin-top: 28px">
        <TemplateList
          v-if="focusedMenu === 'private'"
          :list="templateList"
          :categoryId="focusedCategoryId"
          v-loading="loadingOfTemplateList"
          :hideOperate="false"
          @update="refetchOfTemplateList"
        ></TemplateList>
        <TemplateList
          v-else-if="focusedMenu === 'sys'"
          :list="
            (
              sysFolderList.find((i) => i.folder_id === focusedSysFolderId)
                ?.detail || []
            ).filter((i: any) => i.name.includes(searchStrOfSys))
          "
          :hideOperate="true"
          :categoryId="focusedSysFolderId"
        ></TemplateList>
      </syScrollBar>
    </div>
    <syCommonDialog
      :visible="showAddCategory"
      @closePopup="showAddCategory = false"
      showMask
      type="element"
      elementDialogSize="medium"
      :elementDialogProps="{
        title: '添加分类',
      }"
      :btnConfig="{
        type: 'noBorder',
      }"
    >
      <AddCategory
        v-if="showAddCategory"
        ref="categoryAddRef"
        @close="showAddCategory = false"
        @successCallback="
          syMessage.success('创建成功');
          refetchOfCategoryList();
        "
      >
      </AddCategory>
    </syCommonDialog>
    <syCommonDialog
      :visible="showAddTemplate"
      @closePopup="showAddTemplate = false"
      showMask
      type="element"
      :element-dialog-props="{
        title: '添加模板',
      }"
      :btnConfig="{
        type: 'noBorder',
        btns: btns,
        btnFunctions: [
          {
            name: '取消',
            async click() {
              return true;
            },
          },
          {
            name: '确定',
            click: async () => {
              await ($refs.addTemplateRef as any).checkForm();
              refetchOfTemplateList();
              syMessage.success('创建成功')
              return true;
            },
          },
        ],
      }"
    >
      <AddTemplate
        v-if="showAddTemplate"
        ref="addTemplateRef"
        :activeId="focusedCategoryId"
        @close="showAddTemplate = false"
      >
      </AddTemplate>
    </syCommonDialog>
    <EditCategoryDialog
      v-model:show="editCategoryShow"
      :list="categoryList"
      @setpos="refetchOfCategoryList"
      @delete="
        () => {
          resetCateogryId();
          refetchOfCategoryList();
        }
      "
      :refetch="refetchOfCategoryList"
      :fetchNextPage="fetchNextPageOfCategory"
    ></EditCategoryDialog>
  </Layout>
</template>
<script lang="ts" setup>
import { nextTick, ref, watch, onBeforeMount, onMounted } from "vue";

import {
  syButton,
  GO_URLS,
  syScrollBar,
  syMoreOperate,
  syMessage,
  syCommonDialog,
  syMenu,
} from "cqk-sy-ui";
import Search from "@/components/Search/index.vue";
import Layout from "@/components/Layout.vue";
import Avatar from "@/components/Avatar/index.vue";
import Title from "@/components/Title.vue";
import Icon from "@/components/Icon/index.vue";
import CategoryList from "./components/CategoryList/index.vue";
import HorizontalListWrapper from "@/components/HorizontalListWrapper/index.vue";
import AddCategory from "./components/AddCategory/index.vue";
import TemplateList from "./components/Template/TemplateList.vue";

import { watchDebounced } from "@vueuse/core";
import { $ajax } from "@/service";
import { useTableData } from "@/components/Table/hooks";
import { iFolder } from "./components/CategoryList/types";
import { iTemplate } from "./components/Template/components/type";
import { btns } from "@/config/btns";
import AddTemplate from "./components/AddTemplate/index.vue";
import EditCategoryDialog from "./components/EditCategoryDialog/index.vue";
import { watchStrChangeDebounceTime } from "@/config/time";
import { router } from "@/router";
import { useRoute } from "vue-router";

const route = useRoute();

const searchStrOfSys = ref("");
const searchStr = ref("");

const showAddCategory = ref(false);
const showAddTemplate = ref(false);
const editCategoryShow = ref(false);

const focusedMenu = ref(route.query.menu);

const focusedCategoryId = ref(Number(route.query.categoryId) || NaN);
const categoryListRef = ref<InstanceType<typeof CategoryList>>();

const templateList = ref<iTemplate[]>([]);
const loadingOfTemplateList = ref(false);

const focusedSysFolderId = ref(NaN);
const sysFolderList = ref<
  { folder_id: number; detail: any; folder_name: string; update_time: number }[]
>([]);

onBeforeMount(() => {
  if (focusedMenu.value === "" || focusedMenu.value === undefined) {
    focusedMenu.value = "sys";
  }
});

onMounted(async () => {
  fetchSysTemplateList().then(() => {
    if (focusedMenu.value === "sys") {
      focusedSysFolderId.value =
        Number(route.query.categoryId) || sysFolderList.value[0].folder_id;
    }
  });
});

watch(focusedMenu, (newV) => {
  router.replace({
    name: "templateManagement",
    query: {
      menu: newV,
    },
  });
  if (newV === "sys") {
    focusedSysFolderId.value = sysFolderList.value[0]?.folder_id;
  } else if (newV === "private") {
    focusedCategoryId.value = categoryList.value[0].id;
  }
});

watch(focusedCategoryId, (newV) => {
  router.replace({
    name: "templateManagement",
    query: {
      menu: "private",
      categoryId: newV,
    },
  });
});

watch(focusedSysFolderId, (newV) => {
  router.replace({
    name: "templateManagement",
    query: {
      menu: "sys",
      categoryId: newV,
    },
  });
});

async function fetchSysTemplateList() {
  const res = await $ajax({
    url: GO_URLS.systemList,
    type: "post",
  });
  if (res) {
    sysFolderList.value = res.data.results || [];
  }
}

const operateListOfCreate = [
  {
    value: "createCategory",
    name: "创建分类",
    click() {
      showAddCategory.value = true;
    },
  },
  {
    value: "createTemplate",
    name: "创建模板",
    click() {
      showAddTemplate.value = true;
    },
  },
];

const resetCateogryId = () => {
  focusedCategoryId.value = categoryList.value[0].id;
};

const {
  tableData: categoryList,
  fetchNextPage: fetchNextPageOfCategory,
  refetch: refetchOfCategoryList,
} = useTableData({
  async fetchData({ page, page_size }) {
    let list = [] as iFolder[];
    let total = 0;
    const res = await $ajax({
      type: "post",
      url: GO_URLS.folderList,
      params: {
        page: page,
        page_size: page_size,
        template_type: 1,
      },
    });
    list = res?.data.results || [];
    total = res?.data.total;

    if (page === 1) {
      refetchOfTemplateList();
    }
    return {
      total: total,
      data: list as iFolder[],
    };
  },
});

let focusInTheTagAfterLoad = false;

watch(categoryList, (nv, ov) => {
  async function findFocus(id: number) {
    const the = categoryList.value.find((i) => i.id === id);
    if (!the) {
      fetchNextPageOfCategory();
    }
  }
  if (focusedMenu.value !== "private") return;
  findFocus(focusedCategoryId.value);
  if (!focusInTheTagAfterLoad) {
    nextTick(() => {
      const els = categoryListRef.value?.getEls()!;
      let index = els.findIndex((i) => i.id === focusedCategoryId.value);
      if (index === -1) return;
      focusInTheTagAfterLoad = true;
      if (els[index + 1]?.el) {
        els[index + 1]?.el.scrollIntoView();
      } else {
        els[index]?.el.scrollIntoView();
      }
    });
  }
});

watchDebounced(
  searchStr,
  () => {
    refetchOfTemplateList();
  },
  {
    debounce: watchStrChangeDebounceTime,
  }
);

watch(focusedCategoryId, () => {
  refetchOfTemplateList();
});

const refetchOfTemplateList = async () => {
  loadingOfTemplateList.value = true;
  let list = [] as any;
  if (searchStr.value.trim() === "") {
    const res = await $ajax({
      type: "post",
      url: GO_URLS.personalList,
      params: {
        id: [focusedCategoryId.value],
      },
    });
    list = (res?.data?.results && res?.data?.results[0].detail) || [];
  } else {
    const res2 = await $ajax({
      url: GO_URLS.searchCustomize,
      type: "post",
      params: {
        key: searchStr.value,
        folder_id: focusedCategoryId.value,
      },
    });
    list = res2?.data.results || [];
  }

  templateList.value = list;
  loadingOfTemplateList.value = false;
};
</script>
<style lang="scss"></style>
