import { create } from "zustand";
import {
  getAgents,
  getMyAgent as _getMyAgent,
  getAgent as _getAgent,
  setDefaultAgent as _setDefaultAgent,
  deleteAgent as _deleteAgent,
  editAgentCard as _editAgentCard,
  editAgentCharacter as _editAgentCharacter,
  editAgentWebsite as _editAgentWebsite,
  createNewAgent,
  editAgent as _editAgent,
  getNewAgentInfo,
} from "@/service/agent";
import {
  TAgentDetail,
  TAgent,
  TAgentContactCard,
  TEditAgentCharacter,
  TComponentItem,
  TAgentRequiredData,
} from "@/types/agent";
import { isSuccess } from "@/utils";
import Taro from "@tarojs/taro";
import { TAvatarItem } from "@/service/storage";

export interface AgentStoreState {
  agents: TAgent[];
  agent: Partial<TAgentDetail> | null;
  agentEdit: Partial<TAgentDetail> | null;
  defaultAgent: Partial<TAgentDetail> | TAgent | null;
  currentEditAvatar: TAvatarItem | null;
  // 无需登录查看 agent 信息
  agentProfile: TAgentDetail | null;
  agentContactCard: TAgentContactCard | null;// deprecated
  agentCharacter: TEditAgentCharacter | null;// deprecated
  ents: { entName: string; entId: string | number }[];
  actions: {
    fetchAgents: () => Promise<TAgent[]>;
    // 请求智能体数据登录状态
    fetchAgent: (agentId: string) => Promise<Partial<TAgentDetail> | null>;
    fetchDefaultNewAgentInfo: () => Promise<Partial<TAgentDetail> | null>;
    // 请求智能体数据非登录状态
    fetchAgentProfile: (
      agentId: string,
      shareKey?: string
    ) => Promise<TAgentDetail | null>;
    clearProfileAgent: () => void;
    setDefaultAgent: (agentId: string) => Promise<Partial<TAgentDetail> | null>;
    editAgentCharacter: (
      agentId: string,
      data: TEditAgentCharacter
    ) => Promise<boolean>;
    editAgentCard: (agentId: string, data: TAgentContactCard) => Promise<boolean>;
    editAgentWebsite: (
      agentId: string,
      data: TComponentItem[]
    ) => Promise<boolean>;
    deleteAgent: (agentId: string) => Promise<void>;
    updateEditAgent: (updates: Partial<TAgentDetail>) => void;
    saveAgent: (agentFields?: Partial<TAgentDetail>) => Promise<Partial<TAgentDetail> | null>;
    createAgent: (agentFields?: Partial<TAgentDetail>) => Promise<Partial<TAgentDetail> | null>;
    resetData: () => void;
    clearEditAgent: () => void;
    setCurrentEditAvatar: (avatar: TAvatarItem | null) => void;
  };
}

