import { BasicConstant,ExpertData,perfactAuth,ChangeUtil,authStore,preferenceStore,LoginInfo,
  logger } from '@itcast/basic'
import { LengthMetrics, promptAction, router } from '@kit.ArkUI'
import { EditUserDataItem } from '@itcast/basic/src/main/ets/Views/EditUserDataItem'
import { PerfactInputSheet } from '@itcast/basic/src/main/ets/Views/PerfactInputSheet'
import { PhotoActionSheet } from '@itcast/basic/src/main/ets/Views/PhotoActionSheet'
import { SexSelectedSheet } from '@itcast/basic/src/main/ets/Views/SexSelectedSheet'
import { OfficeSelectedSheet } from '@itcast/basic/src/main/ets/Views/OfficeSelectedSheet'
import { PositionSelectedSheet } from '@itcast/basic/src/main/ets/Views/PositionSelectedSheet'
import { SpecialitySelectedSheet } from '@itcast/basic/src/main/ets/Views/SpecialitySelectedSheet'
import { emitter } from '@kit.BasicServicesKit'
import { BusinessError } from '@kit.BasicServicesKit';
import { rcp } from '@kit.RemoteCommunicationKit';

interface extraData {
  uuid: string
}

interface updateExtraData {
  uuid: string,
  userName: string,
  realName:string,
  type: string,
  sex:string,
  photo: string,
  provId:string,
  cityId:string,
  countyId:string,
  hospitalUuid:string,
  hospitalName:string,
  certificateImg: string,
  positionUuid: string,
  certificate:string
  officeUuid: string,
  officeName: string,
  officePhone:string,
  diseaseUuids: string
}

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

@Component
export struct PerfectUserDataComp {
  scroller: Scroller = new Scroller();
  @Prop state:number=0
  @Prop loginPhone:string = '';
  @Prop checkInfo:string=''

  @State photoPath:string = perfactAuth.getUser(this.loginPhone).photo;
  @State name:string = perfactAuth.getUser(this.loginPhone).realName?perfactAuth.getUser(this.loginPhone).realName:'请输入姓名';
  @State sex:string = perfactAuth.getUser(this.loginPhone).sex?perfactAuth.getUser(this.loginPhone).sex == 0 ? '男' : '女':'请选择性别';
  @State sexnum:number = perfactAuth.getUser(this.loginPhone).sex;
  @State hospatilName:string = perfactAuth.getUser(this.loginPhone).hospitalName?perfactAuth.getUser(this.loginPhone).hospitalName:'请选择所在医院'
  @State officeName:string = perfactAuth.getUser(this.loginPhone).officeName?perfactAuth.getUser(this.loginPhone).officeName:'请选择科室';
  @State officeUuid:string = perfactAuth.getUser(this.loginPhone).officeUuid;
  @State officePhone:string = perfactAuth.getUser(this.loginPhone).officePhone?perfactAuth.getUser(this.loginPhone).officePhone:'请输入所在科室的电话';
  @State positionName:string = perfactAuth.getUser(this.loginPhone).positionName?perfactAuth.getUser(this.loginPhone).positionName:'请选择职称';
  @State positionUuid:string = perfactAuth.getUser(this.loginPhone).positionUuid;
  @State certificate:string = perfactAuth.getUser(this.loginPhone).certificate?perfactAuth.getUser(this.loginPhone).certificate:'请输入执业医师证号码';
  @State certificatePhoto:string = perfactAuth.getUser(this.loginPhone).certificateImg;
  @State diseaseName:string = perfactAuth.getUser(this.loginPhone).diseaseName?perfactAuth.getUser(this.loginPhone).diseaseName:'请选择专长';
  @State diseaseUuid:string = perfactAuth.getUser(this.loginPhone).diseaseUuid?perfactAuth.getUser(this.loginPhone).diseaseUuid:'';

