<script setup lang="tsx">
import { nextTick, ref, useTemplateRef } from 'vue';
import { NButton, NImage, NTag } from 'naive-ui';
import {
  fetchAddCategory,
  fetchDeleteCategory,
  fetchGategoryImport,
  fetchGetAllStoreList,
  fetchGetDeskCategoryList,
  fetchGetFailLogList,
  fetchUpdateCategory
} from '@/service/api/goods/desk-category';
import { fetchGetAllTagList } from '@/service/api/goods/tag';
import { useAppStore } from '@/store/modules/app';
import { useModalFrom } from '@/components/zt/ModalForm/hooks/useModalForm';
import { useForm } from '@/components/zt/Form/hooks/useForm';
import { useModal } from '@/components/zt/Modal/hooks/useModal';
import SVGIcon from '@/components/custom/svg-icon.vue';
import RelatedGoods from './components/related-goods.vue';
const appStore = useAppStore();
const deskData = ref<Api.goods.ShopCategory[]>([]);
const loading = ref(false);
const failData = ref<Api.goods.ShopCategoryLogVO[]>();
const relatedGoodsModalRef = useTemplateRef('relatedGoodsModalRef');
const [registerSearchForm, { getFieldsValue: getSearchForm, setFieldsValue }] = useForm({
  schemas: [
    {
      field: 'name',
      component: 'NInput',
      label: '类目名称'
    },
    {
      label: '门店列表',
      component: 'ApiSelect',
      field: 'shopId',
      componentProps: {
        api: fetchGetAllStoreList,
        labelFeild: 'shopName',
        valueFeild: 'shopId',
        onUpdateValue: () => {
          nextTick(() => {
            getData();
          });
        },
        getOptions: async (options: any) => {
          await setFieldsValue({ shopId: options[0].shopId });
          getData();
        }
      }
    }
  ],
  labelWidth: 120,
  layout: 'horizontal',
  gridProps: {
    cols: '1 xl:4 s:1 l:3',
    itemResponsive: true
  },
  collapsedRows: 1
});
const importTemplateRef = useTemplateRef('importTemplateRef');

