/**
 * json数据转换成FormData
 * @param obj json 对象
 * @parma formData  表单对象
 * @param parentKey 父元素的key
 *
 **/
function objectToFormData(obj, formData, parentKey) {
  formData = formData || new FormData();
  for (const key in obj) {
    if (!obj.hasOwnProperty(key)) continue;
    const value = obj[key];
    const fullKey = parentKey ? String(Number(key)) !== 'NaN' ? `${parentKey}[${key}]` : `${parentKey}.${key}` : key;
    if (value instanceof Object && !(value instanceof File)) {
      objectToFormData(value, formData, fullKey);
    } else {
      formData.append(fullKey, value == undefined ? '' : value);
    }
  }
  return formData;
}

/**
 * @param url 请求路径
 * @param type 请求类型
 * @param data 数据
 * @param processData  防止自动转换数据格, 默认false
 * @param contentType  发送信息至服务器时内容编码类型, 表单默认false
 */

function cyAjax({ url, type, data, processData = false, contentType = false }) {
  if(!contentType) {
    data = objectToFormData(data)
  }
  return new Promise((resolve, reject) => {
    $.ajax({
      url,
      type,
      data,
      processData,
      contentType,
      success: function (data) {
        if(data.success) {
          resolve(data.data)
        }else {
          new $.zui.Messager(`后端异常:${data.msg}`, {
            type: 'danger'
          }).show();
        }
      },
      error: function (data) {
        new $.zui.Messager(`后端异常`, {
          type: 'danger'
        }).show();
        reject()
      }
    })
  })
}

/**
 * 表单校验
 * @param dom 表单提交dom,使用ID选择器
 **/

function cyValidate(dom, rules, messages ) {
  return new Promise((resolve, reject) => {
    $(dom).validate({
      promptPosition: "bottomLeft",
      showErrors : function(errorMap, errorList) {
        if(errorList.length) {
          resolve(false)
        }else {
          resolve(true)
        }
        this.defaultShowErrors();
      },
      rules,
      messages
    })
  })
}
