'use strict';
const helpers = global.yoho.helpers;
const crypto = global.yoho.crypto;
const _ = require('lodash');
const logger = global.yoho.logger;
const authcode = require('./authcode');

/**
 * 转换价格
 *
 * @param float|string $price 价格
 * @param boolean $isSepcialZero 是否需要特殊的0,默认否
 * @return float|string 转换之后的价格
 */
function transPrice(price, isSepcialZero) {
    if (!price) {
        price = 0;
    }

    if (!isSepcialZero) {
        isSepcialZero = false;
    }

    if ((price || isSepcialZero) && _.isNumber(price)) {
        return price.toFixed(2);
    } else {
        return price;
    }
}

/**
 * 有货币使用前端方案显示及是否可单击判断
 */
function yohoCoinCompute(orderCompute) {
    let yohoCoinData = {
        totalYohoCoinNum: (orderCompute.total_yoho_coin_num || 0) * 1,
        yohoCoin: (orderCompute.yoho_coin || 0) * 1,
        useYohoCoin: (orderCompute.use_yoho_coin || 0) * 1,
        yohoCoinClick: 0,
        yohoCoinMsg: '',
        yoho_coin_pay_rule: orderCompute.yoho_coin_pay_rule || {}
    };

    if (!orderCompute) {
        return yohoCoinData;
    }

    if (yohoCoinData.yohoCoin > 0) {
        yohoCoinData.yohoCoin = yohoCoinData.yohoCoin.toFixed(2);
    }

    if (yohoCoinData.useYohoCoin > 0) {
        yohoCoinData.useYohoCoin = yohoCoinData.useYohoCoin.toFixed(2);
    }

    if (yohoCoinData.totalYohoCoinNum < 100) {
        yohoCoinData.yohoCoinMsg = `共${yohoCoinData.totalYohoCoinNum}有货币,满${
            _.get(orderCompute, 'yoho_coin_pay_rule.num_limit', '100')}可用`;
    } else if (yohoCoinData.useYohoCoin > 0 || yohoCoinData.yohoCoin > 0) {
        yohoCoinData.yohoCoinMsg = '可抵¥' + (yohoCoinData.useYohoCoin > 0 ?
            yohoCoinData.useYohoCoin : yohoCoinData.yohoCoin);
        yohoCoinData.yohoCoinClick = 1;
    } else {
        yohoCoinData.yohoCoinMsg = '不满足有货币使用条件';
    }

    return yohoCoinData;
}

/**
 * 转换 原始结算数据 ,适应模板
 * TODO: 其他结算,如果有 相似的 结构,可以移出去
 * @param data 结算页面数据
 * @param orderInfo
 *    orderInfo.paymentType 用户支付常用方式
 * @param cartType
 * @param skuList
 * @param orderComputeData [option]  app.shopping.compute 返回的data数据
 *
 * TODO:
 *     与秒杀结算 一起测试
 */