const [
  registerModalForm,
  {
    openModal: openModalForm,
    setFieldsValue: setModalFormValue,
    getFieldsValue: getModalFormValue,
    closeModal: closeModalForm,
    setModalProps,
    setSubLoading
  }
] = useModalFrom({
  modalConfig: {
    title: '一级分类',
    isShowHeaderText: true
  },
  formConfig: {
    schemas: [
      { label: '', field: 'id', show: false, component: 'NInput' },
      { label: '', field: 'level', show: false, component: 'NInput' },
      { label: '', field: 'pid', show: false, component: 'NInput' },
      { label: '', field: 'parentCode', show: false, component: 'NInput' },
      {
        label: '所属二级分类',
        field: 'BreadName',
        component: 'NGradientText',
        render({ model, field }) {
          return <div> {model[field]} </div>;
        },
        ifShow({ model, field }) {
          return model[field];
        }
      },
      {
        label: '分类名称',
        field: 'name',
        component: 'NInput',
        required: true,
        ifShow({ model }) {
          return model.level == 3;
        }
      },
      {
        label: '分类图标',
        field: 'icon',
        component: 'zUpload',
        componentProps: {
          tipText: '建议图片尺寸比例 1:1',
          aspectRatioW: 1,
          aspectRatioH: 1,
          max: 1
        },
        required: true,
        ifShow({ model }) {
          return model.level != 3;
        }
      },
      {
        label: '标签',
        field: 'label',
        component: 'ApiSelect',
        componentProps: {
          api: fetchGetAllTagList,
          // api: fetchGetTagList,
          labelFeild: 'name',
          valueFeild: 'id'
        },
        ifShow({ model }) {
          return model.level == 1;
        }
      },
      {
        label: '排序',
        component: 'NInputNumber',
        field: 'num',
        labelMessage: '数字越小越靠前',
        required: true,
        defaultValue: 1,
        componentProps: {
          min: 1
        }
      }
    ],
    labelWidth: 120,
    layout: 'horizontal',
    gridProps: {
      cols: '1',
      itemResponsive: true
    }
  }
});
const tableColumns: NaiveUI.TableColumn<Api.goods.ShopCategory>[] = [
  {
    title: '分类名称',
    key: 'name'
  },
  {
    title: '分类图标',
    key: 'icon',
    render(row) {
      return <NImage src={row.icon} class="h-[40px] w-[40px]" />;
    }
  },
  {
    title: '关联商品',
    key: 'prodCount',
    render: row => {
      return row.level == 3 ? `${row.prodCount}个商品` : '';
    }
  },
  {
    title: '标签',
    key: 'labelName',
    render: row => {
      return row.labelName ? <NTag> {row.labelName} </NTag> : '';
    }
  },
  {
    title: '排序',
    key: 'num'
  },
  {
    title: '操作',
    key: 'op',
    fixed: 'right',
    align: 'center',
    width: 230,
    render: row => (
      <div class="flex-center gap-8px">
        {row.level == 2 && (
          <NButton type="primary" size="small" ghost onClick={() => add(row)}>
            添加三级分类
          </NButton>
        )}
        {row.level == 3 && (
          <NButton type="primary" size="small" ghost onClick={() => handleOpenRelatedGoods(row)}>
            关联商品
          </NButton>
        )}
        {
          <NButton type="primary" size="small" ghost onClick={() => edit(row)}>
            编辑
          </NButton>
        }

        {row.level == 3 && (
          <NButton type="primary" size="small" ghost onClick={() => del(row)}>
            删除
          </NButton>
        )}
      </div>
    )
  }
];
const failColumns: NaiveUI.TableColumn<Api.goods.ShopCategoryLogVO>[] = [
  {
    key: 'index',
    title: '序号',
    align: 'center',
    render(_, rowIndex) {
      return rowIndex + 1;
    }
  },
  {
    key: 'taskName',
    title: '任务名称',
    align: 'center'
  },
  {
    key: 'createTime',
    title: '时间',
    align: 'center',
    render(row) {
      return (
        <div>
          <div>创建时间：{row.createTime}</div>
          <div>完成时间：{row.createTime}</div>
        </div>
      );
    }
  },
  {
    key: 'totalUserCount',
    title: '操作人',
    align: 'center',
    render(row) {
      return (
        <div>
          <div>{row.createByRole}</div>
          <div>({row.createByName})</div>
        </div>
      );
    }
  },
  {
    key: 'successStatus',
    title: '状态',
    align: 'center',
    width: 240,
    render(row) {
      return (
        <div class={'flex items-center'}>
          共{Number(row.successStatus) + Number(row.failureStatus)}条，成功：{row.successStatus}，
          <span class={'flex items-center text-red-500'}>
            失败：
            {row.failureStatus}
            {row.failureStatus != 0 && (
              <div onClick={() => hanleExportFailure(row.taskCode)}>
                <SVGIcon
                  icon={'tdesign:download'}
                  class={'ml-1 cursor-pointer text-20px'}
                  style={'color:var(--n-color)'}
                ></SVGIcon>
              </div>
            )}
          </span>
        </div>
      );
    }
  }
];
const [registerModalFail, { openModal: openModalFail, setModalLoading }] = useModal({
  title: '导入分类',
  isShowHeaderText: false,
  showFooter: false
});
async function handleSubmit(file: File) {
  const { error } = await fetchGategoryImport(file);
  if (!error) {
    importTemplateRef.value?.closeModal();
  }
  importTemplateRef.value?.setSubLoading(false);
}
function edit(row: Api.goods.ShopCategory) {
  openModalForm(row);
  setModalProps({ title: `修改${Number(row.level)}级分类` });
  setModalFormValue({ ...row, label: row.label });
}
function add(row: Api.goods.ShopCategory) {
  const { ancestors, current } = getRowHierarchyInfo(row, deskData.value);
  const level1Name = ancestors[0].name;
  const level2Name = current.name;
  openModalForm();
  setModalProps({ title: `新增三级分类` });
  setModalFormValue({ level: 2, pid: row.id, parentCode: row.code, BreadName: `${level1Name} > ${level2Name}` });
}
function del(row: Api.goods.ShopCategory) {
  window.$dialog?.info({
    title: '删除分类',
    content: '你确定要删除吗？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const { error } = await fetchDeleteCategory(row.id);
      if (!error) {
        getData();
      }
    }
  });
}
async function getData() {
  const { data, error } = await fetchGetDeskCategoryList(getSearchForm());

  if (!error) {
    deskData.value = data;
  }
}
function handleOpenRelatedGoods(row: Api.goods.ShopCategory) {
  const { ancestors, current } = getRowHierarchyInfo(row, deskData.value);
  const level1Name = ancestors[0].name;
  const level2Name = ancestors[0].name;
  const level3Name = current.name;
  relatedGoodsModalRef.value?.handleOpenModal({ ...row, level1Name, level2Name, level3Name });
}
async function handleSubmitForm() {
  const form = await getModalFormValue();
  const level = form.level;
  const { error } =
    level != 3 ? await fetchUpdateCategory(form) : await fetchAddCategory({ ...form, shopId: getSearchForm().shopId });
  if (!error) {
    closeModalForm();
    getData();
  }
  setSubLoading(false);
}

