/**
 * 购物车
 * @author: feng.chen<feng.chen@yoho.cn>
 * @date: 2016/12/21
 */

'use strict';
const helpers = global.yoho.helpers;
const _ = require('lodash');
const headerModel = require('../../../doraemon/models/header'); // 头部model

const cartModel = require('../models/index');

// cookie 参数
const actCkOpthn = {
    path: '/cart/index'
};

/**
 * [购物车首页]
 */
const index = (req, res) => {
    let isLogin = req.user && req.user.uid,
        pageData = {
            isLogin,
            signurl: helpers.urlFormat('/signin.html', {
                refer: req.originalUrl
            })
        };

    // 标识是从普通购物车进的提交订单页面,普通购物车进入提交订单页面默认不使用优惠券
    res.cookie('ensure_from', 'cart', actCkOpthn);

    // 唤起 APP 的路径
    res.locals.appPath = 'yohobuy://yohobuy.com/goapp?openby:yohobuy={"action":"go.shopcart","params":{}}';

    res.render('cart-index', Object.assign(pageData, {
        title: '购物车',
        module: 'cart',
        page: 'index',
        localCss: true,
        width750: true,
        pageHeader: headerModel.setNav({
            navTitle: '购物车',
            backUrl: 'javascript:;', // eslint-disable-line
            navBack: true,
            suggestSub: {
                text: ' '
            },
            navBtn: false
        }),
        isWechat: req.yoho.isWechat || req.yoho.isMarsApp // 默认判断微信,mars下同微信
    }));
};

/**
 * [购物车数据]
 */
const indexData = (req, res, next) => {
    if (!req.xhr) {
        return next();
    }
    let shoppingKey = req.cookies._SPK || '',
        channel = req.cookies._Channel,
        cartType = req.cookies.cartType || 'ordinary',
        uid = req.user && req.user.uid;

        // shoppingKey = 'dc9d09e2ffd8607f2cfd8b9c95962923';
        // uid = 20422448;

    return req.ctx(cartModel).indexData(uid, shoppingKey, channel, cartType).then(data => {
        data ? res.json({
            code: 200,
            data
        }) : res.status(400).json({
            message: '操作失败'
        });
    }).catch(next);
};

/**
 * [选择或者取消商品]
 */
const select = (req, res, next) => {
    if (!req.xhr) {
        return next();
    }
    let shoppingKey = req.cookies._SPK || '',
        uid = req.user && req.user.uid;
    let skuList = req.body.skuList,
        cartType = req.cookies.cartType || 'ordinary';

    if (!skuList || !skuList.length) {
        return res.json({
            code: 400,
            message: '参数错误'
        });
    }

    // shoppingKey = 'dc9d09e2ffd8607f2cfd8b9c95962923';
    // uid = 20422448;

    return req.ctx(cartModel).selectGood(uid, skuList, shoppingKey, cartType).then(data => {
        data ? res.json({
            code: 200,
            data
        }) : res.status(400).json({
            message: '操作失败'
        });
    }).catch(next);
};

/**
 * [移出购物车]
 */
const del = (req, res, next) => {
    if (!req.xhr) {
        return next();
    }
    let shoppingKey = req.cookies._SPK || '',
        uid = req.user && req.user.uid;
    let skuList = req.body.skuList,
        cartType = req.cookies.cartType || 'ordinary';

    if (!skuList || !skuList.length) {
        return res.json({
            code: 400,
            message: '参数错误'
        });
    }

    // shoppingKey = 'dc9d09e2ffd8607f2cfd8b9c95962923';
    // uid = 20422448;

    return req.ctx(cartModel).removeFromCart(uid, skuList, shoppingKey, cartType).then(data => {
        data ? res.json({
            code: 200,
            data
        }) : res.status(400).json({
            message: '操作失败'
        });
    }).catch(next);
};

/**
 * [加入购物车]
 */
const add = (req, res, next) => {
    // for guang
    let allowOrigin = _.get(req, 'headers.origin', null) ?
        req.headers.origin : req.protocol + '://guang.' + req.headers.host;

    res.setHeader('Access-Control-Allow-Origin', allowOrigin);
    res.setHeader('Access-Control-Allow-Credentials', 'true');

    // if (!req.xhr) {
    //     return next();
    // }
    let shoppingKey = req.cookies._SPK || '',
        uid = req.user && req.user.uid;
    let productSku = req.body.productSku,
        buyNumber = req.body.buyNumber || 1,
        goodsType = req.body.goodsType || 0,
        promotionId = req.body.promotionId || 0,
        isEdit = req.body.isEdit || 0;

    if (!productSku) {
        return res.json({
            code: 400,
            message: '参数错误'
        });
    }

    // shoppingKey = 'dc9d09e2ffd8607f2cfd8b9c95962923';
    // uid = 20422448;

    return req.ctx(cartModel).addToCart(
        productSku, buyNumber, goodsType, isEdit, promotionId, uid, shoppingKey).then(data => {
        if (!shoppingKey && _.has(data, 'data.shopping_key')) {
            res.cookie('_SPK', data.data.shopping_key, {
                expires: new Date(Date.now() + 86400 * 360),
                domain: '.m.yohobuy.com'
            });
        }
        data ? res.json(data) : res.status(400).json({
            message: '操作失败'
        });
    }).catch(next);
};

