import { create } from "zustand";
import { bluebookAiAgent } from "@/xiaolanbenlib/api/index";
import request from "@/xiaolanbenlib/module/axios.js";

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;
  agentProfile: TAgentDetail | null;
  agentContactCard: TAgentContactCard | null;
  agentProfileContactCard: TAgentContactCard | null;
  agentCharacter: TEditAgentCharacter | null;
  ents: {entName: string, entId: string|number}[]
  fetchAgents: () => Promise<TAgent[]>;
  // 请求智能体数据登录状态
  fetchAgent: (agentId: string) => Promise<TAgentDetail | null>;
  // 请求智能体数据非登录状态
  fetchAgentProfile: (agentId: string) => Promise<TAgentDetail | null>;
  createAgent: () => Promise<TAgentDetail | null>;
  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>
}

export const useAgentStore = create<AgentStoreState>((set, get) => ({
  agents: [],
  agent: null,
  agentProfile: null,
  agentContactCard: null,
  defaultAgent: null,
  agentProfileContactCard: null,
  agentCharacter: null,
  ents: [],
  fetchAgents: async () => {
    const response = await getAgents();
    if (response && response?.data?.length) {
      const defaultAgent = response.data.find( item => item.isDefault)
      set({ agents: response.data, defaultAgent });
      return response.data;
    }

    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;
    }
    return null;
  },
  fetchAgentProfile: async (agentId: string, shareKey?:string) => {
    // 如果自己的智能体列表中有 对应的 agentId，则请求自己的 agent, 否则请求无需登录的 getAgent 接口
    const response = await _getAgent(agentId, shareKey);
    const result = isSuccess(response.status)
    if (result && response.data) {
      const agent = response.data;
      set({
        agentProfile: response.data,
        agentProfileContactCard: {
          address: agent.address ?? "",
          email: agent.email ?? "",
          entName: agent.entName ?? "",
          mobile: agent.mobile ?? "",
          name: agent.name ?? "",
          position: agent.position ?? "",
          qrCodeUrl: agent.qrCodeUrl ?? "",
        },
      });

      return response.data;
    }
    return 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();
    if (response.data) {
      const a: TAgent = {
        agentId: response.data.agentId ?? "",
        isDefault: response.data.isDefault ?? false,
        isEnt: response.data.isEnt ?? false,
        isNewEnt: response.data.isNewEnt ?? false,
        name: response.data.name ?? "",
        enabledChatBg: false,
      }
      set((state) => {
        return {
          agents: [
            ...state.agents,
            a,
          ],
          defaultAgent: a,
        };
      });
      return response.data;
    }
    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)){
      set((state) => {
        const agents = state.agents.filter((item: TAgent) => item.agentId !== agentId)
        return {
          agents: [...agents]
        }
      })
      const agents =await get().fetchAgents()
      if(agents.length <= 0){
        Taro.reLaunch({url: '/pages/index/index'})
        return;
      }
      const defaultAgent = agents.find((item)=> !!item.isDefault)
      if(defaultAgent){
        await get().fetchAgent(defaultAgent.agentId)
      }   
    }
  }
}));