function handleOpen() {
  importTemplateRef.value?.openModal();
}
async function handleOpenFaileModal() {
  openModalFail();
  setModalLoading(true);
  const { data: failList, error } = await fetchGetFailLogList();
  if (!error) {
    failData.value = failList;
  }
  setModalLoading(false);
}
function hanleExportFailure(taskCode: string) {
  window.open(
    `${import.meta.env.VITE_SERVICE_BASE_URL}/platform/shopCategoryLog/export?taskCode=${taskCode}`,
    '_blank'
  );
}

function getRowHierarchyInfo(
  row: Api.goods.ShopCategory,
  allData: Api.goods.ShopCategory[]
): {
  current: Api.goods.ShopCategory;
  parent: Api.goods.ShopCategory | null;
  children: Api.goods.ShopCategory[];
  ancestors: Api.goods.ShopCategory[];
  descendants: Api.goods.ShopCategory[];
} {
  // 查找父节点
  const findParent = (data: Api.goods.ShopCategory[], targetPid: number): Api.goods.ShopCategory | null => {
    for (const item of data) {
      if (item.id === targetPid) {
        return item;
      }
      if (item.children && item.children.length > 0) {
        const found = findParent(item.children, targetPid);
        if (found) return found;
      }
    }
    return null;
  };

  // 查找所有祖先节点
  const findAncestors = (data: Api.goods.ShopCategory[], targetPid: number): Api.goods.ShopCategory[] => {
    const ancestors: Api.goods.ShopCategory[] = [];
    let currentPid = targetPid;

    while (currentPid !== 0) {
      const parent = findParent(data, currentPid);
      if (parent) {
        ancestors.unshift(parent); // 添加到数组开头以保持层级顺序
        currentPid = parent.pid;
      } else {
        break;
      }
    }

    return ancestors;
  };

  // 获取所有子孙节点
  const getAllDescendants = (node: Api.goods.ShopCategory): Api.goods.ShopCategory[] => {
    let descendants: Api.goods.ShopCategory[] = [];

    if (node.children && node.children.length > 0) {
      node.children.forEach(child => {
        descendants.push(child);
        descendants = descendants.concat(getAllDescendants(child));
      });
    }

    return descendants;
  };

  const parent = row.pid === 0 ? null : findParent(allData, row.pid);
  const ancestors = findAncestors(allData, row.pid);
  const descendants = getAllDescendants(row);

  return {
    current: row,
    parent,
    children: row.children || [],
    ancestors,
    descendants
  };
}
</script>

<template>
  <LayoutTable>
    <NCard :bordered="false" size="small">
      <NCollapse display-directive="show" :default-expanded-names="['desk-search']">
        <NCollapseItem title="搜索" name="desk-search">
          <BasicForm @register-form="registerSearchForm" @submit="getData" @reset="getData" />
        </NCollapseItem>
      </NCollapse>
    </NCard>
    <NCard title="前台类目" :bordered="false" size="small" class="card-wrapper sm:flex-1-hidden">
      <template #header-extra>
        <TableHeaderOperation :loading="loading" @refresh="getData">
          <template #prefix>
            <NButton size="small" @click="handleOpen">
              <template #icon>
                <icon-file-icons:microsoft-excel class="text-icon"></icon-file-icons:microsoft-excel>
              </template>
              Excel导入分类
            </NButton>
            <NButton size="small" @click="handleOpenFaileModal">
              <template #icon>
                <icon-file-icons:microsoft-excel class="text-icon"></icon-file-icons:microsoft-excel>
              </template>
              导入记录
            </NButton>
          </template>
        </TableHeaderOperation>
      </template>
      <NDataTable
        :columns="tableColumns"
        :data="deskData"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="1088"
        :loading="loading"
        :row-key="row => row.id"
        remote
        class="sm:h-full"
      />
    </NCard>
    <BasicModal @register="registerModalFail">
      <NDataTable :columns="failColumns" :data="failData" size="small" remote class="sm:h-full" />
    </BasicModal>
    <ZImportTemplate
      ref="importTemplateRef"
      url="/platform/shopCategory/exportTemplate"
      template-text="店内分类导入模版.xlsx"
      modal-text="Excel导入分类"
      @submit="handleSubmit"
    ></ZImportTemplate>

    <BasicModelForm @register-modal-form="registerModalForm" @submit-form="handleSubmitForm"></BasicModelForm>
    <RelatedGoods ref="relatedGoodsModalRef" @refresh="getData"></RelatedGoods>
  </LayoutTable>
</template>

<style scoped></style>
