import { useState } from "react";
import PageCustom from "@/components/page-custom/index";
import NavBarNormal from "@/components/NavBarNormal/index";
import AvatarConfirm from '@/components/AvatarConfirm/index'

import Taro, { nextTick } from "@tarojs/taro";

import { TAvatarItem } from "@/service/storage";
import { useAgentStore, useAgentStoreActions } from "@/store/agentStore";
interface IProps {
  avatarItem?: TAvatarItem
}

export default function Index({ avatarItem }: IProps) {
  // 可以由父组件传入或从 agentStore 中获取
  const currentEditAvatar = avatarItem ?? useAgentStore(state => state.currentEditAvatar)
  const agentEdit = useAgentStore(state => state.agentEdit)
  const { updateEditAgent, saveAgent } = useAgentStoreActions()
  const currentItem = { ...(currentEditAvatar || {}) }
  const [enabledChatBg, setEnabledChatBg] = useState(agentEdit?.enabledChatBg ?? false)

  const handleConfirm = async (edit: TAvatarItem & { enabledChatBg: boolean }) => {
    console.log('confirm')
    console.log(edit, 2222)
    if (edit.avatarLogo && edit.avatarUrl) {
      updateEditAgent({...edit})
      // 如果是编辑，直接编辑形象成功
      if(agentEdit?.agentId){
        nextTick(()=> {
          saveAgent()
          Taro.showToast({title: '形象设置成功', icon: 'success'})
          setTimeout(()=> {
            Taro.navigateBack({delta:2})
          }, 2000)
        })
        return
      }
      // 如果是新建智能体，只是暂时设置并不更新至服务器
      Taro.showToast({title: '形象设置成功', icon: 'success'})
      setTimeout(()=> {
        Taro.navigateBack({delta:2})
      }, 2000)
    }

  }
  const handleChange = () => {
    Taro.navigateBack()
  }

  const handleCropDone = (url: string) => {
    console.log('handleCropDone', url)
    if (currentItem?.avatarLogo) {
      currentItem.avatarLogo = url
    }
  }


  return (
    <PageCustom>
      <NavBarNormal>形象确认</NavBarNormal>
      <>
        {!!currentEditAvatar && <AvatarConfirm
          avatarItem={currentEditAvatar}
          enabledChatBg={enabledChatBg}
          setEnabledChatBg={setEnabledChatBg}
          onCropDone={handleCropDone}
          onChange={handleChange}
          onConfirm={handleConfirm} />}
      </>
    </PageCustom>
  );
}
