1/**
2 * Copyright (c) 2022 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 MorandiColor from '../model/bean/MorandiColor';
17import dataShare from '@ohos.data.dataShare';
18import dataSharePredicates from '@ohos.data.dataSharePredicates';
19import { ContactVo } from '../model/bean/ContactVo';
20import { ContactInfo } from '../model/bean/ContactInfo';
21import { ContactRepository } from '../../../../../feature/contact/src/main/ets/repo/ContactRepository';
22import { DataItem } from '../../../../../feature/contact/src/main/ets/entity/DataItem';
23import { DataItemType } from '../../../../../feature/contact/src/main/ets/contract/DataType';
24import { Data } from '../../../../../feature/contact/src/main/ets/contract/Data';
25import { RawContacts } from '../../../../../feature/contact/src/main/ets/contract/RawContacts';
26import { Contacts } from '../../../../../feature/contact/src/main/ets/contract/Contacts';
27import { HiLog } from '../../../../../common/src/main/ets/util/HiLog';
28import { StringUtil } from '../../../../../common/src/main/ets/util/StringUtil';
29import { ArrayUtil } from '../../../../../common/src/main/ets/util/ArrayUtil';
30import { CallLogRepository } from '../../../../../feature/call/src/main/ets/repo/CallLogRepository';
31import { PhoneNumber } from '../../../../../feature/phonenumber/src/main/ets/PhoneNumber';
32import { FavoriteBean } from './bean/FavoriteBean';
33import { CallLog } from '../../../../../feature/call/src/main/ets/entity/CallLog';
34import { SearchContactsBean } from './bean/SearchContactsBean';
35
36const TAG = 'ContactAbility: ';
37const PROFILE_CONTACT_DATA_URI = 'datashare:///com.ohos.contactsdataability/profile/contact_data';
38
39export default {
40  /**
41   * Add Contact
42   *
43   * @param {Object} addParams Contact Information
44   * @param {Object} callBack
45   */
46  addContact: async function (addParams: ContactInfo, callBack?, context?) {
47    HiLog.i(TAG, 'Start to create a new contact.');
48    if (addParams == undefined || addParams == null) {
49      HiLog.e(TAG, 'The addParams of parameter is NULL');
50      return '';
51    }
52    let DAHelper = await dataShare.createDataShareHelper(context ? context : globalThis.context, Contacts.CONTENT_URI);
53    let insertValues = {
54      'display_name': this.getDisplayName(addParams),
55    };
56    DAHelper.insert(
57    RawContacts.CONTENT_URI,
58      insertValues
59    ).then(data => {
60      if (data == -1 || data == undefined) {
61        HiLog.e(TAG, 'Data inserted failed');
62        return;
63      }
64      addParams.id = data.toString();
65      this.dealParam(DAHelper, addParams, false, callBack);
66    }).catch(error => {
67      HiLog.e(TAG, 'logMessage insert error: ' + JSON.stringify(error.message));
68    });
69    HiLog.i(TAG, 'End of creating a contact.');
70  },
71
72  /**
73   * Read the name, which needs to be optimized.
74   * Edit Contact
75   *
76   * @param {Object} addParams Contact Information
77   * @return {string} Contact Name
78   */
79  getDisplayName: function (addParams: ContactInfo): String {
80    let displayName = '';
81    if (addParams.display_name != undefined && addParams.display_name.length > 0) {
82      displayName = addParams.display_name;
83    } else if (addParams.nickname != undefined && addParams.nickname.length > 0) {
84      displayName = addParams.nickname;
85    } else if (addParams.hasOwnProperty('company') && addParams.company.length > 0) {
86      displayName = addParams.company;
87    } else if (addParams.hasOwnProperty('position') && addParams.position.length > 0) {
88      displayName = addParams.position;
89    } else if (addParams.hasOwnProperty('phones') && addParams.phones.length > 0) {
90      for (let element of addParams.phones) {
91        if (StringUtil.isEmpty(element.num)) {
92          continue;
93        }
94        displayName = PhoneNumber.fromString(element.num).getNumber();
95        break;
96      }
97    }
98    return displayName;
99  },
100
101  /**
102   * Convert the data to the database.
103   *
104   * @param {string} DAHelper Database path
105   * @param {Object} addParams Contact Information
106   * @param {boolean} isCard Indicates whether the information is a business card.
107   */
108  dealParam: function (DAHelper, addParams: ContactInfo, isCard, callBack) {
109    let result = addParams.id;
110    let uri = isCard ? PROFILE_CONTACT_DATA_URI : Data.CONTENT_URI;
111
112    this.dataContact(addParams, DAHelper, result, uri);
113    this.organizationContact(addParams, DAHelper, result, uri);
114    this.noteContact(addParams, DAHelper, result, uri);
115    this.phoneContact(addParams, DAHelper, result, uri);
116    this.emailContact(addParams, DAHelper, result, uri);
117    this.postalContact(addParams, DAHelper, result, uri);
118    this.eventContact(addParams, DAHelper, result, uri);
119    this.imContact(addParams, DAHelper, result, uri);
120    this.groupsContact(addParams, DAHelper, result, uri);
121    this.websiteContact(addParams, DAHelper, result, uri);
122    this.nickContact(addParams, DAHelper, result, uri);
123    this.relationsContact(addParams, DAHelper, result, uri);
124
125    if (callBack != undefined) {
126      HiLog.d(TAG, 'Start the callback function.');
127      callBack(addParams.id);
128    }
129  },
130
131  /**
132   * Save the contact name to the database.
133   *
134   * @param {Object} addParams Contact Information
135   * @param {string} DAHelper Database path
136   * @param {string} result Contact ID
137   * @param {string} uri Database address
138   */
139  dataContact: function (addParams, DAHelper, result, uri) {
140    let displayName = '';
141    let updateFlag = 0;
142    if (addParams.display_name != undefined && addParams.display_name.length > 0) {
143      displayName = addParams.display_name;
144    } else {
145      updateFlag = 1;
146      displayName = this.getDisplayName(addParams);
147    }
148
149    if (displayName.length > 0) {
150      let dataContact = {
151        'raw_contact_id': result,
152        'detail_info': displayName,
153        'alpha_name': displayName,
154        'phonetic_name': addParams.hasOwnProperty('phonetic_name') ? (addParams.phonetic_name) : '',
155        'other_lan_last_name': addParams.hasOwnProperty('other_lan_last_name') ? (addParams.other_lan_last_name) : '',
156        'other_lan_first_name': addParams.hasOwnProperty('other_lan_first_name') ? (addParams.other_lan_first_name) : '',
157        'type_id': 6,
158        'extend7': updateFlag
159      };
160      DAHelper.insert(
161        uri,
162        dataContact
163      ).then(data => {
164        if (data == -1) {
165          HiLog.e(TAG, 'name-insert data failed!');
166        }
167        HiLog.d(TAG, 'name-insert data success!');
168      }).catch(err => {
169        HiLog.e(TAG, 'name-insert failed. Cause: ' + JSON.stringify(err.message));
170      });
171    }
172  },
173
174  /**
175   * Save the contact nickname information to the database.
176   *
177   * @param {Object} addParams Contact Information
178   * @param {string} DAHelper Database path
179   * @param {number} result Contact ID
180   * @param {string} uri Database address
181   */
182  nickContact: function (addParams, DAHelper, result, uri) {
183    if (addParams.nickname != undefined && addParams.nickname.length > 0) {
184      let nickContact = {
185        'raw_contact_id': result,
186        'detail_info': addParams.nickname,
187        'type_id': 9,
188      };
189      DAHelper.insert(
190        uri,
191        nickContact
192      ).then(data => {
193        if (data == -1) {
194          HiLog.e(TAG, 'nickname-insert data failed!');
195        }
196        HiLog.d(TAG, 'nickname-insert data success!');
197      }).catch(err => {
198        HiLog.e(TAG, 'nickname-insert failed. Cause: ' + JSON.stringify(err.message));
199      });
200    }
201  },
202  /**
203   * Save the position information of the contact company to the database.
204   *
205   * @param {Object} addParams Contact Information
206   * @param {string} DAHelper Database path
207   * @param {string} result Contact ID
208   * @param {string} uri Database address
209   */
210  organizationContact: function (addParams, DAHelper, result, uri) {
211    let company = '';
212    let position = '';
213    if (addParams.company != undefined && addParams.company.length > 0) {
214      company = addParams.company;
215    }
216    if (addParams.position != undefined && addParams.position.length > 0) {
217      position = addParams.position;
218    }
219    if (addParams.company != undefined && addParams.company.length > 0
220    || addParams.position != undefined && addParams.position.length > 0) {
221      let organizationContact = {
222        'raw_contact_id': result,
223        'detail_info': company,
224        'position': position,
225        'type_id': 4,
226      };
227      DAHelper.insert(
228        uri,
229        organizationContact
230      ).then(data => {
231        if (data == -1) {
232          HiLog.e(TAG, 'organizationContact-insert data failed!');
233        }
234        HiLog.d(TAG, 'organizationContact-insert data success!');
235      }).catch(error => {
236        HiLog.e(TAG, 'organizationContact-insert failed. Cause: ' + JSON.stringify(error.message));
237      });
238    }
239  },
240
241  /**
242   * Save the contact remarks to the database.
243   *
244   * @param {Object} addParams Contact Information
245   * @param {string} DAHelper Database path
246   * @param {number} result Contact ID
247   * @param {string} uri Database address
248   */
249  noteContact: function (addParams, DAHelper, result, uri) {
250    if (addParams.remarks != undefined && addParams.remarks.length > 0) {
251      let noteContact = {
252        'raw_contact_id': result,
253        'detail_info': addParams.remarks,
254        'type_id': 10,
255      };
256      DAHelper.insert(
257        uri,
258        noteContact
259      ).then(data => {
260        if (data == -1) {
261          HiLog.e(TAG, 'noteContact-insert data failed!');
262        }
263        HiLog.d(TAG, 'noteContact-insert insert data success!');
264      }).catch(error => {
265        HiLog.e(TAG, 'noteContact-insert failed. Cause: ' + JSON.stringify(error.message));
266      });
267    }
268  },
269
270  /**
271   * The contact mobile number information is saved to the database.
272   *
273   * @param {Object} addParams Contact Information
274   * @param {string} DAHelper Database path
275   * @param {number} result Contact ID
276   * @param {string} uri Database address
277   */
278  phoneContact: function (addParams, DAHelper, result, uri) {
279    if (addParams.phones != undefined && addParams.phones.length > 0) {
280      let index = 1;
281      addParams.phones.forEach(element => {
282        if (StringUtil.isEmpty(element.num)) {
283          return;
284        }
285        let phoneContact = {
286          'raw_contact_id': result,
287          'detail_info': element.num,
288          'extend7': (index++).toString(),
289          'custom_data': element.numType,
290          'type_id': 5,
291        };
292        DAHelper.insert(
293          uri,
294          phoneContact
295        ).then(data => {
296          if (data == -1) {
297            HiLog.e(TAG, 'phoneContact-insert data failed!');
298          }
299          HiLog.d(TAG, 'phoneContact-insert data success!');
300        }).catch(error => {
301          HiLog.e(TAG, 'phoneContact-insert failed. Cause: ' + JSON.stringify(error.message));
302        });
303      });
304    }
305  },
306
307  /**
308   * Save the contact email information to the database.
309   *
310   * @param {Object} addParams Contact Information
311   * @param {string} DAHelper Database path
312   * @param {number} result Contact ID
313   * @param {string} uri Database address
314   */
315  emailContact: function (addParams, DAHelper, result, uri) {
316    if (addParams.emails != undefined && addParams.emails.length > 0) {
317      let index = 1;
318      addParams.emails.forEach(element => {
319        if (StringUtil.isEmpty(element.address)) {
320          return;
321        }
322        let emailContact = {
323          'raw_contact_id': result,
324          'detail_info': element.address,
325          'extend7': (index++).toString(),
326          'custom_data': element.emailType,
327          'type_id': 1,
328        };
329        DAHelper.insert(
330          uri,
331          emailContact
332        ).then(data => {
333          if (data == -1) {
334            HiLog.e(TAG, 'emailContact-insert data failed!');
335          }
336          HiLog.d(TAG, 'emailContact-insert data success!');
337        }).catch(error => {
338          HiLog.e(TAG, 'emailContact-insert failed. Cause: ' + JSON.stringify(error.message));
339        });
340      });
341    }
342  },
343
344  /**
345   * The contact address information is saved to the database.
346   *
347   * @param {Object} addParams Contact Information
348   * @param {string} DAHelper Database path
349   * @param {number} result Contact ID
350   * @param {string} uri Database address
351   */
352  postalContact: function (addParams, DAHelper, result, uri) {
353    if (addParams.houses != undefined && addParams.houses.length > 0) {
354      let index = 1;
355      addParams.houses.forEach(element => {
356        if (StringUtil.isEmpty(element.houseName)) {
357          return;
358        }
359        let postalContact = {
360          'raw_contact_id': result,
361          'detail_info': element.houseName,
362          'extend7': (index++).toString(),
363          'custom_data': element.houseType,
364          'type_id': 7,
365        };
366        DAHelper.insert(
367          uri,
368          postalContact
369        ).then(data => {
370          if (data == -1) {
371            HiLog.e(TAG, 'postalContact-insert data failed!');
372          }
373          HiLog.d(TAG, 'postalContact-insert data success!');
374        }).catch(error => {
375          HiLog.e(TAG, 'postalContact-insert failed. Cause: ' + JSON.stringify(error.message));
376        });
377      });
378    }
379  },
380
381
382  /**
383   * Save the contact special date information to the database.
384   *
385   * @param {Object} addParams Contact Information
386   * @param {string} DAHelper Database path
387   * @param {number} result Contact ID
388   * @param {string} uri Database address
389   */
390  eventContact: function (addParams, DAHelper, result, uri) {
391    if (addParams.events != undefined && addParams.events.length > 0) {
392      let index = 1;
393      addParams.events.forEach(element => {
394        if (StringUtil.isEmpty(element.data)) {
395          return;
396        }
397        let eventContact = {
398          'raw_contact_id': result,
399          'detail_info': element.data,
400          'extend7': (index++).toString(),
401          'custom_data': element.eventType,
402          'type_id': 11
403        };
404        DAHelper.insert(
405          uri,
406          eventContact
407        ).then(data => {
408          if (data == -1) {
409            HiLog.e(TAG, 'eventContact-insert data failed!');
410          }
411          HiLog.d(TAG, 'eventContact-insert data success!');
412        }).catch(error => {
413          HiLog.e(TAG, 'eventContact-insert failed. Cause: ' + JSON.stringify(error.message));
414        });
415      });
416    }
417  },
418
419  /**
420   * Save the contact IMA information to the database.
421   *
422   * @param {Object} addParams Contact Information
423   * @param {string} DAHelper Database path
424   * @param {number} result Contact ID
425   * @param {string} uri Database address
426   */
427  imContact: function (addParams, DAHelper, result, uri) {
428    if (addParams.aims != undefined && addParams.aims.length > 0) {
429      let index = 1;
430      addParams.aims.forEach(element => {
431        if (StringUtil.isEmpty(element.aimName)) {
432          return;
433        }
434        let imContact = {
435          'raw_contact_id': result,
436          'detail_info': element.aimName,
437          'extend7': (index++).toString(),
438          'custom_data': element.aimType,
439          'type_id': 2,
440        };
441        DAHelper.insert(
442          uri,
443          imContact
444        ).then(data => {
445          if (data == -1) {
446            HiLog.e(TAG, 'imContact-insert data failed!');
447          }
448          HiLog.d(TAG, 'imContact-insert data success!');
449        }).catch(error => {
450          HiLog.e(TAG, 'imContact-insert failed. Cause: ' + JSON.stringify(error.message));
451        });
452      });
453    }
454  },
455
456  /**
457   * Save the contact group information to the database.
458   *
459   * @param {Object} addParams Contact Information
460   * @param {string} DAHelper Database path
461   * @param {number} result Contact ID
462   * @param {string} uri Database address
463   */
464  groupsContact: function (addParams, DAHelper, result, uri) {
465    if (addParams.groups != undefined && addParams.groups.length > 0) {
466      addParams.groups.forEach(element => {
467        let groupsContact = {
468          'raw_contact_id': result,
469          'detail_info': element.groupName,
470          'extend7': element.groupId + '',
471          'custom_data': element.groupType,
472          'type_id': 9,
473        };
474        DAHelper.insert(
475          uri,
476          groupsContact
477        ).then(data => {
478          if (data == -1) {
479            HiLog.e(TAG, 'groupsContact-insert data failed!');
480          }
481          HiLog.d(TAG, 'groupsContact-insert data success!');
482        }).catch(error => {
483          HiLog.e(TAG, 'groupsContact-insert failed. Cause: %s', JSON.stringify(error.message));
484        });
485      });
486    }
487  },
488
489  /**
490   * Save the contact website information to the database.
491   *
492   * @param {Object} addParams Contact Information
493   * @param {string} DAHelper Database path
494   * @param {number} result Contact ID
495   * @param {string} uri Database address
496   */
497  websiteContact: function (addParams, DAHelper, result, uri) {
498    if (!ArrayUtil.isEmpty(addParams.websites)) {
499      addParams.websites.forEach(element => {
500        if (StringUtil.isEmpty(element))
501        return;
502        let websiteContact = {
503          'raw_contact_id': result,
504          'detail_info': element,
505          'type_id': 12,
506        };
507        DAHelper.insert(
508          uri,
509          websiteContact
510        ).then(data => {
511          if (data == -1) {
512            HiLog.e(TAG, 'websiteContact-insert data failed!');
513          }
514          HiLog.d(TAG, 'websiteContact-insert data success!');
515        }).catch(error => {
516          HiLog.e(TAG, 'websiteContact-insert failed. Cause: %s', JSON.stringify(error.message));
517        });
518      });
519    }
520  },
521
522  /**
523   * The relation information of the contact is saved to the database.
524   *
525   * @param {Object} addParams Contact Information
526   * @param {string} DAHelper Database path
527   * @param {number} result Contact ID
528   * @param {string} uri Database address
529   */
530  relationsContact: function (addParams, DAHelper, result, uri) {
531    if (!ArrayUtil.isEmpty(addParams.relationships)) {
532      let index = 1;
533      addParams.relationships.forEach(element => {
534        if (StringUtil.isEmpty(element.name)) {
535          return;
536        }
537        let relationsContact = {
538          'raw_contact_id': result,
539          'detail_info': element.name,
540          'extend7': (index++).toString(),
541          'custom_data': element.associatedType,
542          'type_id': 13,
543        };
544        DAHelper.insert(
545          uri,
546          relationsContact
547        ).then(data => {
548          if (data == -1) {
549            HiLog.e(TAG, 'relationsContact-insert data failed!');
550          }
551          HiLog.d(TAG, 'relationsContact-insert data success!');
552        }).catch(error => {
553          HiLog.e(TAG, 'relationsContact-insert failed. Cause: %s', JSON.stringify(error.message));
554        });
555      });
556    }
557  },
558
559  /**
560   * Querying the Mobile Numbers of All Contacts
561   *
562   * @param {string} DAHelper
563   * @param {Object} callBack
564   */
565  getAllContact: async function (actionData, callBack, context?) {
566    HiLog.i(TAG, 'Start to query all contacts without PhoneNumbers');
567    if (context) {
568      ContactRepository.getInstance().init(context);
569    }
570    ContactRepository.getInstance().findAll(actionData, contactList => {
571      if (ArrayUtil.isEmpty(contactList)) {
572        HiLog.i(TAG, 'queryContacts-SelectcontactsModel queryContact resultSet is empty!');
573        let emptyResult: ContactVo[] = [];
574        callBack(emptyResult);
575        return;
576      }
577      let resultList = [];
578      for (let contactItem of contactList) {
579        let jsonObj: ContactVo = new ContactVo('', '', '', '', '', '', true, '', '');
580        jsonObj.contactId = contactItem.id.toString();
581        jsonObj.emptyNameData = contactItem.displayName;
582        jsonObj.namePrefix = contactItem.sortFirstLetter;
583        jsonObj.nameSuffix = contactItem.photoFirstName;
584        jsonObj.company = contactItem.company;
585        jsonObj.position = contactItem.position;
586        jsonObj.portraitColor = MorandiColor.Color[Math.abs(parseInt(jsonObj.contactId)) % 6];
587        jsonObj.show = false;
588        jsonObj.setShowName();
589        resultList.push(jsonObj);
590      }
591      callBack(resultList);
592      HiLog.i(TAG, 'End of querying all contacts');
593    });
594  },
595
596  /**
597   * 查询所有联系人手机号
598   *
599   * @param {string} DAHelper 数据库地址
600   * @param {Object} callBack 回调
601   * @param {Object} addParams  Contact Information
602   */
603  getAllContactWithPhoneNumbers: function (callBack, addParams, context?) {
604    HiLog.i(TAG, 'Start to query all contacts with PhoneNumbers');
605    if (context) {
606      ContactRepository.getInstance().init(context);
607    }
608    ContactRepository.getInstance().findByPhoneIsNotNull(addParams.favorite, addParams.editContact, contactList => {
609      if (ArrayUtil.isEmpty(contactList)) {
610        HiLog.i(TAG, 'getAllContactWithPhoneNumbers-SelectcontactsModel queryContact resultSet is empty!');
611        let emptyResult: ContactVo[] = [];
612        callBack(emptyResult);
613        return;
614      }
615      let resultList = [];
616      for (let contactItem of contactList) {
617        let jsonObj: ContactVo = new ContactVo('', '', '', '', '', '', true, '', '');
618        jsonObj.contactId = contactItem.id.toString();
619        jsonObj.emptyNameData = contactItem.displayName;
620        jsonObj.namePrefix = contactItem.sortFirstLetter;
621        jsonObj.nameSuffix = contactItem.photoFirstName;
622        jsonObj.company = contactItem.company;
623        jsonObj.position = contactItem.position;
624        jsonObj.portraitColor = MorandiColor.Color[Math.abs(parseInt(jsonObj.contactId)) % 6];
625        jsonObj.show = false;
626        jsonObj.phoneNumbers = contactItem.phoneNumbers;
627        jsonObj.setShowName();
628        resultList.push(jsonObj);
629      }
630      callBack(resultList);
631      HiLog.i(TAG, 'End of querying all contacts');
632    });
633  },
634
635  /**
636   * Obtain contact details.
637   *
638   * @param {Object} contactId Contact data ID.
639   * @param {Object} callback Contact details
640   */
641  getContactById: function (contactId, callback, context?) {
642    HiLog.i(TAG, 'Start to query contact by id.');
643    if (context) {
644      ContactRepository.getInstance().init(context);
645    }
646    ContactRepository.getInstance().findById(contactId, contact => {
647      let res = {
648        'data': {}
649      };
650      if (contact == undefined || ArrayUtil.isEmpty(contact.rowContacts)) {
651        HiLog.e(TAG, 'Query contact by id failed.');
652        callback(res);
653        return;
654      }
655      let contactDetailInfo: any = {};
656      for (let dataItem of contact.rowContacts[0].dataItems) {
657        this.dealResult(dataItem, contactDetailInfo);
658      }
659      contactDetailInfo.id = contact.rowContacts[0].id;
660      contactDetailInfo.photoFirstName = contact.rowContacts[0].values.get(RawContacts.PHOTO_FIRST_NAME);
661      res.data = contactDetailInfo;
662      callback(res);
663      HiLog.i(TAG, 'End of querying contacts by ID.');
664    });
665  },
666
667  /**
668   * Process contact details
669   *
670   * @param {Object} resultSet
671   * @param {Object} contactDetailInfo Contact details data
672   * @param {Object} actionData Contact data
673   */
674  dealResult: function (dataItem: DataItem, contactDetailInfo) {
675    contactDetailInfo.favorite = dataItem.getFavorite();
676    switch (dataItem.getContentTypeId()) {
677      case DataItemType.NAME:
678        contactDetailInfo.display_name = dataItem.getData();
679        contactDetailInfo.nameUpdate = dataItem.getLabelId();
680        break;
681      case DataItemType.PHONE:
682        let phone_element = {
683          'num': dataItem.getData(),
684          'id': dataItem.getLabelId(),
685          'numType': dataItem.getLabelName()
686        };
687        if (contactDetailInfo.phones) {
688          contactDetailInfo.phones.push(phone_element);
689        } else {
690          contactDetailInfo.phones = [phone_element];
691        }
692        break;
693      case DataItemType.EMAIL:
694        let email_element = {
695          'address': dataItem.getData(),
696          'id': dataItem.getLabelId(),
697          'emailType': dataItem.getLabelName()
698        };
699        if (contactDetailInfo.emails) {
700          contactDetailInfo.emails.push(email_element);
701        } else {
702          contactDetailInfo.emails = [email_element];
703        }
704        break;
705      case DataItemType.NOTE:
706        contactDetailInfo.remarks = dataItem.getData();
707        break;
708      case DataItemType.ORGANIZATION:
709        contactDetailInfo.position = dataItem.values.get(Data.POSITION);
710        contactDetailInfo.company = dataItem.getData();
711        break;
712      case DataItemType.IM:
713        let aim_element = {
714          'aimName': dataItem.getData(),
715          'aimId': dataItem.getLabelId(),
716          'aimType': dataItem.getLabelName()
717        };
718        if (contactDetailInfo.aims) {
719          contactDetailInfo.aims.push(aim_element);
720        } else {
721          contactDetailInfo.aims = [aim_element];
722        }
723        break;
724      case DataItemType.STRUCTURED_POSTAL:
725        let house_element = {
726          'houseName': dataItem.getData(),
727          'houseId': dataItem.getLabelId(),
728          'houseType': dataItem.getLabelName()
729        };
730        if (contactDetailInfo.houses) {
731          contactDetailInfo.houses.push(house_element);
732        } else {
733          contactDetailInfo.houses = [house_element];
734        }
735        break;
736      case DataItemType.GROUP_MEMBERSHIP:
737        contactDetailInfo.nickname = dataItem.getData();
738        break;
739      case DataItemType.EVENT:
740        let event_element = {
741          'id': dataItem.getLabelId(),
742          'data': dataItem.getData(),
743          'eventType': dataItem.getLabelName(),
744          'eventName': ''
745        };
746        if (contactDetailInfo.events) {
747          contactDetailInfo.events.push(event_element);
748        } else {
749          contactDetailInfo.events = [event_element];
750        }
751        break;
752      case DataItemType.WEBSITE:
753        let website_element = dataItem.getData();
754        if (contactDetailInfo.websites) {
755          contactDetailInfo.websites.push(website_element);
756        } else {
757          contactDetailInfo.websites = [website_element];
758        }
759        break;
760      case DataItemType.RELATION:
761        let relation_element = {
762          'id': dataItem.getLabelId(),
763          'associatedPersonId': '',
764          'name': dataItem.getData(),
765          'associatedType': dataItem.getLabelName(),
766        };
767        if (contactDetailInfo.relationships) {
768          contactDetailInfo.relationships.push(relation_element);
769        } else {
770          contactDetailInfo.relationships = [relation_element];
771        }
772        break;
773    }
774  },
775
776  /**
777   * Obtains the contact ID of the number by phone number
778   *
779   * @param {string} DAHelper
780   * @param {string} number Mobile number
781   * @param {Object} callBack Contact ID
782   */
783  getContactIdByNumber: async function (DAHelper, number, callBack) {
784    HiLog.i(TAG, 'Start to query contacts by phone number.');
785    if (DAHelper == undefined || DAHelper.length == 0) {
786      DAHelper = await dataShare.createDataShareHelper(globalThis.context, Contacts.CONTENT_URI);
787    }
788    if (StringUtil.isEmpty(number)) {
789      return;
790    }
791    let resultColumns = [
792      'raw_contact_id',
793    ];
794    let cleanNumber = StringUtil.removeSpace(number);
795    let condition = new dataSharePredicates.DataSharePredicates();
796    condition.equalTo('detail_info', cleanNumber);
797    condition.and();
798    condition.equalTo('is_deleted', 0);
799    condition.and();
800    condition.equalTo('type_id', '5');
801    let resultSet = await DAHelper.query(Data.CONTENT_URI, resultColumns, condition);
802    if (StringUtil.isEmpty(resultSet) || resultSet.rowCount == 0) {
803      HiLog.i(TAG, 'getContactIdByNumber-contactId resultSet is empty!');
804      callBack();
805      return;
806    }
807    resultSet.goToFirstRow();
808    let contactId = resultSet.getString(0);
809    resultSet.close();
810    callBack(contactId);
811    HiLog.i(TAG, 'End of querying contacts by phone number.');
812  },
813
814  /**
815   * Edit Contact Information
816   *
817   * @param {string} DAHelper
818   * @param {Object} addParams  Contact Information
819   * @param {Object} callBack Contact ID
820   */
821  updateContact: async function (DAHelper, addParams, callBack, context?) {
822    HiLog.i(TAG, 'Start to update contacts.');
823    try {
824      if (DAHelper == undefined || DAHelper.length == 0 || DAHelper == null) {
825        DAHelper = await dataShare.createDataShareHelper(context ? context : globalThis.context, Contacts.CONTENT_URI);
826      }
827      let condition = new dataSharePredicates.DataSharePredicates();
828      condition.equalTo('raw_contact_id', addParams.id);
829      DAHelper.delete(
830      Data.CONTENT_URI,
831        condition,
832      ).then(data => {
833        this.dealParam(DAHelper, addParams, false, callBack);
834      }).catch(error => {
835        HiLog.e(TAG, 'updateContact-update contact error: %s', JSON.stringify(error.message));
836      });
837      HiLog.i(TAG, 'End to update contacts.');
838    } catch(err) {
839      HiLog.e(TAG, 'updateContact err : ' + JSON.stringify(err));
840    }
841  },
842  /**
843   * Querying IDs by Phone Number
844   *
845   * @param {string} DAHelper
846   * @param {string} addParams  Phone number
847   * @param {Object} callBack Contact ID array
848   */
849  getIdByTelephone: async function (number, callBack, context?) {
850    HiLog.i(TAG, 'Start to query contactID by phone number.');
851    let DAHelper = await dataShare.createDataShareHelper(context ?context : globalThis.context, Contacts.CONTENT_URI);
852    let condition = new dataSharePredicates.DataSharePredicates();
853    condition.equalTo('detail_info', number)
854      .and()
855      .equalTo('type_id', 5)
856      .and()
857      .equalTo('is_deleted', 0);
858    let columns = ['raw_contact_id'];
859    let data_row = await DAHelper.query(Data.CONTENT_URI, condition, columns);
860    let resultList = [];
861    if (data_row.rowCount <= 0) {
862      data_row.close();
863      callBack(resultList);
864      return;
865    }
866    data_row.goToFirstRow();
867    let maxRows = data_row.rowCount;
868    let tempIndex = data_row.rowCount;
869    let index = 0;
870    do {
871      resultList.push(data_row.getString(data_row.getColumnIndex('raw_contact_id')));
872      if ((++index) >= maxRows) {
873        data_row.close();
874        callBack(resultList);
875      }
876      if (!data_row.goToNextRow()) {
877        break;
878      }
879    } while ((--tempIndex) >= 0)
880    data_row.close();
881    HiLog.i(TAG, 'End to query contactID by phone number.');
882  },
883
884  /**
885   * Edit Contact Favorite
886   *
887   * @param {string} DAHelper
888   * @param {Object} addParams  Contact Information
889   * @param {Object} callBack Contact ID
890   */
891  updateFavorite: async function (DAHelper, addParams, callBack, context?) {
892    HiLog.i(TAG, 'updateFavorite start.');
893    if (DAHelper == undefined || DAHelper == null || DAHelper.length == 0) {
894      DAHelper = await dataShare.createDataShareHelper(context ? context : globalThis.context, Contacts.CONTENT_URI);
895    }
896    let condition = new dataSharePredicates.DataSharePredicates();
897    condition.equalTo('contact_id', addParams.id);
898    const va = {
899      'favorite': addParams.favorite,
900    }
901      DAHelper.update(
902      RawContacts.CONTENT_URI,
903        condition,
904        va
905      ).then(data => {
906        if (data == -1) {
907          HiLog.e(TAG, 'updateFavorite data failed!');
908        }
909        HiLog.i(TAG, 'updateFavorite data success!');
910        callBack(addParams.favorite)
911      }).catch(err => {
912        HiLog.e(TAG, 'updateFavorite failed. Cause: ' + JSON.stringify(err.message));
913      });
914    HiLog.i(TAG, 'updateFavorite end.');
915  },
916
917  /**
918   * Querying the Mobile Numbers of All Favorites
919   *
920   * @param {string} DAHelper
921   * @param {Object} callBack
922   */
923  getAllFavorite: async function (actionData, callBack, context?) {
924    HiLog.i(TAG, 'getAllFavorite start.');
925    if (context) {
926      ContactRepository.getInstance().init(context);
927      ContactRepository.getInstance().findAllFavorite(actionData, favoriteList => {
928        if (ArrayUtil.isEmpty(favoriteList)) {
929          let emptyResult: FavoriteBean[] = [];
930          callBack(emptyResult);
931          return;
932        }
933        let resultList = [];
934        for (let contactItem of favoriteList) {
935          let jsonObj: FavoriteBean = new FavoriteBean('', -1, '', '', '', '', '', true, '', false, 0, '');
936          jsonObj.contactId = contactItem.id.toString();
937          jsonObj.isCommonUseType = 0;
938          jsonObj.displayName = contactItem.displayName;
939          jsonObj.namePrefix = contactItem.sortFirstLetter;
940          jsonObj.nameSuffix = contactItem.photoFirstName;
941          jsonObj.position = contactItem.position;
942          jsonObj.portraitColor = MorandiColor.Color[Math.abs(parseInt(jsonObj.contactId)) % 6];
943          jsonObj.show = contactItem.show;
944          jsonObj.isUsuallyShow = false;
945          jsonObj.favorite = 1;
946          jsonObj.setShowName();
947          resultList.push(jsonObj);
948        }
949        HiLog.i(TAG, 'getAllFavorite data success!');
950        callBack(resultList);
951      });
952    }
953    HiLog.i(TAG, 'getAllFavorite end.');
954  },
955
956  /**
957   * Query call records
958   *
959   * @param {string} DAHelper
960   * @param {Object} callBack call records
961   */
962  getAllUsually: async function (actionData, callBack, context?) {
963    HiLog.i(TAG, 'getAllUsually start.');
964    if (context) {
965      ContactRepository.getInstance().init(context);
966      ContactRepository.getInstance().findAllUsually(actionData, callLog => {
967        if (ArrayUtil.isEmpty(callLog)) {
968          let emptyResult: CallLog[] = [];
969          callBack(emptyResult);
970          return;
971        }
972        let resultList = [];
973        resultList = callLog;
974        HiLog.i(TAG, 'getAllUsually data success! ');
975        callBack(resultList);
976      });
977    }
978    HiLog.i(TAG, 'getAllUsually end.');
979  },
980
981  /**
982   * DisplayName Query Favorite
983   *
984   * @param {string} DAHelper
985   * @param {Object} addParams Contact Information
986   * @param {Object} callBack Contact Information
987   */
988  getDisplayNamesFindUsually:  async function (displayName, usuallyPhone, callBack, context?){
989    HiLog.i(TAG, 'getDisplayNamesFindUsually start.');
990    if (context) {
991      ContactRepository.getInstance().init(context);
992      ContactRepository.getInstance().getDisplayNameByFavorite(displayName, usuallyPhone, favoriteList => {
993        if (ArrayUtil.isEmpty(favoriteList)) {
994          let emptyResult: FavoriteBean[] = [];
995          callBack(emptyResult);
996          return;
997        }
998        let resultList = [];
999        for (let i = 0; i < favoriteList.length; i++) {
1000          let jsonObj: FavoriteBean = new FavoriteBean('', -1, '', '', '', '', '', false, '', false, 0, '');
1001          jsonObj.contactId = favoriteList[i].id.toString();
1002          jsonObj.isCommonUseType = 1;
1003          jsonObj.displayName = favoriteList[i].displayName;
1004          jsonObj.namePrefix = favoriteList[i].sortFirstLetter;
1005          jsonObj.nameSuffix = favoriteList[i].photoFirstName;
1006          jsonObj.position = favoriteList[i].position;
1007          jsonObj.portraitColor = MorandiColor.Color[Math.abs(parseInt(jsonObj.contactId)) % 6];
1008          jsonObj.show = favoriteList[i].show;
1009          jsonObj.isUsuallyShow = false;
1010          jsonObj.favorite = 0;
1011          jsonObj.phoneNum = favoriteList[i].detailInfo;
1012          jsonObj.setShowName();
1013          resultList.push(jsonObj);
1014        }
1015        HiLog.i(TAG, 'getDisplayNamesFindUsually sc.');
1016        callBack(resultList);
1017      })
1018    }
1019    HiLog.i(TAG, 'getDisplayNamesFindUsually end! ');
1020  },
1021
1022  /**
1023   * Move Favorite Data Sorting
1024   *
1025   * @param {string} DAHelper
1026   * @param {Object} addParams Contact Information
1027   * @param {Object} callBack favoriteOrder
1028   */
1029  moveSortFavorite: async function (DAHelper, addParams, callBack, context?) {
1030    HiLog.i(TAG, 'moveSortFavorite start.');
1031    if (DAHelper == undefined || DAHelper == null || DAHelper.length == 0) {
1032      DAHelper = await dataShare.createDataShareHelper(context ? context : globalThis.context, Contacts.CONTENT_URI);
1033    }
1034    let condition = new dataSharePredicates.DataSharePredicates();
1035    condition.equalTo('contact_id', addParams.id);
1036    const va = {
1037      'favorite_order': addParams.favoriteOrder > 9 ? addParams.favoriteOrder : '0' + addParams.favoriteOrder
1038    }
1039    DAHelper.update(
1040    RawContacts.CONTENT_URI,
1041      condition,
1042      va
1043    ).then(data => {
1044      if (data == -1) {
1045        HiLog.e(TAG, 'moveSortFavorite data failed!');
1046        callBack('')
1047        return;
1048      }
1049      HiLog.i(TAG, 'moveSortFavorite data success!');
1050      callBack(addParams.favoriteOrder);
1051    }).catch(err => {
1052      HiLog.e(TAG, 'moveSortFavorite failed. Cause: ' + JSON.stringify(err.message));
1053    });
1054    HiLog.i(TAG, 'End to update moveSortFavorite.');
1055  },
1056
1057  /**
1058   * Querying the Mobile Numbers of Search Contacts
1059   *
1060   * @param {string} DAHelper
1061   * @param {Object} callBack
1062   */
1063  getSearchContact: async function (actionData, callBack, context?) {
1064    HiLog.i(TAG, 'getSearchContact start.');
1065    if (context) {
1066      ContactRepository.getInstance().init(context);
1067    }
1068    ContactRepository.getInstance().searchContact(actionData, contactList => {
1069      if (ArrayUtil.isEmpty(contactList)) {
1070        HiLog.i(TAG, 'getSearchContact resultSet is empty!');
1071        let emptyResult: SearchContactsBean[] = [];
1072        callBack(emptyResult);
1073        return;
1074      }
1075      let resultList = [];
1076      for (let contactItem of contactList) {
1077        let jsonObj: SearchContactsBean = new SearchContactsBean('', '', '', '', '', '', '', '', '', 0,'', '', '', '', '', '');
1078        jsonObj.id = contactItem.id.toString();
1079        jsonObj.accountId = contactItem.accountId;
1080        jsonObj.contactId = contactItem.contactId;
1081        jsonObj.rawContactId = contactItem.rawContactId;
1082        jsonObj.searchName = contactItem.searchName;
1083        jsonObj.displayName = contactItem.displayName;
1084        jsonObj.phoneticName = contactItem.phoneticName;
1085        jsonObj.photoId = contactItem.photoId;
1086        jsonObj.photoFileId = contactItem.photoFileId;
1087        jsonObj.isDeleted = contactItem.isDeleted;
1088        jsonObj.position = contactItem.position;
1089        jsonObj.sortFirstLetter = contactItem.sortFirstLetter;
1090        jsonObj.photoFirstName = contactItem.photoFirstName;
1091        jsonObj.portraitColor = MorandiColor.Color[Math.abs(parseInt(jsonObj.contactId)) % 6];
1092        jsonObj.detailInfo = contactItem.detailInfo;
1093        jsonObj.hasPhoneNumber = contactItem.hasPhoneNumber;
1094        resultList.push(jsonObj);
1095      }
1096      callBack(resultList);
1097      HiLog.i(TAG, 'getSearchContact end.');
1098    });
1099  },
1100
1101  getQueryT9PhoneNumbers: function (callBack, addParams, context?) {
1102    if (context) {
1103      ContactRepository.getInstance().init(context);
1104    }
1105    ContactRepository.getInstance().queryT9PhoneIsNotNull(addParams.favorite, contactList => {
1106      if (ArrayUtil.isEmpty(contactList)) {
1107        HiLog.i(TAG, 'getQueryT9PhoneNumbers queryContact resultSet is empty!');
1108        let emptyResult: ContactVo[] = [];
1109        callBack(emptyResult);
1110        return;
1111      }
1112      let resultList = [];
1113      for (let contactItem of contactList) {
1114        let jsonObj: ContactVo = new ContactVo('', '', '', '', '', '', true, '', '');
1115        jsonObj.contactId = contactItem.id.toString();
1116        jsonObj.emptyNameData = contactItem.displayName;
1117        jsonObj.namePrefix = contactItem.sortFirstLetter;
1118        jsonObj.nameSuffix = contactItem.photoFirstName;
1119        jsonObj.company = contactItem.company;
1120        jsonObj.position = contactItem.position;
1121        jsonObj.portraitColor = MorandiColor.Color[Math.abs(parseInt(jsonObj.contactId)) % 6];
1122        jsonObj.show = false;
1123        jsonObj.phoneNumbers = contactItem.phoneNumbers;
1124        jsonObj.setShowName();
1125        resultList.push(jsonObj);
1126      }
1127      callBack(resultList);
1128      HiLog.i(TAG, 'End of querying all contacts');
1129    });
1130  },
1131}