'use strict';
const _ = require('lodash');
const helpers = global.yoho.helpers;
const co = Promise.coroutine;
const cartModel = require('../models/cart');
const headerModel = require('../../../doraemon/models/header');
const userModel = require('../models/user');
const addressModel = require('../models/address');
const orderModel = require('../models/order');
const buyNowModel = require('../models/buy-now-model');
const shoppingModel = require('../models/shopping');
const paymentProcess = require(global.utils + '/payment-process');
const logger = global.yoho.logger;

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

exports.orderEnsure = (req, res, next) => {
    let headerData = headerModel.setNav({
        navTitle: '确认订单',
        navBtn: false
    });

    let uid = req.user.uid;
    let returnUrl = helpers.urlFormat('/cart/index/index');
    let cartType = req.query.cartType;
    let orderInfo;

    try {
        orderInfo = JSON.parse(req.cookies['order-info']);
    } catch (e) {
        logger.info(`orderEnsure: get orderInfo from cookie error:${JSON.stringify(e)}`);
        orderInfo = {};
        res.clearCookie('order-info', actCkOpthn);
    }

    if (!cartType) {
        cartType = _.get(orderInfo, 'cartType', 'ordinary');
    }

    // 如果传递了code, skn, sku, buy_number 就代表限购商品
    let limitProductCode = req.query.limitproductcode || '';
    let sku = req.query.sku || '';
    let skn = req.query.skn || '';
    let buyNumber = req.query.buy_number || 1;

    if (limitProductCode) {
        headerData.backUrl = req.get('Referer') || returnUrl;
    } else {
        headerData.backUrl = returnUrl;
    }

    let orderPromise;
    let params = {
        uid: uid,
        cartType: cartType,
        orderInfo: orderInfo,
        sku: sku,
        skn: skn,
        buyNumber: buyNumber,
    };

    if (req.query.cartType === 'bundle') {
        if (!req.cookies._cartType) {
            res.cookie('_cartType', 'bundle', actCkOpthn);
        }
        let activityInfo = JSON.parse(req.cookies['activity-info']);

        orderPromise = req.ctx(cartModel).cartPay(_.assign(params, {
            activityInfo: activityInfo
        }));
    } else {
        orderPromise = req.ctx(cartModel).cartPay(params);
    }

    let allPromise = [
        orderPromise,
        req.ctx(userModel).queryProfile(uid),
        req.ctx(addressModel).addressData(uid)
    ];

    if (_.isUndefined(req.cookies._isNewUser)) {
        allPromise.push(req.ctx(orderModel).isNewUser(uid));
    }

    return Promise.all(allPromise).then(result => {
        let order = result[0];
        let userProfile = result[1];
        let address = result[2];
        let isNewUser = result[3];
        let autoSelectCouponCodeStr = _.get(order, 'coupon.couponCode', '');

        if (!_.isUndefined(isNewUser)) {
            if (isNewUser) {
                res.cookie('_isNewUser', true, actCkOpthn);
            } else {
                res.cookie('_isNewUser', false, actCkOpthn);
            }
        }

        if (orderInfo.user_check_coupon !== 'Y' && autoSelectCouponCodeStr) {
            orderInfo.coupon_code = autoSelectCouponCodeStr;
            res.cookie('order-info', JSON.stringify(orderInfo), actCkOpthn);
        }

        if (req.xhr) {
            logger.info(`orderEnsure: ajax request, return json:${JSON.stringify(order)}`);
            return res.json(order);
        }

        if (order.cartUrl) {
            logger.info(`orderEnsure: order cartUrl has value:${order.cartUrl}, order data is null`);
            return res.redirect(order.cartUrl);
        }

        // 获取用户完整手机号
        let mobile = _.get(userProfile, 'data.mobile', '');
        let orderAddress = _.get(order, 'address', []);
        let addressList = _.get(address, 'data', []);

        orderAddress.length && _.forEach(addressList, address => { //eslint-disable-line
            if (address.address_id === orderAddress.address_id) {
                mobile = address.mobile;
                return false;
            }
        });

        let viewData = {
            orderEnsurePage: true,
            isOrdinaryCart: cartType !== 'advance',
            orderEnsure: _.assign(order, {
                isOrdinaryCart: cartType !== 'advance',
                choseGiftCard: helpers.urlFormat('/cart/index/new/selectGiftcard')
            }),
            userMobile: mobile,
            pageHeader: headerData,
            pageFooter: false,
            module: 'cart',
            page: 'order-ensure',
            width750: true,
            localCss: true,
            title: '确认订单'
        };

        res.render('order-ensure', viewData);
    }).catch(next);
};

