import {  hdHttp, HdResponse,BasicConstant,ExpertData, 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 { SpecialitySelectedSheet } from './SpecialitySelectedSheet'
import { http } from '@kit.NetworkKit';

interface extraData {
  uuid: string
}

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

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

interface UploadAvatarResponse {
  url:string;
  uploadAvatarUrl:string,
}

@Component
export struct EditUserDataComp {
  @State photoPath:string = BasicConstant.urlImage+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.urlImage+authStore.getUser().certificateImg;
  @State diseaseName:string = '';
  @State intro:string = authStore.getUser().intro;

  @State updateDataUrl:string = BasicConstant.urlExpert + 'modify';

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

  aboutToAppear() {
    this.initPhotoDialog();
    this.initDatePickerDialog();
    this.initOfficePickerDialog();
    this.initPositionPickerDialog();
    this.initCerficatePhotoDialog();
    this.initDiseaseSheetDIalog();
    this.uploadUserDataAction();
    console.log('用户资料：'+authStore.getUser().specialy);
  }

  // 添加public修饰符暴露方法
  public refreshData() {
    this.uploadUserDataAction();
  }

  uploadUserDataAction() {
    const userDataUrl:string = BasicConstant.urlExpert+'getExpertByUuid';
    hdHttp.post<string>(userDataUrl, {
      uuid: authStore.getUser().uuid,
    } as extraData).then(async (res: HdResponse<string>) => {
      let json:callBackData = JSON.parse(res+'') as callBackData;
      if(json.code == 1 && json.expert && typeof json.expert === 'object') {
        authStore.updateUser(json.expert)
        this.arrToStringSpecialy(json.specialy);
        console.log('用户信息成功:', authStore.getUser().intro);
      } else {
        console.error('用户信息失败：'+json.message)
        promptAction.showToast({ message: json.message, duration: 1000 })
      }
    }).catch((err: BusinessError) => {
      console.info(`Response login fail222222222222222: ${err}`);
    })
  }

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

  private initPhotoDialog() {
    this.photoSheetDialog = new CustomDialogController({
      builder: PhotoActionSheet({
        controller: this.photoSheetDialog,
        onPhotoSelected: async (url: string) => {
          this.photoPath = url;
          console.log('Selected image URI:', url);
          try {
            promptAction.showToast({ message: '正在上传图片...', duration: 2000 });
            // 调用上传方法，使用明确的返回类型
            const response = await hdHttp.uploadImage<UploadAvatarResponse>(
              this.updateDataUrl,
              url
            );
            if (response.code === 1) {
              promptAction.showToast({ message: '图片上传成功' });
              console.log('上传成功，返回数据:', response.data);
              // 处理上传成功后的逻辑
              // this.currentUser.avatar = response.data.avatarUrl;
            } else {
              promptAction.showToast({ message: response.message || '图片上传失败' });
            }
          } catch (error) {
            console.error('图片上传出错:', error);
            promptAction.showToast({ message: '图片上传出错，请重试' });
          }
        }
      }),
      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;
            hdHttp.post<string>(this.updateDataUrl, {
              uuid: authStore.getUser().uuid,
              userName: authStore.getUser().userName,
              officeName: name,
              officeUuid:uuid,
              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)
                this.arrToStringSpecialy(json.special);
                console.log('更新用户信息科室成功:', authStore.getUser().intro);
              } else {
                console.error('更新用户信息科室失败：'+json.message)
                promptAction.showToast({ message: json.message, duration: 1000 })
              }
            }).catch((err: BusinessError) => {
              console.info(`更新用户信息职称科室失败: ${err}`);
            })
          }
      }),
      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;
          hdHttp.post<string>(this.updateDataUrl, {
            uuid: authStore.getUser().uuid,
            userName: authStore.getUser().userName,
            positionUuid: uuid,
            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)
              this.arrToStringSpecialy(json.special);
              console.log('更新用户信息职称成功:', authStore.getUser().intro);
            } else {
              console.error('更新用户信息职称失败：'+json.message)
              promptAction.showToast({ message: json.message, duration: 1000 })
            }
          }).catch((err: BusinessError) => {
            console.info(`更新用户信息职称请求失败: ${err}`);
          })
        }
      }),
      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;
          hdHttp.post<string>(this.updateDataUrl, {
            uuid: authStore.getUser().uuid,
            userName: authStore.getUser().userName,
            birthDate: date,
            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)
              this.arrToStringSpecialy(json.special);
              console.log('更新用户信息生日成功:', authStore.getUser().intro);
            } else {
              console.error('更新用户信息生日失败：'+json.message)
              promptAction.showToast({ message: json.message, duration: 1000 })
            }
          }).catch((err: BusinessError) => {
            console.info(`更新用户信息生日请求失败: ${err}`);
          })
        }
      }),
      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: (url: string) => {
          this.certificatePhoto = 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)=>{
          hdHttp.post<string>(this.updateDataUrl, {
            uuid: authStore.getUser().uuid,
            userName: authStore.getUser().userName,
            diseaseUuids: diseaseUuids,
            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)
              this.arrToStringSpecialy(json.special);
              console.log('更新用户信息专长成功:', authStore.getUser().intro);
            } else {
              console.error('更新用户信息专长失败：'+json.message)
              promptAction.showToast({ message: json.message, duration: 1000 })
            }
          }).catch((err: BusinessError) => {
            console.info(`更新用户信息专长请求失败: ${err}`);
          })
        }
      }),
      alignment: DialogAlignment.Bottom,
      customStyle: true,
      autoCancel: false,
      backgroundColor: ('rgba(0,0,0,0.5)'),
      height: '100%'
    })
  }

  build() {
    Scroll() {
      Column() {
        // 第一部分：基本资料
        Column() {
          Column(){
            Text('基本资料')
              .height(20)
              .fontSize(16)
              .margin({left:15})
              .fontColor($r('app.color.main_color'))
          }
          .width('100%')
          .height(20)
          .backgroundColor('#D1D1D1')
          .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',
                params:{
                  onBack:()=>{
                    this.uploadUserDataAction();
                  }
                }
              })
            })
          EditUserDataItem({ label: '邮箱', content: this.email , hasArrow: true})
            .onClick(()=>{
              router.pushUrl({
                url:'pages/MinePage/ChooseEmail'
              })
            })
        }
        .height('auto')

        // 第二部分：专业资料
        Column() {
          Column(){
            Text('专业资料')
              .height(20)
              .fontSize(16)
              .margin({left:15})
              .fontColor($r('app.color.main_color'))
          }
          .width('100%')
          .height(20)
          .backgroundColor('#D1D1D1')
          .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})
            .onClick(()=>this.diseaseSheetDialog.open())
          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')
  }
}