/**
 * [获取购物车数据]
 */
const goodinfo = (req, res, next) => {
    if (!req.xhr) {
        return next();
    }
    let result = {};
    let uid = req.user && req.user.uid,
        buyNum = req.body.buy_num,
        mnum = req.body.mnum,
        skn = req.body.skn,
        promotionId = req.body.promotion_id;

    if (!buyNum || !skn) {
        return res.json({
            code: 400,
            message: '参数错误'
        });
    }

    return req.ctx(cartModel).cartProductData(uid, skn, buyNum).then(data => {
        return new Promise((resolve) => {
            if (mnum && data) {
                return req.ctx(cartModel).handleBundleInfo(skn).then(disRes => {
                    result.discountBuy = disRes;
                    resolve(data);
                });
            }
            resolve(data);
        }).then(cartInfo => {
            result.cartInfo = cartInfo;
            cartInfo ? res.json(Object.assign({
                code: 200,
                promotionId: promotionId
            }, result)) : res.status(400).json({
                message: '操作失败'
            });
        });

    }).catch(next);
};

/**
 * [加入收藏]
 */
const col = (req, res, next) => {
    if (!req.xhr) {
        return next();
    }
    let uid = req.user && req.user.uid;
    let skuList = req.body.skuList,
        cartType = req.cookies.cartType || 'ordinary';

    if (!skuList || !skuList.length) {
        return res.json({
            code: 400,
            message: '参数错误'
        });
    }

    // shoppingKey = 'dc9d09e2ffd8607f2cfd8b9c95962923';
    // uid = 20422448;
    if (!uid) {
        return res.json({
            code: 401,
            message: '请先登录',
            data: helpers.urlFormat('/signin.html')
        });
    }
    return req.ctx(cartModel).addToFav(uid, skuList, cartType).then(data => {
        data ? res.json({
            code: 200,
            data
        }) : res.status(400).json({
            message: '操作失败'
        });
    }).catch(next);

};

/**
 * [修改购物车数量]
 */
const modifyNum = (req, res, next) => {
    if (!req.xhr) {
        return next();
    }
    let uid = req.user && req.user.uid,
        shoppingKey = req.cookies._SPK || '',
        sku = req.body.sku,
        increaseNum = req.body.increaseNum,
        decreaseNum = req.body.decreaseNum;

    if (!sku || (!increaseNum && !decreaseNum)) {
        return res.json({
            code: 400,
            message: '参数错误'
        });
    }

    // shoppingKey = 'dc9d09e2ffd8607f2cfd8b9c95962923';
    // uid = 20422448;

    let promise;

    if (increaseNum > 0) {
        promise = req.ctx(cartModel).increaseProductNum(uid, sku, increaseNum, shoppingKey);
    } else if (decreaseNum > 0) {
        promise = req.ctx(cartModel).decreaseProductNum(uid, sku, decreaseNum, shoppingKey);
    }

    return promise.then(data => {
        if (data && data.code === 200 && data.data) {
            res.json({
                code: 200,
                goodsCount: data.data.goods_count
            });
        } else {
            res.json({
                code: 400,
                message: data.message
            });
        }

    }).catch(next);
};

/**
 * [修改购物车数据]
 */
const modify = (req, res, next) => {
    if (!req.xhr) {
        return next();
    }
    let uid = req.user && req.user.uid,
        shoppingKey = req.cookies._SPK || '';

    let oldProductSku = req.body.old_product_sku || 0,
        newProductSku = req.body.new_product_sku || 0,
        buyNumber = req.body.buy_number || 0,
        activity_id = req.body.activity_id,
        batch_no = req.body.batch_no,
        selected = req.body.selected;

    if (!oldProductSku || !newProductSku) {
        return res.json({
            code: 400,
            message: '参数错误'
        });
    }

    // shoppingKey = 'dc9d09e2ffd8607f2cfd8b9c95962923';
    // uid = 20422448;
    return req.ctx(cartModel).modifyCartProduct(uid, [{
        old_product_sku: oldProductSku,
        new_product_sku: newProductSku,
        buy_number: buyNumber,
        selected: selected,
        activity_id: activity_id,
        batch_no: batch_no
    }], shoppingKey).then(data => {
        data ? res.json(data) : res.status(400).json({
            message: '操作失败'
        });
    }).catch(next);
};

