<script setup lang="tsx">
import { nextTick, ref } from 'vue';
import type { TreeOption } from 'naive-ui';
import { NButton, NImage, NSwitch, NTree } from 'naive-ui';
import {
  delCategory,
  fetchAddCategoryOne,
  fetchAddCategoryTwo,
  fetchEditCategory,
  fetchGetAllCategory,
  fetchGetCategoryDetail,
  fetchGetCategoryList
} from '@/service/api/goods-center/type-admin';
import { useAppStore } from '@/store/modules/app';
import { useModalFrom } from '@/components/zt/ModalForm/hooks/useModalForm';
import { useForm } from '@/components/zt/Form/hooks/useForm';
import DictTag from '@/components/zt/dict-tag/index.vue';
interface ContactForm {
  otherCategoryId: any;
  code: string;
  programCode: string;
}
const appStore = useAppStore();
const deskData = ref<Api.goods.ShopCategory[]>([]);
const loading = ref(false);
const [registerSearchForm, { getFieldsValue: getSearchForm }] = 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 loadedTreeData = ref<Record<string, any[]>>({});
const chooseData = ref<Record<string, any[]>>({});

const loadingStates = ref<Record<string, boolean>>({});
const selectChekedKeys = ref<Record<string, TreeOption[]>>({});

