import React, { useState } from "react";
import Taro, { nextTick } from "@tarojs/taro";
import { TAvatarItem } from "@/service/storage";
import AvatarConfirm from '@/components/AvatarConfirm/index'
import { useAgentStore, useAgentStoreActions } from "@/store/agentStore";
interface IProps {
  prev: ()=>void
  pickedAvatar: TAvatarItem
}
export default React.memo(function Index({prev, pickedAvatar}:IProps) {
  const currentItem = { ...(pickedAvatar || {}) }
  const agentEdit = useAgentStore((state) => state.agentEdit);
  const { saveAgent, updateEditAgent} = useAgentStoreActions();
  const [enabledChatBg, setEnabledChatBg] = useState(true)

  const handleConfirm = async (edit: TAvatarItem & { enabledChatBg: boolean }) => {
    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 = () => {
    prev()
  }

  const handleCropDone = (url: string) => {
    console.log('handleCropDone', url)
    if(url){
      currentItem.avatarLogo = url
      updateEditAgent({avatarLogo: url})
    }
  }
  return (
    <>
    {!!currentItem && <AvatarConfirm
      avatarItem={currentItem}
      enabledChatBg={enabledChatBg}
      setEnabledChatBg={setEnabledChatBg}
      onCropDone={handleCropDone}
      onChange={handleChange}
      onConfirm={handleConfirm} />}
  </>
  )
});
