import {  hdHttp, HdResponse,BasicConstant,ExpertData, authStore,RequestDefaultModel } from '@itcast/basic'
import { BusinessError } from '@kit.BasicServicesKit';
import { HeroPopWindow } from '../view/HeroPopWindow'
import HashMap from '@ohos.util.HashMap'
import { router } from '@kit.ArkUI'

interface extraData {
  uuid: string
}

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

interface heroFirst {
  id: string;
  nick_name: string;
}

@Preview
@Component
export struct HeaderView {
  @State heroIndex: number = 0  // 当前页索引
  @State photoPath:string = BasicConstant.urlImage+authStore.getUser().photo;
  @State name:string = authStore.getUser().realName;
  @State myPageData:object = new Object;
  @State heroArray:Array<object> = [];

  private scrollerForList: Scroller = new Scroller()
  private heroList: string[] = ['2020年英雄榜','2021年英雄榜','2022年英雄榜','2023年英雄榜','2024年英雄榜']

  dialogController: CustomDialogController = new CustomDialogController({
    builder: HeroPopWindow(),
    alignment: DialogAlignment.Center,
    customStyle: true
  })

  aboutToAppear(): void {
    this.uploadUserDataAction();
    this.uploadBackImgAction();
  }

  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 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)
        console.log('用户信息成功:', authStore.getUser().intro);
      } else {
        console.error('用户信息失败：'+json.message)
      }
    }).catch((err: BusinessError) => {
      console.info(`Response login fail222222222222222: ${err}`);
    })
  }

  uploadBackImgAction() {
    const hashMap: HashMap<string, string> = new HashMap();
    const userDataUrl:string = BasicConstant.urlExpertAPI+'my';
    hdHttp.httpReq<string>(userDataUrl,hashMap).then(async (res: HdResponse<string>) => {
      console.info(`我的背景图: ${res}`);
      let json:RequestDefaultModel = JSON.parse(res+'') as RequestDefaultModel;
      if(json.code == '200') {
        this.myPageData = json.data;
        // 获取ranking值（带安全类型转换）
        const ranking: string = this.myPageData["ranking"]?.toString() ?? "";
        if (Number(ranking) > 0) {
          // 创建排名对象[4](@ref)
          const rankDic: heroFirst = {
            "id": "ranking",
            "nick_name": `随访达人 I 排名${ranking}`
          };
          // 插入数组首位[9](@ref)
          this.heroArray.unshift(rankDic);
        }
      } else {
        console.error('我的背景图：'+json.message)
      }
    }).catch((err: BusinessError) => {
      console.info(`Response login fail: ${err}`);
    })
  }

  handleAvatarClick() {
    router.pushUrl({url:'pages/MinePage/EditUserDataPage'})
  }

  build() {
    // Row() {
      Column({space:5}) {
        Row({space:10}) {
          Image(this.photoPath)
            .alt($r('app.media.userPhoto_default'))
            .margin({left:15})
            .width(60)
            .height(60)
            .borderRadius(5)
            .objectFit(ImageFit.Fill)
            .onClick(()=>this.handleAvatarClick())
          Column({space:5}) {
            Text(this.name)
              .fontSize(18)
              .fontColor('#FFFFFF')
              .onClick(()=>this.handleAvatarClick())
            List({space:5,initialIndex:this.heroIndex,scroller:this.scrollerForList}) {
              ForEach(this.heroArray, (item: object,index:number) => {
                ListItem() {
                  Row() {
                    Image($r('app.media.my_home_hero_ranking'))
                      .width(13)
                      .height(13)
                      .margin({left:7})
                    Text(item["nick_name"])
                      .fontColor(Color.White)
                      .fontSize(11)
                      .margin({left:4,right:10})
                  }
                  .height(18)
                  .margin({right:5})
                  .borderRadius(9)
                  .borderWidth(1)
                  .borderColor(Color.White)
                  .onClick(() => {
                    console.log('Show HeroPopWindow');
                  })
                  .onClick(()=>{
                    this.dialogController.open();
                    // if (!this.heroArray[index] as heroFirst == 'ranking') {
                    //   this.dialogController.open(heroId:this.heroArray[index]['id'] as string);
                    // }
                  })
                }
              })
            }
            .listDirection(Axis.Horizontal)
            .scrollBar(BarState.Off)
            .width('100%')
            .height(18)
          }
          .alignItems(HorizontalAlign.Start)
          .height(60)
          .width('70%')
          .margin({top:22})
        }
        .width('100%')
        .height(97)
      }
      .width('100%')
      .height(97)
      .backgroundImage(this.myPageData["myInfoBackGround"]).backgroundImageSize(ImageSize.Cover)
    }
  // }
}