  @State inputTitle:string = '';
  @State inputPlaceholder:string = '';
  @State info:string=''
  @State cityId:string = perfactAuth.getUser(this.loginPhone).cityId?perfactAuth.getUser(this.loginPhone).cityId:'';
  @State provId:string = perfactAuth.getUser(this.loginPhone).provId?perfactAuth.getUser(this.loginPhone).provId:'';
  @State countyId:string = perfactAuth.getUser(this.loginPhone).countyId?perfactAuth.getUser(this.loginPhone).countyId:'';
  @State hospitalUuid:string = perfactAuth.getUser(this.loginPhone).hospitalUuid?perfactAuth.getUser(this.loginPhone).hospitalUuid:'';
  @State base64Stringphoto:string=''
  @State base64Stringcertificate:string=''

  private photoSheetDialog!: CustomDialogController;
  private officePickerDialog!: CustomDialogController;
  private positionPickerDialog!: CustomDialogController;
  private certificatePhotoSheetDialog!: CustomDialogController;
  private diseaseSheetDialog!:CustomDialogController;
  private sexSheetDilog!:CustomDialogController;
  private perfactInputSheet!:CustomDialogController;

  aboutToAppear() {
    this.initSexDialog();
    this.initPhotoDialog();
    this.initPerfactInputDialog();
    this.initOfficePickerDialog();
    this.initPositionPickerDialog();
    this.initCerficatePhotoDialog();
    this.initDiseaseSheetDIalog();
    this.handleState()
    // logger.info("Response this.photoPath "+this.photoPath)

    emitter.on({ eventId: 250516 }, () => {
      this.handleSave()
    })
    // 收到eventId为1的事件后执行回调函数
    emitter.on({ eventId: 250517 },  (eventData: emitter.EventData) => {
      console.info(`eventData: ${JSON.stringify(eventData)}`);
      const params =eventData.data as Record<string, string>; // 获取传递过来的参数对象
      this.hospatilName=params.name
      this.countyId=params.county_id
      this.cityId=params.city_id
      this.provId=params.prov_id
      this.hospitalUuid=params.uuid

    });
  }

  aboutToDisappear() {
    emitter.off(250516)
    emitter.off(250517)
  }

  private handleState()
  {
    if(this.state==0||this.state==1||this.state==11||this.state==10
      ||this.state==9||this.state==3||this.state==4||this.state==5
      ||this.state==7) {
      if(this.state==3||this.state==4||this.state==5)
      {
        this.info='您的资料未通过审核，请修改完善后重新提交。'
        if(this.checkInfo!=''||this.checkInfo!=null)
        {
          this.info=this.checkInfo
          promptAction.showDialog({ title: '温馨提示', message: this.checkInfo,
            buttons: [{ text: '确定', color: $r('app.color.main_color') }],
          })
            .then(data => {
              if (data.index == 1) {

              }
            })
        }

      }
    }
    else
    {
      this.info='肝胆相照将尽快对您的资料进行审核，请耐心等待。'
    }
    if(this.state!=0&&this.state!=1)
    {
       this.photoPath = BasicConstant.urlImage+authStore.getUser().photo
       this.name = authStore.getUser().realName?authStore.getUser().realName:'请输入姓名'
       this.sex = authStore.getUser().sex?'请选择性别':authStore.getUser().sex == 0 ? '男' : '女';
       this.sexnum = authStore.getUser().sex;
       this.hospatilName = authStore.getUser().hospitalName?authStore.getUser().hospitalName:'请选择所在医院'
       this.officeName = authStore.getUser().officeName?authStore.getUser().officeName:'请选择科室';
       this.officeUuid = authStore.getUser().officeUuid;
       this.officePhone = authStore.getUser().officePhone?authStore.getUser().officePhone:'请输入所在科室的电话';
       this.positionName = authStore.getUser().positionName?authStore.getUser().positionName:'请选择职称';
       this.positionUuid = authStore.getUser().positionUuid;
       this.certificate = authStore.getUser().certificate?authStore.getUser().certificate:'请输入执业医师证号码';
       this.certificatePhoto = BasicConstant.urlImage+authStore.getUser().certificateImg;
       this.diseaseName = preferenceStore.getItemString('diseaseName')?preferenceStore.getItemString('diseaseName'):'请选择专长';
       this.diseaseUuid = preferenceStore.getItemString('diseaseUuid')?preferenceStore.getItemString('diseaseUuid'):'';
       this.cityId = authStore.getUser().cityId?authStore.getUser().cityId+'':''
       this.provId = authStore.getUser().provId?authStore.getUser().provId+'':'';
       this.countyId = authStore.getUser().countyId?authStore.getUser().countyId+'':'';
       this.hospitalUuid = authStore.getUser().hospitalUuid?authStore.getUser().hospitalUuid:'';

    }
  }

