$.formdataPost = function (url, formdata, sucFn, errFn, alwaysFn) {
  $.ajax({
    type: 'POST',
    dataType: 'json',
    url: url,
    contentType: false,
    processData: false,
    data: formdata,
  }).always(function (resp) {
    if (resp.success) {
      typeof sucFn === 'function' && sucFn(resp);
    } else {
      typeof errFn === 'function' && errFn(resp);
    };
    typeof alwaysFn === 'function' && alwaysFn(resp);
  });
};
$.isNullOrEmpty = function (val) {
  if (val == null || val == '') {
    return true;
  }
  return false;
};
$.leftPadding = function (value, length, char = '0') {
  while (value.length < length) {
    value = char + value;
  };
  return value;
};
$.getYearRange = function (number) {
  const year = new Date().getFullYear();
  const result = [year];
  for (let i = 1; i <= number; i++) {
    result.push(year + i);
  };
  return result;
};
$.multi_contain = function (inputs, contains) {
  const result = [];
  if (inputs != null && inputs.length > 0) {
    inputs.map(input => {
      if (input.index & contains > 0) {
        result.push(input);
      }
    })
  };
  return result;
};
/** 时间格式化 */
$.timeFormat = function (time) {
  var datetime = new Date(time);
  var year = datetime.getFullYear();
  var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
  var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
  return year + "/" + month + "/" + date;
};
$.countdown = function (start, end, hour, minute, second, day = null,callback = null) {
  const now = new Date().getTime();
  const time = start <= now ? (end - now) / 1000 : (start - now) / 1000;
  let d = Math.max(parseInt(time / 60 / 60 / 24), 0),
    h = Math.max(parseInt(time / 60 / 60 % 24), 0),
    m = Math.max(parseInt(time / 60 % 60), 0),
    s = Math.max(parseInt(time % 60), 0);
  if (day && d > 1) {
    day.text(`${d}Days`);
  } else if (day && d > 0) {
    day.text(`${d}Day`);
  }
  h = h < 10 ? '0' + h : h;
  hour.text(h);
  m = m < 10 ? '0' + m : m;
  minute.text(m);
  s = s < 10 ? '0' + s : s;
  second.text(s);
  if (typeof callback == 'function') callback();
}
/**
 * 隐藏用户名
 * @param {String} userName 
 * @returns 
 */
$.hideUserName = function (userName) {
  if (!userName) {
    return "";
  }
  const len = userName.length;
  if (len == 1) {
    return userName + "***";
  }
  return `${userName[0]}***${userName[len - 1]}`
};

$.timeTag = function (value) {
  if (!value)
    return "";
  const c = new Date(value).toDateString('en-US').split(" ");
  c.shift();
  return c.join(' ')
}
$.i18n_formate = function (val, t) {
  if (!val || !t) return ""
  return t.replace('{0}', val)
}
$.i18n_is_required = function (val) {
  if (!val) return ""
  const t = i18n.general.is_required
  return $.i18n_formate(val, t)
}
$.formValidation = function (el) {
  const val = el.val();
  const isEmail = el.is("#email") || el.is('[name=email]') || el.is('[name=Email]');
  const pat = isEmail ? /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ : null;
  const cond = pat ? !pat.test(val) : el.val() === "" || el.val() === null;
  if (cond) {
    el.parents(".form-col").eq(0).addClass("invalid");
  } else {
    el.parents(".form-col").eq(0).removeClass("invalid");
  }
}
$.htmlEncode = function (str) {
  return String(str)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}
$.copyToClipboard = function (t) {
  if (!t) return;
  let n
    , r = document.createRange()
    , s = window.getSelection();
  if (typeof t == "string") {
    n = document.createElement('textarea');
    $(n).css({
      position: "fixed",
      top: 0,
      left: 0,
      opacity: 0,
      width: 2,
      height: 2
    }).val(t);
    $("body").append($(n));
  } else {
    n = t instanceof jQuery ? t[0] : t;
  }
  r.selectNode(n)
  if (s.rangeCount > 0) s.removeAllRanges();
  s.addRange(r);
  try {
    const s = document.execCommand('copy');
    if (s) {
      $.toast.success(`${i18n.general.copy_succeeded}`);
    } else {
      $.toast.error(`${i18n.general.copy_failed}`);
    }
  } catch (err) {
    $.toast.error(`${i18n.general.copy_failed}`);
  }
  if (typeof t == "string") $(n).remove();
}

/**订阅方法 */
Newsletter = {
  key: `newsleeter_${window.FS_MRSHOPPLUS.shop_id}`,
  getNewsletter: function (popupId) {
    return Cookies.get(Newsletter.key + popupId);
  },
  setNewsletter: function (popupId, value) {
    Cookies.set(Newsletter.key + popupId, value);
  },
};
/**
 * 
 * @param {string} email 邮箱
 * @returns 
 */
function newsletter(email) {
  const pat = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ig;
  if (!pat.test(email)) {
    $.toast.error(i18n.address.pls_vaild_email);
    return false;
  }
  $.invokeBcfMethod('/biz/DTB_memMember/Subscribe', [email], function (resp) {
    $.toast.success(i18n.email.Thanks_subs_newsletter)
  }, function (resp) {
    $.toast.error(resp.result && resp.result.data || resp.result);
  });
  return true;
};

