import {
  BasicType,
  IBestToast,
  ReqString,
  reviseImgHeaderBuilder,
  takePicture,
  Upload,
  userInfo,
  UserInfo,
  YTAvoid,
  YTButton,
  YTHeader,
  YTLog,
  YTRequest,
  yTRouter,
  yTToast,
  YTUserRequest,

} from 'basic'
import { LoginInput } from '../components/LoginInput'
import { CodeInputType} from '../models'

@Builder
function settingBuilder() {
  NavDestination() {
    SettingPage()
  }
  .hideTitleBar(true)
}

@Component
struct SettingPage {
  @StorageProp(YTAvoid.SAFE_TOP_KEY) safeTop: number = 0
  @StorageProp(YTAvoid.SAFE_BOTTOM_KEY) safeBottom: number = 0
  @StorageProp(UserInfo.KEY) userInfo: UserInfo = userInfo
  @State showReviseName: boolean = false
  @State showHeaderImgRevise: boolean = false
  @State value: string = ''

  @State phoneNumber: string = ''
  @State captcha: string = ''
  @State password: string = ''
  @State confirmPassword: string = ''
  @State time: number = 61
  private declare sa: number
  needCode: boolean = true
  @Prop isAgree:boolean = false
  @Prop isPassword: boolean = false
  //方便区分各个操作的uuid
  // @Prop userOperation: UserOperation = UserOperation.RESET_PASSWORD

  reviseBuilderArr: Array<BasicType<undefined>> = [
    {
      text: '头像修改',
      src: '',
      click: () => {
        this.showHeaderImgRevise = true
      }
    },
    {
      text: '昵称修改',
      click: () => {
        this.showReviseName = true
      }
    },
    {
      text:"密码设置",
      click:()=>{
        //跳转到密码设置界面
        this.isShowPassWordReSet=true

      }
    }
  ]
  options: BasicType<undefined>[] = [
    {
      text: '拍照',
      click: async () => {
        try {
          const fullpath = await takePicture(this.getUIContext().getHostContext()!)
          this.showHeaderImgRevise = false
          yTRouter.router2DelPhotoPage({ src: fullpath, type: 'header' })
        } catch (e) {
          YTLog.warn(e)
        }
      }
    },
    {
      text: '从相册中选择',
      click: () => {
        Upload.selectImage(this.getUIContext().getHostContext()!, (fullPath) => {
          this.showHeaderImgRevise = false
          yTRouter.router2DelPhotoPage({ src: fullPath, type: 'header' })
        })
      }
    },
    {
      text: '取消',
      click: () => {
        this.showHeaderImgRevise = false
      }
    },
  ]
  inputPhoneNumberType: CodeInputType = {
    txt: '+86',
    placeHolder: '请输入手机号码'
  }
  inputCaptchaType: CodeInputType = {
    txt: '验证码',
    placeHolder: '请输入验证码'
  }
  inputPasswordType: CodeInputType = {
    txt: '密码',
    placeHolder: '设置密码'
  }
  //确认
  inputConfirmPasswordType: CodeInputType = {
    txt: '确认密码',
    placeHolder: '再次确认密码'
  }

  private ReSetPassWordList:CodeInputType[]=[
    this.inputPhoneNumberType,this.inputCaptchaType,this.inputPasswordType,this.inputConfirmPasswordType
  ]

  @State isShowPassWordReSet:boolean=false