  canEdit()
  {
    if(this.state==0||this.state==1||this.state==11||this.state==10
      ||this.state==9||this.state==3||this.state==4||this.state==5
      ||this.state==7) {
      return true;
    }
    else
    {
      return false
    }
  }

  private handleSave() {
    promptAction.showToast({ message: '您输入的个人资料已经保存，请完善所有信息后提交审核', duration: 1000 })
    const userData:ExpertData = {
      positionName: this.positionName,
      userName: this.loginPhone,
      createDate: '',
      password: '',
      officeName: this.officeName,
      certificateImg: this.certificatePhoto,
      birthDate: '',
      isStar: 0,
      countyId: this.countyId,
      cityId:this.cityId,
      email: '',
      photo: this.photoPath,
      qrcode: '',
      mobile: this.loginPhone,
      hospitalName: this.hospatilName,
      officeUuid: this.officeUuid,
      checkInfo: '',
      hospitalUuid: this.hospitalUuid,
      officePhone: this.officePhone,
      positionUuid: this.positionUuid,
      sex: this.sexnum,
      provId: this.provId,
      certificate: this.certificate,
      realName: this.name,
      isEnable: 0,
      isVisit: 0,
      modifyDate: '',
      currentSpec: '',
      deviceType: 0,
      currentType: 0,
      deviceSpec: '',
      nation: 0,
      wechat_qrcode: '',
      uuid: '',
      intro: '',
      state: 0,
      specialy: [],
      diseaseName:this.diseaseName,
      diseaseUuid:this.diseaseUuid
    };
    perfactAuth.setUser(this.loginPhone,userData);
    // console.info('个人资料=name：',perfactAuth.getUser(this.loginPhone).realName,'\n科室:',perfactAuth.getUser(this.loginPhone).positionName);
  }

