import { authStore, hdHttp, HdResponse,HdNav,BasicConstant, logger,LoginInfo,ChangeUtil } from '@itcast/basic'
import { promptAction, router } from '@kit.ArkUI'
import { BusinessError } from '@kit.BasicServicesKit';
import HashMap from '@ohos.util.HashMap';
import { DataWebModel,preferenceStore ,SpecialDisease} from '@itcast/basic'

@Preview
@Component
export struct LoginComp {
  @State
  mobile: string = '13419527489'
  @State
  code: string = '123456a'
  @State
  current_code: string = '123456a'
  @State
  isAgree: boolean = false
  @State
  loading: boolean = false
  @StorageProp('topHeight')
  topHeight: number = 0
  @State
  isPassLogin:boolean=false

  istime:boolean=false
  time: number = 60
  timer: number | null = null
  @State
  timeText:string ='获取验证码'
  @State
  type:string ='账号密码登录'

  loginUrl:string=BasicConstant.urlExpertAPI+'umSmsLogin'

  hashMap: HashMap<string, string> = new HashMap();



  login() {
    if (this.loading) return;
    if (!this.mobile) {
      return promptAction.showToast({ message: '手机号码不为空' })
    }
    if (!ChangeUtil.isMobileNum(this.mobile)) {
      return promptAction.showToast({ message: "手机号码不正确" })
    }
    if(this.isPassLogin) {
      if (!this.code) {
        return promptAction.showToast({ message: '密码不为空' })
      }
      if (!ChangeUtil.isPassword(this.code)) {
        return promptAction.showToast({ message: "请输入6-16位字母、数字组合密码" })
      }
    } else {
     if (!this.current_code) {
       return promptAction.showToast({ message: '请输入验证码' })
     }
   }

    if (!this.isAgree) {
      return promptAction.showToast({ message: '请勾选已阅读并同意' })
    }
    this.loading = true
    this.hashMap.clear();
    this.hashMap.set('mobile',this.mobile)
    if(this.isPassLogin) {
      this.hashMap.set('password',this.code)
      this.loginUrl=BasicConstant.urlExpertAPI+'login'
    } else {
     this.hashMap.set('sms',this.current_code)
     this.loginUrl=BasicConstant.urlExpertAPI+'umSmsLogin'
   }
    this.hashMap.set('current_spec','hongmeng')
    hdHttp.httpReq<string>(this.loginUrl,this.hashMap).then(async (res: HdResponse<string>) => {
      this.loading = false
      logger.info('Response login'+res);
      console.info(`Response login succeeded: ${res}`);
      let json:LoginInfo = JSON.parse(res+'') as LoginInfo;
      if(json.code=='1'||json.code=='200') {
        this.arrToStringSpecialy(json.special)
        this.getSaveUserInfor(1,json)
      } else {
        promptAction.showToast({ message: json.message, duration: 1000 })
      }
    }).catch((err: BusinessError) => {
      this.loading = false
      console.info(`Response login fail: ${err}`);
    })
  }

