import {  hdHttp, HdResponse,BasicConstant, logger,LoginInfo, authStore } from '@itcast/basic'
import HashMap from '@ohos.util.HashMap'
import { BusinessError } from '@kit.BasicServicesKit';
import { promptAction, router } from '@kit.ArkUI'
import { EditUserDataItem } from './EditUserDataItem'
import { PhotoActionSheet } from './PhotoActionSheet'
import { DatePickerDialog } from './DatePickerDialog'
import { OfficeSelectedSheet } from './OfficeSelectedSheet'
import { PositionSelectedSheet } from './PositionSelectedSheet'
import { http } from '@kit.NetworkKit';

interface LoginParams {
  uuid: string
}

@Component
export struct EditUserDataComp {
  @State photoPath:string = BasicConstant.imageHeader+authStore.getUser().photo;
  @State name:string = authStore.getUser().realName;
  @State sex:string = authStore.getUser().sex == 0 ? '男' : '女';
  @State birthday:string = authStore.getUser().birthDate;
  @State phone:string = authStore.getUser().mobile;
  @State email:string = authStore.getUser().email;

  @State hospatilName:string = authStore.getUser().hospitalName;
  @State officeName:string = authStore.getUser().officeName;
  @State officePhone:string = authStore.getUser().officePhone;
  @State positionName:string = authStore.getUser().positionName;
  @State certificate:string = authStore.getUser().certificate;
  @State certificatePhoto:string = BasicConstant.imageHeader+authStore.getUser().certificateImg;
  @State diseaseName:string = '';
  @State intro:string = authStore.getUser().intro;

  private photoSheetDialog!: CustomDialogController;
  private datePickerDialog!: CustomDialogController;
  private officePickerDialog!: CustomDialogController;
  private positionPickerDialog!: CustomDialogController;
  private certificatePhotoSheetDialog!: CustomDialogController;

  aboutToAppear() {
    this.initPhotoDialog();
    this.initDatePickerDialog();
    this.initOfficePickerDialog();
    this.initPositionPickerDialog();
    this.initCerficatePhotoDialog();

    this.uploadUserDataAction();
    console.log('用户资料：'+authStore.getUser().specialy);
  }

  uploadUserDataAction() {
    const hashMap: HashMap<string, string> = new HashMap();
    const userDataUrl:string = BasicConstant.urlExpert+'getExpertByUuid';
    hashMap.set('uuid',authStore.getUser().uuid)
    hdHttp.post<string>(userDataUrl, {
      uuid: authStore.getUser().uuid,
    } as LoginParams).then(async (res: HdResponse<string>) => {
      logger.info('Response login111'+res);
      console.info(`Response login succeeded333: ${res}`);
    }).catch((err: BusinessError) => {
      console.info(`Response login fail222222222222222: ${err}`);
    })


    // hdHttp.oldPost<string>(userDataUrl,hashMap).then(async (res: HdResponse<string>) => {
    //   console.info(`Response officelist succeeded: ${res}`);
    //   let json:LoginInfo = JSON.parse(res+'') as LoginInfo;
    //   if(json.code=='1') {
    //     authStore.setUser(json.data)
    //     console.log('用户信息成功:', json);
    //   } else {
    //     console.error('用户信息失败：'+json.message)
    //     promptAction.showToast({ message: json.message, duration: 1000 })
    //   }
    // }).catch((err: BusinessError) => {
    //     console.error(`Response login fail: ${err}`);
    // })
    // hdHttp.httpReq<string>(userDataUrl,hashMap).then(async (res: HdResponse<string>) => {
    //   logger.info('Response officelist success'+res);
    //   console.info(`Response officelist succeeded: ${res}`);
    //   let json:LoginInfo = JSON.parse(res+'') as LoginInfo;
    //   if(json.code=='1') {
    //     authStore.setUser(json.data)
    //     console.log('用户信息成功:', json);
    //   } else {
    //     console.error('用户信息失败：'+json.message)
    //     promptAction.showToast({ message: json.message, duration: 1000 })
    //   }
    // }).catch((err: BusinessError) => {
    //   console.info(`Response login fail: ${err}`);
    // })
  }

  arrToStringSpecialy(specialy: Array<object>) {
    // 声明类型化数组
    let zhuangArr: string[] = [];
    // 获取响应数据中的specialy数组（需根据实际API调整类型）
    const array = specialy['specialy'] as Array<Record<string, string>>;
    // 遍历提取diseaseName
    if (specialy) {
      zhuangArr = array
        .filter(item => item['diseaseName']) // 过滤空值[8](@ref)
        .map(item => item['diseaseName'] ?? ''); // 安全转换[9](@ref)
    }
    // 拼接为逗号分隔字符串
    const DiseaseName = zhuangArr.join(','); // 等效componentsJoinedByString[8](@ref)
    return DiseaseName;
  }

