EditUserInfoPage.ets 12.4 KB

import { CustomTitleUI } from '../reusable/CustomTitleUI';
import { EditListInfo, editModel, editModelParams, WDEditDataModelType } from '../../model/EditInfoModel';
import EditInfoViewModel from '../../viewmodel/EditInfoViewModel';
import { WDRouterPage, WDRouterRule } from 'wdRouter';
import {AreaPickerDialog} from '../view/areaPickerDialog/AreaPickerDialog'
import {EditUserInfoCustomDialog} from '../view/areaPickerDialog/EditUserInfoCustomDialog'
import {EditUserSexCustomDialog} from '../view/areaPickerDialog/EditUserSexCustomDialog'
import {CustomDialogUI} from '../view/areaPickerDialog/CustomDialogUI'
import {AreaListModel } from '../../model/AreaListModel';
import router from '@ohos.router';
import TrackingPageBrowseUtils from '../../utils/TrackingPageBrowseUtils'
import { TrackConstants } from 'wdTracking/Index';

import { SPHelper } from 'wdKit/Index';
import { SpConstants } from 'wdConstant/Index';

import { abilityAccessCtrl, common, Permissions } from '@kit.AbilityKit';
import { picker } from '@kit.CoreFileKit';
import { camera, cameraPicker } from '@kit.CameraKit';
import { BusinessError } from '@kit.BasicServicesKit';

let mContext = getContext(this) as common.Context;

const PERMISSIONS: Array<Permissions> = [
  'ohos.permission.READ_IMAGEVIDEO',
  'ohos.permission.WRITE_IMAGEVIDEO'
];
@Entry
@Component
struct EditUserInfoPage {
  @State listData: EditListInfo[] = []
  @State  headerImg: string = ''
  @State dataSource: AreaListModel[] = []
  @State currentUserInfo: editModel = {} as editModel
  @State topSafeHeight: number = AppStorage.get<number>('topSafeHeight') || 0
  @State bottomSafeHeight: number = AppStorage.get<number>('bottomSafeHeight') || 0

  userType:string = "1"

  @State firstSelect:number = 0
  @State secondSelect:number = 0
  @State thirdSelect:number = 0

  dialogController: CustomDialogController = new CustomDialogController({
    builder: AreaPickerDialog({dataSource:this.dataSource,firstSelect:this.firstSelect,secondSelect:this.secondSelect,thirdSelect:this.thirdSelect,
      confirmCallback:(province:string,city:string,county:string,address:string)=>{
        this.currentUserInfo.userExtend.province = province;
        this.currentUserInfo.userExtend.city = city;
        this.currentUserInfo.userExtend.county = county;
        this.currentUserInfo.userExtend.address = address;
        this.currentUserInfo.editDataType = WDEditDataModelType.WDEditDataModelType_region
        this.updateEditModel()
        this.getAreaIndex()
      }
    }),
    alignment: DialogAlignment.Bottom,
    customStyle: true,
    closeAnimation:{duration:0}
  })

  dateDialogController: CustomDialogController = new CustomDialogController({
    builder: EditUserInfoCustomDialog({
      confirmCallback:(selectDate:Date)=>{
        let mon = selectDate.getUTCMonth() as number + 1
        let monStr = mon.toString().padStart(2,'0')
        let dayStr = selectDate.getUTCDate().toString().padStart(2,'0')
        this.currentUserInfo.userExtend.birthday = selectDate.getUTCFullYear()+'-'+monStr+'-'+dayStr;
        this.currentUserInfo.editDataType = WDEditDataModelType.WDEditDataModelType_birthday
        this.updateEditModel()
      }
    }),
    alignment: DialogAlignment.Bottom,
    customStyle: true,
    closeAnimation:{duration:0}
  })

  sexDialogController: CustomDialogController = new CustomDialogController({
    builder: EditUserSexCustomDialog({
      confirmCallback:(index)=>{
        ///1男 2女
        this.currentUserInfo.userExtend.sex = index == 0?2:1;
        this.currentUserInfo.editDataType = WDEditDataModelType.WDEditDataModelType_sex
        this.updateEditModel()
      }
    }),
    alignment: DialogAlignment.Bottom,
    customStyle: true,
    closeAnimation:{duration:0}
  })