/**
 * 购物车选择改变字段,重新运算订单数据
 */
exports.orderCompute = (req, res, next) => {
    let cartType = req.body.cartType || 'ordinary';
    let deliveryId = req.body.deliveryId || 1;
    let paymentType = req.body.paymentType || 1;
    let couponCode = req.body.couponCode || null;
    let gift_card_code = req.body.gift_card_code || null;
    let yohoCoin = req.body.yohoCoin || null;
    let productSku = req.body.productSku || null;
    let buyNumber = req.body.buyNumber || null;
    let uid = req.user.uid;
    let skuList = req.body.skuList;
    let type = req.body.type;
    let orderInfo;

    try {
        orderInfo = JSON.parse(req.cookies['order-info']);
    } catch (e) {
        logger.info(`orderEnsure: get orderInfo from cookie error:${JSON.stringify(e)}`);
        orderInfo = {};
        res.clearCookie('order-info', actCkOpthn);
    }

    if (type !== 'tickets') {
        let params = {
            uid: uid,
            cart_type: cartType,
            delivery_way: deliveryId,
            payment_type: paymentType,
            coupon_code: couponCode,
            gift_card_code: gift_card_code,
            use_yoho_coin: yohoCoin,
        };

        if (req.body.cartType === 'bundle') {
            let activityInfo = JSON.parse(req.cookies['activity-info']);

            req.ctx(cartModel).orderCompute(_.assign(params, {
                activityInfo: activityInfo
            })).then(result => {
                res.json(result);
            }).catch(next);
        } else {
            req.ctx(cartModel).orderCompute(_.assign(params, {
                product_sku_list: skuList,
                userCheckCoupon: orderInfo.user_check_coupon
            })).then(result => {
                res.json(result);
            }).catch(next);
        }
    } else {
        req.ctx(cartModel).ticketsOrderCompute(uid, productSku, buyNumber, yohoCoin,
            gift_card_code).then(result => {
            res.json(result);
        }).catch(next);
    }
};

/**
 * 确认结算订单
 */
exports.orderSub = (req, res, next) => {
    let uid = req.user.uid;
    let udid = req.cookies.udid || 'yoho';
    let addressId = req.body.addressId;
    let cartType = req.body.cartType || 'ordinary';
    let deliveryTimeId = req.body.deliveryTimeId || 1;
    let deliveryId = req.body.deliveryId || 1;
    let paymentTypeId = req.body.paymentTypeId || 15;
    let paymentType = req.body.paymentType || 1;
    let msg = req.body.msg || null;
    let couponCode = req.body.couponCode || null;
    let gift_card_code = req.body.gift_card_code || null;
    let verifyCode = req.body.verifyCode || null;
    let yohoCoin = req.body.yohoCoin || 0;
    let skuList = req.body.skuList || '';
    let isPrintPrice = req.body.isPrintPrice || 'Y';
    let orderInfo;

    try {
        orderInfo = JSON.parse(req.cookies['order-info']);
    } catch (e) {
        orderInfo = {};
        res.cookie('order-info', null, actCkOpthn);
    }

    let times = req.body.times || 1;

    // 电子发票信息数组
    let invoices = {};

    // 是否有发票数据
    if (orderInfo && orderInfo.invoice) {
        let invoicePayableType = _.parseInt(orderInfo.invoice_payable_type) || 1;
        let invoicesTitlePersonal = orderInfo.invoices_title_personal ? orderInfo.invoices_title_personal : '个人';

        invoices = {
            invoices_type_id: 12, // 发票类型写死【明细】
            invoices_type: orderInfo.invoices_type, // 区分电子发票还是纸质发票
            receiverMobile: orderInfo.receiverMobile, // 电话
            invoice_payable_type: invoicePayableType // 区分个人或企业发票
        };

        if (invoicePayableType === 1) {
            // 开个人发票
            invoices.invoices_title = invoicesTitlePersonal;
        } else {
            // 开公司发票
            invoices.invoices_title = orderInfo.invoices_title;
            invoices.buyerTaxNumber = orderInfo.buyerTaxNumber;
        }
    }

    /* 判断是否是友盟过来的用户 */
    let unionInfo = {};

    if (req.cookies.mkt_code || req.cookies._QYH_UNION) {
        unionInfo = paymentProcess.unionInfoHandle(req.cookies, uid);
    }

    return co(function* () {
        // 使用礼品卡,发送验证码
        if (gift_card_code) {
            if (!verifyCode) {
                yield req.ctx(orderModel).giftCardSendSms(uid);

                return res.json({
                    code: 411
                });
            } else {
                let verifyResult = yield req.ctx(orderModel).validRegCode({
                    uid, verifyCode, udid
                });

                if (verifyResult.code !== 200) {
                    return res.json(verifyResult);
                }
            }
        }

        let result;
        let params = {
            uid: uid,
            address_id: addressId,
            delivery_time: deliveryTimeId,
            delivery_way: deliveryId,
            invoices: invoices,
            payment_id: paymentTypeId,
            payment_type: paymentType,
            remark: msg,
            coupon_code: couponCode,
            gift_card_code: gift_card_code,
            use_yoho_coin: yohoCoin,
            is_print_price: isPrintPrice,
            qhy_union: unionInfo.unionKey, // 友盟数据
            userAgent: unionInfo.userAgent,
            isWechat: req.yoho.isWechat,
            ip: req.yoho.clientIp,
            udid: udid
        };

        /* tar modified 161206 套餐 */
        if (req.body.cartType === 'bundle') {
            let activityInfo = JSON.parse(req.cookies['activity-info']);

            result = yield req.ctx(cartModel).orderSub(_.assign(params, {
                cart_type: 'bundle',
                times: times,
                activityInfo: activityInfo
            }));
        } else {
            result = yield req.ctx(cartModel).orderSub(_.assign(params, {
                cart_type: cartType,
                product_sku_list: skuList
            }));
        }

        // 提交成功清除Cookie
        orderInfo = {};
        res.cookie('order-info', null, actCkOpthn);

        if (result.code === 409) {
            return res.json(decodeURI(result));
        } else {
            return res.json(result);
        }
    })().catch(next);
};