function tranformPayment(data, orderInfo, cartType, skuList, orderComputeData) {
    orderInfo = orderInfo || {};
    let result = {};
    let isSunfengSupport;

    // orderComputeData 覆盖 data中对应的值
    if (orderComputeData && !_.isEmpty(orderComputeData)) {
        _.assign(data, orderComputeData);
        _.set(data, 'shopping_cart_data.promotion_formula_list', orderComputeData.promotion_formula_list);
        _.set(data, 'shopping_cart_data.last_order_amount', orderComputeData.last_order_amount);
        _.set(data, 'delivery_way', orderComputeData.delivery_way);
    }

    // delivery_address 中 提取信息
    if (data.hasOwnProperty('delivery_address') && !_.isEmpty(data.delivery_address)) {
        let cookieAddress = orderInfo.address;
        let addressData = data.delivery_address;
        let isSupport = cookieAddress ? cookieAddress.is_support : '';

        result.name = cookieAddress ? cookieAddress.consignee : addressData.consignee;
        result.phoneNum = cookieAddress ? cookieAddress.mobile : addressData.mobile;
        result.addressId = addressData.address_id;
        result.addressInfo = cookieAddress ?
            cookieAddress.address_info : [addressData.area, addressData.address].join(' ');
        isSunfengSupport = isSupport === 'N';
    }

    // delivery_way 配送信息
    if (data.delivery_way) {
        let arr = [];
        let cookieWayId = orderInfo.deliveryId;
        let deliveryWay = data.delivery_way;
        let isDeliveryId = true;
        let defaultKey = 0;

        deliveryWay.forEach((way, index) => {
            if (way.delivery_way_name === '顺丰速运' && isSunfengSupport) {
                return;
            }

            let obj = {};

            (way.default === 'Y') && (defaultKey = index);

            if (cookieWayId && (way.delivery_way_id === cookieWayId)) {
                obj.isSelected = true;
                isDeliveryId = false;
            }

            arr.push(
                Object.assign({
                    id: way.delivery_way_id,
                    name: way.delivery_way_name,
                    cost: way.delivery_way_cost,
                    is_support_message: (way.is_support === 'N' && way.is_support_message !== '') ?
                        way.is_support_message : ''
                }, obj)
            );
        });

        if (isDeliveryId) {
            arr[defaultKey].isSelected = true;
        }

        result.dispatchMode = arr;
    }

    // delivery_time 配送时间
    if (data.delivery_time) {
        let cookieTimeId = orderInfo.deliveryTimeId;
        let defaultKey = 0;
        let times = data.delivery_time;

        times = times.map((time, index) => {
            (time.default === 'Y') && (defaultKey = index);

            return {
                isSelected: false,
                id: time.delivery_time_id,
                name: time.delivery_time_string
            };
        });

        times[defaultKey].isSelected = true;

        if (cookieTimeId) {
            let selectTime = times.find(time => time.id === cookieTimeId);

            if (selectTime) {
                times[defaultKey].isSelected = false;
                selectTime.isSelected = true;
            }
        }

        result.dispatchTime = times;
    }

    // goods_list 订单商品
    if (data.goods_list) {
        let goods = data.goods_list;
        let goodsPrice = 0;

        goods = goods.map(good => {
            var obj = {};

            obj.id = good.product_sku;
            obj.thumb = helpers.image(good.goods_images, 120, 160);
            obj.name = good.product_name;
            obj.color = good.factory_goods_name || good.color_name;
            obj.size = good.size_name;
            obj.count = good.buy_number;
            obj.price = good.sales_price;
            obj.isLimitSkn = good.is_limit_skn === 'Y';
            obj.notSevenExchange = _.get(good, 'tags[0]', '');

            if (good.goods_type === 'gift') {
                obj.gift = true;
                obj.price = good.is_advance === 'Y' ? good.sale_price : good.last_price;
            } else if (good.goods_type === 'price_gift') { // eslint-disable-line
                obj.advanceBuy = true;
                obj.price = good.last_price;
            }

            // Total Price
            goodsPrice += obj.count * obj.price;

            return obj;
        });

        result.goods = goods;
        result.goodsPrice = goodsPrice.toFixed(2);
    }

    // 支付方式
    if (data.payment_way) {
        let payway = data.payment_way;

        payway = payway.map(way => {
            let obj = {};

            obj.id = way.payment_id;
            obj.paymentType = way.payment_type;
            obj.name = way.payment_type_name;
            obj.isSupport = way.is_support === 'Y';
            obj.isSupportMessage = way.payment_type === 2 ? _.get(way, 'is_support_message', false) : false;

            return obj;
        });

        payway.some(way => {
            let bool = way.paymentType === orderInfo.paymentType;

            if (bool) {
                way.recommend = true;
            }

            return bool;
        }) || (payway[0].recommend = true);

        result.paymentWay = payway;
    }

    // 发票
    if (data.invoices) {
        let invTypes = data.invoices.invoiceContentList || [];

        invTypes = invTypes.map(type => {
            return {
                id: type.invoices_type_id,
                name: type.invoices_type_name
            };
        });

        result.invoice = invTypes;

        if (orderInfo.invoice) {
            result.needInvoice = orderInfo.invoice;

            if (orderInfo.invoices_title) {
                if (orderInfo.invoices_title.length > 10) {
                    orderInfo.invoices_title = orderInfo.invoices_title.substring(0, 10) + '...';
                }

                result.invoiceText = `电子发票(${orderInfo.invoices_title})`;
            } else {
                result.invoiceText = orderInfo.invoices_title_personal ?
                    `电子发票(${orderInfo.invoices_title_personal})` : '电子发票(个人)';
            }
        }
    }

    // 订单数据
    if (data.shopping_cart_data) {
        let cartData = data.shopping_cart_data;

        // 判断 是否为jit商品
        if (cartData.is_multi_package === 'Y') {
            result.isJit = true;

            let jitInfo = {};

            if (orderInfo) {
                jitInfo = {
                    deliveryId: orderInfo.deliveryId,
                    paymentType: orderInfo.paymentType,
                    couponCode: orderInfo.couponCode,
                    yohoCoin: orderInfo.yohoCoin
                };
            }

            let param = Object.assign({
                cartType: cartType,
                skuList: skuList
            }, jitInfo);

            if (_.get(orderInfo, 'product_sku', '')) {
                result.jitDetailUrl = helpers.urlFormat('/cart/index/new/jitDetail', {
                    buynow: 'Y',
                    product_sku: _.get(orderInfo, 'product_sku', '')
                });
            } else {
                result.jitDetailUrl = helpers.urlFormat('/cart/index/new/jitDetail', param);
            }

            result.packageTitle = cartData.package_title;
        }

        result.cartPayData = cartData.promotion_formula_list;
        result.num = cartData.goods_count;
        result.goodsPrice = cartData.str_order_amount;
        result.price = orderComputeData && _.isNumber(orderComputeData.last_order_amount) ?
            orderComputeData.last_order_amount : cartData.last_order_amount;

        if (cartData.gain_yoho_coin > 0) {
            result.yohoCoinNum = cartData.gain_yoho_coin;
            result.returnYohoCoin = true;
        }

    }

    // 有货币
    result.yohoCoinCompute = yohoCoinCompute(data);

    // 留言
    orderInfo.msg && (result.msg = orderInfo.msg);
    result.isPrintPrice = true; // 是否不打印价格,默认不勾选,预留

    return result;
}