  photoDialogController: CustomDialogController = new CustomDialogController({
    builder: CustomDialogUI({
      itemData:['相册','拍照'],
      confirmCallback:(index)=>{
        if (index === 0) {
          this.getPhotoPicker()
        }else {
          this.getCamera()
        }
      }
    }),
    alignment: DialogAlignment.Bottom,
    customStyle: true,
    closeAnimation:{duration:0}
  })

  async getPhotoPicker(){
    ///权限查询
    const context = getContext(this) as common.UIAbilityContext;
    const atManager = abilityAccessCtrl.createAtManager();
    await atManager.requestPermissionsFromUser(context, PERMISSIONS);

    let PhotoSelectOptions = new picker.PhotoSelectOptions();
    PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE; // 过滤选择媒体文件类型
    PhotoSelectOptions.maxSelectNumber = 1; // 选择媒体文件的最大数目
    let photoPicker = new picker.PhotoViewPicker(); // 使用图库选择器对象前,需要先创建PhotoViewPicker实例
    photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult) => {
      if (PhotoSelectResult !== null && PhotoSelectResult !==
        undefined) {
        // 接口采用callback异步返回形式,返回PhotoSelectResult对象,故进行下一步操作前要先判断是否已经成功返回PhotoSelectResult对象了
        this.headerImg = PhotoSelectResult['photoUris'][0]
      }
    })
  }

  async getCamera(){
    try {
      let pickerProfile: cameraPicker.PickerProfile = {
        cameraPosition: camera.CameraPosition.CAMERA_POSITION_BACK
      };
      let pickerResult: cameraPicker.PickerResult = await cameraPicker.pick(mContext,
        [cameraPicker.PickerMediaType.PHOTO, cameraPicker.PickerMediaType.VIDEO], pickerProfile);
      if (pickerResult['resultCode'] === 0) {
        this.headerImg = pickerResult['resultUri']
      }
      console.log("the pick pickerResult is:" + JSON.stringify(pickerResult));
    } catch (error) {
      let err = error as BusinessError;
      console.error(`the pick call failed. error code: ${err.code}`);
    }
  }

  aboutToAppear() {
    let userType = SPHelper.default.getSync(SpConstants.USER_Type,"") as string
    if (userType && userType.length > 0) {
      this.userType = userType
    }

    this.getAccountOwnerInfo()
    this.getAreaList()
  }

  onPageShow(){
    this.updateUserNameAndIntroduction()
    TrackingPageBrowseUtils.TrackingPageBrowseExposureStart()
  }

  onPageHide(): void {
    TrackingPageBrowseUtils.TrackingPageBrowseExposureEnd(TrackConstants.PageName.Edit_Information,TrackConstants.PageName.Edit_Information)
  }

  build() {
    Row() {
      Column() {
        CustomTitleUI({titleName:'编辑资料'})

        Stack(){
          Image(this.headerImg)
            .alt($r('app.media.default_head'))
            .backgroundColor(Color.Gray)
            .width(84)
            .height(84)
            .borderRadius(42)

          if (this.headerImg.length === 0){
            Image('')
              .width('84')
              .height('84')
              .backgroundColor(Color.Gray)
              .opacity(0.7)
              .borderRadius(5)
              .borderRadius(42)

            Image($r('app.media.seletct_photo'))
              .width('30')
              .height('30')
          }
        }.margin({top:20})
        .onClick(()=>{
          this.photoDialogController.open()
        })

        ///目前不支持头像上传,暂时屏蔽
        Button('点击更换头像')
          .fontColor(Color.Gray)
          .fontSize(15)
          .backgroundColor(Color.White)
          .margin({top:10,bottom:20})

        List({}){
          ForEach(this.listData,(item:EditListInfo,index:number) =>{
            ListItem(){
              this.RouterItem(item,index+1)
            }
          }
          )
        }
        .layoutWeight(1)
        .alignListItem(ListItemAlign.Center)
        .width('100%')
      }
    }
    .width('100%')
    .height('100%')
    .padding({top:px2vp(this.topSafeHeight),bottom:px2vp(this.bottomSafeHeight)})
  }

  @Builder
  RouterItem(r:EditListInfo,i:Number){
    Column(){
      Row(){
        Text(r.title)
          .fontSize(15)
          .fontColor('#666666')
        Blank()

        Text(r.subTitle)
          .textOverflow({overflow:TextOverflow.Ellipsis})
          .maxLines(1)
          .fontSize(14)
          .fontColor(r.subTitle === '待完善'?'#cccccc':'#666666')
          .padding({right:10})
          .width('70%')
          .textAlign(TextAlign.End)

        Image($r('app.media.mine_user_edit'))
          .width('12')
          .height('12')
      }
      .alignItems(VerticalAlign.Center)
      .width('100%')
      .padding(16)

      Divider()
        .width('90%')
    }
    .height(60)
    .width('100%')
    .onClick(()=>{
      if (i === 1){
        // TODO 缺失特殊用户判断
        let params: editModelParams = {
          editContent: this.currentUserInfo.userName
        }
        WDRouterRule.jumpWithPage(WDRouterPage.editUserNikeNamePage,params)
      }else if (i === 2){
        let params: editModelParams = {
          editContent: this.currentUserInfo.userExtend.introduction
        }
        WDRouterRule.jumpWithPage(WDRouterPage.editUserIntroductionPage,params)
      }else if (i === 3){
        this.dialogController.open()
      } else if (i === 4) {
        this.dateDialogController.open()
      }else if(i === 5){
        this.sexDialogController.open()
      }
    })
  }

  updateUserNameAndIntroduction(){
    let  backParams:editModelParams =  router.getParams() as editModelParams;
    if (backParams) {
      let userName = backParams.userName as string ///昵称
      let introduction = backParams.introduction as string ///简介
      this.listData = []
      if (userName) {
        if (userName != this.currentUserInfo.userName) {
          this.currentUserInfo.userName = userName;
          this.currentUserInfo.editDataType = WDEditDataModelType.WDEditDataModelType_nickname
          this.listData.push(...EditInfoViewModel.getEditListInfo(this.currentUserInfo))
          // this.updateEditModel()
          // this.getAccountOwnerInfo()
        }
      } else if (introduction){
        if (introduction != this.currentUserInfo.userExtend.introduction ) {
          this.currentUserInfo.userExtend.introduction = introduction;
          this.currentUserInfo.editDataType = WDEditDataModelType.WDEditDataModelType_intro
          this.listData.push(...EditInfoViewModel.getEditListInfo(this.currentUserInfo))
          // this.updateEditModel()
          // this.getAccountOwnerInfo()
        }
      }
    }
  }

  updateEditModel(){
    // this.listData.push(...EditInfoViewModel.getEditListInfo(this.currentUserInfo))
    EditInfoViewModel.updateUserInfo(this.currentUserInfo).then(()=>{
      this.getAccountOwnerInfo()
    })
  }

  async  getAccountOwnerInfo(){

    if (this.userType === '1') {
      EditInfoViewModel.queryAccountOwnerInfo(getContext(this)).then((editModel) => {
        this.listData = []
        if (editModel.userExtend?.headPhotoUrl) {
          this.headerImg = editModel.userExtend.headPhotoUrl
        }
        this.currentUserInfo = editModel as editModel;
        this.listData.push(...EditInfoViewModel.getEditListInfo(editModel))
      });
    }else {
      EditInfoViewModel.queryPeopleAccountOwnerInfo(getContext(this)).then((peopleItem) => {
        EditInfoViewModel.queryAccountOwnerInfo(getContext(this)).then((editM) => {
          this.listData = []
          editM.userExtend.introduction = peopleItem.introduction
          editM.userName = peopleItem.userName
          this.headerImg = peopleItem.headPhotoUrl
          this.currentUserInfo = editM as editModel;
          this.listData.push(...EditInfoViewModel.getEditListInfo(editM))
        });
      });
    }
  }

  getAreaList(){
    EditInfoViewModel.getAreaList(getContext(this)).then((value) =>{
      this.dataSource.push(...value)
      this.getAreaIndex()
    })
  }

  getAreaIndex(){
    ///地区选择器当前位置
    if (this.currentUserInfo.userExtend.province.length > 0) {
      this.dataSource.forEach((element,index) => {
        if (element.label === this.currentUserInfo.userExtend.province) {
          this.firstSelect = index
          let currentFirst = EditInfoViewModel.getAreaListManageModel(element)
          currentFirst.children.forEach((element,index) => {
            if (element.label === this.currentUserInfo.userExtend.city) {
              this.secondSelect = index
              let currentSecondBean = EditInfoViewModel.getAreaListManageModel(element)
              currentSecondBean.children.forEach((element,index) => {
                if (element.label === this.currentUserInfo.userExtend.county) {
                  this.thirdSelect = index
                }
              });
            }
          });
        }
      });
    }
  }
}