export const useAgentStore = create<AgentStoreState>((set, get) => ({
  agents: [],
  agent: null,
  // agentEdit 编辑时临时存储的智能体信息, 如果直接用 agent 存储，则切页面时会有空白数据的瞬间
  agentEdit: null,
  agentProfile: null,
  agentContactCard: null,
  defaultAgent: null,
  agentCharacter: null,
  ents: [],
  currentEditAvatar: null,
  actions: {
    resetData: () => {
      set({
        agents: [],
        agent: null,
        agentProfile: null,
        agentContactCard: null,
        defaultAgent: null,
        agentCharacter: null,
        ents: [],
      });
    },
    fetchAgents: async () => {
      const response = await getAgents();
      const agentsData = response?.data;
      // const agentsData = response?.data?.filter(item => !item.isEnt)
      if (isSuccess(response.status) && agentsData.length) {
        const defaultAgent = agentsData.find((item) => item.isDefault);
        set({ agents: agentsData, defaultAgent });
        return agentsData;
      }
      set({ agents: [], defaultAgent: null });
      return [];
    },
    fetchAgent: async (agentId: string) => {
      const response = await _getMyAgent(agentId);
      const result = isSuccess(response.status);
      if (result && response.data) {
        const agent = response.data;
        set({
          agent: agent,
          agentEdit: agent,
        });

        return response.data;
      }
      set({
        agent: null,
      });
      return null;
    },
    // 请求无需登录的 getAgent 接口
    fetchAgentProfile: async (agentId: string, shareKey?: string) => {
      if (shareKey) {
        shareKey = decodeURIComponent(shareKey);
      }
      const response = await _getAgent(agentId, shareKey);
      const result = isSuccess(response.status);
      const agent = response.data;
      if (result && agent) {
        agent.components = (agent.components ?? []).filter(
          (item) => item.enabled
        );
        set({
          agentProfile: agent,
        });
        return agent;
      }
      return null;
    },
    clearProfileAgent: () => {
      set({
        agentProfile: null,
      });
    },
    setDefaultAgent: async (agentId: string) => {
      const response = await _setDefaultAgent(agentId);
      const result = isSuccess(response.status);
      if (result) {
        const agent = await get().actions.fetchAgent(agentId);
        set({
          defaultAgent: agent,
        });
        return agent;
      }
      return null;
    },
    saveAgent: async (agentFields = {}) => {
      const { agentEdit } = get();

      // 如果当前agent有agentId，则执行编辑操作
      if (agentEdit?.agentId) {
        // 处理null值转换为undefined以符合TAgentRequiredData类型
        const mixedAgent = {
          ...agentEdit,
          ...agentFields,
        };
        console.log(mixedAgent,3333333)
        const cleanAgent = {
          ...mixedAgent,
          address: mixedAgent.address ?? undefined,
          email: mixedAgent.email ?? undefined,
          entName: mixedAgent.entName ?? undefined,
          mobile: mixedAgent.mobile ?? undefined,
          name: mixedAgent.name ?? undefined,
          position: mixedAgent.position ?? undefined,
          qrCodeUrl: mixedAgent.qrCodeUrl ?? undefined,
          avatarUrl: mixedAgent.avatarUrl ?? undefined,
          avatarLogo: mixedAgent.avatarLogo ?? undefined,
          entId: mixedAgent.entId ? Number(mixedAgent.entId) : undefined,
        };

        const updateData: TAgentRequiredData = {
          ...cleanAgent,
          agentId: agentEdit.agentId,
        };

        const response = await _editAgent(updateData);
        const result = isSuccess(response.status);

        if (result) {
          // 重新获取 agent 详情
          const response = await get().actions.fetchAgent(updateData.agentId)
          // 重新获取agents列表以更新缓存
          await get().actions.fetchAgents();
          return response;
        }
        return null;
      }
      return null
    },
    createAgent: async (agentFields = {}) => {
      const { agentEdit } = get();
      if (!agentEdit) {
        return null;
      }
      const mixedAgent = {
        ...agentFields,
        ...agentEdit,
      }

      const createData: Omit<TAgentRequiredData, 'agentId'> = {
        address: mixedAgent.address ?? undefined,
        avatarLogo: mixedAgent.avatarLogo ?? undefined,
        avatarUrl: mixedAgent.avatarUrl ?? undefined,
        email: mixedAgent.email ?? undefined,
        enabledChatBg: mixedAgent.enabledChatBg ?? false,
        enabledPersonalKb: mixedAgent.enabledPersonalKb ?? true,
        entId: mixedAgent.entId ? Number(mixedAgent.entId) : undefined,
        entName: mixedAgent.entName ?? undefined,
        greeting: mixedAgent.greeting ?? undefined,
        mobile: mixedAgent.mobile ?? undefined,
        name: mixedAgent.name ?? undefined,
        personality: mixedAgent.personality ?? undefined,
        position: mixedAgent.position ?? undefined,
        qrCodeUrl: mixedAgent.qrCodeUrl ?? undefined,
        questionGuides: mixedAgent.questionGuides ?? undefined,
        voiceId: mixedAgent.voiceId ?? undefined,
        voiceName: mixedAgent.voiceName ?? undefined,
      };

      const response = await createNewAgent(createData);
      const result = isSuccess(response.status);

      if (result) {
        // 创建成功后立即设置为当前默认智能体
        const newAgent = await get().actions.setDefaultAgent(response.data.agentId);
        if (newAgent) {
          set((state) => ({
            agents: [...state.agents, newAgent as TAgent],
            agent: newAgent,
            agentEdit: newAgent, // 创建成功后，将新智能体数据回填至 agentEdit
          }));
          return newAgent;
        }
      }
      return null;
    },
    // 更新 agent 字段
    updateEditAgent: async (updates: Partial<TAgentDetail>) => {
      set((state) => ({
        agentEdit: {
          ...state.agentEdit,
          ...updates,
        },
      }));
    },
    // 编辑声音，人设，开场白，问题引导，知识库
    // deprecated
    editAgentCharacter: async (agentId: string, data: TEditAgentCharacter) => {
      const response = await _editAgentCharacter(agentId, data);
      console.log(response.data);
      const result = isSuccess(response.status);
      //@ts-ignore
      set((state) => {
        return {
          agent: {
            ...state.agent,
            voiceId: data.voiceId,
          },
        };
      });
      return result;
    },
    // deprecated
    editAgentCard: async (agentId: string, data: TAgentContactCard) => {
      console.log(agentId, data);
      const response = await _editAgentCard(agentId, data);
      console.log(response);
      const result = isSuccess(response.status);

      return result;
    },
    editAgentWebsite: async (agentId: string, data: TComponentItem[]) => {
      console.log(agentId, data);
      const response = await _editAgentWebsite(agentId, { components: data });
      console.log(response);
      const result = isSuccess(response.status);

      return result;
    },

    deleteAgent: async (agentId: string) => {
      const response = await _deleteAgent(agentId);
      if (isSuccess(response.status)) {
        const de = get()
          .agents.filter((item: TAgent) => item.agentId !== agentId)
          .reverse()[0];
        console.log(agentId, de, "setDefault");
        // 默认设置自创的智能体
        if (de) {
          await get().actions.setDefaultAgent(de.agentId);
        }

        // 重新拉取智能体列表
        const restAgents = await get().actions.fetchAgents();
        if (restAgents.length <= 0) {
          set({ agent: null, defaultAgent: null });
          Taro.reLaunch({ url: "/pages/index/index" });
          return;
        }

        const defaultAgent = restAgents.find((item) => !!item.isDefault);
        if (defaultAgent) {
          await get().actions.fetchAgent(defaultAgent.agentId);
        }
      }
    },
    setCurrentEditAvatar: (avatarItem) => {
      set({
        currentEditAvatar: avatarItem,
      });
    },
    clearAgent: () => {
      set({
        agent: null,
      });
    },
    fetchDefaultNewAgentInfo: async () => {
      const response = await getNewAgentInfo()
      if (isSuccess(response.status)) {
        // set({
        //   agentEdit: response.data,
        // });
      }
      return response.data
    },
    clearEditAgent: async () => {
      set({
        agentEdit: null,
      });
    },
  }
}));

export const useAgentStoreActions = () => {
  const actions = useAgentStore((state) => state.actions);
  return actions;
};