  build() {
    Column() {
      YTHeader({ title: '用户设置' })
      if (!this.isShowPassWordReSet) {
        Column() {
          ForEach(this.reviseBuilderArr, (item: BasicType<undefined>, index) => {
            this.reviseBuilder(item)
            if (item.text == '头像修改') {
              Column() {
                Text('')
                  .height(1)
                  .width('100%')
                  .backgroundColor('#0A000000')
              }
              .padding({ left: 12, right: 8 })
              .bindSheet($$this.showHeaderImgRevise, this.changeBuilder, {
                height: 204,
                backgroundColor: Color.White,
                showClose: false,
                radius: { topLeft: 10, topRight: 10 }
              })
            }else{
              Text('')
                .height(1)
                .width('100%')
                .backgroundColor('#0A000000')
            }
          })
          YTButton({
            btContent: '退出登录',
            btHeight: 48,
            btPadding: {
              top: 12,
              bottom: 12
            },
            btBorderRadius: 40,
            bgc: Color.Transparent,
            click: () => {
              this.userInfo.logout()
              yTRouter.routerBack()
              IBestToast.show({ message: '退出登录成功' })
            }
          })
            .margin({ top: 324, bottom: 12 })
            .borderRadius(40)
            .linearGradient({
              angle: 135,
              colors: [
                ['rgba(230, 163, 240,1)', 0.2],
                ['rgba(191, 242, 255, 1)', 1]
              ]
            })
          YTButton({
            btContent: '注销用户',
            btFontColor: 'rgba(28, 28, 28, 0.6)',
            btHeight: 48,
            btBorderRadius: 40,
            btPadding: {
              top: 12,
              bottom: 12
            },
            bgc: Color.White,
            click: () => {
              yTToast.doubleConfirm({
                message: '注销后数据无法恢复，是否注销？', click: () => {
                  IBestToast.show({ message: '注销成功' })
                  YTUserRequest.logout()
                  userInfo.logout()
                  yTToast.hide()
                  yTRouter.routerBack()
                }
              })
            }
          })
        }
        .bindSheet($$this.showReviseName, this.reviseNameBuilder, {
          height: 275,
          showClose: false,
          backgroundColor: Color.White,
          radius: { topLeft: 10, topRight: 10 }
        })
        .padding({
          top: 29,
          left: 16,
          right: 16,
        })
      }else{
        Column(){
          Row({ space: 8 }) {
            Text(this.inputPhoneNumberType.txt).width(75)
            Blank()
            TextInput({ placeholder: this.inputPhoneNumberType?.placeHolder, text: $$this.phoneNumber })
              .layoutWeight(1)
              .type(InputType.PhoneNumber)
              .borderRadius(0)
              .textAlign(TextAlign.Start)
              .height(31)
              .placeholderFont({ size: 16 })
              .fontSize(16)
              .fontWeight(500)
              .fontColor('rgba(28, 28, 28, 1)')
              .placeholderColor($r('[basic].color.main_na_color'))
              .backgroundColor(Color.Transparent)
              .padding(0)
              .caretColor('rgba(0, 0, 0, 0.85)')
          }
          .height(56)
          .width('100%')
          .padding({ left: 8,right:10})
          Divider().strokeWidth(1).color('#1A1C1C1C').margin({bottom:12})


          Row({ space: 8 }) {
            Text(this.inputCaptchaType.txt).width(75)
            Blank()
            TextInput({ placeholder: this.inputCaptchaType?.placeHolder, text: $$this.captcha })
              .layoutWeight(1)
              .type(InputType.PhoneNumber)
              .borderRadius(0)
              .textAlign(TextAlign.Start)
              .height(31)
              .placeholderFont({ size: 16 })
              .fontSize(16)
              .fontWeight(500)
              .fontColor('rgba(28, 28, 28, 1)')
              .placeholderColor($r('[basic].color.main_na_color'))
              .backgroundColor(Color.Transparent)
              .padding(0)
              .caretColor('rgba(0, 0, 0, 0.85)')

            if (this.needCode) {
              Text(this.time == 61 ? '获取验证码' : this.time + '后重新发送')
                .height(32)
                .fontSize(12)
                .borderRadius(8)
                .padding({left:12,right:12,top:8,bottom:8})
                .textAlign(TextAlign.Center)
                .fontColor($r('[basic].color.login_main_yellow'))
                .onClick(() => {
                  const rep = new RegExp('^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\\d{8}$');
                  if (this.phoneNumber.match(rep) && this.time == 61) {
                      this.time = 60
                      this.sa = setInterval(() => {
                        this.time--
                        if (this.time < 1) {
                          this.time = 61
                          clearInterval(this.sa)
                        }
                      }, 1000)
                      //重置密码
                      // TODO  此处放置验证码获取逻辑
                    YTUserRequest.getMyCaptcha(this.phoneNumber, (res) => {
                      if (!res) {
                        IBestToast.show({ message: '请勿重复发送验证码' })
                        return
                      }
                      AppStorage.setOrCreate<string>('resetPassword'+'uuid', res)
                    }, (err) => {
                      // IBestToast.show({ message: err })
                      clearInterval(this.sa)
                      this.time = 61
                    })


                      // YTUserRequest.getCaptcha(this.phoneNumber, (res) => {
                      //   if (!res) {
                      //     IBestToast.show({ message: '请勿重复发送验证码' })
                      //     return
                      //   }
                      //   AppStorage.setOrCreate<string>(this.userOperation +'uuid', res)
                      // }, (err) => {
                      //   // IBestToast.show({ message: err })
                      //   clearInterval(this.sa)
                      //   this.time = 61
                      // })
                  } else {
                    if (!this.phoneNumber.match(rep)) {
                      IBestToast.show({ message: '请输入正确的手机号' })
                    }
                  }

                  // IBestToast.show({ message: '请同意用户协议后发送验证码' })
                })
                .enabled(this.time == 61)
            }


          }
          .height(56)
          .width('100%')
          .padding({ left: 8,right:10})

          Divider().strokeWidth(1).color('#1A1C1C1C').margin({bottom:12})


          Row({ space: 8 }) {
            Text(this.inputPasswordType.txt).width(75)
            Blank()
            TextInput({ placeholder: this.inputPasswordType?.placeHolder, text: $$this.password})
              .layoutWeight(1)
              .type(InputType.Password)
              .borderRadius(0)
              .textAlign(TextAlign.Start)
              .height(31)
              .placeholderFont({ size: 16 })
              .fontSize(16)
              .maxLength(20)
              .fontWeight(500)
              .fontColor('rgba(28, 28, 28, 1)')
              .placeholderColor($r('[basic].color.main_na_color'))
              .backgroundColor(Color.Transparent)
              .padding(0)
              .caretColor('rgba(0, 0, 0, 0.85)')



          }
          .height(56)
          .width('100%')
          .padding({ left: 8,right:10})



          Divider().strokeWidth(1).color('#1A1C1C1C').margin({bottom:12})
          Text('密码必须包含8-20位数字或字母、特殊符号')
            .fontSize(10)
            .fontColor('rgba(0, 0, 0, 0.85)')
            .height(24)
            .textAlign(TextAlign.Center)

          Row({ space: 8 }) {
            Text(this.inputConfirmPasswordType.txt).width(75)
            Blank()
            TextInput({ placeholder: this.inputConfirmPasswordType?.placeHolder, text: $$this.confirmPassword })
              .layoutWeight(1)
              .type(InputType.Password)
              .borderRadius(0)
              .textAlign(TextAlign.Start)
              .height(31)
              .placeholderFont({ size: 16 })
              .fontSize(16)
              .fontWeight(500)
              .fontColor('rgba(28, 28, 28, 1)')
              .placeholderColor($r('[basic].color.main_na_color'))
              .backgroundColor(Color.Transparent)
              .padding(0)
              .maxLength(20)
              .caretColor('rgba(0, 0, 0, 0.85)')
          }
          .height(56)
          .width('100%')
          .padding({ left: 8,right:10})

          Divider().strokeWidth(1).color('#1A1C1C1C').margin({bottom:12})

          YTButton({
            btContent: '完成',
            btHeight: 48,
            btPadding: {
              top: 12,
              bottom: 12
            },
            btBorderRadius: 40,
            bgc: Color.Transparent,
            click: () => {
              //设置成功
              if (this.phoneNumber.trim() == '') {
                IBestToast.show({ message: '请输入手机号码', duration: 500 })
                return
              }
              if (this.captcha.trim() == '') {
                IBestToast.show({ message: '请输入验证码', duration: 500 })
                return
              }
              if (this.password.trim() == '') {
                IBestToast.show({ message: '请输入密码', duration: 500 })
                return
              }
              if (this.password.trim().length < 8 || this.password.trim().length > 20) {
                IBestToast.show({ message: '密码长度不符合要求', duration: 500 })
                return
              }

              if (this.password != this.confirmPassword) {
                IBestToast.show({ message: '两次输入的密码不一致', duration: 500 })
                return
              }
              let param: ReqString = {
                'phonenumber': this.phoneNumber,
                'smsCode': this.captcha,
                'password': this.password,
                'confirmPassword': this.confirmPassword
              }
              // LoginApi.resetPassword(param, () => {
              //   this.confirm?.()
              // })
              YTUserRequest.resetMyPassword(param,()=>{
                //重置密码成功之后返回密码登录页面
                // this.confirm?.()
                IBestToast.show({
                  message:"重置成功"
                })
                this.userInfo.logout()
                this.isShowPassWordReSet=false
                yTRouter.routerBack()
              })

              //todo:设置密码
            }
          })
            .margin({ top: 324, bottom: 12 })
            .borderRadius(40)
            .backgroundColor($r('[basic].color.login_main_yellow'))
            // .linearGradient({
            //   angle: 135,
            //   colors: [
            //     ['rgba(230, 163, 240, 1)', 0.2],
            //     ['rgba(191, 242, 255, 1)', 1]
            //   ]
            // })

        } .padding({
          top: 29,
          left: 16,
          right: 16,
        })
      }
    }
    .padding({ bottom: this.safeBottom })

  }

