import { Image, View } from "@tarojs/components";
import Popup from "@/components/popup/popup";
import style from "./index.module.less";
import QrcodeUploadTips from "@/components/qrcode-upload-tips";
import { useAgentStore, useAgentStoreActions } from "@/store/agentStore";
import { pickAndUploadImageWithCrop } from "@/utils/upload";
import Taro from "@tarojs/taro";
import { TAgentDetail } from "@/types/agent";

interface IProps {
  show: boolean;
  setShow: (show: boolean) => void;
  isVisitor?: boolean
  agent: TAgentDetail
}
export default ({ show, setShow, agent, isVisitor }: IProps) => {
  const { saveAgent, updateEditAgent } = useAgentStoreActions();
  const agentEdit = useAgentStore((state) => state.agentEdit);
  const isMine = (!isVisitor)
  // 如果是自己的，则直接使用编辑的，如果是访问别人的则用 agent 内存储的信息`
  const currentAgent = isMine ? agentEdit : agent

  const handleClick = async () => {
    Taro.showLoading();
    try{
      const result = await pickAndUploadImageWithCrop(["album"]);
      Taro.hideLoading()
      if (!result?.url) {
        return;
      }
      updateEditAgent({'qrCodeUrl': result.url})
      saveAgent({'qrCodeUrl': result.url})

    }catch(e:any){
      Taro.hideLoading()
    }
  };

  const handleClear = () => {
    updateEditAgent({'qrCodeUrl': ''})
    saveAgent({'qrCodeUrl': ''})
  }

  const renderQrcode = () => {
    if (currentAgent?.qrCodeUrl) {
      return <Image src={currentAgent?.qrCodeUrl} showMenuByLongpress mode="widthFix" style={{width: '206px', height: '206px'}}></Image>;
    }

    if(isMine){
      return (
        <View onClick={handleClick}>
          <QrcodeUploadTips />
        </View>
      );
    }
    return <></>;
  };

  return (
    <View className="relative">
      <Popup setShow={setShow} show={show} title="二维码">
        <View className="text-14 text-gray-4 leading-24 pt-16 pb-24">方便客户快速沟通，扫码即可联系你</View>
        <View className={style.container}>
          <View className={style.card}>
            {renderQrcode()}
          </View>

          {isMine && currentAgent?.qrCodeUrl && <View className='flex items-center text-12 font-pingfangSCMedium font-medium gap-16 pt-24'>
            <View className="text-primary" onClick={handleClick}>替换</View>
            <View className="text-gray-3">|</View>
            <View className="text-primary" onClick={handleClear}>清空</View>
          </View>}
        </View>
      </Popup>
    </View>
  );
};
