import { useEffect, useState } from 'react'
import {
  Button, Select,
  //  Collapse, Tree 
  Input,
  message,
  Spin
} from 'antd'
import {
  SyncOutlined,
} from '@ant-design/icons';
import { uptrademarkList } from '../../../../request/api'
const { Search } = Input;
import {
  CloseOutlined,
  DeleteOutlined
} from '@ant-design/icons';
// import {
//   DownOutlined,
// } from '@ant-design/icons';
import TreeMenu from './components/TreeMenu/TreeMenu'
// import type { TreeDataNode } from 'antd';
import './edit-tow.css'
export default function EditTwo(props: any) {
  // const [messageApi, contextHolder] = message.useMessage();
  const [messageApi, contextHolder] = message.useMessage();
  const height = window.innerHeight - 350;
  const [loading, setLoading] = useState(false)
  const handleSubmit = async () => {
    // console.log('selectedCategories', selectedCategories);
    console.log('checkedIds', checkedIds);
    console.log('props', props.editTwoArray);


    // console.log('两个数组内容是否相同:', isEqual);
    // return;
    if (checkedIds.length === 0) {
      message.error('请选择分类');
      // props.setEditProcess(3);

      return;
    } else {
      // props.setEditProcess(3);
      // 使用 Set 数据结构比较
      const getElementCount = (arr: string[]) => {
        const countMap = new Map<string, number>();
        arr.forEach((element) => {
          countMap.set(element, (countMap.get(element) || 0) + 1);
        });
        return countMap;
      };

      const checkedIdsCount = getElementCount(checkedIds);
      const editTwoArrayCount = getElementCount(props.editTwoArray);

      const isEqual =
        checkedIdsCount.size === editTwoArrayCount.size &&
        Array.from(checkedIdsCount.entries()).every(([key, value]) =>
          editTwoArrayCount.get(key) === value
        );
      if (isEqual) {
        props.setEditProcess(3);
        return;
      }
      try {
        setLoading(true)
        await uptrademarkList(props.trademarkId, {
          typeIds: checkedIds
        })
        props.setEditTwoArray(checkedIds)
        setLoading(false)
        props.setEditProcess(3);
        // props.getOrderList()

      } catch (error: any) {
        setLoading(false)
        if (error.response) {
          const data = error.response.data;
          messageApi.open({
            type: 'error',
            content: data.msg ? data.msg : `${data.path}(${data.status})`,
          });
        } else {
          console.error(error)
        }
      } finally {
        setLoading(false)
      }

    }
    // props.setEditProcess(3);


  };
  // 初始化展开状态，默认所有大类的小类都隐藏
  const [expandedIds, setExpandedIds] = useState<any[]>([]);
  // 初始化勾选状态，默认所有小类都未勾选
  const [checkedIds, setCheckedIds] = useState<any[]>([]);

  const formatNumber = (num: number) => {
    return Number.isInteger(num) ? num : num.toFixed(2);
  };
  const [selectedCategories, setSelectedCategories] = useState<{
    id: any;
    name: string;
    code: string;
    children: {
      id: any;
      name: string;
      code: string;
      children: { id: any; name: string; code: string }[];
    }[];
  }[]>([]);
  // // 模拟商标分类数据
  // const trademarkCategories = [

  //   {
  //     id: 1,
  //     name: '大类1',
  //     children: [
  //       {
  //         id: 11,
  //         name: '中类1-1',
  //         children: [
  //           { id: 111, name: '小类1-1-1' },
  //           { id: 112, name: '小类1-1-2' },
  //           { id: 113, name: '小类1-1-3' },
  //           { id: 114, name: '小类1-1-4' },
  //           { id: 115, name: '小类1-1-5' },
  //           { id: 116, name: '小类1-1-6' },
  //           { id: 117, name: '小类1-1-7' },
  //           { id: 118, name: '小类1-1-8' },
  //           { id: 119, name: '小类1-1-9' },
  //           { id: 120, name: '小类1-1-10' },
  //           { id: 1211, name: '小类1-1-11' },
  //           { id: 1222, name: '小类1-1-12' },
  //           { id: 1233, name: '小类1-1-13' },
  //           { id: 1244, name: '小类1-1-14' },
  //           { id: 1255565, name: '计算机嘻嘻嘻嘻哈哈哈哈' },
  //         ]
  //       },
  //       {
  //         id: 12,
  //         name: '中类1-2',
  //         children: [
  //           { id: 121, name: '小类1-2-1' },
  //           { id: 122, name: '小类1-2-2' },
  //           { id: 123, name: '小类1-2-3' },
  //           { id: 124, name: '小类1-2-4' },
  //           { id: 125, name: '小类1-2-5' },
  //           { id: 126, name: '小类1-2-6' },
  //           { id: 127, name: '小类1-2-7' },
  //         ]
  //       }

  //     ]
  //   },
  //   {
  //     id: 2,
  //     name: '大类2',
  //     children: [
  //       {
  //         id: 21,
  //         name: '中类2-1',
  //         children: [
  //           { id: 211, name: '小类2-1-1' },
  //           { id: 212, name: '小类2-1-2' },
  //         ]
  //       },
  //       {
  //         id: 22,
  //         name: '中类2-2',
  //         children: [
  //           { id: 221, name: '小类2-2-1' },
  //           { id: 222, name: '小类2-2-2' },
  //         ]
  //       },
  //       {
  //         id: 23,
  //         name: '中类2-3',
  //         children: [
  //           { id: 231, name: '小类2-3-1' },
  //           { id: 232, name: '小类2-3-2' },
  //         ]

  //       }
  //     ]
  //   },
  //   {
  //     id: 3,
  //     name: '大类3',
  //     children: [
  //       {
  //         id: 31,
  //         name: '中类3-1',
  //         children: [
  //           { id: 311, name: '小类3-1-1' },
  //           { id: 312, name: '小类3-1-2' },
  //         ]
  //       },
  //       {
  //         id: 32,
  //         name: '中类3-2',
  //         children: [
  //           { id: 321, name: '小类3-2-1' },
  //           { id: 322, name: '小类3-2-2' },
  //         ]
  //       }
  //     ]
  //   }




  // ];
  const [trademarkCategories ] = useState<any[]>([]);
  // const [filteredCategories, setFilteredCategories] = useState(trademarkCategories);
  const [filteredCategories, setFilteredCategories] = useState<any[]>([]);



  const handleExpandClick = (id: any) => {
    setExpandedIds(prevIds => {
      if (prevIds.includes(id)) {
        return prevIds.filter(prevId => prevId !== id);
      } else {
        return [...prevIds, id];
      }
    });
  };

  // 处理小类点击事件，切换勾选状态
  const handleSmallMenuClick = (id: any) => {
    let targetCategory: any;
    let targetMiddleCategory: any;
    // 找到小类所属的大类和中类
    outerLoop: for (const category of trademarkCategories) {
      for (const middleCategory of category.children) {
        // 检查 middleCategory.children 是否存在
        if (middleCategory.children && middleCategory.children.some((child: any) => child.id === id)) {
          targetCategory = category;
          targetMiddleCategory = middleCategory;
          break outerLoop;
        }
      }
    }

    if (!targetCategory || !targetMiddleCategory) return;

    const isChecked = checkedIds.includes(id);

    setCheckedIds(prevIds => {
      if (isChecked) {
        return prevIds.filter(prevId => prevId !== id);
      } else {
        return [...prevIds, id];
      }
    });

    setSelectedCategories(prevSelectedCategories => {
      const categoryIndex = prevSelectedCategories.findIndex(
        category => category.id === targetCategory.id
      );

      if (isChecked) {
        // 取消勾选
        if (categoryIndex > -1) {
          const middleCategoryIndex = prevSelectedCategories[categoryIndex].children.findIndex(
            middleCategory => middleCategory.id === targetMiddleCategory.id
          );
          if (middleCategoryIndex > -1) {
            const updatedChildren = prevSelectedCategories[categoryIndex].children[middleCategoryIndex].children.filter(
              child => child.id !== id
            );

            if (updatedChildren.length === 0) {
              // 若该中类下没有选中的小类，移除该中类
              const updatedMiddleCategories = prevSelectedCategories[categoryIndex].children.filter(
                (_, index) => index !== middleCategoryIndex
              );
              if (updatedMiddleCategories.length === 0) {
                // 若该大类下没有选中的中类，移除该大类
                return prevSelectedCategories.filter(
                  (_, index) => index !== categoryIndex
                );
              } else {
                return prevSelectedCategories.map((category, index) =>
                  index === categoryIndex
                    ? { ...category, children: updatedMiddleCategories }
                    : category
                );
              }
            } else {
              return prevSelectedCategories.map((category, catIndex) =>
                catIndex === categoryIndex
                  ? {
                    ...category,
                    children: category.children.map((middleCategory, midIndex) =>
                      midIndex === middleCategoryIndex
                        ? { ...middleCategory, children: updatedChildren }
                        : middleCategory
                    )
                  }
                  : category
              );
            }
          }
        }
      } else {
        // 勾选
        const newChild = targetMiddleCategory.children.find((child: any) => child.id === id);
        if (categoryIndex > -1) {
          const middleCategoryIndex = prevSelectedCategories[categoryIndex].children.findIndex(
            middleCategory => middleCategory.id === targetMiddleCategory.id
          );
          if (middleCategoryIndex > -1) {
            // 若该中类已存在，添加小类到 children 中
            return prevSelectedCategories.map((category, catIndex) =>
              catIndex === categoryIndex
                ? {
                  ...category,
                  children: category.children.map((middleCategory, midIndex) =>
                    midIndex === middleCategoryIndex
                      ? {
                        ...middleCategory,
                        children: [...middleCategory.children, {
                          id: newChild.id,
                          name: newChild.name,
                          code: newChild.code // 添加 code 字段
                        }]
                      }
                      : middleCategory
                  )
                }
                : category
            );
          } else {
            // 若该中类不存在，新增一个中类项
            return prevSelectedCategories.map((category, catIndex) =>
              catIndex === categoryIndex
                ? {
                  ...category,
                  children: [
                    ...category.children,
                    {
                      id: targetMiddleCategory.id,
                      name: targetMiddleCategory.name,
                      code: targetMiddleCategory.code, // 添加 code 字段
                      children: [{
                        id: newChild.id,
                        name: newChild.name,
                        code: newChild.code // 添加 code 字段
                      }]
                    }
                  ]
                }
                : category
            );
          }
        } else {
          // 若该大类不存在，新增一个大类项
          return [
            ...prevSelectedCategories,
            {
              id: targetCategory.id,
              name: targetCategory.name,
              code: targetCategory.code, // 添加 code 字段
              children: [
                {
                  id: targetMiddleCategory.id,
                  name: targetMiddleCategory.name,
                  code: targetMiddleCategory.code, // 添加 code 字段
                  children: [{
                    id: newChild.id,
                    name: newChild.name,
                    code: newChild.code // 添加 code 字段
                  }]
                }
              ]
            }
          ];
        }
      }
      return prevSelectedCategories;
    });
  };
  // 处理删除小类的点击事件
  const handleDeleteSmallCategory = (categoryId: any, middleCategoryId: any, smallCategoryId: any) => {
    setSelectedCategories(prevSelectedCategories => {
      return prevSelectedCategories.map(category => {
        if (category.id === categoryId) {
          return {
            ...category,
            children: category.children.map(middleCategory => {
              if (middleCategory.id === middleCategoryId) {
                return {
                  ...middleCategory,
                  children: middleCategory.children.filter(child => child.id !== smallCategoryId)
                };
              }
              return middleCategory;
            }).filter(middleCategory => middleCategory.children.length > 0)
          };
        }
        return category;
      }).filter(category => category.children.length > 0);
    });

    // 更新 checkedIds 状态
    setCheckedIds(prevCheckedIds => prevCheckedIds.filter(id => id !== smallCategoryId));
  };
  // 处理删除大类的点击事件
  const handleDeleteCategory = (categoryId: any) => {
    // 找到要删除的大类下所有小类的 id
    const targetCategory = selectedCategories.find(category => category.id === categoryId);
    const smallCategoryIdsToRemove = targetCategory?.children.flatMap(middleCategory =>
      middleCategory.children.map(child => child.id)
    ) || [];

    // 更新 selectedCategories 状态，移除对应的大类
    setSelectedCategories(prevSelectedCategories =>
      prevSelectedCategories.filter(category => category.id !== categoryId)
    );

    // 更新 checkedIds 状态，移除该大类下所有小类的 id
    setCheckedIds(prevCheckedIds =>
      prevCheckedIds.filter(id => !smallCategoryIdsToRemove.includes(id))
    );
  };

  // useEffect(() => {
  //   console.log('selectedCategories', selectedCategories);

  // }, [selectedCategories])
  const [keyWords, setKeyWords] = useState<string>('');
  const [searchKeyWords, setSearchKeyWords] = useState<string>('');
  const onSearch = (value: string) => {
    console.log('search:', value);
    setSearchKeyWords(value);
  }

  const filterCategories = (categories: any[], keyword: string, expanded: any[]) => {
    return categories.filter(category => {
      const isMatch = category.name.includes(keyword);
      let childMatch = false;
      if (category.children) {
        const filteredChildren = filterCategories(category.children, keyword, expanded);
        if (filteredChildren.length > 0) {
          childMatch = true;
          category.children = filteredChildren;
          // 若子级有匹配，记录当前分类 ID 为需要展开
          expanded.push(category.id);
        }
      }
      if (isMatch || childMatch) {
        // 若当前项匹配或子级有匹配，记录当前分类 ID 为需要展开
        if (!expanded.includes(category.id)) {
          expanded.push(category.id);
        }
        return true;
      }
      return false;
    });
  };


  // 监听关键字变化，更新筛选后的分类数据和展开状态

  useEffect(() => {
    const expanded: any[] = [];
    if (searchKeyWords) {
      const filtered = filterCategories([...trademarkCategories], searchKeyWords, expanded);
      setFilteredCategories(filtered);
      setExpandedIds([...new Set(expanded)]); // 去重后更新展开状态
    } else {
      setFilteredCategories(trademarkCategories);
      // 初始化需要展开的 ID 数组
      const initialExpandedIds: any[] = [];

      // 遍历所有大类
      trademarkCategories.forEach((category: any) => {
        // 遍历每个大类下的中类
        category.children.forEach((middleCategory: any) => {
          // 检查当前中类下是否有选中的小类
          const hasSelectedChild = middleCategory.children.some((child: any) =>
            checkedIds.includes(child.id)
          );

          if (hasSelectedChild) {
            // 若有选中的小类，添加大类和中类的 ID 到需要展开的数组
            initialExpandedIds.push(category.id, middleCategory.id);
          }
        });
      });


      // 设置展开状态
      setExpandedIds([...new Set(initialExpandedIds)]);
    }
  }, [searchKeyWords]);
  // const getTrademarkTypeList = async (id:string) => {
  //   try {
  //     const res: any = await trademarkTypeList(id)
  //     // console.log('类型数组', res);
  //     setTrademarkCategories(res)
  //     setFilteredCategories(res)
  //   } catch (error: any) {
  //     if (error.response) {
  //       const data = error.response.data;
  //       messageApi.open({
  //         type: 'error',
  //         content: data.msg ? data.msg : `${data.path}(${data.status})`,
  //       });
  //     } else {
  //       console.error(error)
  //     }
  //   }
  // }
  // const initialCheckedIds = [111, 112, 113, 121, 122];
  // const initialCheckedIds = ['42d2b6d5-adbf-485f-944e-4ca8c50c0b16'];
  useEffect(() => {
    // console.log('嘎嘎嘎', props.editTwoArray);

    // getTrademarkTypeList()
    // setCheckedIds(initialCheckedIds);
    // setCheckedIds(initialCheckedIds);
  }, [])

  // 封装获取展开 ID 的逻辑
  // const getExpandedIds = (checkedIds: any[], trademarkCategories: any[]) => {
  //   const expandedIds: any[] = [];
  //   trademarkCategories.forEach((category) => {
  //     category.children.forEach((middleCategory: any) => {
  //       middleCategory.children.forEach((child: any) => {
  //         if (checkedIds.includes(child.id)) {
  //           if (!expandedIds.includes(category.id)) {
  //             expandedIds.push(category.id);
  //           }
  //           if (!expandedIds.includes(middleCategory.id)) {
  //             expandedIds.push(middleCategory.id);
  //           }
  //         }
  //       });
  //     });
  //   });
  //   return [...new Set(expandedIds)];
  // };

  // 封装获取选中分类的逻辑
  // const getSelectedCategories = (checkedIds: any[], trademarkCategories: any[]) => {
  //   const selectedCategories: {
  //     id: any;
  //     name: string;
  //     code: string;
  //     children: {
  //       id: any;
  //       name: string;
  //       code: string;
  //       children: { id: any; name: string; code: string }[];
  //     }[];
  //   }[] = [];

  //   trademarkCategories.forEach((category) => {
  //     category.children.forEach((middleCategory: any) => {
  //       const selectedChildren = middleCategory.children.filter((child: any) =>
  //         checkedIds.includes(child.id)
  //       );
  //       if (selectedChildren.length === 0) return;

  //       const categoryIndex = selectedCategories.findIndex((cat) => cat.id === category.id);
  //       if (categoryIndex > -1) {
  //         const middleCategoryIndex = selectedCategories[categoryIndex].children.findIndex(
  //           (midCat) => midCat.id === middleCategory.id
  //         );
  //         if (middleCategoryIndex > -1) {
  //           selectedCategories[categoryIndex].children[middleCategoryIndex].children = [
  //             ...selectedCategories[categoryIndex].children[middleCategoryIndex].children,
  //             ...selectedChildren
  //           ];
  //         } else {
  //           selectedCategories[categoryIndex].children.push({
  //             id: middleCategory.id,
  //             name: middleCategory.name,
  //             code: middleCategory.code,
  //             children: selectedChildren
  //           });
  //         }
  //       } else {
  //         selectedCategories.push({
  //           id: category.id,
  //           name: category.name,
  //           code: category.code,
  //           children: [
  //             {
  //               id: middleCategory.id,
  //               name: middleCategory.name,
  //               code: middleCategory.code,
  //               children: selectedChildren
  //             }
  //           ]
  //         });
  //       }
  //     });
  //   });
  //   return selectedCategories;
  // };
  // 有id数组时候使用 后续 使用已保存得时候可能回用到
  useEffect(() => {
    if (props.editTwoArray.length > 0) {
      // getTrademarkTypeList().then(() => {

      //   setCheckedIds(props.editTwoArray);
      //   const expandedIds = getExpandedIds(props.editTwoArray, trademarkCategories);
      //   setExpandedIds(expandedIds);
      //   const selectedCategories = getSelectedCategories(props.editTwoArray, trademarkCategories);
      //   setSelectedCategories(selectedCategories);

      // });
    }
  }, [props.editTwoArray])
  useEffect(() => {
    if (trademarkCategories.length > 0) {
      // 初始化需要展开的 ID 数组
      const initialExpandedIds: any[] = [];

      // 遍历所有大类
      trademarkCategories.forEach((category: any) => {
        // 遍历每个大类下的中类
        category.children.forEach((middleCategory: any) => {
          // 检查当前中类下是否有选中的小类
          const hasSelectedChild = middleCategory.children.some((child: any) =>
            checkedIds.includes(child.id)
          );

          if (hasSelectedChild) {
            // 若有选中的小类，添加大类和中类的 ID 到需要展开的数组
            initialExpandedIds.push(category.id, middleCategory.id);
          }
        });
      });

      // 设置默认展开状态
      setExpandedIds([...new Set(initialExpandedIds)]);

      // 初始化一个空数组来存储选中的分类信息
      const initialSelectedCategories: {
        id: any;
        name: string;
        code: string;
        children: {
          id: any;
          name: string;
          code: string;
          children: { id: any; name: string; code: string }[];
        }[];
      }[] = [];

      // 遍历所有大类
      trademarkCategories.forEach((category: any) => {
        // 遍历每个大类下的中类
        category.children.forEach((middleCategory: any) => {
          // 筛选出当前中类下被选中的小类
          const selectedChildren = middleCategory.children.filter((child: any) =>
            checkedIds.includes(child.id)
          );

          if (selectedChildren.length > 0) {
            // 查找大类是否已存在于 initialSelectedCategories 中
            const categoryIndex = initialSelectedCategories.findIndex(
              (cat) => cat.id === category.id
            );

            if (categoryIndex > -1) {
              // 若大类已存在，查找中类是否已存在
              const middleCategoryIndex = initialSelectedCategories[categoryIndex].children.findIndex(
                (midCat) => midCat.id === middleCategory.id
              );

              if (middleCategoryIndex > -1) {
                // 若中类已存在，添加选中的小类
                initialSelectedCategories[categoryIndex].children[middleCategoryIndex].children = [
                  ...initialSelectedCategories[categoryIndex].children[middleCategoryIndex].children,
                  ...selectedChildren
                ];
              } else {
                // 若中类不存在，添加新的中类和选中的小类
                initialSelectedCategories[categoryIndex].children.push({
                  id: middleCategory.id,
                  name: middleCategory.name,
                  code: middleCategory.code,
                  children: selectedChildren
                });
              }
            } else {
              // 若大类不存在，添加新的大类、中类和选中的小类
              initialSelectedCategories.push({
                id: category.id,
                name: category.name,
                code: category.code,
                children: [
                  {
                    id: middleCategory.id,
                    name: middleCategory.name,
                    code: middleCategory.code,
                    children: selectedChildren
                  }
                ]
              });
            }
          }
        });
      });

      // 设置 selectedCategories 状态
      setSelectedCategories(initialSelectedCategories);
    }
  }, [trademarkCategories]);
  return (
    <Spin tip="正在提交，请稍后..." size="small" spinning={loading}>
      <div className='editTwoBox'>
        {contextHolder}
        <div className='topLine'></div>
        <div className='' style={{
          height: height,
          // background: 'red'
        }}>
          <div style={{
            height: '15%',
            width: '100%',
            // background: 'pink',
            padding: '10px',
            boxSizing: 'border-box',
            display: 'flex',
            flexDirection: 'column',
            justifyContent: 'space-between',
          }}>
            <div className='editTwoTitle'>选择推荐方案</div>
            <div style={{
              display: 'flex',
              alignItems: 'center',
            }}>
              <Select
                allowClear
                style={{ width: '183px', fontSize: '16px' }}
                onChange={(value: string) => {
                  console.log(`selected ${value}`);
                  // alert(`selected ${value}`)
                  // lyp



                }}
                options={[
                  // { value: '', label: '全部类型' },
                  { value: '1', label: '领域1' },
                  { value: '2', label: '领域2' },
                  { value: '3', label: '领域3' },
                  { value: '4', label: '领域4' },
                  { value: '5', label: '领域5' }
                ]}
                placeholder="请选择领域"
              // defaultValue=""
              />
              <Button type="primary" style={{
                marginLeft: '10px',
              }}>
                确认添加
              </Button>
              <div style={{
                color: '#5a5a5a',
                marginLeft: '10px'
              }}>
                {/* 常用商标类别: */}
              </div>

            </div>

          </div>
          <div style={{
            height: '85%',
            width: '100%',
            // background: 'skyblue',
            display: 'flex',
          }}>
            <div className='editTwoBotL' >
              <div className='editTwoBTopSearch'>
                <Search placeholder="请输入关键字" onSearch={onSearch} value={keyWords} onChange={(e) => {
                  setKeyWords(e.target.value)
                  if (e.target.value == '') {
                    setSearchKeyWords('');
                    // setFilteredCategories(trademarkCategories);
                    // setExpandedIds([]); // 清空展开状态
                    // console.log(trademarkCategories);
                    // setFilteredCategories(trademarkCategories); 
                    // getTrademarkTypeList()
                    setExpandedIds(checkedIds)
                    // initialExpandedIds
                    console.log(checkedIds);

                  }
                }} style={{ width: '85%' }} />
                <Button style={{
                  width: '13%'
                }} onClick={() => {
                  setKeyWords('');
                  setSearchKeyWords('');
                  // setFilteredCategories(trademarkCategories);
                  // getTrademarkTypeList()
                  setExpandedIds(checkedIds)

                  // setExpandedIds(checkedIds)
                  // setExpandedIds([]); // 清空展开状态
                }} icon={<SyncOutlined />}></Button>
              </div>
              <div className='editTwoBTopTitle'>类目索引</div>
              <div className='editTwoBTopText editTwoBTopTextL'>

                <TreeMenu
                  trademarkCategories={filteredCategories}
                  expandedIds={expandedIds}

                  checkedIds={checkedIds}

                  handleExpandClick={handleExpandClick}
                  handleSmallMenuClick={handleSmallMenuClick}

                ></TreeMenu>
              </div>
            </div>
            <div className='editTwoBotR'>
              <div className='editTwoBTopTitle' style={{
                display: 'flex',
              }}>
                <div style={{
                  textWrap: 'nowrap',
                }}>已选得商标类别 ：</div>
                <div style={{
                  width: '100%',
                  display: selectedCategories.length > 0 ? 'unset' : 'none'
                }}>
                  <div style={{
                    // background: 'skyblue',
                    width: '100%',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    paddingRight: 10,
                    boxSizing: 'border-box',
                  }}>
                    <div>
                      {(() => {
                        let middleCategoryCount = 0;
                        let smallCategoryCount = 0;

                        // 遍历 selectedCategories 计算中类和小类的数量
                        selectedCategories.forEach(category => {
                          middleCategoryCount += category.children.length;
                          category.children.forEach(middleCategory => {
                            smallCategoryCount += middleCategory.children.length;
                          });
                        });

                        return `共${selectedCategories.length}大类 累计${middleCategoryCount}个小类/${smallCategoryCount}项商品服务`;
                      })()}
                    </div>
                    <div style={{
                      fontSize: 14,
                    }}>
                      <a style={{
                        cursor: 'pointer',
                      }}
                        onClick={() => {
                          setSelectedCategories([]);
                          setCheckedIds([]);
                          setExpandedIds([]);
                        }}
                      >清空</a>
                      <a style={{
                        marginLeft: 10,
                        cursor: 'pointer',
                      }}
                        onClick={() => {
                          console.log('selectedCategories', selectedCategories);

                        }}
                      >保存为常用</a>
                    </div>

                  </div>
                </div>
                <span style={{
                  display: selectedCategories.length == 0 ? 'unset' : 'none'
                }}>
                  无
                </span>

              </div>

              <div className='editTwoBTopText editTwoBTopTextR'>

                {/* {Array.from({ length: 100 }).map((item, index) => (
                <div key={index} className='editTwoBTopTextItem'>
                  11111
                </div>
              ))} */}
                <div className='editTwoGoodsBox' style={{
                  border: selectedCategories.length > 0 ? '1px solid #e9e9e9' : 'none',
                }}>
                  {selectedCategories.map((item: any) => {
                    const totalCount = item.children.reduce((acc: any, child: any) => acc + child.children.length, 0);
                    return (
                      <div key={item.id} style={{
                        // marginBottom: 20
                      }}>
                        <div
                          className='editTwoGoodsBoxItem'
                        >
                          <div style={{
                            display: 'flex',
                          }}>

                            <div>
                              {item.name}
                            </div>
                            <div>(共{totalCount}项 , 10项以上每项附加收费31.8元)</div>
                          </div>
                          <div style={{
                            paddingRight: 10,
                            boxSizing: 'border-box',
                            color: 'red'
                          }}>
                            ￥{formatNumber(31.8 * totalCount <= 318 ? 318 : 31.8 * totalCount)}

                            <span onClick={() => {
                              // 调用删除中类的函数
                              handleDeleteCategory(item.id);
                            }}
                              style={{
                                marginLeft: 10,
                                cursor: 'pointer',
                                color: 'rgb(116, 116, 116)'
                              }}><DeleteOutlined /></span>
                          </div>
                        </div>
                        <div className='editTwoGoodsBoxChildItem'>
                          {item.children.map((child: any) => {
                            return (
                              <div style={{

                              }} key={child.id}>
                                <div style={{
                                  display: 'flex',
                                  // flexWrap: 'wrap',
                                  textWrap: 'nowrap',
                                }}>
                                  <div style={{
                                    marginRight: 10,
                                  }}>{child.name} : </div>
                                  <div style={{
                                    display: 'flex',
                                    flexWrap: 'wrap',
                                  }}>
                                    {child.children.map((children: any) => {
                                      return (
                                        <div
                                          style={{
                                            padding: '2px 10px',
                                            // background: '#E6E6E6',
                                            border: '1px solid #E6E6E6',
                                            borderRadius: '5px',
                                            marginRight: 10,
                                            marginBottom: 10,
                                          }}
                                          key={children.id}>
                                          {children.code}-{children.name}  <span
                                            onClick={() => {
                                              handleDeleteSmallCategory(item.id, child.id, children.id);
                                            }}
                                            style={{
                                              marginLeft: 10,
                                              cursor: 'pointer',
                                            }}><CloseOutlined /></span>
                                        </div>
                                      )
                                    })}
                                  </div>
                                </div>
                              </div>
                            )
                          })}</div>
                      </div>

                    )
                  })}
                </div>
                <div style={{
                  display: selectedCategories.length <= 0 ? 'unset' : 'none'
                }}>
                  <div className='editTwoGoodsBox' style={{
                    // background: 'pink',
                    width: '100%',
                    height: '100%',

                  }}>
                    <div style={{
                      width: '100%',
                      height: '100%',
                      display: 'flex',
                      justifyContent: 'center',
                      alignItems: 'center',
                    }}>
                      <div>
                        <div style={{
                          fontSize: 16,
                          color: 'rgb(135, 135, 135)'
                        }}>点击左侧类目列表选择商标类别群组或使用推荐方案</div>
                        <div style={{
                          color: 'red'
                        }}>特别提醒:若申请主体执照经营范围含有“商标代理”、“专利代理”、“知识产权服务“等</div>
                        <div style={{
                          color: 'red'
                        }}>只可注册<span style={{
                          color: '#1677ff'
                        }}> 4506 </span> 下的商品服务项目，否则将被商标局不予受理或驳回，请知悉。</div>
                      </div>
                    </div>

                  </div>
                </div>
              </div>
            </div>

          </div>



        </div>
        <div className='topLine'></div>
        <div style={{
          marginTop: '8px',
          display: 'flex',
          justifyContent: 'flex-end',
        }}>
          <Button
            style={{
              width: '100px',
              height: '40px',
              borderRadius: '5px',
            }}
            onClick={() => {
              props.setEditProcess(1)
            }}
          >上一步</Button>
          <Button
            type='primary'
            style={{
              width: '100px',
              height: '40px',
              borderRadius: '5px',
              marginLeft: '10px',
            }}
            onClick={() => {
              handleSubmit()

            }}
          >下一步</Button>
        </div>
      </div>
    </Spin>
  )
}
