import { HMRouter, HMRouterMgr } from '@hadss/hmrouter';
import { common } from '@kit.AbilityKit';

import { AppCache, AUTH_SYSCODE } from '../../app/AppCache';
import { UserCache } from '../../app/UserCache';
import { StringUtils } from '../../util/StringUtils';
import { UserInfoModel } from '../../model/cacheModel/UserInfoModel';
import { buffer, util } from '@kit.ArkTS';
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { ToastUtils } from '../../util/ToasUtils';
import { createWaterMark } from '../custom/Watermark';
import { AuthUserModel, IAuthTaskType } from '../../model/uiModel/IAuthTaskType';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { RuanseeAbilityStag } from '../../app/RuanseeAbilityStag';
import { DialogAction, ToastUtil } from '@pura/harmony-utils';
import { AnHuiAddressModel } from '../../model/uiModel/AnHuiAddressModel';
import { DialogHelper } from '@pura/harmony-dialog';
import { preferences } from '@kit.ArkData';

@HMRouter({ pageUrl: 'StartPage' })
@Component
export struct StartPage {
  @State message: string = '正在初始化...';
  context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  ipAddress: string | undefined = undefined

  aboutToAppear() {
    this.context.eventHub.on('NotPermissions', (data: string) => {
      if (data) {
        this.showNotPermissionsDialog()
      }
    });
    this.context.eventHub.on('PermissionsSuccess', (data: string) => {
      RuanseeAbilityStag.appCache.setPermissionsStatus = true
      this.getIpAddress();
    });
  }

  aboutToDisappear(): void {
    this.context.eventHub.off('NotPermissions')
    this.context.eventHub.off('PermissionsSuccess')
  }

  onPageHide(): void {

  }

  onPageShow(): void {

  }

  showNotPermissionsDialog() {
    let dialogID = DialogHelper.showAlertDialog({
      content: "由于您拒绝了应用的权限，应用无法正常运行，请前往设置页面授权！",
      onAction: (action) => {
        if (action == DialogAction.ONE) {
          DialogHelper.closeDialog(dialogID)
          HMRouterMgr.pop({ pageUrl: 'StartPage' })
          this.context.terminateSelf()
        } else if (action == DialogAction.TWO) {
          DialogHelper.closeDialog(dialogID)
          // 确认操作处理
          this.jumpToAppDetails()
          HMRouterMgr.pop({ pageUrl: 'StartPage' })
          this.context.terminateSelf()
        }
      }
    })
  }

  jumpToAppDetails() {
    const context = getContext() as common.UIAbilityContext;
    context.startAbility({
      bundleName: 'com.huawei.hmos.settings',
      abilityName: 'com.huawei.hmos.settings.MainAbility',
      uri: 'application_info_entry', // 固定值表示应用详情页
      parameters: {
        pushParams: context.abilityInfo.bundleName // 当前应用包名
      }
    });
  }

  //TODO 测试登录信息
  testLogin(){
    let userCache = RuanseeAbilityStag.userCache
    userCache.setUserName = "陈乐（测试账号）"
    userCache.setUserCode = "999013"
    userCache.setDeptCode = '340012000000'
    userCache.setDeptName = "测试单位001"
    userCache.setIdCardNum = "420113199310297548"
    // userCache.setAuthToken = authUserModel.token
    // userCache.setProfilePhoto = StringUtils.get(authUserModel.profilePhoto, "")
    userCache.setPhoneNum = '18815656560'
    // userCache.setEmail = StringUtils.get(authUserModel.email, "")
    userCache.setWorkPhone = '19915155150'
    // userCache.setPoliceTypeId = StringUtils.get(authUserModel.policeTypeId, "")
    // userCache.setPoliceTypeName = StringUtils.get(authUserModel.policeTypeName, "")
    userCache.setBirthdate = '19931029'
    userCache.setAge = 32
    let departmentCode = userCache.getDeptCode.substring(0, 4)
    let departmentName = new  AnHuiAddressModel().getAddress(departmentCode)
    userCache.setDepartmentCode = departmentCode
    userCache.setDepartmentName = departmentName
    this.handUserInfo(this.ipAddress)
  }

