import { hdHttp, HdResponse, BasicConstant, ExpertData, authStore } from '@itcast/basic'
import { BusinessError } from '@kit.BasicServicesKit';
import promptAction from '@ohos.promptAction';
import { router } from '@kit.ArkUI';

interface updateExtraData {
  uuid: string,
  userName: string,
  birthDate: string,
  type: string,
  photo: string,
  email: string,
  certificateImg: string,
  positionUuid: string,
  officeUuid: string,
  officeName: string,
  diseaseUuids: string
}

interface callBackData {
  expert:ExpertData,
  code:number,
  message:string,
  specialy:[],
  data:ExpertData,
  special:[]
}

@Component
export struct ChooseEmailComp {
  @State emailString: string = ''
  @State countdown: number = 0

  // 验证码倒计时
  private startCountdown() {
    this.countdown = 60
    const timer = setInterval(() => {
      if (this.countdown > 0) {
        this.countdown--
      } else {
        clearInterval(timer)
      }
    }, 1000)
  }

  commitEmailData(editEmail:string){
    const updateDataUrl:string = BasicConstant.urlExpert + 'modify';
    hdHttp.post<string>(updateDataUrl, {
      uuid: authStore.getUser().uuid,
      userName: authStore.getUser().userName,
      email: editEmail,
      type:'2'
    } as updateExtraData).then(async (res: HdResponse<string>) => {
      let json:callBackData = JSON.parse(res+'') as callBackData;
      if(json.code == 1 && json.data && typeof json.data === 'object') {
        authStore.updateUser(json.data)
        console.log('更新用户邮箱成功:', authStore.getUser().email);
        promptAction.showToast({message:'修改成功', duration: 1000})
        router.back();
      } else {
        console.error('更新用户邮箱失败：'+json.message)
        promptAction.showToast({ message: json.message, duration: 1000 })
      }
    }).catch((err: BusinessError) => {
      console.info(`更新用户邮箱请求失败: ${err}`);
    })
  }

  private validateEmailFormat(email: string): boolean {
    return EMAIL_REGEX.test(email.trim())
  }

  build() {
    Column() {
      // 手机号输入框
      Row() {
        TextInput({ placeholder: authStore.getUser().email.length>0?authStore.getUser().email:'请输入您的邮箱' })
          .fontSize(16)
          .contentType(ContentType.EMAIL_ADDRESS)
          .backgroundColor(Color.White)
          .onChange((value: string) => {
            this.emailString = value
          })
      }
      .margin({ top: 10 })
      .width('95%')
      .height(48)
      .borderRadius(4)
      .borderWidth(1)
      .borderColor('#CCCCCC')

      // 验证码输入区域
      Row() {
        Text('请填写您的真实邮箱，以便联系上您')
          .fontSize(15)
          .fontColor('#333333')
          .width('95%')
      }
      .margin({top:15})
      .width('95%')
      .justifyContent(FlexAlign.SpaceBetween)

      // 登录按钮
      Button({type:ButtonType.Normal}){
        Text('保 存')
      }
      .width('90%')
      .height(48)
      .borderRadius(8)
      .borderWidth(1)
      .borderColor('#8B2316')
      .backgroundColor(Color.White)
      .fontColor('#8B2316')
      .fontSize(18)
      .position({x:'5%',y:'80%'})
      .onClick(() => {
        // if (this.validateEmailFormat(this.emailString)) {
        //   promptAction.showToast({message:'请输入正确的邮箱格式'})
        //   return
        // }
        this.commitEmailData(this.emailString);
      })
    }
    .width('100%')
    .height('100%')
    .backgroundColor('#FFFFFF')
  }
}

// 邮箱正则表达式
const EMAIL_REGEX = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