// 模拟接口请求函数
const fetchTreeDataByCode = async (code: string) => {
  loadingStates.value[code] = true;
  try {
    // 这里替换为实际的 API 调用
    const { data } = await fetchGetAllCategory(code); // 或其他获取树形数据的接口
    console.log('dadads', data);

    loadedTreeData.value[code] = data;
  } finally {
    loadingStates.value[code] = false;
  }
};
const [
  registerModalForm,
  {
    openModal: openModalForm,
    setFieldsValue: setModalFormValue,
    getFieldsValue: getModalFormValue,
    closeModal: closeModalForm,
    setModalProps,
    setSubLoading,
    updateSchema
  }
] = useModalFrom({
  modalConfig: {
    title: '一级分类',
    isShowHeaderText: true
  },
  formConfig: {
    schemas: [
      {
        field: 'createTime',
        label: 'createTime',
        show: false,
        component: 'NInput'
      },
      {
        field: 'updateTime',
        label: 'updateTime',
        show: false,
        component: 'NInput'
      },
      {
        field: 'sort',
        label: 'sort',
        show: false,
        component: 'NInput'
      },
      {
        field: 'categoryCode',
        label: 'categoryCode',
        show: false,
        component: 'NInput'
      },
      {
        field: 'isDelete',
        label: 'isDelete',
        show: false,
        component: 'NInput'
      },
      {
        field: 'children',
        label: 'children',
        show: false,
        component: 'NInput'
      },
      {
        field: 'id',
        label: '分类ID',
        show: false,
        component: 'NInput'
      },
      {
        field: 'level',
        label: 'level',
        show: false,
        component: 'NInput'
      },
      {
        field: 'parentId',
        label: '上级分类',
        component: 'ApiSelect',
        show: false
      },
      {
        field: 'parentName',
        label: '上级分类名称',
        component: 'NInput',
        componentProps: {
          disabled: true
        },
        ifShow({ model }) {
          return model.parentId;
        }
      },
      {
        field: 'name',
        component: 'NInput',
        label: '分类名称',
        required: true
      },
      {
        field: 'iconUrl',
        component: 'zUpload',
        label: '分类图标',
        componentProps: {
          max: 1
        }
      },
      {
        field: 'adPicture',
        component: 'zUpload',
        label: '广告位图片',
        componentProps: {
          max: 1
        },
        ifShow({ model }) {
          return !model.parentId;
        }
      },
      {
        field: 'adLink',
        component: 'NInput',
        label: '广告位链接',
        ifShow({ model }) {
          return !model.parentId;
        }
      },
      {
        field: 'visible',
        component: 'NSwitch',
        label: '状态',
        defaultValue: 1,
        required: true,
        componentProps: {
          checkedValue: 1,
          uncheckedValue: 0
        }
      },
      {
        field: 'businessType',
        label: '适用业务',
        component: 'NSelect',
        required: true,
        componentProps: {
          options: [
            {
              label: '关联分类',
              value: 0
            },
            {
              label: '活动链接	',
              value: 1
            }
          ]
        },
        ifShow({ model }) {
          return model.parentId;
        }
      },
      {
        field: 'adLink',
        component: 'NInput',
        label: '跳转链接',
        required: true,
        ifShow({ model }) {
          return model.businessType == 1;
        }
      },
      {
        field: 'code',
        label: '业务类型',
        required: true,
        component: 'dictSelect',
        componentProps: {
          dictCode: 'sys_business_type',
          immediate: true,
          multiple: true
        },
        ifShow({ model }) {
          return model.businessType == 0 && model.parentId;
        }
      },
      {
        field: 'contactsForm',
        label: '',
        component: 'NInput',
        render: ({ model }) => {
          return (
            <div>
              {model.code?.map((code: string) => {
                // 自动加载数据 - 如果数据不存在且未在加载中，则发起请求
                if (!loadedTreeData.value[code] && !loadingStates.value[code]) {
                  nextTick(() => {
                    fetchTreeDataByCode(code);
                  });
                }

                return (
                  <div class={'ml120px w500px border rounded-16px border-solid px8px py4px'} key={code}>
                    <DictTag dictCode={'sys_business_type'} value={code}></DictTag>
                    <div class={'ml20px'}>
                      {loadingStates.value[code] ? (
                        <div>加载中...</div>
                      ) : (
                        loadedTreeData.value[code] &&
                        loadedTreeData.value[code].map((item: any) => {
                          return (
                            <div>
                              <div>{item.shopName}</div>
                              <NTree
                                data={item.shopCategoryVOS || []}
                                key-field={'id'}
                                label-field={'name'}
                                onUpdate:checked-keys={(keys: Array<string | number>, options: Array<TreeOption>) =>
                                  handleCheckedKeys(code, keys, options)
                                }
                                default-checked-keys={chooseData.value[code]}
                                expand-on-click
                                cascade
                                checkable
                                block-line
                                default-expand-all
                              />
                            </div>
                          );
                        })
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          );
        },
        ifShow({ model }) {
          return model.code;
        }
      }
    ],
    labelWidth: 120,
    layout: 'horizontal',
    gridProps: {
      cols: '1',
      itemResponsive: true
    }
  }
});
const tableColumns: NaiveUI.TableColumn<Api.goods.ShopCategory>[] = [
  {
    title: '分类名称',
    key: 'name'
  },
  {
    title: '关联商品',
    key: 'prodCount',
    render: row => {
      return row.level == 3 ? `${row.prodCount}个商品` : '';
    }
  },
  {
    title: '广告位',
    key: 'adPicture',
    render: row => {
      return <NImage src={row.adPicture} width={60} height={60}></NImage>;
    }
  },
  {
    title: '跳转链接',
    key: 'adLink'
  },
  {
    title: '状态',
    key: 'visible',
    render: row => <NSwitch uncheckedValue={0} disabled checkedValue={1} value={row.visible}></NSwitch>
  },
  {
    title: '操作',
    key: 'op',
    fixed: 'right',
    align: 'center',
    width: 230,
    render: row => (
      <div class="flex-center gap-8px">
        {row.level == 1 && (
          <NButton type="primary" size="small" ghost onClick={() => add(row)}>
            添加二级分类
          </NButton>
        )}
        {
          <NButton type="primary" size="small" ghost onClick={() => edit(row)}>
            编辑
          </NButton>
        }
        <NButton type="primary" size="small" ghost onClick={() => del(row)}>
          删除
        </NButton>
      </div>
    )
  }
];

async function edit(row: Api.goods.ShopCategory) {
  chooseData.value = {};

  openModalForm(row);
  const { data } = await fetchGetCategoryDetail(row.id);
  data.businessType = Number(data.businessType);
  let code: string[] = [];
  data.children?.forEach((item: Api.goods.ShopCategory) => {
    code.push(item.programCode);
    if (chooseData.value[item.programCode as string]) {
      chooseData.value[item.programCode as string].push(item.id);
    } else {
      chooseData.value[item.programCode] = [item.id];
    }
  });
  code = Array.from(new Set(code));
  // if (code.length) {
  //   code.forEach(item => {
  //     fetchTreeDataByCode(item);
  //   });
  // }
  data.code = code;
  console.log(chooseData.value);
  setModalProps({ title: `修改${Number(row.level)}级分类` });
  setModalFormValue({ ...data, label: row.label });
}
function add(row: Api.goods.ShopCategory) {
  chooseData.value = {};
  openModalForm();
  console.log(row, 'row-key');
  updateSchema({ field: 'iconUrl', required: true });
  setModalProps({ title: `新增二级分类` });
  setModalFormValue({ parentName: row.name, name: '', parentId: row.id });
}
function del(row: Api.goods.ShopCategory) {
  window.$dialog?.info({
    title: '删除分类',
    content: '你确定要删除吗？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const { error } = await delCategory(row.id);
      if (!error) {
        getData();
      }
    }
  });
}
async function getData() {
  const { data, error } = await fetchGetCategoryList({ categoryListQuery: getSearchForm() });
  if (!error) {
    deskData.value = data;
  }
}
function handleOpenModal() {
  openModalForm();
}
async function handleSubmit() {
  const form = await getModalFormValue();
  console.log(form, '表单', selectChekedKeys.value);
  setSubLoading(false);
  // 二级分类数据处理
  if (form.parentId) {
    const contactsForm: ContactForm[] = [];
    for (const key in selectChekedKeys.value) {
      if (Object.hasOwn(selectChekedKeys.value, key)) {
        selectChekedKeys.value[key].forEach(i => {
          contactsForm.push({
            otherCategoryId: i.id,
            code: i.code as string,
            programCode: key
          });
        });
      }
    }
    form.contactsForm = contactsForm;
  }
  if (!form.id) {
    if (!form.parentId) {
      // 新增一级分类
      await fetchAddCategoryOne(form);
    } else {
      // 新增二级分类

      await fetchAddCategoryTwo(form);
    }
  } else {
    // 修改
    await fetchEditCategory(form);
  }
  closeModalForm();
  getData();
}
getData();
function handleCheckedKeys(code: string, _keys: Array<string | number>, option: Array<TreeOption>) {
  selectChekedKeys.value[code] = option;
  console.log(code, selectChekedKeys.value);
}
</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="handleOpenModal">新增一级分类</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>
    <BasicModelForm @register-modal-form="registerModalForm" @submit-form="handleSubmit"></BasicModelForm>
  </LayoutTable>
</template>

<style scoped></style>