function handleCallback(callback, ...args) {
  typeof callback === 'function' && callback(...args);
}

/**
 * 购物车全局对象
 */
Cart = {
  key: `cart_key_${window.FS_MRSHOPPLUS.shop_id}`,
  exc_key: `cart_exc_key_${window.FS_MRSHOPPLUS.shop_id}`,
  getBindObjectFromString: function (bindStr) {
    // "1&11|11.11|1|1/22|22.22|2|0/33|33.33|3|1&200&188&12&1"
    const bsMap = {
      0: 'bsid', // 组合销售id
      1: 'skumap', // skus的元素组合，{ skuid skuid，price 价格，quantity数量, ischecked 勾选 }
      2: 'subtotal', // 组合销售原价
      3: 'total', // 优惠后总价
      4: 'discount', // 优惠额,
      5: 'count', // 购买数量
      6: 'ischecked',
      7: 'refid',
    };
    const skuMap = {
      0: 'skuid',
      1: 'price',
      2: 'quantity',
      3: 'ischecked'
    };
    const item = {};
    const parts = bindStr.split("&");
    parts.map((part, index) => {
      if (bsMap[index] == 'skumap') {
        item.skus = item.skus || [];
        const skus = part.split("/");
        skus.map(sku => {
          const skuPart = sku.split("|");
          const kv = {};
          skuPart.map((p, spIndex) => {
            const key = skuMap[spIndex];
            kv[key] = p;
          });
          item.skus.push(kv);
        });
      } else {
        const key = bsMap[index];
        item[key] = part;
      }
    });
    // { bsid: 1, skus: [ { skuid: 11, price: 11.11, quantity: 1, ischecked: 1 } ], subtotal: 100, total: 88, discount: 12, count: 1, ischecked: 1 }
    return item;
  },
  getBindStringFromObject: function (bindObj) {
    // { bsid: 1, skus: [ { skuid: 11, price: 11.11, quantity: 1, ischecked: 1 } ], subtotal: 100, total: 88, discount: 12, count: 1, ischecked: 1 }
    const strAry = [];
    const bsMap = {
      0: 'bsid', // 组合销售id
      1: 'skumap', // skus的元素组合，{ skuid skuid，price 价格，quantity数量, ischecked 勾选 }
      2: 'subtotal', // 组合销售原价
      3: 'total', // 优惠后总价
      4: 'discount', // 优惠额
      5: 'count', // 购买数量
      6: 'ischecked',
      7: 'refid',
    };
    const mapValues = Object.values(bsMap);
    mapValues.map(field => {
      if (field == 'skumap') {
        const skuAry = [];
        bindObj.skus.map(sku => {
          skuAry.push(`${sku.skuid}|${sku.price}|${sku.quantity}|${sku.ischecked}`);
        });
        strAry.push(skuAry.join('/'));
      } else {
        strAry.push(bindObj[field])
      }
    });
    // "1&11|11.11|1|1/22|22.22|2|0/33|33.33|3|1&200&188&12&1"
    return strAry.join('&');
  },
  getCart: function () {
    const cookies = Cookies.get(Cart.key);
    // "385397921973522|1|1,1&11|11.11|1|1/22|22.22|2|0/33|33.33|3|1&200&188&12&1"
    const cart = [];
    if (cookies && cookies.length) {
      const carts = cookies.split(",");
      carts.map(bind => {
        if (bind.indexOf('&') == -1) {
          // 单个商品
          cart.push(bind);
        } else {
          // 组合商品
          cart.push(Cart.getBindObjectFromString(bind));
        }
      });
      return cart;
    }
    return null;
  },
  getExcCart: function() {
    const cookies = Cookies.get(Cart.exc_key);
    if (cookies && cookies.length) {
      return cookies.split(",");
    }
    return null;
  },
  /**
   * 添加换购商品列表
   * @param { Array< product_id, variant_id, exc_id> } rows
   * @param {*} args
   */
  addExcItems: function(rows, args) {
    if(rows && rows.length > 0) {
      let { addExcCartItem, genCartSummary, model } = args;
      handleCallback(addExcCartItem, rows);
      $.invokeBcfMethod('/biz/DTB_sstoCart/GetCurrentCartObject', [], function (resp) {
        handleCallback(genCartSummary, resp.result);
      }, function (resp) {
        handleCallback(genCart, model.cartObj);
      });
    }
  },
  addExcLocalItems: function(rows) {
    if(rows && rows.length > 0) {
      const carts = Cart.getExcCart() || [];
      const rest = [];
      rows.map( row => {
        let exsitCartProd = false;
        const val = `${row.product_id}|${row.variant_id}|${row.exc_id}|1|${row.qty}`;
        for(let i = 0; i < carts.length; i++) {
          const cart = carts[i];
          const prodId = cart.split('|')[0];
          if(row.product_id == prodId) {
            carts[i] = val;
            exsitCartProd = true;
            break;
          }
        }
        if(!exsitCartProd) {
          rest.push(val);
        }
      });
      const result = [...rest, ...carts];
      Cookies.set(Cart.exc_key, result.join(','), {
        expires: 7
      });
    }
  },
  /**
   * 移除换购商品
   * @param {Object<product_id, variant_id, exc_id>} row 
   */
  deleteExcItem: function (rows, args) {
    if (rows) {
      let { removeExcCartItem, genCartSummary, model } = args;
      handleCallback(removeExcCartItem, rows);
      $.invokeBcfMethod('/biz/DTB_sstoCart/GetCurrentCartObject', [], function (resp) {
        handleCallback(genCartSummary, resp.result);
      }, function (resp) {
        handleCallback(genCart, model.cartObj);
      });

    }
  },
  updateExcItem: function (rows, args) {
     if (rows) {
       let { updateExcCartItem, genCartSummary, model } = args;
       handleCallback(updateExcCartItem, rows);
       
      $.invokeBcfMethod('/biz/DTB_sstoCart/GetCurrentCartObject', [], function (resp) {
        handleCallback(genCartSummary, resp.result);
      }, function (resp) {
        handleCallback(genCart, model.cartObj);
      });

    }
  },
  deleteExcLocalItem: function(row) {
    const carts = Cart.getExcCart() || [];
    for(let i = 0; i < carts.length; i++) {
      const cart = carts[i];
      const pId = cart.split('|')[0];
      if(pId == row.product_id) {
        carts.splice(i, 1);
        break;
      }
    }
    Cookies.set(Cart.exc_key, carts.join(','), {
      expires: 7
    });
  },
  updateExcLocalItem: function (row) {
    const carts = Cart.getExcCart() || [];
    for (let i = 0; i < carts.length; i++) {
      const cart = carts[i];
      const pId = cart.split('|')[0];
      if (pId == row.product_id) {
        carts[i] = `${row.product_id}|${row.variant_id}|${row.exc_id}|${row.checked}|${row.qty}`
        break;
      }
    }
    Cookies.set(Cart.exc_key, carts.join(','), {
      expires: 7
    });
  },
  addCart: function (row) {
    window.FS_MRSHOPPLUS.customer_id ? Cart.addMemItem(row) : Cart.addLocalItem(row);
  },
  addLocalItem: function (row) {
    let cartList = Cart.getCart() || [];
    if (row.bsid) {
      // { bsid: 1, skus: [ { skuid: 11, price: 11.11, quantity: 1, ischecked: 1 } ], subtotal: 100, total: 88, discount: 12, count: 1, ischecked: 1 }
      // 组合销售添加购物车, 直接添加组合即可。
      // 不用计算组合数量累加，因为sku组合存在相同商品相同sku、sku各个数量可变、组合折扣类型不同，导致合并时，商品sku的数量不好计算。
      cartList.unshift(row);
    } else {
      // 单个商品添加购物车
      let exsitCartProd;
      for (let i = 0; i < cartList.length; i++) {
        const cart = cartList[i];
        if (typeof cart === 'string') {
          let part = cart.split("|");
          if (row.variant_id == part[0]) {
            const quantity = Number(part[1]) + Number(row.quantity);
            cartList[i] = `${part[0]}|${quantity}|${part[2]}`;
            exsitCartProd = true;
            break;
          }
        }
      };
      if (!exsitCartProd) {
        cartList.unshift(`${row.variant_id}|${row.quantity}|1`)
      };
      Cart.ruleInfo.setRuleInfo(row.variant_id, row.ProductRules);
    }
    Cart.updateCookie(cartList);
    $(document).trigger('mrs.common.cart.change');
    $.toast.show(i18n.general.add_cart_successfully);
  },
  addMemItem: function (row) {
    $.loading.show();
    $.invokeBcfMethod('/biz/DTB_sstoCart/AddCart', [row.product_id, row.variant_id, row.quantity, false, row.ProductRules], function (resp) {
      $.loading.hide();
      Cart.ruleInfo.setRuleInfo(row.variant_id, row.ProductRules);
      $.toast.show(i18n.general.add_cart_successfully);
      $(document).trigger('mrs.common.cart.change');
    }, function (resp) {
      $.loading.hide();
      $.toast.show({ type: 'error', content: resp.result && resp.result.data || resp.result });
    })
  },
  addMemBindItem: function (row) {
    $.loading.show();
    $.invokeBcfMethod('/biz/DTB_sstoCart/AddBindCart', [row], function (resp) {
      $.loading.hide();
      $.toast.show(i18n.general.add_cart_successfully);
      $(document).trigger('mrs.common.cart.change');
    }, function (resp) {
      $.loading.hide();
      $.toast.show({ type: 'error', content: resp.result && resp.result.data || resp.result });
    })
  },
  addBindCart: function (row) {
    window.FS_MRSHOPPLUS.customer_id ? Cart.addMemBindItem(row) : Cart.addLocalItem(row);
  },
  deleteBindItem: function (row, args) {
    let { removeCartItem, genCartSummary, genCart, model } = args;
    const backup = JSON.parse(JSON.stringify(model.cartObj));
    model.selected_cart_bsids = model.selected_cart_bsids.filter((t, e) => {
      return t == row.refid && model.selectedBS.splice(e, 1),
        t != row.refid
    });
    row.selectedBS = model.selectedBS;
    row.selected_cart_bsids = model.selected_cart_bsids;
    if (FS_MRSHOPPLUS.customer_id) {
      $.invokeBcfMethod('/biz/DTB_sstoCart/DeleteBindItem', [row.refid, row.bsid], function (resp) {
        handleCallback(removeCartItem, row);
        handleCallback(genCartSummary, resp.result);
      }, function (resp) {
        $.toast.show({ type: 'error', content: resp.result && resp.result.data || resp.result });
        handleCallback(genCart, backup);
      })
    } else {
      model.cartObj.bind_sales = model.cartObj.bind_sales.filter(line => line.refid != row.refid);
      handleCallback(removeCartItem, row);
      handleCallback(genCartSummary, model.cartObj);
    }
  },
  deleteItem: function (row, args) {
    let { removeCartItem, genCartSummary, genCart, model } = args;
    if (typeof ga_remove_from_cart === 'function') {
      const item = model.cartObj.line_items.find(item => item.variant_id == row.variant_id);
      if (item) {
        ga_remove_from_cart(item.product_id, item.name, item.options.map(opt => opt.value).join(','), item.quantity, item.price.toFixed(2));
      }
    };
    const backup = JSON.parse(JSON.stringify(model.cartObj));
    model.selected_cart_ids = model.selected_cart_ids.filter((t, e) => {
      return t == row.id && model.selected.splice(e, 1),
        t != row.id
    });
    row.selected = model.selected;
    row.selected_cart_ids = model.selected_cart_ids;
    if (FS_MRSHOPPLUS.customer_id) {
      $.invokeBcfMethod('/biz/DTB_sstoCart/DeleteItem', [row.variant_id], function (resp) {
        handleCallback(removeCartItem, row);
        handleCallback(genCartSummary, resp.result);
      }, function (resp) {
        $.toast.show({ type: 'error', content: resp.result && resp.result.data || resp.result });
        handleCallback(genCart, backup);
      })
    } else {
      model.cartObj.line_items = model.cartObj.line_items.filter(line => line.id != row.id);
      $.invokeBcfMethod('/biz/DTB_Rebate/GetPromotions', [JSON.stringify(model.cartObj.line_items)], function (resp) {
        model.cartObj.promotions = resp.result;
        handleCallback(removeCartItem, row);
        handleCallback(genCartSummary, model.cartObj);
      }, function (resp) {
        handleCallback(genCart, backup);
      });
    }
  },
  deleteLocalItem: function (row) {
    let cartList = Cart.getCart() || [];
    for (let i = 0; i < cartList.length; i++) {
      const item = cartList[i];
      if (typeof item === 'string') {
        let cart = item.split("|");
        if (row.variant_id == cart[0]) { cartList.splice(i, 1); break; }
      } else {
        if (item.refid == row.refid) {
          cartList.splice(i, 1); break;
        }
      }
    };
    Cart.updateCookie(cartList);
  },
  // 更新单个商品购物车
  updateChecked(args) {
    let { model, emptyCartObject, genCartSummary, skipHeaderSummary, skipGetCookies } = args;
    if (FS_MRSHOPPLUS.customer_id) {
      $.invokeBcfMethod('/biz/DTB_sstoCart/UpdateCheckedStatus', [model.selected], function (resp) {
        handleCallback(emptyCartObject, resp.result);
        handleCallback(genCartSummary, resp.result, skipHeaderSummary);
      }, function (resp) {
        $.toast.error(resp.result && resp.result.data || resp.result)
      });
    } else {
      Cart.updateLocalChecked(model.selected);
      if (skipGetCookies) return;
      $.invokeBcfMethod('/biz/DTB_sstoCart/DoGetCartInfoCookie', [], function (resp) {
        handleCallback(emptyCartObject, resp.result);
        handleCallback(genCartSummary, resp.result, skipHeaderSummary);
      }, function (resp) {
        $.toast.error(resp.result && resp.result.data || resp.result)
      });
    }
  },
  // 更新组合销售 购物车
  updateBindSaleChecked(args) {
    let { model, emptyCartObject, genCartSummary, skipHeaderSummary } = args;
    if (FS_MRSHOPPLUS.customer_id) {
      $.invokeBcfMethod('/biz/DTB_sstoCart/updateBindSaleCheckedStatus', [model.selectedBS], function (resp) {
        handleCallback(emptyCartObject, resp.result);
        handleCallback(genCartSummary, resp.result, skipHeaderSummary);
      }, function (resp) {
        $.toast.error(resp.result && resp.result.data || resp.result)
      });
    } else {
      Cart.updateLocalChecked(model.selectedBS, true);
      $.invokeBcfMethod('/biz/DTB_sstoCart/DoGetCartInfoCookie', [], function (resp) {
        handleCallback(emptyCartObject, resp.result);
        handleCallback(genCartSummary, resp.result, skipHeaderSummary);
      }, function (resp) {
        $.toast.error(resp.result && resp.result.data || resp.result)
      });
    }
  },

  // 未登录
  updateLocalChecked(selectedCariantIds, isBs) {
    const ids = selectedCariantIds.map(id => String(id));
    const cartList = Cart.getCart() || [];
    for (let i = 0; i < cartList.length; i++) {
      const cartItem = cartList[i];
      // line item
      if (typeof cartItem === "string") {
        if (!isBs) {
          const cart = cartItem.split("|");
          if (-1 == ids.indexOf(cart[0])) {
            cartList[i] = `${cart[0]}|${cart[1]}|0`
          } else {
            cartList[i] = `${cart[0]}|${cart[1]}|1`
          }
        }
      } else if (isBs) {
        // bs items
        if (-1 == ids.indexOf(cartItem.refid)) {
          cartList[i].ischecked = '0'
        } else {
          cartList[i].ischecked = '1'
        }
      }


    };
    Cart.updateCookie(cartList);
  },
  getCartsCount: function (onlyChecked) {
    let result = 0;
    let cartList = Cart.getCart() || [];
    for (let i = 0; i < cartList.length; i++) {
      const item = cartList[i];
      if (typeof item === 'string') {
        let cart = item.split("|");
        if (cart[2] == "1" || !onlyChecked) {
          result += Number(cart[1])
        }
      } else {
        const count = item.skus.reduce((acc, cur) => {
          acc += parseInt(cur.quantity);
          return acc;
        }, 0);
        result += (count * parseInt(item.count));
      }
    };
    const excCart = Cart.getExcCart() || [];
    excCart.map(item =>{
      const i = item.split("|")
      if (i && i[3] == 1) {
        result += 1;
      }
    })
    return result
  },
  changeBindQuantity: function (e, args) {
    let index = e.index;
    let { model, setBindItem, genCartSummary, genCart } = args;
    const cartObj = model.cartObj;
    if (e.refid && e.bsid) {
      index = cartObj.bind_sales.findIndex(bs => bs.bsid == e.bsid && bs.refid == e.refid);
    };
    const bs = cartObj.bind_sales[index];
    if (bs) {
      if (FS_MRSHOPPLUS.customer_id) {
        $.invokeBcfMethod('/biz/DTB_sstoCart/OperateBindNumber', [e.refid, e.bsid, e.count], function (resp) {
          handleCallback(setBindItem, bs, e.count);
          handleCallback(genCartSummary, resp.result);
        }, function (resp) {
          handleCallback(genCart, cartObj);
        });
      } else {
        handleCallback(setBindItem, bs, e.count);
        Cart.changeQuantityLocal(e, model);
        handleCallback(genCartSummary, cartObj);
      }
    }
  },
  changeQuantity: function (e, args) {
    let { model, setItem, genCartSummary, genCart } = args;
    const cartObj = model.cartObj;
    let copyTmp, t = e.quantity, r = cartObj.line_items.find(line => line.id == e.id);
    if (r && r.quantity == t) {
      handleCallback(genCart, cartObj);
    } else {
      copyTmp = JSON.parse(JSON.stringify(cartObj));
      if (FS_MRSHOPPLUS.customer_id) {
        $.invokeBcfMethod('/biz/DTB_sstoCart/OperateNumber', [e.product_id, e.variant_id, e.quantity], function (resp) {
          const current = resp.result.available_items.find(item => e.variant_id == item.variant_id && e.product_id == item.product_id);
          handleCallback(setItem, current);
          handleCallback(genCartSummary, resp.result);
        }, function (resp) {
          handleCallback(genCart, copyTmp);
        });
      } else {
        Cart.changeQuantityLocal(e, model);
        $.invokeBcfMethod('/biz/DTB_sstoCart/GetCurrentCartObject', [], function (resp) {
          handleCallback(genCartSummary, resp.result);
        }, function (resp) {
          handleCallback(genCart, copyTmp);
        });
      }
    }
  },
  changeQuantityLocal: function (e, model) {
    let cartList = Cart.getCart() || [];
    for (let i = 0; i < cartList.length; i++) {
      const cart = cartList[i];
      if (typeof cart === 'string') {
        let item = cart.split("|");
        if (e.variant_id == item[0]) { cartList[i] = `${item[0]}|${e.quantity}|${item[2]}`; break; }
      } else {
        const newValue = model.cartObj.bind_sales.find(bs => bs.bsid == e.bsid && bs.refid == e.refid);
        if (newValue && cart.bsid == newValue.bsid && cart.refid == newValue.refid) {
          cartList[i] = newValue;
        }
      }
    };
    Cart.updateCookie(cartList);
  },
  direct2Checkout: function () {
    if ($('[data-template-type]').data('template-type') == 104 && cartObj.selected_count == 0) {
      $.toast.error(i18n.general.select_one)
      return;
    }
    $.invokeBcfMethod('/biz/DTB_sysTradeSet/GetMemberRequire', [], function (resp) {
      const url = "/checkout-f" + Date.now();
      if (typeof resp.result === 'boolean' && resp.result && !FS_MRSHOPPLUS.customer_id) {
        window.location.href = "/account/login?cartcheckout=" + Cart.getCart()
      } else {
        window.location.href = url
      }
    })
  },
  updateCookie(cartList) {
    //['385397921973522|1|1', { bsid: 1, skus: [ { skuid: 11, price: 11.11, quantity: 1, ischecked: 1 } ], subtotal: 100, total: 88, discount: 12 } ]
    // "385397921973522|1|1,1&11|11.11|1|1/22|22.22|2|0/33|33.33|3|1&200&188&12"
    const value = [];
    cartList.map(item => {
      if (typeof item === 'string') {
        value.push(item);
      } else {
        // 组合销售
        value.push(Cart.getBindStringFromObject(item));
      }
    });
    Cookies.set(Cart.key, value.join(','), {
      expires: 7
    });
  },
  updateCookieString(value) {
    Cookies.set(Cart.key, value, {
      expires: 7
    });
  },
  clearCart: function () {
    Cookies.remove(Cart.key)
  },
  ruleInfo: {
    setRuleInfo(skuId, productRule) {
      let productRulesJsonString = localStorage.getItem(Cart.key);
      if (productRulesJsonString) {
        let productRules = JSON.parse(productRulesJsonString);
        if (productRules) {
          productRules[skuId] = productRule;
          localStorage.setItem(Cart.key, JSON.stringify(productRules));
        }
        else {
          productRules = {};
          productRules[skuId] = productRule;
          localStorage.setItem(Cart.key, JSON.stringify(productRules));
        }
      }
      else {
        let productRules = {};
        productRules[skuId] = productRule;
        localStorage.setItem(Cart.key, JSON.stringify(productRules));
      }
    },
    delRuleInfo(skuId) {
      let productRulesJsonString = localStorage.getItem(Cart.key);
      if (productRulesJsonString) {
        let productRules = JSON.parse(productRulesJsonString);
        if (productRules) {
          delete productRules[skuId];
          localStorage.setItem(Cart.key, JSON.stringify(productRules));
        }
      }
    },
    getRuleInfo(skuId) {
      let productRulesJsonString = localStorage.getItem(Cart.key);
      let productRules = JSON.parse(productRulesJsonString);
      if (productRules && productRules[skuId]) {
        return JSON.parse(productRules[skuId]);
      }
      return null;
    },
  }
};

