import { HMRouter } from "@hadss/hmrouter";
import { AxiosError, AxiosResponse } from "@ohos/axios";
import { DialogHelper } from "@pura/harmony-dialog";
import { FileUtil, ImageUtil, JSONUtil } from "@pura/harmony-utils";
import { ToastUtil } from "@pura/harmony-utils/src/main/ets/action/ToastUtil";
import AppConstants from "../../app/AppConstant";
import { RuanseeAbilityStag } from "../../app/RuanseeAbilityStag";
import { downLoadUserPhoto, updateWorkPhone, uploadUserPhoto } from "../../request/Api";
import { FileUtils } from "../../util/FileUtils";
import { StringUtils } from "../../util/StringUtils";
import { BaseTopBar } from "../custom/BaseTopTar";
import { createWaterMark } from "../custom/Watermark";
import { fileIo, fileUri, picker } from "@kit.CoreFileKit";
import { camera, cameraPicker } from "@kit.CameraKit";
import { photoAccessHelper } from "@kit.MediaLibraryKit";
import { DateUtil } from "@pura/harmony-utils/src/main/ets/utils/DateUtil";
import { StrUtil } from "@pura/harmony-utils/src/main/ets/utils/StrUtil";
import { common } from "@kit.AbilityKit";
import { preferences } from "@kit.ArkData";

@Component
@HMRouter({ pageUrl: "MyUserInfoPage" })
export struct MyUserInfoPage {
  @State userPhoto: string | Resource = $r('app.media.icon_police_woman')
  @State workPhone: string = RuanseeAbilityStag.userCache.getWorkPhone
  dialogId: string = ''

  aboutToAppear(): void {
    this.getImage()
  }

  getImage() {
    if (FileUtil.accessSync(FileUtils.IMAGE_DIR + '/' + RuanseeAbilityStag.userCache.getProfilePhoto)) {
      this.userPhoto = fileUri.getUriFromPath(FileUtils.IMAGE_DIR + '/' + RuanseeAbilityStag.userCache.getProfilePhoto)
      return
    }
    downLoadUserPhoto(FileUtils.IMAGE_DIR + '/' + RuanseeAbilityStag.userCache.getProfilePhoto)
      .then((res: AxiosResponse) => {
        console.info("result:" + JSON.stringify(res.data));
        if (res.status == 200) {
          this.userPhoto =
            fileUri.getUriFromPath(FileUtils.IMAGE_DIR + '/' + RuanseeAbilityStag.userCache.getProfilePhoto)
        }
      })
      .catch((error: AxiosError) => {
        console.error("error:" + JSON.stringify(error));
      })
  }

  showUpdatePhone() {
    DialogHelper.showTextInputDialog({
      title: "修改工作号码",
      fontColor: $r('app.color.colorGrey8'),
      fontSize: $r('app.float.text_size_16'),
      inputHeight: $r('app.float.default_40'),
      maxLength: 11,
      defaultFocus: true,
      inputBorder: {
        width: $r('app.float.default_1'),
        color: $r('app.color.colorGrey2'),
        radius: $r('app.float.default_5'),
      },
      text: this.workPhone,
      placeholder: '请输入手机号码',
      placeholderColor: $r('app.color.colorGrey6'),
      onAction: (action: number, dialogId: string, value: string) => {
        DialogHelper.closeDialog(dialogId)
        if (action == -1) {
        }
        if (action == -2) {
          this.updatePhone(value);
        }
      }
    })
  }