  handleModify()
  {
    if(this.base64Stringphoto.length<1&&(this.photoPath==undefined||this.photoPath.length<0))
    {
      promptAction.showToast({ message: "请选择头像" , duration: 1000 })
      return
    }
    if(this.name.length<1||this.name=='请输入姓名')
    {
      promptAction.showToast({ message: "姓名不为空" , duration: 1000 })
      return
    }
    if(this.sex.length<1||this.sex=='请选择性别')
    {
      promptAction.showToast({ message: "请选择性别" , duration: 1000 })
      return
    }
    if(this.hospatilName.length<1||this.hospatilName=='请选择所在医院')
    {
      promptAction.showToast({ message: "医院不为空" , duration: 1000 })
      return
    }
    if(this.hospitalUuid.length<1)
    {
      promptAction.showToast({ message: "医院不为空" , duration: 1000 })
      return
    }
    if(this.officeName.length<1||this.officeName=='请选择科室')
    {
      promptAction.showToast({ message: "科室不为空" , duration: 1000 })
      return
    }
    if(this.officeUuid.length<1)
    {
      promptAction.showToast({ message: "科室不为空" , duration: 1000 })
      return
    }
    if(this.officePhone.length<1||this.officePhone=='请输入所在科室的电话')
    {
      promptAction.showToast({ message: "科室电话不为空" , duration: 1000 })
      return
    }
    if(this.positionName.length<1||this.positionName=='请选择职称')
    {
      promptAction.showToast({ message: "职称不为空" , duration: 1000 })
      return
    }
    if(this.positionUuid.length<1)
    {
      promptAction.showToast({ message: "职称不为空" , duration: 1000 })
      return
    }
    if(this.certificate.length<1||this.certificate=='请输入执业医师证号码')
    {
      promptAction.showToast({ message: "执业医师资格证号码不为空" , duration: 1000 })
      return
    }
    if(this.base64Stringcertificate.length<1&&(this.certificatePhoto==undefined||this.certificatePhoto.length<0))
    {
      promptAction.showToast({ message: "请选择执业医师资格证照片" , duration: 1000 })
      return
    }
    if(this.diseaseName.length<1||this.diseaseName=='请选择专长')
    {
      promptAction.showToast({ message: "请选择专长" , duration: 1000 })
      return
    }
    if(this.diseaseUuid.length<1)
    {
      promptAction.showToast({ message: "请选择专长" , duration: 1000 })
      return
    }
    const updateDataUrl:string = BasicConstant.urlExpert + 'modify';
    // 定义content，请根据实际情况选择
    const postContent = new rcp.MultipartForm({
      'uuid': authStore.getUser().uuid,
      'userName': this.loginPhone,
      'realName':this.name,
      'type': '1',
      'sex':this.sexnum+'',
      'photo': this.base64Stringphoto,
      'provId':this.provId,
      'cityId':this.cityId,
      'countyId':this.countyId,
      'hospitalUuid':this.hospitalUuid,
      'hospitalName':this.hospatilName,
      'certificateImg': this.base64Stringcertificate,
      'positionUuid': this.positionUuid,
      'certificate':this.certificate,
      'officeUuid': this.officeUuid,
      'officeName': this.officeName,
      'officePhone':this.officePhone,
      'diseaseUuids': this.diseaseUuid
    })

    const session = rcp.createSession();
    session.post(updateDataUrl, postContent)
      .then((response) => {
        let json:LoginInfo = JSON.parse(response+'') as LoginInfo;
        if(json.code=='1') {
          this.state=-1
          this.info='肝胆相照将尽快对您的资料进行审核，请耐心等待。'
        }
        else
        {
          promptAction.showToast({ message: "提交失败，请重试" +json.message, duration: 1000 })
        }
        // console.info(`Response succeeded2: ${JSON.stringify(response.headers)}`);
        // console.info(`Response succeeded: ${JSON.stringify(response.statusCode)}`);
        // console.info(`Response succeeded22: ${JSON.stringify(response)}`);

        // console.info(`Response postContent: ${JSON.stringify(postContent)}`);

      })
      .catch((err: BusinessError) => {
        console.error(`Response err: Code is ${JSON.stringify(err.code)}, message is ${JSON.stringify(err)}`);
      })

  }

  initSexDialog(){
    this.sexSheetDilog = new CustomDialogController({
      builder:SexSelectedSheet({
        controller:this.sexSheetDilog,
        sexSelected:(index: number)=>{
          this.sex = index == 0 ? '男' : '女';
          this.sexnum = index;
        }
      }),
      alignment: DialogAlignment.Bottom,
      customStyle: true,
      autoCancel: false,
      backgroundColor: ('rgba(0,0,0,0.5)'),
      height: '100%'
    })
  }

  initPerfactInputDialog() {
    this.perfactInputSheet = new CustomDialogController({
      builder:PerfactInputSheet({
        controller:this.perfactInputSheet,
        inputTitle:this.inputTitle,
        inputPlaceholder:this.inputPlaceholder,
        inputCallBack:(input: string,title:string)=>{
          if (title == '请输入姓名') {
            this.name = input;
          } else if (title == '请输入所在科室电话') {
            this.officePhone = input;
          } else if (title == '请输入执业医师资格证号码') {
            this.certificate = input;
          }
        }
      }),
      keyboardAvoidDistance: LengthMetrics.vp(0), // 设置弹窗底部与键盘顶部间距（单位：vp）
      alignment: DialogAlignment.Bottom,
      customStyle: true,
      autoCancel: false,
      backgroundColor: ('rgba(0,0,0,0.5)'),
      height: '100%'
    })
  }