// header
$.fn.accountDomBase = function () {
    if (!$('.header-right-account').length) return;
  const s = (FS_MRSHOPPLUS.customer_name || '').split(' ');
  const first_name = s.length ? s[0] : '';
    const d = ` <div class="header-account-info">
      ${FS_MRSHOPPLUS.customer_id ? '' : `<div class="header-info-login"><a class="header-login-btn button button--primary" href="/account/login">${i18n.navigation.sign_in || 'Sign In'}</a><span class="header-info-register">${i18n.account.new_customer || 'New customer'}? <a href='/account/register'>Start here</a></span></div>`
      }
      <div class="header-info-list">
        <a class="header-info-order" href='/account/order'>${i18n.navigation.orders || 'Orders'}</a>
        <a class="header-info-address" href='/account'>${i18n.navigation.account || "Account"}</a>
        ${FS_MRSHOPPLUS.apps.Distribution || false ? `<a class="header-info-distribution" href='/account/distribution_distrcenter'>${i18n.navigation.affiliate_alliance || "Affiliate alliance"}</a>` : ''
      }
      </div>
      ${FS_MRSHOPPLUS.customer_id ? `<div class="header-sign-out">
          <span>Not ${first_name}?</span>
          <a class="sign-out-btn" href='/biz/DTB_memMember/Logout'>${i18n.navigation.sign_out || 'Sign out'}</a>
        </div>` : ''
      }
      </div>`;
    $('.header-right-account').append(d);
};
$.fn.mAccountDomBase = function (){
  if (!$('.mobile-nav-account').length) return;
  const s = (FS_MRSHOPPLUS.customer_name || '').split(' ');
  const first_name = s.length ? s[0] : '';
  const d = `<li class="mobile-account-item">
      ${FS_MRSHOPPLUS.customer_id ? `<a href='/biz/DTB_memMember/Logout'>Not ${first_name}? <u>${i18n.navigation.sign_out || 'Sign out'}</u></a>` :
      `<a href='/account/login'>${i18n.general.already_a_customer}? <u>${i18n.navigation.sign_in || 'Sign In'}</u></a>`
    }</li>`
  $('.mobile-nav-account').append(d)
}
$.header = function (params) {
  // header account hover
  if($(window).width() > 767 ){
    typeof $.fn.accountDom == 'undefined' ? $.fn.accountDomBase() : $.fn.accountDom();
    $('.header-right-account').hover(function () {
      $(this).children('.header-account-info').stop().show()
    }, function () {
      $(this).children('.header-account-info').stop().hide()
    });
  }else{
    typeof $.fn.mAccountDom == 'undefined' ? $.fn.mAccountDomBase() : $.fn.mAccountDom();
  }
  $(document).on('mrs.common.cart.change', function () {
    const cartnum = $('[data-header-cart-badge]');
    let count = 0;
    if (FS_MRSHOPPLUS.customer_id) {
      $.invokeBcfMethod('/biz/DTB_sstoCart/GetCartsCount', [], function (res) {
        count = res.result;
        if (count > 99) {
          cartnum.text('99+').show()
        } else {
          cartnum.text(count).show();
        }
      });
    } 
    $(document).trigger('mrs.common.cart.popup');
  });

  $(document).on('mrs.common.cart.popup', function () {
    // 更新头部购物车商品金额
    $.invokeBcfMethod('/biz/DTB_sstoCart/GetCartSubtotal', [], function (resp) {
      if (resp.success) {
        const items = resp.result.items || [];
        let count = 0;
        const cartnum = $('[data-header-cart-badge]');
        items.map(item => count += item.quantity)
        if (count) {
          if (count > 99) {
            cartnum.text('99+').show();
          } else {
            cartnum.show();
            count == 0 ? cartnum.text(count).hide() : cartnum.text(count).show();
          }
        } else {
          cartnum.text(count).hide();
        }
        if ($(window).width() > 767) {
        const $cartContent = $('.header-minicart-info')
          , img_w = $('[data-minitcart-img-w]').data('minitcart-img-w') || 120;
        if (items.length > 0) {
          const text = `${i18n.cart.subtotal}: <i class="minicart-subtotal-price">${$.moneyWithSymbol(resp.result.subtotal)}</i>`;
          const itemList = items.map(item => {
            return `<li class="minicart-item">
              <a class="minicart-item-content" href="${item.url}">
                <div class="minicart-item-img img-box">
                  <img src="${$.img_url_fit_w(item.imgurl, img_w, true)}" loading="lazy" alt="${item.name}">
                </div>
                <div class="minicart-item-info">
                  <div class="minicart-item-name">${item.name}</div>
                  <div class="minicart-item-sku">${item.attrs}*${item.quantity}</div>
                  <div class="minicart-item-price">
                    ${$.moneyWithSymbol(item.price)}
                  </div>
                </div>
              </a>
            </li>`
          }).join('');
          const content = `<div class="header-minicart-subtotal">
              <div class="minicart-header">
                <span class="minicart-subtotal">${text}</span>
                <a href="/cart" class="header-minicart-edit">${i18n.cart.edit_cart}</a>
              </div>
              <a href="javascript: Cart.direct2Checkout()" class="minicart-button button button--primary">${i18n.product.buy_now}</a>
              ${enabledPaypal ? '<div id="paypal-button-container-cart-popup"></div>' : ''}
            </div>
            <ul class="minicart-list">
              ${itemList}
            </ul>`;
          $cartContent.html(content).removeClass("header-minicart-empty");
          if ($('[data-minicart-price]').length) {
            $('[data-minicart-price]').text($.moneyWithSymbol(resp.result.subtotal));
          }
          if (enabledPaypal) {
            genCartPaypalBtn(paypalClientid, resp.result.subtotal, '#paypal-button-container-cart-popup')
          }
        } else {
          const emptyContent = `
            <div class="cartEmpty-link-wrapper">
              ${i18n.cart.empty_msg}
            </div>
            <a class="show-now-link" href="/all-products/">${i18n.general.shop_now}!</a>`;
          $cartContent.html(emptyContent).addClass("header-minicart-empty")
        }
      }
      }
    });
  });

  function genCartPaypalBtn(client_id, total, selector) {
    $.loadScript('https://www.paypal.com/sdk/js', { 'client-id': client_id, 'commit': false, 'disable-funding': 'credit,card' }, genPaypalButton);
    function genPaypalButton() {
      paypal.Buttons({
        style: {
          color: 'gold',
          shape: 'rect',
          tagline: false,
          layout: 'vertical',
          height: 48
        },
        createOrder: function (data, actions) {
          const currency = 'USD';
          // Set up the transaction
          const form = {
            purchase_units: [{
              amount: {
                value: total,
                currency_code: currency,
              },
            }]
          };
          return actions.order.create(form);
        },
        onApprove: function (data, actions) {
          const paypalOrderId = data.orderID;
          Cookies.set(paypalOrderId, data.facilitatorAccessToken);
          $(document).trigger('mrs.common.cart.paypal', { paypalOrderId })
        }
      }).render(selector);
    };
  };
  if (FS_MRSHOPPLUS.template_type != 104) {
    $(document).trigger('mrs.common.cart.change');
  }
  /**
   * 搜索
   */
  function triggerSearch(val) {
    if (val != null && val.trim().length > 0) {
      let n = true;
      if (typeof beforeSearch === "function") n = beforeSearch(val);
      if (n) {
        const value = val.trim().replaceAll(/[\+\*\&\^\%\#\\]/ig, '-');
        const search_term = encodeURIComponent(value)
        const url = `/search/${search_term}`;
        location.href = url;
      }
    } else {
      $.toast.error($.i18n_is_required(i18n.general.search.label))
    }
  }
  $(function () {
    $('header').on('keypress', '[name=search]', function (e) {
      if (e.keyCode === 13) {
        e.preventDefault()
        triggerSearch($(this).val());
      }
    });
    $('header').on('click', '.j-search', function (e) {
      e.preventDefault()
      const val = $(this).siblings("input").val();
      triggerSearch(val);
    });

  });
  /**
   * 币别
   */
  $('.currencies').hover(function () {
    $(this).find('.currencies-dropdown-menu').show()
    $.header.junstDropdownMenu();
  }, function () {
    $(this).find('.currencies-dropdown-menu').hide()
  });

  $('.currencies .currencies-item').on('click', function (obj) {
    $.invokeBcfMethod('/biz/DTB_ShopCurrency/PageCurrencySelect', [obj.currentTarget.id], function (resp) {
      location.reload();
    }, function () { });
  });

  var getChildrens = function (obj) {
    var childrens = $(obj).children();
    for (var i = 0; i < childrens.length; i++) {
      var nextChildren = getChildrens(childrens[i]);
      nextChildren.map((index, el) => {
        childrens.push(el);
      })
    }
    return childrens;
  }
};

$.extend($.header, {
  junstDropdownMenu: function () {
    var dropdownmenu = $('.currencies .currencies-dropdown-menu');
    var a = $(dropdownmenu).outerWidth();
    var dropdown = $('.currencies');
    if (dropdown.length) {
      for (var i = 0; i < dropdown.length; i++) {
        var b = $('.currencies').eq(i).offset().left;
        var c = $('body').outerWidth();
        if (c - b < a) {
          $(dropdownmenu).css({
            'left': (c - b - a - 5) + 'px'
          });
        } else {
          $(dropdownmenu).css({
            'left': 0 + 'px'
          });
        }
      }
    }
  }
});

/**
 * paypal product to checkout
 */
$(document).on("mrs.common.product.paypal", function (e, options) {
  const url = `/checkout-f${Date.now()}?paypal_checkout=${options.variant_id}|${options.quantity}&paypalOrderId=${options.paypalOrderId}`;
  location.href = url;
});
/**
 * paypal cart to checkout
 */
$(document).on("mrs.common.cart.paypal", function (e, options) {
  const url = `/checkout-f${Date.now()}?paypalOrderId=${options.paypalOrderId}`;
  location.href = url;
});
/**
 * paypal to checkout
 */
$(document).on("mrs.common.checkout.paypal", function (e, options) {
  const query = $.toQuery($.extend($.params(), {
    paypalOrderId: options.paypalOrderId,
    step: "contact_information"
  }));
  const pathAndQuery = `${location.pathname}?${query}`;
  window.history.replaceState(null, "", pathAndQuery);
  const modeldata = options.modeldata;
  $.extend(true, order.shipping_address, modeldata.shipping_address);
  CHECKOUT.replaceStateAndRender('1');
});

/**
 * 接收预览postmessage事件
 */
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event) {
  if (event.data) {
    switch (event.data.type) {
      case "scroll": {
        sectionScrollTop(event.data.selector);
        break;
      };
      case "reload": {
        Cookies.set(event.data.key, event.data.id);
        location.reload();
        break;
      }
      default: {
        break;
      }
    }
  }
};
function sectionScrollTop(selector) {
  const el = document.getElementById(selector);
  if (el) {
    const { top, height } = el.getBoundingClientRect();
    const elCenter = top + height / 2;
    const winCenter = window.innerHeight / 2;
    window.scrollTo({
      top: getWindowScrollTop() - (winCenter - elCenter),
      behavior: 'smooth'
    });
  }
};
function getWindowScrollTop() {
  let scrollTop = 0;
  if (document.documentElement && document.documentElement.scrollTop) {
    scrollTop = document.documentElement.scrollTop;
  } else if (document.body) {
    scrollTop = document.body.scrollTop;
  }
  return scrollTop;
};

$(function () {
  document.body.onresize = function () {
    $.header.junstDropdownMenu();
  }
  if ($('[data-section-type="header"]').length > 0) {
    $.header && $.header()
  }

  if ($('#email-subs-btn').length > 0) {
    $(document).on('click', '#email-subs-btn', function () {
      const email = $('#email-subs-input').val().trim();
      if (newsletter(email)) {
        $(this).siblings('#email-subs-input').val('')
      };
    });
    $("#email-subs-input").keypress(function (event) {
      if (event.keyCode === 13) {
        $(this).siblings('#email-subs-btn').trigger('click')
      }
    })
  }
  // account —— mobile title slide
  $(document).on("click", ".account-main .section-title", function () {
    if ($(window).width() < 768) {
      $(this).siblings().stop().slideToggle();
      $(this).children("i").toggleClass("icon-down").toggleClass("icon-up");
    }
  });
  // announce swiper
  if ($('.j-announcement-newswiper').length > 0) {
    const is_autoplay = $('.j-announcement-newswiper').data('autoplay')
    const delay = $('.j-announcement-newswiper').data('delay')
    const config = {
      navigation: {
        prevEl: '.icon-left.announcement-btn',
        nextEl: '.icon-right.announcement-btn',
      },
      spaceBetween: 10,
      mousewheel: true,
      speed: 200
    }
    if (is_autoplay) {
      config['autoplay'] = {
        delay: delay * 1000
      }
      config['loop'] = true
    }
    let announcementSwiper = new Swiper('.j-announcement-newswiper', config)
  }
})