/**
 * [修改购物车赠品、加价购数据]
 */
const modifyPriceGift = (req, res, next) => {
    if (!req.xhr) {
        return next();
    }
    let uid = req.user && req.user.uid,
        shoppingKey = req.cookies._SPK || '';

    let newProductSku = req.body.new_product_sku || 0,
        newProductSkn = req.body.new_product_skn || 0,
        promotionId = req.body.promotionId || 0;

    if (!promotionId || !newProductSku) {
        return res.json({
            code: 400,
            message: '参数错误'
        });
    }

    // shoppingKey = 'dc9d09e2ffd8607f2cfd8b9c95962923';
    // uid = 20422448;
    return req.ctx(cartModel).modifyCartPriceGiftProduct(uid, newProductSku,
        newProductSkn, promotionId, shoppingKey)
        .then(data => {
            data ? res.json(data) : res.status(400).json({
                message: '操作失败'
            });
        }).catch(next);
};

/**
 * [获取赠品商品列表]
 */
const gift = (req, res, next) => {
    let cartType = req.cookies.cartType || 'ordinary',
        promotionIds = req.query.promotion_ids;

    if (!promotionIds) {
        return next();
    }
    return req.ctx(cartModel).getPriceGiftList(promotionIds, 'Gift').then(data => {
        res.render('gift', Object.assign(data, {
            title: '赠品',
            module: 'cart',
            page: 'gift',
            localCss: true,
            pageHeader: headerModel.setNav({
                navTitle: '赠品',
                navBack: true,
                suggestSub: {
                    text: ' '
                },
                navBtn: false
            })
        }, {
            giftPage: true,
            cartType: cartType
        }));
    }).catch(next);
};

/**
 * [获取加价购商品列表]
 */
const advanceBuy = (req, res, next) => {
    let cartType = req.cookies.cartType || 'ordinary',
        promotionIds = req.query.promotion_ids;

    if (!promotionIds) {
        return next();
    }
    return req.ctx(cartModel).getPriceGiftList(promotionIds, 'Needpaygift').then(data => {
        res.render('gift', Object.assign(data, {
            title: '加价购',
            module: 'cart',
            page: 'gift',
            localCss: true,
            pageHeader: headerModel.setNav({
                navTitle: '加价购',
                navBack: true,
                suggestSub: {
                    text: ' '
                },
                navBtn: false
            })
        }, {
            advanceBuyPage: true,
            cartType: cartType
        }));
    }).catch(next);
};

/**
 * [获取购物车加价购商品数据]
 */
const giftinfo = (req, res, next) => {
    if (!req.xhr) {
        return next();
    }
    let skn = req.body.skn,
        promotionId = req.body.promotionId;

    if (!skn) {
        return res.json({
            code: 400,
            message: '参数错误'
        });
    }
    return req.ctx(cartModel).giftProductData(skn, promotionId).then(data => {
        data ? res.json({
            promotionId: promotionId,
            cartInfo: data
        }) : res.status(400).json({
            message: '操作失败'
        });
    }).catch(next);
};


/**
 * 增加套餐的数量
 * @param {*} req
 * @param {*} res
 * @param {*} next
 */
const incrBundle = (req, res, next) => {
    let uid = req.user.uid;
    let shoppingKey = req.cookies._SPK || '';

    return req.ctx(cartModel).incrBundle({
        uid: uid,
        shopping_key: shoppingKey,
        activity_id: req.body.activity_id,
        sku_ids: req.body.sku_ids,
        batch_no: req.body.batch_no,
    }).then(result => {
        res.json(result);
    }).catch(next);
};

/**
 * 增加套餐的数量
 * @param {*} req
 * @param {*} res
 * @param {*} next
 */
const decrBundle = (req, res, next) => {
    let uid = req.user.uid;
    let shoppingKey = req.cookies._SPK || '';

    return req.ctx(cartModel).decrBundle({
        uid: uid,
        shopping_key: shoppingKey,
        activity_id: req.body.activity_id,
        sku_ids: req.body.sku_ids,
        batch_no: req.body.batch_no,
    }).then(result => {
        res.json(result);
    }).catch(next);
};

module.exports = {
    index,
    indexData,
    select,
    del,
    goodinfo,
    col,
    modifyNum,
    add,
    modify,
    gift,
    giftinfo,
    advanceBuy,
    modifyPriceGift,
    incrBundle,
    decrBundle
};