  private initPhotoDialog() {
    this.photoSheetDialog = new CustomDialogController({
      builder: PhotoActionSheet({
        controller: this.photoSheetDialog,
        onPhotoSelected: (uri: string) => {
          this.photoPath = uri;
          console.log('Selected image URI:', 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;
        }
      }),
      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;
        }
      }),
      alignment: DialogAlignment.Bottom,
      customStyle: true,
      autoCancel: false,
      backgroundColor: ('rgba(0,0,0,0.5)'),
      height: '100%'
    })
  }

  private initDatePickerDialog() {
    this.datePickerDialog = new CustomDialogController({
      builder: DatePickerDialog({
        controller:this.datePickerDialog,
        dateSelected:(date:string) => {
          this.birthday = date;
        }
      }),
      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: (uri: string) => {
          this.certificatePhoto = uri;
          console.log('Selected image URI:', uri);
        }
      }),
      alignment: DialogAlignment.Bottom,
      customStyle: true,
      autoCancel: false,
      backgroundColor: ('rgba(0,0,0,0.5)'),
      height: '100%'
    });
  }

  build() {
    Scroll() {
      Column() {
        // 第一部分：基本资料
        Column() {
          Column(){
            Text('基本资料')
              .fontSize(16)
              .margin({left:15})
              .fontColor($r('app.color.main_color'))
          }
          .width('100%')
          .height(17)
          .backgroundColor(Color.Gray)
          .alignItems(HorizontalAlign.Start)
          // 基本信息字段
          EditUserDataItem({ label: '头像', required: true, content: this.photoPath, hasArrow: true })
            .onClick(()=>this.photoSheetDialog.open())
          EditUserDataItem({ label: '姓名', required: true, content: this.name })
          EditUserDataItem({ label: '性别', required: true, content: this.sex })
          EditUserDataItem({ label: '出生日期', content: this.birthday , hasArrow: true})
            .onClick(()=>this.datePickerDialog.open())
          EditUserDataItem({ label: '手机号码', required: true, content: this.phone , hasArrow: true})
            .onClick(()=>{
              router.pushUrl({
                url:'pages/MinePage/ChangePhonePage'
              })
            })
          EditUserDataItem({ label: '邮箱', content: this.email , hasArrow: true})
            .onClick(()=>{
              router.pushUrl({
                url:'pages/MinePage/ChooseEmail'
              })
            })
        }
        .height('auto')

        // 第二部分：专业资料
        Column() {
          Column(){
            Text('专业资料')
              .fontSize(16)
              .margin({left:15})
              .fontColor($r('app.color.main_color'))
          }
          .width('100%')
          .height(17)
          .backgroundColor(Color.Gray)
          .alignItems(HorizontalAlign.Start)

          EditUserDataItem({ label: '医院', required: true, content: this.hospatilName })
          EditUserDataItem({ label: '科室', required: true, content: this.officeName, hasArrow: true })
            .onClick(()=>this.officePickerDialog.open())
          EditUserDataItem({ label: '科室电话', required: true, content: this.officePhone, hasArrow: true })
            .onClick(()=>{
              router.pushUrl({
                url:'pages/MinePage/ChooseOfficePhone'
              })
            })
          EditUserDataItem({ label: '职称', required: true, content: this.positionName, hasArrow: true })
            .onClick(()=>this.positionPickerDialog.open())
          EditUserDataItem({ label: '执业医师证编号', required: true, content: this.certificate })
          EditUserDataItem({ label: '执业医师证图片或胸牌', required: true, content: this.certificatePhoto })
            .onClick(()=>this.certificatePhotoSheetDialog.open())
          EditUserDataItem({ label: '专长', required: true, content: this.diseaseName , hasArrow: true})
          EditUserDataItem({ label: '个人简介', content: this.intro, hasArrow: true })
            .onClick(()=>{
              router.pushUrl({
                url:'pages/MinePage/EditIntroductionPage'
              })
            })
        }
        .height('auto')
      }
      .width('100%')
      .height('100%')
      .layoutWeight(1)// 占据剩余空间
    }
    .height('auto')
    .scrollBar(BarState.Off)
    .scrollable(ScrollDirection.Vertical)
    .backgroundColor('#ffffff')
  }
}
