1/*
2 * Copyright (c) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16import UIExtensionContentSession from '@ohos.app.ability.UIExtensionContentSession';
17import { CustomContentDialog, ButtonOptions } from '@ohos.arkui.advanced.Dialog';
18import GlobalContext from '../common/GlobalContext';
19import { GetAlertMessage } from '../common/GetAlertMessage';
20import common from '@ohos.app.ability.common';
21import Want from '@ohos.app.ability.Want';
22import { BusinessError } from '@ohos.base';
23import Constants from '../common/constant';
24import ability from '@ohos.ability.ability';
25import account_osAccount from '@ohos.account.osAccount';
26import dlpPermission from '@ohos.dlpPermission';
27import { sendDlpManagerAccountLogin, checkNetworkStatus } from '../common/utils';
28import { HiLog } from '../common/HiLog';
29
30const TAG = 'Alert';
31let abilityResult: ability.AbilityResult = {
32  'resultCode': 0,
33  'want': {}
34};
35
36let storage = LocalStorage.getShared();
37@Entry(storage)
38@Component
39struct Index {
40  @State dialogUIExtWant: Want | undefined = GlobalContext.load('dialogUIExtWant');
41  @State session: UIExtensionContentSession | undefined =
42    storage === undefined ? undefined : storage.get<UIExtensionContentSession>('session');
43  @State title: ResourceStr = '';
44  @State message: ResourceStr = '';
45  @State cancel: ResourceStr = '';
46  @State actionButton: ResourceStr = '';
47  @State buttonOptions: ButtonOptions[] = [];
48
49  dialogControllerButton: CustomDialogController | null = new CustomDialogController({
50    builder: CustomContentDialog({
51      primaryTitle: this.title,
52      contentBuilder: () => {
53        this.buildContent();
54      },
55      buttons: this.buttonOptions
56    }),
57    autoCancel: false,
58    maskColor: Constants.TRANSPARENT_BACKGROUND_COLOR
59  });
60
61  async authWithPop(): Promise<void> {
62    HiLog.info(TAG, `authwithpop start`);
63    try {
64      await checkNetworkStatus();
65    } catch {
66      let errInfo = GetAlertMessage.getAlertMessage(
67        { code: Constants.ERR_JS_APP_NETWORK_INVALID } as BusinessError);
68      this.title = '';
69      this.message = errInfo.msg;
70      this.cancel = errInfo.cancel;
71      this.buttonOptions = [{
72        value: this.cancel ? this.cancel : $r('app.string.da_button'),
73        background: $r('sys.color.ohos_id_color_button_normal'), action: () => {
74          abilityResult.resultCode = 0;
75          (getContext(this) as common.UIAbilityContext).terminateSelfWithResult(abilityResult);
76      }}];
77      this.dialogControllerButton?.open();
78      HiLog.info(TAG, `network failed`);
79      return;
80    };
81    try {
82      account_osAccount.DomainAccountManager.authWithPopup({
83        onResult: async (resultCode: number, authResult: account_osAccount.AuthResult) => {
84          sendDlpManagerAccountLogin(resultCode);
85          HiLog.info(TAG, `auth resultCode: ${resultCode}`);
86          HiLog.info(TAG, `auth authResult: ${JSON.stringify(authResult)}`);
87        }
88      })
89      abilityResult.resultCode = 0;
90      (getContext(this) as common.UIAbilityContext).terminateSelfWithResult(abilityResult);
91    } catch (err) {
92      HiLog.info(TAG, `auth exception: ${JSON.stringify(err)}`);
93    }
94  }
95
96  getErrInfo(messageCode: number, errorMsg: BusinessError, accountType: number) {
97    let errInfo: Record<string, Resource> = {};
98    if ([
99      Constants.ERR_JS_APP_PARAM_ERROR,
100      Constants.ERR_JS_APP_OPEN_REJECTED,
101      Constants.ERR_JS_APP_ENCRYPTION_REJECTED,
102      Constants.ERR_JS_APP_ENCRYPTING,
103      Constants.ERR_JS_FILE_EXPIRATION,
104      Constants.ERR_JS_DLP_FILE_READ_ONLY,
105      Constants.ERR_JS_SYSTEM_NEED_TO_BE_UPGRADED,
106    ].includes(messageCode)) {
107      errInfo = GetAlertMessage.getAlertTitleMessage(errorMsg);
108    } else if ([Constants.ERR_JS_APP_SYSTEM_IS_AUTHENTICATED].includes(messageCode)) {
109      errInfo = GetAlertMessage.getAlertButtonMessage(errorMsg);
110    } else if ([Constants.ERR_JS_USER_NO_PERMISSION].includes(messageCode)) {
111      errInfo = accountType === dlpPermission.AccountType.CLOUD_ACCOUNT ?
112      GetAlertMessage.getAlertMessage(errorMsg) : GetAlertMessage.getAlertTitleMessage(errorMsg);
113    } else {
114      errInfo = GetAlertMessage.getAlertMessage(errorMsg);
115    }
116    this.title = errInfo.title;
117    this.message = errInfo.msg;
118    this.cancel = errInfo.cancel;
119    this.actionButton = errInfo.ok;
120    this.buttonOptions = [{
121      value: this.cancel ? this.cancel : $r('app.string.da_button'),
122      background: $r('sys.color.ohos_id_color_button_normal'), action: () => {
123        abilityResult.resultCode = 0;
124        (getContext(this) as common.UIExtensionContext).terminateSelfWithResult(abilityResult);
125      }}];
126    if (errInfo.ok) {
127      this.buttonOptions.push({ value: this.actionButton, background: $r('sys.color.ohos_id_color_text_primary_activated'),
128        fontColor: $r('sys.color.font_on_primary'), action: () => {
129          this.authWithPop();
130        }});
131    }
132    this.dialogControllerButton?.open();
133  }
134
135  async aboutToAppear() {
136    HiLog.info(TAG, `alert aboutToAppear start`);
137    try {
138      let messageCode = -1;
139      let errorMsg = {} as BusinessError;
140      let accountType = -1;
141      if (this.session === undefined) {
142        errorMsg = this.dialogUIExtWant?.parameters?.error as BusinessError;
143        messageCode = errorMsg.code;
144        accountType = this.dialogUIExtWant?.parameters?.accountType as number;
145      } else {
146        errorMsg = storage.get('error') as BusinessError;
147        messageCode = errorMsg.code;
148        accountType = dlpPermission.AccountType.DOMAIN_ACCOUNT;
149      }
150      this.getErrInfo(messageCode, errorMsg, accountType);
151    } catch (err) {
152      HiLog.error(TAG, `showErrorDialog failed: ${JSON.stringify(err)}`);
153    }
154  }
155
156  aboutToDisappear() {
157    this.dialogControllerButton = null;
158  }
159
160  build() {
161  }
162
163  @Builder
164  buildContent(): void {
165    Column() {
166      Text() {
167        Span(this.message)
168      }
169    }
170    .width(Constants.HEADER_TEXT_WIDTH)
171    .align(this.title ? Alignment.Start : Alignment.Center)
172    .margin({
173      bottom: Constants.START_ABILITY_CUSTOM_CONTENT_MARGIN_BOTTOM
174    })
175  }
176}
177