  authLogin() {
    let pref = preferences.getPreferencesSync(this.context, { name: 'AppStore' });
    let isUpdate = pref.getSync('updateUserInfo',false)


    let want: Want = {
      bundleName: 'hm.anhui.police.auth',
      abilityName: 'OhosAuthAbility',
      parameters: {
        'action': 'getAuthUser',
        // 'IAuthTaskType': isUpdate?IAuthTaskType.AUTH_TASK_START_AUTH:IAuthTaskType.AUTH_TASK_USER,
        'IAuthTaskType': IAuthTaskType.AUTH_TASK_USER,
        'packageName': 'com.ycgis.macall.personalcenter',
        'sysCode': AUTH_SYSCODE
      }
    };
    try {
      this.context.startAbilityForResult(want, (err: BusinessError, result: common.AbilityResult) => {
        if (err.code) {
          // 处理业务逻辑错误
          console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`);
          return;
        }
        // 执行正常业务
        console.info(`startAbility succeed resultCode：${result.resultCode} result:${JSON.stringify(result)}  want:${JSON.stringify(want)}`);
        if (result.resultCode === -1) {
          this.message = '未获取到用户信息';
          return;
        }
        pref.put('updateUserInfo',false)
        const iAuthTaskType = result.want?.parameters?.IAuthTaskType
        const message = result.want?.parameters?.message
        if (iAuthTaskType === IAuthTaskType.AUTH_TASK_USER) {
          this.message = `开始处理认证数据`;
          let authUser = result.want?.parameters?.authUser;
          hilog.info(0x0000, 'carousel', '%{public}s', `authUser:${authUser}`);
          if (result.resultCode === 200) {
            // 获取到用户信息
            let authUserModel = JSON.parse(StringUtils.get(authUser, "")) as AuthUserModel
            if (authUserModel) {
              let userCache = RuanseeAbilityStag.userCache
              userCache.setUserName = authUserModel.realName
              userCache.setUserCode = authUserModel.userNum
              userCache.setDeptCode = authUserModel.orgId
              userCache.setDeptName = authUserModel.orgName
              userCache.setIdCardNum = authUserModel.code
              userCache.setAuthToken = authUserModel.token
              userCache.setProfilePhoto = StringUtils.get(authUserModel.profilePhoto, "")
              userCache.setPhoneNum = StringUtils.get(authUserModel.phoneNum, "")
              userCache.setEmail = StringUtils.get(authUserModel.email, "")
              userCache.setWorkPhone = StringUtils.get(authUserModel.workPhone, "")
              userCache.setPoliceTypeId = StringUtils.get(authUserModel.policeTypeId, "")
              userCache.setPoliceTypeName = StringUtils.get(authUserModel.policeTypeName, "")
              userCache.setBirthdate = StringUtils.get(authUserModel.birthdate, "")
              userCache.setAge = StringUtils.getNumber(authUserModel.age, 0)
              let departmentCode = userCache.getDeptCode.substring(0, 4)
              userCache.setDepartmentCode = departmentCode
              userCache.setDepartmentName = new  AnHuiAddressModel().getAddress(departmentCode)
              this.handUserInfo(this.ipAddress)
            } else {
              this.loginError(`获取用户信息失败！${message}}`);
            }
          } else if (result.resultCode === 100) {
            this.message = `用户主动关闭登录页面，未获取到用户信息`;
            this.loginError(`用户主动关闭登录页面，未获取到用户信息`);
          } else {
            this.message = `未获取到用户信息，错误码(${result.resultCode})`;
            this.loginError(`未获取到用户信息，错误码(${result.resultCode})`);
          }
        } else {
          this.message = `获取用户信息失败:${result.want?.parameters?.message}`;
          this.loginError(`获取用户信息失败:${result.want?.parameters?.message}`);
        }
      });
    } catch (err) {
      // 处理入参错误异常
      let code = (err as BusinessError).code;
      let message = (err as BusinessError).message;
      console.error(`startAbility failed, code is ${code}, message is ${message}`);
      this.loginError(`startAbility failed, code is ${code}, message is ${message}`);
    }
  }

  loginError(msg: string) {
    ToastUtil.showLong(msg)
    setTimeout(() => {
      HMRouterMgr.pop({ pageUrl: 'StartPage' })
      this.context.terminateSelf()
    }, 1500)
  }

  handUserInfo(ipAddress: string | undefined) {
    let appCache = AppCache.getAppCache();
    let userCache = UserCache.getUserCache();
    appCache.setIpOrPort('20.90.2.2', '80', "/ypc_test_out/")
    //设置用户信息，后期改成单点登录获取用户信息
    // userCache.setUserName = "陈乐（测试）"
    // userCache.setUserCode = "999013"
    // userCache.setDeptName = "测试单位001"
    // userCache.setDeptCode = "340012000000"
    // userCache.setIdCardNum = "420113199310297548"

    // let departmentCode = userCache.getUserCode.substring(0, 4)
    // let departmentName = new  AnHuiAddressModel().getAddress(departmentCode)
    // userCache.setDepartmentCode = departmentCode
    // userCache.setDepartmentName = departmentName

    //本机IP
    appCache.setLocalIp = StringUtils.get(ipAddress, "10.115.101.1");

    let userInfos = userCache.getUserInfo();
    if (StringUtils.isNullOrEmpty(userInfos)) {
      let cs: UserInfoModel = {
        "userCode": userCache.getUserCode,
        "userName": userCache.getUserName,
        "deptName": userCache.getDeptName,
        "deptCode": userCache.getDeptCode,
        "idCardNum": userCache.getIdCardNum,
        "ip": appCache.setLocalIp,
        "departmentCode": userCache.getDepartmentCode,
        "departmentName": userCache.getDepartmentName,
      }
      let userInfo = JSON.stringify(cs)
      let byte = new Uint8Array(buffer.from(userInfo, 'utf-8').buffer);
      userCache.setUserInfo = new util.Base64Helper().encodeToStringSync(byte);
    }

    setTimeout(() => {
      this.message = "正在获取用户信息..."
      if (appCache.getPermissionsStatus) {
        this.jumpAdPage();
      }
    }, 500)
  }

  /**
   * 获取IP地址
   */
  getIpAddress() {
    let defNet = connection.getDefaultNet()
    defNet.then((netHandle: connection.NetHandle) => {
      connection.getConnectionProperties(netHandle, (error: BusinessError, data: connection.ConnectionProperties) => {
        if (error) {
          console.error(`Failed to get connection properties. Code:${error.code}, message:${error.message}`);
          ToastUtils.toastBottom("获取IP地址失败！")
          // this.testLogin()
          this.authLogin()
          return;
        }
        console.info("Succeeded to get data: " + JSON.stringify(data));
        try {
          let ip = data['linkAddresses'][0]['address']['address']
          console.info('本地ip：', ip)
          this.ipAddress = ip
          // this.testLogin()
          this.authLogin()
        } catch (e) {
          console.error("e", JSON.stringify(e));
          ToastUtils.toastBottom("获取IP地址失败！")
          // this.testLogin()
          this.authLogin()
        }
      });
    }).catch((error: Error) => {
      console.error("e", JSON.stringify(error));
      this.loginError(error.message);
    })
  }

  build() {
    Column() {
      Image($r('app.media.icon_applogin'))
        .width(100)
        .aspectRatio(1)
        .margin({ top: 190 });

      Text($r('app.string.EntryAbility_label'))
        .fontSize($r('app.float.text_size_24'))
        .fontColor($r('app.color.bull'))
        .fontWeight(700)
        .letterSpacing(1)
        .margin({
          top: $r('app.float.default_20'),
          bottom: $r('app.float.default_8')
        })

      Text(this.message)
        .fontColor($r('app.color.grad'))
        .fontSize($r("app.float.text_size_14"))
        .margin({ top: 32 })

      Text($r('app.string.ownership_dept'))
        .fontColor($r('app.color.grad'))
        .fontSize($r("app.float.text_size_14"))
        .height('100%')
        .margin({ bottom: $r('app.float.default_20') })

    }
    .width('100%')
    .height('100%')
    .expandSafeArea([SafeAreaType.SYSTEM])
    .overlay(createWaterMark())
  }

  /**
   * 跳转主页
   */
  jumpAdPage() {
    setTimeout(() => {
      this.message = "正在跳转..."
      HMRouterMgr.replace({ navigationId: 'startNavigation', pageUrl: "MainPage" })
    }, 800);
  }
}