/**
 * 下单流程-选择优惠券页面
 */
exports.selectCouponsPage = (req, res) => {
    let headerData = headerModel.setNav({
        navTitle: '选择优惠券',
        myConponPageNavBtn: true,
        navBtn: false
    });

    res.render('select-coupons-page', {
        module: 'cart',
        page: 'select-coupons',
        title: '选择优惠券',
        selectCouponPage: true,
        pageHeader: headerData,
        pageFooter: false,
        localCss: true,
        width750: true
    });
};

/**
 * 下单流程--获取优惠券列表
 */
exports.couponList = (req, res, next) => {
    let uid = req.user.uid;
    let delivery_way = req.body.delivery_way || 1;
    let coupon_code = req.body.coupon_code || '';

    co(function* () {
        let couponApi = yield req.ctx(shoppingModel).listCoupon({
            uid: uid,
            delivery_way: delivery_way,
            coupon_code: coupon_code
        });
        let result = paymentProcess.couponProcess(_.get(couponApi, 'data', {}));

        res.render('select-coupons', {
            pageFooter: false,
            result: result,
            layout: false
        });
    })().catch(next);
};

/**
 * 选择礼品卡页面
 */
exports.selectGiftcard = (req, res, next) => {
    let headerData = headerModel.setNav({
        navTitle: '礼品卡',
        navBtn: false
    });
    let uid = req.user.uid;

    co(function* () {
        let usable_giftCards = []; // 可用礼品卡列表
        let sureActice = false; // 确认按钮状态
        let giftCardsData = yield req.ctx(shoppingModel).listGiftCard(uid);
        let usableGiftCardsOrigin = _.get(giftCardsData, 'data.usable_giftCards', false);

        if (usableGiftCardsOrigin) {
            let orderInfo;

            try {
                orderInfo = JSON.parse(req.cookies['order-info']);
            } catch (e) {
                logger.info(`orderEnsure: get orderInfo from cookie error:${JSON.stringify(e)}`);
                orderInfo = {};
                res.clearCookie('order-info', actCkOpthn);
            }

            let handleResult = paymentProcess.handleGiftCardsRender(usableGiftCardsOrigin,
                _.get(orderInfo, 'gift_card_code'));

            usable_giftCards = handleResult.giftCards;
            sureActice = handleResult.sureActice;
        }


        res.render('select-giftcard', {
            module: 'cart',
            page: 'select-giftcard',
            title: '礼品卡',
            pageHeader: _.assign(headerData, {
                useGiftCard: true
            }),
            pageFooter: false,
            localCss: true,
            width750: true,
            usable_giftCards: usable_giftCards,
            sureActice: sureActice
        });
    })().catch(next);
};

