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

export interface AgentStoreState {
  agents: TAgent[];
  agent: TAgentDetail | null;
  defaultAgent: TAgentDetail | TAgent | null;
  // 无需登录查看 agent 信息
  agentProfile: TAgentDetail | null;
  agentContactCard: TAgentContactCard | null;
  agentCharacter: TEditAgentCharacter | null;
  ents: { entName: string; entId: string | number }[];
  fetchAgents: () => Promise<TAgent[]>;
  // 请求智能体数据登录状态
  fetchAgent: (agentId: string) => Promise<TAgentDetail | null>;
  // 请求智能体数据非登录状态
  fetchAgentProfile: (
    agentId: string,
    shareKey?: string
  ) => Promise<TAgentDetail | null>;
  createAgent: () => Promise<TAgentDetail | null>;
  clearProfileAgent: () => void;
  setDefaultAgent: (agentId: string) => Promise<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>;
  resetData: () => void;
}

export const useAgentStore = create<AgentStoreState>((set, get) => ({
  agents: [],
  agent: null,
  agentProfile: null,
  agentContactCard: null,
  defaultAgent: null,
  agentCharacter: null,
  ents: [],
  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: response.data,
        agentContactCard: {
          address: agent.address ?? "",
          email: agent.email ?? "",
          entName: agent.entName ?? "",
          mobile: agent.mobile ?? "",
          name: agent.name ?? "",
          position: agent.position ?? "",
          qrCodeUrl: agent.qrCodeUrl ?? "",
        },
        agentCharacter: {
          enabledPersonalKb: agent.enabledPersonalKb ?? false,
          greeting: agent.greeting ?? `你好，我是${agent.name}`,
          personality: agent.personality ?? "",
          questionGuides: agent.questionGuides ?? [],
          voiceId: agent.voiceId ?? "",
        },
      });

      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().fetchAgent(agentId);
      set({
        defaultAgent: agent,
      });
      return agent;
    }
    return null;
  },
  // 创建并设置其为默认智能体
  createAgent: async () => {
    const response = await _createAgent();
    const agentDetail = response.data;
    if (agentDetail?.agentId) {
      // 创建新智能体，自动设置为默认智能体
      await get().setDefaultAgent(agentDetail.agentId);

      const a: TAgent = {
        agentId: agentDetail.agentId ?? "",
        isDefault: true,
        isEnt: agentDetail.isEnt ?? false,
        isNewEnt: agentDetail.isNewEnt ?? false,
        name: agentDetail.name ?? "",
        enabledChatBg: false,
      };

      set((state) => {
        return {
          agents: [...state.agents, a],
          defaultAgent: a,
        };
      });
      return agentDetail;
    }
    return null;
  },
  // 编辑声音，人设，开场白，问题引导，知识库
  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;
  },
  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().setDefaultAgent(de.agentId);
      }

      // 重新拉取智能体列表
      const restAgents = await get().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().fetchAgent(defaultAgent.agentId);
      }
    }
  },
}));