  updatePhone(value: string) {
    if (StringUtils.isNullOrEmpty(value)) {
      ToastUtil.showToast("请输入手机号码！")
      return
    }
    if (this.workPhone ==  value) {
      ToastUtil.showToast("请修改手机号码！")
      return
    }
    updateWorkPhone(value)
      .then((res) => {
        console.debug("updatePhone", JSON.stringify(res))
        ToastUtil.showToast(res.msg)
        if (res.code == 200) {
          this.workPhone = value
          RuanseeAbilityStag.userCache.setWorkPhone = value
          let context = getContext(this) as  common.UIAbilityContext;
          let pref = preferences.getPreferencesSync(context, { name: 'AppStore' });
          pref.put('updateUserInfo',false)
        }
      })
      .catch((err: AxiosError) => {
        console.error("updatePhone", JSON.stringify(err))
        ToastUtil.showToast("修改失败")
      })
  }

  async selectImage() {
    let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
    let photoPicker = new photoAccessHelper.PhotoViewPicker();
    // 过滤选择媒体文件类型为IMAGE
    photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_VIDEO_TYPE;
    // 设置最大选择数量
    photoSelectOptions.maxSelectNumber = 1;
    let chooseFile: picker.PhotoSelectResult = await photoPicker.select(photoSelectOptions);
    let newFilePath = FileUtils.IMAGE_DIR + '/' + DateUtil.getTodayTime() + ".jpg";
    let newFileUri = fileUri.getUriFromPath(newFilePath)
    let isCopy = await FileUtils.copyToLocal(chooseFile.photoUris[0], newFileUri)
    if (isCopy) {
      newFileUri = await ImageUtil.compressPhoto(newFileUri, 260);
      this.updatePhoto(newFileUri)
    } else {
      ToastUtil.showToast("复制文件失败！")
    }
  }

  /**
   * 拍照
   */
  async takePhoto() {
    let pathDir = FileUtils.IMAGE_DIR;
    let fileName = `${new Date().getTime()}.JPEG`
    let filePath = `${pathDir}/${fileName}`
    let imageFileUri: string | undefined = undefined;
    fileIo.createRandomAccessFileSync(filePath, fileIo.OpenMode.CREATE);

    let fileUris = fileUri.getUriFromPath(filePath);
    let pickerProfile: cameraPicker.PickerProfile = {
      cameraPosition: camera.CameraPosition.CAMERA_POSITION_BACK,
      saveUri: fileUris,
    };
    let result: cameraPicker.PickerResult =
      await cameraPicker.pick(getContext(), [cameraPicker.PickerMediaType.PHOTO],
        pickerProfile);
    console.info(`picker resultCode: ${result.resultCode},resultUri: ${result.resultUri},mediaType: ${result.mediaType}`);
    if (result.resultCode == 0) {
      if (result.mediaType === cameraPicker.PickerMediaType.PHOTO) {
        imageFileUri = result.resultUri
        imageFileUri = await ImageUtil.compressPhoto(imageFileUri, 150);
        this.updatePhoto(imageFileUri);
      }
    } else {
      ToastUtil.showToast("取消选择")
    }
  }

  /**
   * 更新图片
   * @param imageFileUri
   */
  updatePhoto(imageFileUri: string) {
    //自定义文字内容
    this.dialogId = DialogHelper.showLoadingDialog({
      loadColor: Color.White,
      content: "正在上传,请稍后...",
      fontSize: 15,
      backgroundColor: '#ED000000',
      autoCancel: true,
      onWillDismiss: () => {
        DialogHelper.closeDialog(this.dialogId)
        this.dialogId = ''
      }
    })

    //常见问题
    uploadUserPhoto(imageFileUri)
      .then((res) => {
        DialogHelper.closeDialog(this.dialogId)
        console.debug("updatePhoto", JSON.stringify(res))
        if (res.code == 200) {
          this.userPhoto = imageFileUri
         let data = res.data;
          if(data){
            let id :string=  data['id']
            if(StrUtil.isNotEmpty(id)){
              FileUtil.renameSync(FileUtil.getFilePath(imageFileUri),FileUtils.IMAGE_DIR+"/"+id);
              RuanseeAbilityStag.userCache.setProfilePhoto = id
              this.userPhoto = fileUri.getUriFromPath(FileUtils.IMAGE_DIR+"/"+id);
              let context = getContext(this) as  common.UIAbilityContext;
              context.eventHub.emit('updateUserPhoto')
              let pref = preferences.getPreferencesSync(context, { name: 'AppStore' });
              pref.put('updateUserInfo',false)
            }
          }
        }
      })
      .catch((err: AxiosError) => {
        DialogHelper.closeDialog(this.dialogId)
        console.error("updatePhoto", JSON.stringify(err))
      })
  }