/**
 * 购物车输入优惠券码使用优惠券
 */
exports.useCouponCode = (req, res, next) => {
    let couponCode = req.body.couponCode || '';
    let uid = req.user.uid;

    co(function* () {
        if (req.xhr) {
            let result = yield req.ctx(cartModel).useCouponCode(uid, couponCode);

            res.json(result);
        } else {
            return next();
        }

    })().catch(next);
};

/**
 * 选择地址
 */
exports.selectAddress = (req, res, next) => {
    let uid = req.user.uid;

    return req.ctx(addressModel).addressData(uid).then(address => {

        let moreUrl = (req.get('Referer') && !/\/home\/addressAct/.test(req.get('Referer')) &&
            !/selectAddress/.test(req.get('Referer'))) ?
            req.get('Referer') : ''; // 取跳过来的url

        address = address.data;

        // 购物车订单进来,秒杀进来
        if (
            moreUrl.indexOf('/cart/index/new/orderEnsure') !== -1 ||
            moreUrl.indexOf('/cart/index/seckill') !== -1
        ) {
            req.session.addressMore = moreUrl; // TODO: 注意cookie-session
        }

        moreUrl = req.session.addressMore || moreUrl || helpers.urlFormat('/cart/index/new/orderEnsure', {
            cartType: req.cookies._cartType
        });

        let headerData = headerModel.setNav({
            navTitle: '选择地址',
            navBtn: false,
            backUrl: moreUrl
        });

        res.render('select-address', {
            module: 'cart',
            page: 'select-address',
            pageHeader: headerData,
            pageFooter: true,
            moreUrl,
            address,
            localCss: true
        });
    }).catch(next);
};

/**
 * 发票信息
 */
exports.invoiceInfo = (req, res, next) => {
    let uid = req.user.uid;
    let orderInfo;

    try {
        orderInfo = JSON.parse(req.cookies['order-info']);
    } catch (e) {
        orderInfo = {};
    }

    co(function* () {
        let userData = yield req.ctx(userModel).queryProfile(uid);
        let mobile = _.get(userData, 'data.mobile', '');
        let addresslist = yield req.ctx(userModel).addressTextData(uid);
        let returnData = req.ctx(orderModel).processInvoiceData(orderInfo, mobile, addresslist);
        let headerData = headerModel.setNav({
            invoiceNotice: '发票须知',
            navTitle: '发票信息',
            navBtn: false
        });

        res.render('select-invoice', _.assign(returnData, {
            pageHeader: headerData,
            module: 'cart',
            page: 'select-invoice',
            localCss: true,
            addressMore: helpers.urlFormat('/cart/index/new/orderEnsure', {cartType: req.cookies._cartType})
        }));
    })().catch(next);
};

/**
 * JIT 拆单配送信息页面
 */
exports.jitDetail = (req, res, next) => {
    let uid = req.user.uid;
    let cartType = req.query.cartType;
    let deliveryId = req.query.deliveryId;
    let headerData = headerModel.setNav({
        navTitle: '配送信息',
        navBtn: false
    });

    co(function* () {
        let result = {};

        if (req.query.buynow === 'Y') {
            let resultFromApi = yield req.ctx(buyNowModel).compute({
                delivery_way: deliveryId,
                uid: uid,
                product_sku: req.query.product_sku,
                buy_number: 1
            });

            result = paymentProcess.transformJit(_.get(resultFromApi, 'data.package_list', []));
        } else {
            result = yield req.ctx(cartModel).jitDetailData(
                uid,
                cartType,
                req.query.skuList,
                req.query.orderCode,
                req.session.TOKEN,
                deliveryId,
                req.query.paymentType,
                req.query.couponCode,
                req.query.yohoCoin
            );
        }

        if (cartType) {
            _.assign(headerData, {
                backUrl: result.returnUrl
            });
        }

        res.render('jit-detail', _.assign(result, {
            pageHeader: headerData,
            jitDetailPage: true,
            module: 'cart',
            page: 'jit-detail',
            localCss: true
        }));
    })().catch(next);
};

/**
 * 重发验证码
 */
exports.giftCardSendSms = (req, res, next) => {
    let uid = req.user.uid;

    req.ctx(orderModel).giftCardSendSms(uid).then(result => {
        res.json(result);
    }).catch(next);
};