  private initPhotoDialog() {
    this.photoSheetDialog = new CustomDialogController({
      builder: PhotoActionSheet({
        controller: this.photoSheetDialog,
        onPhotoSelected: async (uri: string) => {
          this.photoPath = uri;
          this.base64Stringphoto = await ChangeUtil.convertUriToBase64(uri);
        }
      }),
      alignment: DialogAlignment.Bottom,
      customStyle: true,
      autoCancel: false,
      backgroundColor: ('rgba(0,0,0,0.5)'),
      height: '100%'
    });
  }

  private initOfficePickerDialog() {
    this.officePickerDialog = new CustomDialogController({
      builder:OfficeSelectedSheet({
        controller:this.officePickerDialog,
        officeSelected: (name:string , uuid:string) => {
          this.officeName = name;
          this.officeUuid = uuid;
        }
      }),
      alignment: DialogAlignment.Bottom,
      customStyle: true,
      autoCancel: false,
      backgroundColor: ('rgba(0,0,0,0.5)'),
      height: '100%'
    })
  }

  private initPositionPickerDialog() {
    this.positionPickerDialog = new CustomDialogController({
      builder:PositionSelectedSheet({
        controller:this.officePickerDialog,
        officeSelected: (name:string , uuid:string) => {
          this.positionName = name;
          this.positionUuid = uuid;
        }
      }),
      alignment: DialogAlignment.Bottom,
      customStyle: true,
      autoCancel: false,
      backgroundColor: ('rgba(0,0,0,0.5)'),
      height: '100%'
    })
  }

  private initCerficatePhotoDialog() {
    this.certificatePhotoSheetDialog = new CustomDialogController({
      builder: PhotoActionSheet({
        controller: this.certificatePhotoSheetDialog,
        onPhotoSelected: async (url: string) => {
          this.certificatePhoto = url;
          this.base64Stringcertificate = await ChangeUtil.convertUriToBase64(url);

          console.log('Selected image URI:', url);
        }
      }),
      alignment: DialogAlignment.Bottom,
      customStyle: true,
      autoCancel: false,
      backgroundColor: ('rgba(0,0,0,0.5)'),
      height: '100%'
    });
  }

  private initDiseaseSheetDIalog() {
    this.diseaseSheetDialog = new CustomDialogController({
      builder: SpecialitySelectedSheet({
        controller:this.diseaseSheetDialog,
        specialitySelected: (diseaseUuids:string,diseaseName:string)=>{
          this.diseaseName = diseaseName;
          this.diseaseUuid = diseaseUuids;
        }
      }),
      alignment: DialogAlignment.Bottom,
      customStyle: true,
      autoCancel: false,
      backgroundColor: ('rgba(0,0,0,0.5)'),
      height: '100%'
    })
  }