  showUpdatePhoto() {
    //带标题
    DialogHelper.showActionSheetDialog({
      title: "选择头像",
      titleFontColor: Color.Black,
      cancelFontColor: Color.Red,
      cancelFontWeight: FontWeight.Normal,
      sheets: ['相机', '相册'],
      onAction: (index) => {
        switch (index) {
          case 0:
            this.takePhoto()
            break;
          case 1:
            this.selectImage()
            break;
        }
      }
    })
  }

  build() {
    Column() {
      BaseTopBar({
        title: $r('app.string.title_user_info'),
      })

      Row() {

        Text("头像")
          .fontColor($r('app.color.colorGrey8'))
          .fontSize($r('app.float.text_size_16'))

        Blank()
          .layoutWeight(1)

        Image(this.userPhoto)
          .width($r('app.float.default_68'))
          .height($r('app.float.default_52'))
          .onClick(() => {
            this.showUpdatePhoto()
          })

        Image($r('app.media.arrow_right'))
          .width($r('app.float.default_22'))
          .height($r('app.float.default_22'))
          .margin({ left: $r('app.float.default_10') })

      }
      .padding($r('app.float.default_10'))
      .width(AppConstants.PERCENTAGE_MAX)
      .height('auto')
      .alignItems(VerticalAlign.Center)
      .backgroundColor($r('app.color.white'))

      Divider()
        .width(AppConstants.PERCENTAGE_MAX)
        .height($r('app.float.default_1'))
        .backgroundColor($r('app.color.colorGrey2'))

      Row() {

        Text("姓名")
          .fontColor($r('app.color.colorGrey8'))
          .fontSize($r('app.float.text_size_16'))

        Blank()
          .layoutWeight(1)

        Text(RuanseeAbilityStag.userCache.getUserName)
          .fontColor($r('app.color.colorGrey8'))
          .fontSize($r('app.float.text_size_16'))

        Image($r('app.media.arrow_right'))
          .width($r('app.float.default_22'))
          .height($r('app.float.default_22'))
          .visibility(Visibility.Hidden)
          .margin({ left: $r('app.float.default_10') })

      }
      .width(AppConstants.PERCENTAGE_MAX)
      .alignItems(VerticalAlign.Center)
      .backgroundColor($r('app.color.white'))
      .padding($r('app.float.default_10'))

      Divider()
        .width(AppConstants.PERCENTAGE_MAX)
        .height($r('app.float.default_1'))
        .backgroundColor($r('app.color.colorGrey2'))

      Row() {

        Text("警号")
          .fontColor($r('app.color.colorGrey8'))
          .fontSize($r('app.float.text_size_16'))

        Blank()
          .layoutWeight(1)

        Text(RuanseeAbilityStag.userCache.getUserCode)
          .fontColor($r('app.color.colorGrey8'))
          .fontSize($r('app.float.text_size_16'))

        Image($r('app.media.arrow_right'))
          .width($r('app.float.default_22'))
          .height($r('app.float.default_22'))
          .visibility(Visibility.Hidden)
          .margin({ left: $r('app.float.default_10') })

      }
      .width(AppConstants.PERCENTAGE_MAX)
      .alignItems(VerticalAlign.Center)
      .backgroundColor($r('app.color.white'))
      .padding($r('app.float.default_10'))

      Blank()
        .width(AppConstants.PERCENTAGE_MAX)
        .height($r('app.float.default_10'))

      Row() {

        Text("职位")
          .fontColor($r('app.color.colorGrey8'))
          .fontSize($r('app.float.text_size_16'))

        Blank()
          .layoutWeight(1)

        Text(StringUtils.get(RuanseeAbilityStag.userCache.getPoliceTypeName, "暂无"))
          .fontColor($r('app.color.colorGrey8'))
          .fontSize($r('app.float.text_size_16'))

        Image($r('app.media.arrow_right'))
          .width($r('app.float.default_22'))
          .height($r('app.float.default_22'))
          .visibility(Visibility.Hidden)
          .margin({ left: $r('app.float.default_10') })

      }
      .width(AppConstants.PERCENTAGE_MAX)
      .alignItems(VerticalAlign.Center)
      .backgroundColor($r('app.color.white'))
      .padding($r('app.float.default_10'))

      Divider()
        .width(AppConstants.PERCENTAGE_MAX)
        .height($r('app.float.default_1'))
        .backgroundColor($r('app.color.colorGrey2'))

      Row() {

        Text("单位")
          .fontColor($r('app.color.colorGrey8'))
          .fontSize($r('app.float.text_size_16'))

        Blank()
          .layoutWeight(1)

        Text(RuanseeAbilityStag.userCache.getDeptName)
          .fontColor($r('app.color.colorGrey8'))
          .fontSize($r('app.float.text_size_16'))

        Image($r('app.media.arrow_right'))
          .width($r('app.float.default_22'))
          .height($r('app.float.default_22'))
          .visibility(Visibility.Hidden)
          .margin({ left: $r('app.float.default_10') })

      }
      .width(AppConstants.PERCENTAGE_MAX)
      .alignItems(VerticalAlign.Center)
      .backgroundColor($r('app.color.white'))
      .padding($r('app.float.default_10'))

      Blank()
        .width(AppConstants.PERCENTAGE_MAX)
        .height($r('app.float.default_10'))

      Row() {

        Text("证件号码")
          .fontColor($r('app.color.colorGrey8'))
          .fontSize($r('app.float.text_size_16'))

        Blank()
          .layoutWeight(1)

        Text(RuanseeAbilityStag.userCache.getIdCardNum)
          .fontColor($r('app.color.colorGrey8'))
          .fontSize($r('app.float.text_size_16'))

        Image($r('app.media.arrow_right'))
          .width($r('app.float.default_22'))
          .height($r('app.float.default_22'))
          .visibility(Visibility.Hidden)
          .margin({ left: $r('app.float.default_10') })

      }
      .width(AppConstants.PERCENTAGE_MAX)
      .alignItems(VerticalAlign.Center)
      .backgroundColor($r('app.color.white'))
      .padding($r('app.float.default_10'))

      Divider()
        .width(AppConstants.PERCENTAGE_MAX)
        .height($r('app.float.default_1'))
        .backgroundColor($r('app.color.colorGrey2'))

      Row() {

        Text("工作号码")
          .fontColor($r('app.color.colorGrey8'))
          .fontSize($r('app.float.text_size_16'))

        Blank()
          .layoutWeight(1)

        Text(this.workPhone)
          .fontColor($r('app.color.colorGrey8'))
          .fontSize($r('app.float.text_size_16'))

        Image($r('app.media.arrow_right'))
          .width($r('app.float.default_22'))
          .height($r('app.float.default_22'))
          .margin({ left: $r('app.float.default_10') })

      }
      .width(AppConstants.PERCENTAGE_MAX)
      .alignItems(VerticalAlign.Center)
      .backgroundColor($r('app.color.white'))
      .padding($r('app.float.default_10'))
      .onClick(() => {
        this.showUpdatePhone();
      })
    }
    .width(AppConstants.PERCENTAGE_MAX)
    .height(AppConstants.PERCENTAGE_MAX)
    .overlay(createWaterMark())
    .backgroundColor($r('app.color.page_background'))
  }
}