  getSaveUserInfor(type:number,objs:LoginInfo) {
    let state:number=objs.data.state
    let checkInfo:string=objs.data.checkInfo
    if(state!=6) {
      authStore.setUser(objs.data)
      router.pushUrl({
        url: 'pages/LoginPage/LoginSetInfoPage', // 目标url
        params: {
          loginInputPhone:this.mobile,
          state:state,
          checkInfo:checkInfo
        }
      })
    } else {
      authStore.setUser(objs.data)
      // emitter.emit({ eventId: 100401 })
      logger.info('Response state'+state);
      promptAction.showToast({ message: '登录成功', duration: 1000 })
      preferenceStore.setItemBoolean('isLogin',true)
      router.replaceUrl({
        url: 'pages/Home', // 目标url
      })
    }
  }
  arrToStringSpecialy(data:SpecialDisease[]) {
    let diseaseName=''
    let diseaseUuid=''
    if(data!=null&&data.length>0)
    {
      data.forEach((element,index) => {
        if(index!=data.length-1)
        {
          diseaseName+=element.diseaseName+','
          diseaseUuid+=element.diseaseUuid+','
        }
        else
        {
          diseaseName+=element.diseaseName
          diseaseUuid+=element.diseaseUuid
        }
      });
    }
    preferenceStore.setItemString('diseaseName',diseaseName)
    preferenceStore.setItemString('diseaseUuid',diseaseUuid)
  }
  getMessage() {
    if (!this.mobile) {
      return promptAction.showToast({ message: '手机号码不为空' })
    }
    this.hashMap.clear();
    this.hashMap.set('mobile',this.mobile)
    this.hashMap.set('type','7')
    hdHttp.httpReq<string>(BasicConstant.urlExpertAPI+'smsSend',this.hashMap).then(async (res: HdResponse<string>) => {
    }).catch((err: BusinessError) => {
      this.loading = false
      console.info(`Response login succeeded: ${err}`);
    })
  }
  build() {
      Column() {
        HdNav({ title: '登录', showRightIcon: false,showLeftIcon:false })

          Image($r('app.media.icon_logo'))
            .width(64)
            .margin({top:45})
            .aspectRatio(1)
          Text('专家版')
            .fontSize(16)
            .margin({ bottom: 15,top:10 })
            .fontColor($r('app.color.main_color'))
        Column({ space: 15 }) {
          Column()
          {
            Row()
            {
              Image($r('app.media.icon_mobile'))
                .width(18)
                .margin(5)
              TextInput({ placeholder: '请输入手机号码', text: $$this.mobile })
                .customStyle()
            }
            Text().width('100%').height(0.8).backgroundColor('#CCCCCC')
            if(this.isPassLogin)
            {
              Row() {
                Image($r('app.media.icon_password'))
                  .width(18)
                  .margin(5)
                TextInput({ placeholder: '请输入密码', text: $$this.code })
                  .type(InputType.Password)
                  .passwordIcon({ onIconSrc:$r('app.media.icon_show_password'), offIconSrc: $r('app.media.icon_hidden_password') })
                  .customStyle()
              }
            }
            else
            {
              Row() {
                Image($r('app.media.send_message'))
                  .width(18)
                  .margin(5)
                TextInput({ placeholder: '请输入验证码', text: $$this.current_code })
                  .customStyle()
                  .width(150)
                Blank()
                Text(this.timeText)
                  .width(100)
                  .height(27)
                  .borderRadius(12)
                  .textAlign(TextAlign.Center)
                  .fontSize(14)
                  .fontColor($r('app.color.top_title'))
                  .borderRadius(30)
                  .margin({right:15})
                  .border({ width: 1, color: $r('app.color.top_title') })
                  .onClick(() => {

                    if(this.istime)
                    {
                    }
                    else
                    {
                      this.getMessage()
                      this.istime=true
                      this.startTime()
                    }

                  })
              }.width('100%')
            }
          }
            .borderRadius(5)
            .border({ width: 1, color: '#CCCCCC' })
          Button({ type: ButtonType.Normal }) {
            Row() {
              if (this.loading) {
                LoadingProgress()
                  .color($r('app.color.white'))
                  .width(24)
                  .height(24)
                  .margin({ right: 10 })
              }
              Text('登录').fontColor($r('app.color.white'))
            }
          }
          .width('100%')
          .backgroundColor($r('app.color.top_title'))
          .borderRadius(4)
          .height(44)
          .stateEffect(false)
          .onClick(() => {
            this.login()
          })
          Text(this.type)
            .fontSize(14)
            .fontColor($r('app.color.top_title'))
            .alignSelf(ItemAlign.Start)
            .onClick(() => {
              if(this.isPassLogin)
              {
                this.isPassLogin=false
                this.type='账号密码登录'
              }
              else
              {
                this.isPassLogin=true
                this.type='短信验证码登录'
              }

            })
          Row() {
            Checkbox()
              .shape(CheckBoxShape.CIRCLE)
              .selectedColor($r('app.color.top_title'))
              .size({ width: 22, height: 22 })
              .select(this.isAgree)
              .alignSelf((ItemAlign.Start))
              .onChange((val) => {
                this.isAgree = val
              })
            if(this.isPassLogin)
            {
              Text() {
                Span('登录即代表同意').fontColor($r('app.color.common_gray_03'))
                Span('《肝胆相照隐私政策》').fontColor($r('app.color.top_title')).onClick(() => {
                  this.ToWeb(BasicConstant.getyyzc,'《肝胆相照隐私政策》')
                })
                Span('和').fontColor($r('app.color.common_gray_03'))
                Span('《肝胆相照用户服务协议》').fontColor($r('app.color.top_title'))
                  .onClick(() => {
                    this.ToWeb(BasicConstant.getzcxy,'《肝胆相照用户服务协议》')
                  })

              }
              .fontSize(14)
              .padding({ left: 4 ,right:20})
            }
            else
            {

              Text() {
                Span('未注册的手机号验证登录后将自动创建肝胆相照账号，登录即代表同意').fontColor($r('app.color.common_gray_03'))
                Span('《肝胆相照隐私政策》').fontColor($r('app.color.top_title')).onClick(() => {
                  this.ToWeb(BasicConstant.getyyzc,'《肝胆相照隐私政策》')
                })
                Span('和').fontColor($r('app.color.common_gray_03'))
                Span('《肝胆相照用户服务协议》').fontColor($r('app.color.top_title'))
                  .onClick(() => {
                    this.ToWeb(BasicConstant.getzcxy,'《肝胆相照用户服务协议》')
                  })

              }
              .fontSize(14)
              .padding({ left: 4 ,right:20})

            }


          }.padding({bottom:20}).alignSelf(ItemAlign.End)
        }
        .height("100%")
        .padding({ left: 20, right: 20, top: 30 })

      }
  }
  startTime() {
    this.time=60
    this.timer = setInterval(() => {
      this.timeText=this.time+'s'
      if (this.time <= 0) {
        clearInterval(this.timer)
        this.timeText='获取验证码'
        this.istime=false
      }
      this.time--

    }, 1000)
  }
  ToWeb(u:string,t:string)
  {
    let paramsInfo: DataWebModel = {
      url:u ,
      title:t

    };
    router.pushUrl({
      url: 'pages/WebView/WebPage', // 目标url
      params: paramsInfo // 添加params属性，传递自定义参数
    })
  }
}
@Extend(TextInput)
function customStyle() {
  .placeholderColor('#C3C3C5')
  .caretColor('#fa711d')
  .height(45)
  .borderRadius(0)
  .backgroundColor($r('app.color.white'))
  .margin({right:30})
}


