import NavBarNormal from "@/components/NavBarNormal/index";
import { View, Image, Text } from "@tarojs/components";
import PageCustom from "@/components/page-custom/index";
import WemetaInput from '@/components/wemeta-input/index'
import WemetaTextarea from '@/components/wemeta-textarea/index'
import Taro, { useRouter } from "@tarojs/taro";
import { useAgentStore, useAgentStoreActions } from "@/store/agentStore";
import IconPlusBig from "@/components/icon/icon-plus-big";
import { useState } from "react";
import BottomBar from "@/components/BottomBar";
import WemetaButton from "@/components/buttons/WemetaButton";
import style from './index.module.less'
import { pickAndUploadImageWithCrop } from "@/utils/upload";



export default function Index() {
  const router = useRouter();
  const agentEdit = useAgentStore((state) => state.agentEdit)
  const { updateEditAgent, saveAgent } = useAgentStoreActions()

  const [disabled, setDisabled] = useState(false)
  const handleSave = ()=>{
    console.log(agentEdit,111)
    if(agentEdit?.agentId){
      saveAgent()
    }
    Taro.navigateBack();
  }

  const handleFieldChange = (field: string, value: string) => {
    // 如果是手机号字段，只允许数字且限制11位
    if (field === 'mobile') {
      value = value.replace(/\D/g, '').slice(0, 11);
    }
    console.log(field, value)
    updateEditAgent({ [field]: value });
  };
  const handleChooseAddress = () => {
    Taro.chooseLocation({
      success: (res) => {
        console.log(res)
        handleFieldChange('address', res.address)
      },
    })
  };

  const handleUpload = async () => {
    Taro.showLoading();
    try{
      const result = await pickAndUploadImageWithCrop(["album"]);

      Taro.hideLoading();
      if (!result?.url) {
        return;
      }
      handleFieldChange('qrCodeUrl', result.url)
    }catch(e:any){
      Taro.hideLoading();
    }
  }

  const renderQrcode = () => {
    if(agentEdit?.qrCodeUrl){
      return <Image showMenuByLongpress className="w-full" src={agentEdit?.qrCodeUrl || ''} mode="widthFix"></Image>
    }

    return <View className="flex flex-col items-center justify-center" onClick={handleUpload}>
        <View className={style.icon}>
          <IconPlusBig></IconPlusBig>
        </View>
        <View className="pt-8 text-12 leading-22 text-primary">
          上传微信二维码
        </View>
    </View>
  }

  return (
    <PageCustom>
      <NavBarNormal backText="数字名片"></NavBarNormal>
      <View className="p-16 w-full pb-126">
        <View className="flex flex-col gap-16 w-full">
          <View className="flex flex-col gap-6">
            <View className={style.label}>姓名 <Text className="text-red leading-22 text-14">*</Text> </View>
            <View className={style.value}>
              <WemetaInput
                value={agentEdit?.name || ''}
                onBlur={(value) => handleFieldChange('name', value)}
                onInput={(value) => handleFieldChange('name', value)}
                placeholderStyle="color: rgba(17,17,17,.25)"
                placeholder="输入姓名"
                maxlength={40}
              />
            </View>
          </View>
          <View className="flex flex-col gap-6">
            <View className={style.label}>职位</View>
            <View className={style.value}>
              <WemetaInput
                value={agentEdit?.position || ''}
                onBlur={(value) => handleFieldChange('position', value)}
                onInput={(value) => handleFieldChange('position', value)}
                placeholderStyle="color: rgba(17,17,17,.25)"
                placeholder="输入职位名称"
              />
            </View>
          </View>

          <View className="flex flex-col gap-6">
            <View className={style.label}>企业</View>
            <View className={style.value}>
              <WemetaInput
                value={agentEdit?.entName || ''}
                onBlur={(value) => handleFieldChange('entName', value)}
                onInput={(value) => handleFieldChange('entName', value)}
                placeholderStyle="color: rgba(17,17,17,.25)"
                placeholder="输入企业名称"
              />
            </View>
          </View>
          <View className="flex flex-col gap-6">
            <View className={style.label}>手机号</View>
            <View className={style.value}>
              <WemetaInput
                value={agentEdit?.mobile || ''}
                onBlur={(value) => handleFieldChange('mobile', value)}
                onInput={(value) => handleFieldChange('mobile', value)}
                placeholderStyle="color: rgba(17,17,17,.25)"
                placeholder="手机号"
              />
            </View>
          </View>
          <View className="flex flex-col gap-6">
            <View className={style.label}>联系邮箱</View>
            <View className={style.value}>
              <WemetaInput
                value={agentEdit?.email || ''}
                onBlur={(value) => handleFieldChange('email', value)}
                onInput={(value) => handleFieldChange('email', value)}
                placeholderStyle="color: rgba(17,17,17,.25)"
                placeholder="联系邮箱"
              />
            </View>
          </View>
          <View className="flex flex-col gap-6">

            <View className={style.label}>
              <View className="flex-1 font-pingfangSCMedium font-medium">地址</View>
              <View className="font-pingfangSCMedium font-medium text-primary" onClick={handleChooseAddress}>选择地址</View>
            </View>
            <View className={style.value}>
              <WemetaTextarea
                value={agentEdit?.address || ''}
                style={{ height: '46px' }}
                onBlur={(value) => handleFieldChange('address', value)}
                onInput={(value) => handleFieldChange('address', value)}
                placeholderStyle="color: rgba(17,17,17,.25)"
                placeholder="地址"
              />
            </View>
          </View>
          <View className="flex flex-col gap-6">
            <View className={style.label}>
              <View className="flex-1">二维码</View>
              {!!agentEdit?.qrCodeUrl?.length && <View className="flex items-center font-pingfangSCMedium font-medium text-primary gap-16">
                <View onClick={handleUpload}>替换</View>
                <View>|</View>
                <View onClick={() => handleFieldChange('qrCodeUrl', '')}>清空</View>
              </View>}
            </View>
            <View>
              <View className={style.qrcodeContainer}>
                {renderQrcode()}
              </View>
            </View>
          </View>
        </View>
      </View>

      <BottomBar>
        <WemetaButton disabled={disabled} className="flex-1" onClick={handleSave}>保存</WemetaButton>
      </BottomBar>
    </PageCustom>
  );
}