  @Builder
  reviseBuilder(item: BasicType<undefined>) {
    Row() {
      Text(item.text)
        .fontSize(16)
        .fontWeight(500)
        .fontColor('rgba(28, 28, 28, 1)')
      Row() {
        if (typeof item.src == 'string') {
          Image(this.userInfo.getHeadImg() ? this.userInfo.getHeadImg() : $r("app.media.app_icon"))
            .height(24)
            .width(24)
            .borderRadius(12)
        } else {
          if (item.text == '密码设置') {
            Text()

          } else{
            Text(this.userInfo.getName() ?? this.userInfo.getPhoneNumber() ?? this.userInfo.getId()?.toString())
              .fontSize($r('[basic].float.page_text_font_size_12'))
              .fontColor('#CC000000')
          }
        }
        Image($r('app.media.rightxx'))
          .width(24)
          .width(24)
      }
    }
    .width('100%')
    .justifyContent(FlexAlign.SpaceBetween)
    .padding({ left: 12, right: 4,top:17,bottom:18 })
    .height(56)
    .onClick(item.click)
  }

  @Builder
  reviseNameBuilder() {
    Column() {

      Text('昵称')
        .width('100%')
        .height(36)
        .textAlign(TextAlign.Start)
        .fontSize(12)

      TextInput({ text: $$this.value, placeholder: '请输入昵称' })
        .placeholderColor('rgba(28, 28, 28, 1)')
        .borderRadius(4)
        .fontSize(12)
        .placeholderFont({ size: 12 })
        .placeholderColor('#14000000')
        .height(36)
        .width('100%')
        .backgroundColor(Color.White)
        .border({ width: 1, color: '#14000000' })
        .margin({ bottom: 25 })
        .onChange((value) => {
          if (value.length > 7) {
            this.value = value.slice(0, 7)
            IBestToast.show({message: '用户名称最大为7位' })
          }
        })

      Row({ space: 32 }) {
        YTButton({
          btContent: '取消',
          btHeight: 42,
          btWidth: 104,
          btFontSize:16,
          btPadding: {
            left: 36,
            right: 36,
            top: 9,
            bottom: 9
          },
          bgc: 'rgba(245, 245, 247, 1)',
          btFontColor: 'rgba(53, 60, 70, 1)',
          click: () => {
            this.showReviseName = false
            this.value = ''

          }
        })
        YTButton({
          btContent: '完成',
          btHeight: 42,
          btWidth: 104,
          btFontSize:16,
          bgc:Color.Transparent,
          btPadding: {
            left: 36,
            right: 36,
            top: 9,
            bottom: 9
          },
          click: () => {
            if (!this.value) {
              IBestToast.show({
                type: "warning",
                message: "昵称不能为空"
              })
              return
            }
            YTUserRequest.changeNickname(this.value, () => {
              IBestToast.show({ message: '名称修改成功' })
            })
            //TODO 发送请求后关闭弹窗
            this.showReviseName = false
          }
        }).borderRadius(21)
          .backgroundColor($r('[basic].color.login_main_yellow'))
          // .linearGradient({
          //   angle: 135,
          //   colors: [
          //     ['rgba(230, 163, 240, 1)', 0.2],
          //     ['rgba(191, 242, 255, 1)', 1]
          //   ]
          // })
      }
      .justifyContent(FlexAlign.Center)
      .width('100%')

    }
    .padding({ left: 22, right: 22, top: 8 })
  }

