import { View } from "@tarojs/components";
import NavBarNormal from "@/components/NavBarNormal/index";
import PageCustom from "@/components/page-custom/index";
import style from "./index.module.less";
import CompItem, { CompType } from "./components/comp-item/compItem";
import Taro from "@tarojs/taro";

import { useComponentStore } from "@/store/componentStore";
import { generateRandomId } from "@/utils/index";

import CardList from "@/components/list/card-list";
import CardListItem from "@/components/list/card-list-item";
import { useState } from "react";
import { EComponentType } from "@/consts/enum";
import { TComponentItem } from "@/types/agent";
import { createComponentData } from "./components/createComponentData";
import { useAgentStore, useAgentStoreActions } from "@/store/agentStore";

type TWidget = {
  type: EComponentType;
  typeStyle: string;
  num: number;
  text: string;
};
export default () => {
  const { loading, insertComponent, setLoading } = useComponentStore();
  const agent = useAgentStore((state) => state.agent);
  const { editAgentWebsite, fetchAgent } = useAgentStoreActions();

  const [commonWidget, setCommonWidget] = useState<TWidget[]>([
    {
      type: EComponentType.title,
      typeStyle: CompType.title,
      num: 0,
      text: "章节标题",
    },
    {
      type: EComponentType.text,
      typeStyle: CompType.text,
      num: 0,
      text: "文本内容",
    },
    {
      type: EComponentType.link,
      typeStyle: CompType.link,
      num: 0,
      text: "链接",
    },
    {
      type: EComponentType.media,
      typeStyle: CompType.image,
      num: 0,
      text: "图片/视频",
    },
    { type: EComponentType.tel, typeStyle: CompType.tel, num: 0, text: "电话" },
    {
      type: EComponentType.address,
      typeStyle: CompType.local,
      num: 0,
      text: "地图",
    },
    {
      type: EComponentType.bluebook,
      typeStyle: CompType.bluebook,
      num: 0,
      text: "智能体",
    },
  ]);

  const [wechatWidget, setWechatWidget] = useState<TWidget[]>([
    {
      type: EComponentType.wechatArticle,
      typeStyle: CompType.wechat,
      num: 0,
      text: "微信公众号文章",
    },
    {
      type: EComponentType.shiping,
      typeStyle: CompType.shiping,
      num: 0,
      text: "视频号",
    },
    {
      type: EComponentType.miniProgram,
      typeStyle: CompType.miniProgram,
      num: 0,
      text: "小程序",
    },
    {
      type: EComponentType.shipingVideo,
      typeStyle: CompType.shipingVideo,
      num: 0,
      text: "视频号视频",
    },
  ]);

  const handleChange = (num: number, type: string) => {
    console.log(num, type);
    setCommonWidget((prevArr) =>
      prevArr.map((item) => (item.type === type ? { ...item, num } : item))
    );
  };
  const handleWechatWidgeChange = (num: number, type: string) => {
    console.log(num, type);
    setWechatWidget((prevArr) =>
      prevArr.map((item) => (item.type === type ? { ...item, num } : item))
    );
  };

  const getComponents = (widgets: TWidget[]) => {
    let list = widgets
      .filter((w) => w.num > 0)
      .reduce((prev: EComponentType[], current) => {
        let arr: EComponentType[] = [];
        for (let i = 0; i < current.num; i++) {
          arr.push(current.type);
        }
        prev.push(...arr);
        return prev;
      }, []);

    const results = list.map((item) => {
      let data = createComponentData(item);
      if (data === null) {
        console.warn("没有对应的组件");
        return null;
      }
      data.id = generateRandomId();

      return {
        type: item,
        data,
        enabled: true,
      };
    });
    return results.filter((item) => !!item);
  };

  const handleSubmit = async () => {
    if (loading) {
      return;
    }
    const a = getComponents(commonWidget) as TComponentItem[];
    const b = getComponents(wechatWidget) as TComponentItem[];

    // 统一增加 index 值
    const results = [...a, ...b].map((item, index) => {
      item.data.index = index;
      return item;
    });
    console.log(results);
    if (!agent?.agentId) {
      return;
    }
    setLoading(true);
    const inserted = await insertComponent(results);
    setLoading(false);
    if (!inserted) {
      return;
    }
    console.log(inserted);
    const result = await editAgentWebsite(agent.agentId, inserted);
    if (result) {
      await fetchAgent(agent.agentId);
      Taro.navigateBack();
    }
  };

  return (
    <PageCustom>
      <NavBarNormal>添加组件</NavBarNormal>
      <View className='p-16 w-full'>
        <View className={style.compComtainer}>
          <View className={style.title}>通用组件</View>
          <CardList>
            {commonWidget.map((item) => {
              return (
                <CardListItem>
                  <View className="px-16 py-16">
                    <CompItem
                      num={item.num}
                      onChange={handleChange}
                      typeStyle={item.typeStyle}
                      type={item.type}
                    >
                      {item.text}
                    </CompItem>
                  </View>
                </CardListItem>
              );
            })}
          </CardList>
        </View>

        <View className={`${style.compComtainer} mb-130`}>
          <View className={style.title}>微信组件</View>
          <CardList>
            {wechatWidget.map((item) => {
              return (
                <CardListItem>
                  <View className="px-16 py-16">
                    <CompItem
                      num={item.num}
                      onChange={handleWechatWidgeChange}
                      typeStyle={item.typeStyle}
                      type={item.type}
                    >
                      {item.text}
                    </CompItem>
                  </View>
                </CardListItem>
              );
            })}
          </CardList>
        </View>

        <View className="bottom-bar">
          <View className="px-20 pt-12" onClick={handleSubmit}>
            <View className="button-rounded-big">添加组件</View>
          </View>
        </View>
      </View>
    </PageCustom>
  );
};
