import Common from '../../common/Common.js';
import UserStorageResource from '../../api/base/UserStorageResource.js';
import { Notify } from 'pc-component-v3';

export default {


  /**
	 * 克隆表单字段
	 * @param {表单字段} formField 
	 */
  cloneFormField: function (formField) {
    var formFieldClone = {
      'fieldName': formField.fieldName,
      'displayName': formField.displayName,
      'visible': formField.visible,
      'entityFieldIndex': formField.entityFieldIndex,
      'mandatory': formField.mandatory,
      'sortNo': formField.sortNo,
      'width': formField.width,
    };
    return formFieldClone;
  },


  /**
	 * 保存表单字段的显示属性至UserStorage
	 * @param {窗口编号} windowNo 
	 * @param {页签编号} tabIndex 
	 * @param {表单字段} formField 
	 */
  saveFormFieldDef: function (windowNo, tabIndex, formFields) {
    var key = 'TabFormField_' + windowNo + '_' + tabIndex;
    var userStorageDtos = [
      {
        key: key,
        value: JSON.stringify(formFields),
      },
    ];

    return new Promise(function (resolve, reject) {
      UserStorageResource.uploadUserStorage(userStorageDtos).then(successData => {
        resolve(successData);
      }, errorData => {
        Common.processException(errorData);
        reject();
      });
    });
  },



  /**
	 * 从UserStorage中恢复所有表单字段的显示属性
	 * @param {窗口编号} windowNo 
	 * @param {页签编号} tabIndex 
	 * @param {表单字段} formField 
	 */
  restoreTabFormFieldDef: function (windowNo, tabIndex, tabFormFields) {
    var key = 'TabFormField_' + windowNo + '_' + tabIndex;
    UserStorageResource.uniqueByKey(key).then(successData => {
      // if(successData.errorCode != 0) {
      //   Notify.error('提示', successData.errorMessage, false);
      //   return;
      // }
      var tabFormFields1 = null;
      if (successData.data != null) {
        tabFormFields1 = JSON.parse(successData.data);
      } else {
        tabFormFields1 = null;
      }
      if (tabFormFields != null) {
        tabFormFields.forEach(tabFormField => {
          if (tabFormFields1 != null) {
            tabFormFields1.forEach(tabFormFieldClone => {
              if (tabFormFieldClone != null &&
								tabFormField.fieldName == tabFormFieldClone.fieldName &&
								tabFormField.entityFieldIndex == tabFormFieldClone.entityFieldIndex) {
                tabFormField.visible = tabFormFieldClone.visible;
                tabFormField.sortNo = tabFormFieldClone.sortNo;
                tabFormField.width = tabFormFieldClone.width;
              }
            });
          }
        });
        tabFormFields.sort(function (item1, item2) {
          return item1.sortNo - item2.sortNo;
        });
      }
    }, errorData => {
      Common.processException(errorData);
    });
  },
};