  @Builder
  changeBuilder() {
    reviseImgHeaderBuilder(this.options)
  }
}



// import {
//   BasicType,
//   IBestToast,
//   reviseImgHeaderBuilder,
//   takePicture,
//   Upload,
//   userInfo,
//   UserInfo,
//   YTAvoid,
//   YTButton,
//   YTHeader,
//   YTLog,
//   yTRouter,
//   yTToast,
//   YTUserRequest
// } from 'basic'
//
// @Builder
// function settingBuilder() {
//   NavDestination() {
//     SettingPage()
//   }
//   .hideTitleBar(true)
// }
//
// @Component
// struct SettingPage {
//   @StorageProp(YTAvoid.SAFE_BOTTOM_KEY) safeBottom: number = 0
//   @StorageProp(UserInfo.KEY) userInfo: UserInfo = userInfo
//   @State showReviseName: boolean = false
//   @State showHeaderImgRevise: boolean = false
//   @State value: string = ''
//   reviseBuilderArr: Array<BasicType<undefined>> = [
//     {
//       text: '头像修改',
//       src: '',
//       click: () => {
//         this.showHeaderImgRevise = true
//       }
//     },
//     {
//       text: '昵称修改',
//       click: () => {
//         this.showReviseName = true
//       }
//     }
//   ]
//   options: BasicType<undefined>[] = [
//     {
//       text: '拍照',
//       click: async () => {
//         try {
//           const fullpath = await takePicture(this.getUIContext().getHostContext()!)
//           this.showHeaderImgRevise = false
//           yTRouter.router2DelPhotoPage({ src: fullpath, type: 'header' })
//         } catch (e) {
//           YTLog.warn(e)
//         }
//       }
//     },
//     {
//       text: '从相册中选择',
//       click: () => {
//         Upload.selectImage(this.getUIContext().getHostContext()!, (fullPath) => {
//           this.showHeaderImgRevise = false
//           yTRouter.router2DelPhotoPage({ src: fullPath, type: 'header' })
//         })
//       }
//     },
//     {
//       text: '取消',
//       click: () => {
//         this.showHeaderImgRevise = false
//       }
//     },
//   ]
//
//   build() {
//     Column() {
//       YTHeader({ title: '用户设置' })
//       Column() {
//         ForEach(this.reviseBuilderArr, (item: BasicType<undefined>, index) => {
//           this.reviseBuilder(item)
//           if (index < this.reviseBuilderArr.length - 1) {
//             Column() {
//               Text('')
//                 .height(1)
//                 .width('100%')
//                 .backgroundColor('#0A000000')
//             }
//             .padding({ left: 12, right: 8 })
//             .bindSheet($$this.showHeaderImgRevise, this.changeBuilder, {
//               height: 204,
//               backgroundColor: Color.White,
//               showClose: false
//             })
//           }
//         })
//         YTButton({
//           btContent: '退出登录', click: () => {
//             this.userInfo.logout()
//             yTRouter.routerBack()
//             IBestToast.show({ message: '退出登录成功' })
//           }
//         })
//           .margin({ top: 426, bottom: 12 })
//         YTButton({
//           btContent: '注销用户',
//           btFontColor: Color.Red,
//           bgc: Color.White,
//           click: () => {
//             yTToast.doubleConfirm({
//               text: '警告⚠', message: '确定要注销吗？\n注销后数据可能丢失无法恢复！', click: () => {
//                 userInfo.logout()
//                 yTToast.hide()
//                 yTRouter.routerBack()
//               }
//             })
//           }
//         })
//       }
//       .bindSheet($$this.showReviseName, this.reviseNameBuilder, {
//         height: 275,
//         showClose: false,
//         backgroundColor: Color.White
//       })
//       .padding({
//         left: 16,
//         right: 16,
//       })
//     }
//     .padding({ bottom: this.safeBottom })
//
//   }
//
//   @Builder
//   reviseBuilder(item: BasicType<undefined>) {
//     Row() {
//       Text(item.text)
//         .fontSize($r('[basic].float.page_text_font_size_12'))
//         .fontColor('#80000000')
//       Row() {
//         if (typeof item.src == 'string') {
//           Image(this.userInfo.getHeadImg() ? this.userInfo.getHeadImg() : $r('app.media.default_img'))
//             .height(24)
//             .width(24)
//             .borderRadius(12)
//         } else {
//           Text(this.userInfo.getName() ?? this.userInfo.getPhoneNumber() ?? this.userInfo.getId()?.toString())
//             .fontSize($r('[basic].float.page_text_font_size_12'))
//             .fontColor('#CC000000')
//         }
//         Image($r('app.media.right_arrow'))
//           .width(24)
//           .width(24)
//       }
//     }
//     .width('100%')
//     .justifyContent(FlexAlign.SpaceBetween)
//     .padding({ left: 12, right: 4 })
//     .height(36)
//     .onClick(item.click)
//   }
//
//   @Builder
//   reviseNameBuilder() {
//     Column() {
//
//       Text('昵称')
//         .width('100%')
//         .height(36)
//         .textAlign(TextAlign.Start)
//         .fontSize(12)
//
//       TextInput({ text: $$this.value, placeholder: '请输入昵称' })
//         .borderRadius(4)
//         .fontSize(12)
//         .placeholderFont({ size: 12 })
//         .placeholderColor('#14000000')
//         .height(36)
//         .width('100%')
//         .backgroundColor(Color.White)
//         .border({ width: 1, color: '#14000000' })
//         .margin({ bottom: 25 })
//         .onChange((value) => {
//           if (value.length > 7) {
//             this.value = value.slice(0, 7)
//             IBestToast.show({ type: "warning", message: '用户名称最大为7位' })
//           }
//         })
//
//       Row({ space: 32 }) {
//         YTButton({
//           btContent: '取消',
//           btHeight: 25,
//           btWidth: 78,
//           btBorder: { width: 1, color: '#1A000000' },
//           btPadding: {
//             left: 26,
//             right: 26,
//             top: 4,
//             bottom: 4
//           },
//           bgc: Color.White,
//           btFontColor: $r('sys.color.mask_secondary'),
//           click: () => {
//             this.showReviseName = false
//             this.value = ''
//
//           }
//         })
//         YTButton({
//           btContent: '完成',
//           btHeight: 25,
//           btWidth: 78,
//           btPadding: {
//             left: 26,
//             right: 26,
//             top: 4,
//             bottom: 4
//           },
//           click: () => {
//             if (!this.value) {
//               IBestToast.show({
//                 type: "warning",
//                 message: "昵称不能为空"
//               })
//               return
//             }
//             YTUserRequest.changeNickname(this.value, () => {
//               IBestToast.show({ message: '名称修改成功' })
//               this.showReviseName = false
//             })
//
//           }
//         })
//       }
//       .justifyContent(FlexAlign.Center)
//       .width('100%')
//
//     }
//     .padding({ left: 22, right: 22, top: 8 })
//   }
//
//   @Builder
//   changeBuilder() {
//     reviseImgHeaderBuilder(this.options)
//   }
// }