/**
 *  优惠券数据
 *  @param count int 用户有效优惠券
 *  @param orderComputeData obj app.Shopping.compute返回的data数据
 *  @param orderInfo cookie中的数据
 *  @return obj
 */
function coupon(count, orderInfo, orderComputeData) {
    let coupons = {
        count: count,
        selectedAmount: 0,
        info: ''
    };

    let couponAmount = _.get(orderComputeData, 'coupon_amount', 0);

    if (_.get(orderInfo, 'usable_usual_code', null)) {
        coupons.selectedAmount++;
    }

    if (_.get(orderInfo, 'usable_free_code', null)) {
        coupons.selectedAmount++;
    }

    if (count) {
        if (coupons.selectedAmount) {
            coupons.info = `-¥${couponAmount.toFixed(2)}`;
        } else {
            coupons.info = '未使用';
        }
    } else {
        coupons.info = '无可用';
    }

    return coupons;
}

/**
 * 选择礼品卡页面礼品卡数据处理
 */
function handleGiftCardsRender(giftCards, selectCards) {
    let result = {
        sureActice: false,
        giftCards: giftCards
    };

    let selectCardsArray = selectCards && selectCards.split(',');

    _.forEach(result.giftCards, perCard => {
        let checked = _.find(selectCardsArray, per => {
            return per === _.get(perCard, 'cardCode');
        });

        if (checked) {
            result.sureActice = true;
        }

        _.assign(perCard, {
            checked: checked
        });
    });

    result.giftCards = giftCards;

    return result;
}

/**
 * 结算页处理礼品卡数据
 */
function handleGiftCards(params) {
    let count = params.validGiftCardCount; // 几张可用
    let amount = _.get(params, 'orderCompute.gift_card.amount', 0); // 可抵用金额
    let selectCount = _.get(params, 'orderCompute.gift_card.count', 0); // 用户选择了几张
    let leftInfo = '';
    let rightInfo = '未使用';

    if (!count) {
        return false;
    }

    if (selectCount) {
        leftInfo = `已选${selectCount}张`;
    } else if (count) {
        leftInfo = `${count}张可用`;
    }

    if (selectCount && amount) {
        rightInfo = `可以抵用¥${amount.toFixed(2)}`;
    }

    return {
        leftInfo: leftInfo,
        rightInfo: rightInfo
    };
}

/**
 * JIT 拆单数据处理
 */
function transformJit(packageList) {
    let result = {
        packages: []
    };

    _.forEach(packageList, pValue => {
        let perPackageData = {
            packageType: pValue.title,
            goods: []
        };

        _.forEach(pValue.goods_list, gValue => {
            perPackageData.goods.push({
                thumb: gValue.goods_images,
                isAdd: gValue.goods_type === 'price_gift',
                isGift: gValue.goods_type === 'gift'
            });
        });

        result.packages.push(perPackageData);
    });
    return result;
}

/**
 * 联盟相关
 * @param {*} cookies
 * @param {*} uid
 */
function unionInfoHandle(cookies, uid) {
    /* 判断是否是友盟过来的用户 */
    let userAgent = null;
    let unionKey = '';
    let unionInfo = {};
    let clientId = null;

    /* tar modified 161108 添加新的联盟数据处理逻辑,兼容原有联盟数据处理,
                    区别是旧的北京写 cookie 加密过来,新的 node 写 cookie,没有加密 */
    if (cookies._QYH_UNION) {
        unionKey = authcode(cookies._QYH_UNION, 'q_union_yohobuy');

        if (!unionKey) {
            let encryData = crypto.decrypt('', decodeURIComponent(cookies._QYH_UNION));

            encryData = encryData.substr(0, encryData.lastIndexOf('}') + 1);
            let testQyhUnion = JSON.parse(encryData);

            unionKey = testQyhUnion.client_id ? encryData : '';
        }

        try {
            unionInfo = JSON.parse(unionKey);
        } catch (e) {
            unionInfo = {};
            logger.error(`orderEnsure: _QYH_UNION:${cookies._QYH_UNION}`);
        }

        clientId = unionInfo && unionInfo.client_id;
    } else {
        let unionObj = {
            client_id: cookies.mkt_code
        };

        if (cookies.union_data) {
            unionObj.union_data = cookies.union_data;
        }

        unionKey = JSON.stringify(unionObj);
        clientId = cookies.mkt_code;
    }

    /* 模拟APP的User-Agent */
    let clientIdSub = _.split(clientId, ',')[0];

    userAgent = clientIdSub ? 'YOHO!Buy/3.8.2.259(Model/H5;Channel/' +
        clientIdSub + ';uid/' + uid + ')' : null;

    return {
        unionKey: unionKey,
        userAgent: userAgent
    };
}

module.exports = {
    transPrice,
    tranformPayment,
    yohoCoinCompute,
    coupon,
    handleGiftCards,
    handleGiftCardsRender,
    transformJit,
    unionInfoHandle
};