  build() {
    Scroll(this.scroller) {
      Column() {
          // 基本信息字段
        EditUserDataItem({ label: '头像', required: false, content: this.photoPath, hasArrow: true, isLine:false })
          .backgroundColor(Color.White)
          .onClick(()=>
          {
            if(!this.canEdit())
            {
              return
            }
            this.photoSheetDialog.open()
          }
         )
        EditUserDataItem({ label: '姓名', required: false, content: this.name, hasArrow:true, isLine:false })
          .backgroundColor(Color.White)
          .margin({top:8})
          .onClick(()=>{
            if(!this.canEdit())
            {
              return
            }
            this.inputTitle = '请输入姓名';
            this.inputPlaceholder = this.name;
            this.perfactInputSheet.open()
          })
        EditUserDataItem({ label: '性别', required: false, content: this.sex, hasArrow:true, isLine:false })
          .backgroundColor(Color.White)
          .margin({top:8})
          .onClick(()=> {
            if(!this.canEdit())
            {
              return
            }
            this.sexSheetDilog.open()
          })
        EditUserDataItem({ label: '医院', required: false, content: this.hospatilName, hasArrow: true, isLine:false })
          .backgroundColor(Color.White)
          .margin({top:8})
          .onClick(()=> {
            if(!this.canEdit())
            {
              return
            }
            router.pushUrl({
              url: 'pages/LoginPage/SelectedHospitalPage'
            })
          })
        EditUserDataItem({ label: '科室', required: false, content: this.officeName, hasArrow: true, isLine:false })
          .backgroundColor(Color.White)
          .margin({top:8})
          .onClick(()=> {
            if(!this.canEdit())
            {
              return
            }
            this.officePickerDialog.open()
          }
            )
        EditUserDataItem({ label: '科室电话', required: false, content: this.officePhone, hasArrow: true, isLine:false })
          .backgroundColor(Color.White)
          .margin({top:8})
          .onClick(()=>{
            if(!this.canEdit())
            {
              return
            }
            this.inputTitle = '请输入所在科室电话';
            this.inputPlaceholder = this.officePhone;
            this.perfactInputSheet.open()
          })
        EditUserDataItem({ label: '职称', required: false, content: this.positionName, hasArrow: true, isLine:false })
          .backgroundColor(Color.White)
          .margin({top:8})
          .onClick(()=> {
            if(!this.canEdit())
            {
              return
            }
            this.positionPickerDialog.open()
          }
            )
        EditUserDataItem({ label: '执业医师证编号', required: false, content: this.certificate ,hasArrow: true, isLine:false })
          .backgroundColor(Color.White)
          .margin({top:8})
          .onClick(()=>{
            if(!this.canEdit())
            {
              return
            }
            this.inputTitle = '请输入执业医师资格证号码';
            this.inputPlaceholder = this.certificate;
            this.perfactInputSheet.open()}
          )
        EditUserDataItem({ label: '执业医师证图片或胸牌', required: false, content: this.certificatePhoto, hasArrow: true, isLine:false })
          .backgroundColor(Color.White)
          .margin({top:8})
          .onClick(()=> {
            if(!this.canEdit())
            {
              return
            }
            this.certificatePhotoSheetDialog.open()
          })
        EditUserDataItem({ label: '专长(可选一到十项)', required: false, content: this.diseaseName , hasArrow: true, isLine:false })
          .backgroundColor(Color.White)
          .margin({top:8})
          .onClick(()=>
          {
            if(!this.canEdit())
            {
              return
            }
            this.diseaseSheetDialog.open()
          })

        Column() {

          Text(this.info) .fontSize(18).fontColor('#ffff5454').padding(10).margin({top:20})
            .visibility(this.info==''?Visibility.None:Visibility.Visible)

            // 登录按钮
            Button({type:ButtonType.Normal}){
              Text('提交')
            }
            .width('95%')
            .height(48)
            .borderRadius(8)
            .backgroundColor($r('app.color.main_color'))
            .fontColor('#FFFFFF')
            .fontSize(18)
            // .position({x:'2.5%'})
            .visibility(this.state==0||this.state==1||this.state==11||this.state==10
              ||this.state==9||this.state==3||this.state==4||this.state==5
              ||this.state==7?Visibility.Visible:Visibility.None)
            .onClick(() => {

              this.handleModify()


            })


        }
        .width('100%')
        .padding({top:50,bottom:20})
      }
      .width('100%')
      .height('100%')
      .padding(8)
      .backgroundImage($r('app.media.bg_reg'))
      .backgroundImageSize(ImageSize.FILL)
    }
    .height('auto')
    .scrollable(ScrollDirection.Vertical)
    // .scrollBar(BarState.Off)
    .backgroundColor('#ffffff')
  }
}

