/**
 * Created by Jack on 2016/4/7.
 */

'use strict';

var $ = require('Zepto');
var $ext = require('core/ext');
var $consts = require('core/consts');

!String.formatPara && (String.prototype.formatPara = function() {
    var isJson = arguments.length == 1 && arguments[0] instanceof Object,
        args = isJson ? arguments[0] :arguments,
        regs = isJson ? /\{(\w+)\}/g :  /\{(\d+)\}/g;
    return this.replace(regs,function(k,v) {
        return args[v] || '';

    });
});

var decode = true; //decode = true 为开启数据加密
$consts ? $consts.decode = decode : $consts = {decode : decode};

var requests = {

    dataDecode: function(success, data, error) {
      !error && (error = this.getDefError);
      $.ajax({
          url: this.getWholeURL('pub/decode/do'),
          success: success,
          error: error,
          async: true,
          dataType: "json",
          data: JSON.stringify({strDecode: data}),
          type: 'post',
          timeout: 60000
      });
    },

    getDefError: function(data){
        $ext.tipNetError();
    },
    getWholeURL: function(url){
        return url.indexOf('http') === -1 ? ($consts.PRO_PATH + url) : url;
    },
    getImagesURL: function(url){
        return url.indexOf('http') === -1 ? ($consts.PRO_IMG + url) : url;
    },

    dataToParam:function(url,json){
        var p = json || {},
            noP = url.indexOf('?') ==-1,
            tpl = "&{0}={1}",
            params = '';
        $.each(p,function(k,v){
            params += tpl.formatPara(k,v);
        });
        noP && (params = params.replace("&","?"));
        return params;
    },
    beforeSend:function(){
        if (!document.querySelector(".pre-load")) {
            $('body').append('<div class="pre-load"></div>');
        }
    },
    completeFun:function(){
        var pre = $(".pre-load");
        if (pre[0]) {
            $(".pre-load").remove();
        }
    },
    /**
     * 底层请求
     */
    req:function(url,success,data,async,error,before,completed){
        var _this = this;
        //默认错误设置
        !error && (error = this.getDefError);
        !before && (before = this.beforeSend);
        !completed && (completed = this.completeFun);
        //console.log(JSON.stringify(data));
        $.ajax({
            url: this.getWholeURL(url),
            success: decode ? function(datas) {_this.dataDecode(success, datas, error, before, completed);} : success,
            beforeSend:before,
            error: error,
            complete:completed,
            async: async === undefined ? true : async,
            dataType: decode ? 'text' : 'json',
            data:JSON.stringify(data),
            type: 'post',
            timeout: 60000/*,
            xhrFields:{
                'withCredentials': 'true'   //凭证
            }*/
        });

    },
    reqGet:function(url,success,data,async,error,before,completed){
        //默认错误设置
        !error && (error = this.getDefError);
        !before && (before=this.beforeSend);
        !completed && (completed=this.completeFun)
        var that = this;
        $.ajax({
            url: this.getWholeURL(url),
            success: decode ? function(datas) {that.dataDecode(success, datas, error, before, completed);} : success,
            error: error,
            beforeSend:before,
            complete:completed,
            async: async === undefined ? true : async,
            dataType: decode ? 'text' : 'json',
            data: this.dataToParam(that.getWholeURL(url), data),
            type: 'get',
            timeout: 60000/*,
             xhrFields:{
             'withCredentials': 'true'   //凭证
             }*/
        });

    },

  reqImg:function(url,success,data,async,error){
    //默认错误设置
    !error && (error = this.getDefError);

    $.ajax({
        url: this.getImagesURL(url),
        success:  success,
        error: error,
        async: async === undefined ? true : async,
        dataType: 'json',
        data:data,
        type: 'post',
        processData:false,
        contentType:false,
        cache:false
    });
      return false;

  },

    wxLoginReq:function(successFn, data, errorFn, error){
        this.req($consts.WX_BIND, successFn, data);  //微信登录获取out_id
    },
    profileReq:function(successFn, data, errorFn, error){
        this.reqGet($consts.PROFILE, successFn, data);  //不登录获取用户信息
    },
    nearByReq:function(successFn, data, errorFn, error){
        this.reqGet($consts.NEARBY, successFn, data, null, null, function(){}, function(){});  //地图预约设备
    },
    operatorRq:function(successFn, data, errorFn, error){
        this.reqGet($consts.OPLIST, successFn, data, null, null, function(){}, function(){});  //地图预约机手
    },
    versionReq: function(successFn, data){
        this.reqGet($consts.VERSION_NUM, successFn, data);  //下载URL版本号
    },
    searchWord: function(successFn, data){
        this.reqGet($consts.SEARCH_WORD, successFn, data);  //搜索关键词
    },
    searchEqReq:function(successFn, data, errorFn, error){
        this.reqGet($consts.SEARCH_EQ, successFn, data);  //搜索设备
    },
    weChat:function(successFn, data, errorFn, error){
        this.reqGet($consts.WE_CHAT2, successFn, data);  //微信接口
    },
    eqDetail:function(successFn, data, errorFn, error){
        this.reqGet($consts.DETAIL_EQ, successFn, data);  //设备详情
    },
    operatorDetail:function(successFn, data, errorFn, error){
        this.reqGet($consts.OPERATOR_LIST, successFn, data);  //机手详情
    },
    commentsCon:function(successFn, data, errorFn, error){
        this.reqGet($consts.COMMENT_LIST, successFn, data);  //机手、工程师评论列表
    },
    commentsCount:function(successFn, data, errorFn, error){
        this.req($consts.COMMENT_COUNT, successFn, data);  //评论标签
    },
    checkCode:function(successFn, data, errorFn, error){
        this.req($consts.CHECKCODE, successFn, data);  //发送验证码
    },
    loginReq:function(successFn, data, errorFn, error){
        this.req($consts.LOGIN, successFn, data);  //验证码登录
    },
    login2Req:function(successFn, data, errorFn, error){
        this.req($consts.LOGIN2, successFn, data);  //密码登录
    },
    updateMember:function(successFn, data, errorFn, error){
        this.req($consts.UPDATE_MEMBER, successFn, data);  //编辑用户资料
    },
    areaListReq:function(successFn, data, errorFn, error){
        this.reqGet($consts.AREA_LIST, successFn, data);  //地区
    },
    serviceListReq:function(successFn, data, errorFn, error){
        this.reqGet($consts.SERVICE_LIST, successFn, data);  //底盘服务站列表
    },
    brandListReq:function(successFn, data, errorFn, error){
        this.reqGet($consts.BRAND_LIST, successFn, data);  //底盘品牌
    },
    repairListReq: function(successFn, data, errorFn, error){
        this.reqGet($consts.REPAIR_LIST, successFn, data);  //大修厂列表
    },
    repairTypesReq:function(successFn, data, errorFn, error){
        this.reqGet($consts.REPAIR_TYPES, successFn, data);  //大修厂维修类型
    },
    concatReq:function(successFn, data, errorFn, error){
        this.req($consts.CONCAT, successFn, data);  //感兴趣
    },

    promotionLoginReq: function(successFn, data) {
        this.req($consts.PROMOTER_LOGIN, successFn, data);  //推广员登录
    },
    promotionCheckReq: function(successFn, data) {
        this.req($consts.PROMOTER_CHECK, successFn, data);  //判断推广员身份
    },
    promotionIdReq: function(successFn, data) {
        this.req($consts.PROMOTER_ID, successFn, data);  //推广员ID
    },
    promotionReq: function(successFn, data) {
        this.req($consts.PROMOTER, successFn, data);  //推广用户信息
    },
    promotionMobReq: function(successFn, data) {
        this.req($consts.PROMOTER_MOB, successFn, data);  //号码是否重复
    },

    couponCheckReq: function(successFn, data) {
        this.req($consts.COUPON_CHECK, successFn, data);  //验证优惠券
    },
    promoterBindReq: function(successFn, data) {
        this.req($consts.PROMOTER_BIND, successFn, data);  //推广员绑定
    },
    couponDetailReq: function(successFn, data) {
        this.reqGet($consts.COUPON_DETAIL, successFn, data);  //优惠券详情
    },

    receiveCouponReq: function(successFn, data) {
        this.req($consts.RECEIVE_COUPON, successFn, data);  //领取优惠券
    },

    recordListReq: function(successFn, data) {
        this.reqGet($consts.RECORD_LIST, successFn, data);  //大转盘获奖名单列表
    },
    luckyDrawReq: function(successFn, data) {
        this.req($consts.LUCKY_DRAW, successFn, data);  //大转盘抽奖
    },
    wechatRedReq: function(successFn, data) {
        this.reqGet($consts.WECHAT_RED, successFn, data);  //微信红包
    },
    loginCheckcodeReq: function(successFn, data) {
        this.req($consts.LOGIN_CHECKCODE, successFn, data);  //用户登录验证码
    },
    activityDetailReq:function(successFn, data) {
        this.req($consts.ACTIVITY_DETAIL, successFn, data);  //活动详情
    }
    

};

module.exports = requests;
