/**
 * 逛详情页
 * @author: chenfeng<feng.chen@yoho.cn>
 * @date: 2016/09/07
 */
'use strict';
const co = require('bluebird').coroutine;
const helpers = global.yoho.helpers;
const mRoot = '../models';
const typeLib = require('../../../config/type-lib');
const _ = require('lodash');
const DetailModel = require(`${mRoot}/detail`);
const stringProcess = require(`${global.utils}/string-process`);
const guangProcess = require(`${global.utils}/guang-process`);
const headerModel = require('../../../doraemon/models/header'); // 头部model
const aboutModel = require('../../../doraemon/models/about');
const tdk = require('../../../utils/getTDK');
const qs = require('querystring');
const channels = {
    boys: 1,
    girl: 2,
    kids: 3,
    lifestyle: 4
};

/**
 * [处理品牌数据]
 * @param  {[array]} getBrand [品牌原数据]
 */
const _relatedBrand = (getBrand, isApp) => {
    let relatedBrand = getBrand;

    relatedBrand.forEach(brand => {
        brand.thumb = brand.thumb.replace('http://', '//');
        if (brand.isGlobal === 'Y') {
            brand.url = helpers.urlFormat('/product/global/list', {brand: brand.tbl_id});
        }

        if (isApp) {
            if (brand.isGlobal === 'Y') {
                brand.url = brand.url +
                    '?openby:yohobuy={"action":"go.globalpurchase","params":{"brand":"' + brand.id + '"}}';
            } else {
                brand.url = brand.url +
                    '?openby:yohobuy={"action":"go.brand","params":{"brand_id":"' + brand.id + '"}}';
            }
        }
    });

    return relatedBrand;
};

/**
 * [处理标签数据]
 * @param  {[array]} tags [标签原数据]
 * @param  {[Boolean]} isApp [是否app]
 */
const _relatedTag = (tags, isApp) => {
    let relatedTag = [];
    let tagUrl;

    tags.forEach(value => {

        tagUrl = helpers.urlFormat('/tags/index', {query: value.name}, 'guang');

        if (!isApp) {
            value.url = tagUrl;
        } else {
            if (value.url.indexOf('openby') >= 0) {
                value.url = value.url;
            } else {
                value.url = tagUrl + '&openby:yohobuy={"action":"go.h5","params":{"query":"' + value.name + '","type":0,"title":"' + value.name + '","url":"http://guang.m.yohobuy.com/tags/index","islogin":"N"}}';
            }
        }

        relatedTag.push(value);
    });

    return relatedTag;
};

/**
 * [处理相关文章数据]
 * @param  {[array]} getOtherArticle [相关文章原数据]
 * @param  {[Boolean]} isApp [是否app]
 */
const _relatedInfo = (getOtherArticle, isApp) => {
    let relatedInfo = [];
    let articleUrl;

    getOtherArticle.forEach(value => {
        articleUrl = helpers.urlFormat('/info/index', {
            id: value.id
        }, 'guang');

        if (isApp) {
            value.url = articleUrl + '&openby:yohobuy={"action":"go.h5","params":{"id":"' + value.id + '","shareparam":{"id":"' + value.id + '"},"islogin":"N","type":1,"url":"http://guang.m.yohobuy.com/info/index","param":{"id":"' + value.id + '"}}}';
        } else {
            value.url = articleUrl;
        }

        value.thumb = helpers.image(value.thumb, 279, 175);
        relatedInfo.push(value);
    });

    return relatedInfo;
};

/**
 * [处理分享内容]
 * @param  {[int]} id [资讯id]
 * @param  {[array]} getArticle [资讯内容]
 */
const _shareInfo = (id, getArticle) => {
    let shareInfo = {};

    shareInfo.shareLink = 'http:' + helpers.urlFormat('/info/index', {
        id: id
    }, 'guang');
    shareInfo.shareTitle = getArticle.article_title;
    shareInfo.shareDesc = getArticle.article_summary;
    if (getArticle.cover_image_type === 1) {
        shareInfo.shareImg = 'http:' + helpers.image(getArticle.cover_image, 640, 640);
    } else {
        shareInfo.shareImg = 'http:' + helpers.image(getArticle.cover_image, 640, 320);
    }
    return shareInfo;
};

/**
 * [逛资讯详情页]
 */
const index = (req, res, next) => {
    let id = req.query.id || req.params[0] || req.params.id,
        uid = req.user.uid,
        udid = req.sessionID || require('yoho-md5')(req.ip) || 'yoho',
        gender = req.query.gender ||
            req.query.channel && typeLib.channels[req.query.channel] ||
            req.cookies._Channel && channels[req.cookies._Channel] ||
            1,
        isApp = req.query.app_version || req.query.appVersion || false, // 标识是不是APP访问的
        parameter = {},
        title = '逛',
        isWeixin = req.yoho.isWechat,
        channel = req.query.channel || req.cookies._Channel,
        isqq = req.yoho.isqq,
        isWeibo = req.yoho.isWeibo,
        isShare;

    res.locals.appPath = `yohobuy://yohobuy.com/goapp?openby:yohobuy={"action":"go.h5","params":{"id":"${id}","share":"/guang/api/v1/share/guang?id=${id}","shareparam":{"id":"${id}"},"islogin":"N","type":1,"url":"http://guang.m.yohobuy.com/info/index","param":{"id":"${id}"}}}`;

    // 判断参数是否有效, 无效会跳转到错误页面
    if (!stringProcess.isNumeric(id)) {
        res.json({
            code: 400,
            message: '非法请求',
            data: ''
        });
        return;
    }

    parameter = {
        pageHeader: headerModel.setNav({
            navTitle: title
        })
    };

    isShare = isWeixin || isqq || isWeibo ? true : false;

    co(function* () {
        let ret = yield tdk('article', id, req);

        if (ret[0]) {
            req.tdk = {
                title: ret[1],
                keywords: ret[2],
                description: ret[3]
            };
        }
        let detail = yield req.ctx(DetailModel).packageData(id, isApp, isWeixin, channel, isShare);
        let commentsTotal = yield req.ctx(DetailModel).commentsTotal({article_id: id, udid: udid});
        let praise = yield req.ctx(DetailModel).getArticlePraiseAndFavor({
            uid: uid,
            id: id,
            udid: udid
        });
        let data = {
            guangDetail: true,
            guang: {}
        };

        data.guang.isWeixin = isWeixin;
        data.guang.channel = channel;
        data.guang.isShare = isShare;

        if (detail.code === 400) {
            return next();
        }
        if (!detail.getArticle) {
            // TODO 跳转到逛首页
            return;
        }

        if (isShare && detail && detail.sideNav) {
            data.sideNav = detail.sideNav;
        }

        // 作者信息数据
        if (detail && detail.getAuthor && (typeof detail.getAuthor.name !== 'undefined')) {
            data.guang.author = {
                avatar: detail.getAuthor.avatar.replace('http://', '//'),
                name: detail.getAuthor.name,
                intro: detail.getAuthor.author_desc
            };

            // guang双头部的问题 20160601
            // 正确的URL
            let url = `${detail.getAuthor.url}&openby:yohobuy={"action":"go.h5","params":{"param":{},"share":"","id":${detail.getAuthor.author_id},"type":0,"islogin":"N","url":"${detail.getAuthor.url}"}}`; // eslint-disable-line

            data.guang.author.url = helpers.https(url);
        }
        let guang = data.guang;

        guang.detail = {
            id: _.get(detail, 'getArticle.id'),
            title: detail.getArticle.article_title,
            publishTime: detail.getArticle.publishTime,
            pageView: _.get(praise, 'browseNum', 0),
            content: [],
            praise: _.get(praise, 'praiseNum', 0),
            praiseHeadIco: _.get(praise, 'praiseHeadIco', []),
            commentsTotal: commentsTotal
        };
        if (!detail.getArticleContent) {
            return next();
        }

        let processContents = guangProcess.processArticleDetail(detail.getArticleContent,
            isApp,
            gender,
            isWeixin,
            isqq,
            isWeibo);

        let goodsList = yield req.ctx(DetailModel).productInfoBySkns(processContents.allgoods);

        guang.detail.content = guangProcess.pushGoodsInfo(processContents.finalDetail, goodsList, isApp);

        // 相关品牌
        if (detail.getBrand && detail.getBrand.length) {
            guang.relatedBrand = _relatedBrand(detail.getBrand, isApp);
        }

        // 相关标签
        if (detail.getArticle.tags && detail.getArticle.tags.length) {
            guang.relatedTag = _relatedTag(detail.getArticle.tags, isApp);
        }

        // 相关文章
        if (detail.getOtherArticle && detail.getOtherArticle.length) {
            guang.relatedInfo = _relatedInfo(detail.getOtherArticle, isApp);
        }

        // 分享参数
        if (detail.getArticle.cover_image) {
            let shareInfo = _shareInfo(id, detail.getArticle);

            Object.assign(guang, shareInfo);
            data.title = detail.getArticle.article_title + ' | Yoho!Buy有货 | 潮流购物逛不停';
            data.title_more = true;
            data.description = detail.getArticle.article_summary;
            data.description_more = true;
        }

        // 标识有微信分享
        data.hasWxShare = true;

        let resu = yield req.ctx(aboutModel).about(req.yoho.isApp);

        data.guang.wxFooter = resu;
        res.render('info/index', Object.assign({
            page: 'info-index',
            gender: gender,
            wechatShare: true,
            isWeixin: isWeixin,
            localCss: true,
            isShare: isShare,
            id: id
        }, data, parameter));
    })().catch(next);
};

// 301到新路由
const indexRedirect = (req, res, next) => {
    let id = req.query.id;

    if (id) {
        let redirectUrl = '/guang/info/';

        if (req.yoho.channel !== req.cookies._Channel) {
            redirectUrl += `${req.yoho.channel}-`;
        }
        delete req.query.id;
        let param = qs.stringify(req.query);

        if (param) {
            param = '?' + param;
        }
        redirectUrl += `${id}.html${param}`;
        res.redirect(301, redirectUrl);
    } else {
        return next();
    }
};

/**
 * [逛mini内容页]
 */
const mini = (req, res, next) => {
    let id = req.query.id,
        uid = req.user.uid,
        udid = req.sessionID || require('yoho-md5')(req.ip) || 'yoho',
        gender = req.query.gender || req.cookies._Channel && channels[req.cookies._Channel] || 1,
        isApp = req.query.app_version || req.query.appVersion || false; // 标识是不是APP访问的

    // 判断参数是否有效, 无效会跳转到错误页面
    if (!stringProcess.isNumeric(id)) {
        res.json({
            code: 400,
            message: '非法请求',
            data: ''
        });
        return;
    }

    co(function* () {
        let detail = yield req.ctx(DetailModel).packageData(id, isApp);
        let commentsTotal = yield req.ctx(DetailModel).commentsTotal({article_id: id, udid: udid});
        let praise = yield req.ctx(DetailModel).getArticlePraiseAndFavor({
            uid: uid,
            id: id,
            udid: udid
        });
        let data = {
            guangEzine: true,
            guang: {}
        };

        if (detail.code !== 400) {
            if (!detail.getArticle) {
                // TODO 跳转到逛首页
                return;
            }
            let guang = data.guang;

            guang.detail = {
                title: detail.getArticle.article_title,
                publishTime: detail.getArticle.publishTime,
                pageView: _.get(praise, 'browseNum', 0),
                content: [],
                praise: _.get(praise, 'praiseNum', 0),
                praiseHeadIco: _.get(praise, 'praiseHeadIco', []),
                commentsTotal: commentsTotal
            };


            if (detail.getArticleContent) {

                let processContents = guangProcess.processArticleDetail(detail.getArticleContent,
                    isApp,
                    gender);
                let goodsList = yield req.ctx(DetailModel).productInfoBySkns(processContents.allgoods);

                guang.detail.content = guangProcess.pushGoodsInfo(processContents.finalDetail, goodsList, isApp);

                // 相关品牌
                if (detail.getBrand && detail.getBrand.length) {
                    guang.relatedBrand = _relatedBrand(detail.getBrand, isApp);
                }

                // 分享参数
                if (detail.getArticle.cover_image) {
                    let shareInfo = _shareInfo(id, detail.getArticle);

                    Object.assign(guang, shareInfo);
                }

                // 标识有微信分享
                data.hasWxShare = true;
                res.render('info/index', Object.assign({
                    page: 'info-index',
                    title: '逛',
                    gender: gender,
                    wechatShare: true,
                    id: id
                }, data));
            } else {
                return next();
            }
        }
    })().catch(next);
};

/**
 * [提供给YOHO资讯站调用的接口]
 */
const foryoho = (req, res, next) => {
    let id = req.query.id,
        gender = req.query.gender || req.cookies._Channel && channels[req.cookies._Channel] || 1,
        isApp = req.query.app_version || req.query.appVersion || false; // 标识是不是APP访问的

    // 判断参数是否有效, 无效会跳转到错误页面
    if (!stringProcess.isNumeric(id)) {
        res.json({
            code: 400,
            message: '非法请求',
            data: ''
        });
        return;
    }

    co(function* () {
        let detail = yield req.ctx(DetailModel).packageData(id, isApp);
        let data = {};

        if (detail.code !== 400) {
            if (!detail.getArticle) {
                // TODO 跳转到逛首页
                return;
            }
            data.brand = detail.getBrand;

            if (detail.getArticleContent) {
                // 生成内容部分

                let processContents = guangProcess.processArticleDetail(detail.getArticleContent,
                    isApp,
                    gender);

                let goodsList = yield req.ctx(DetailModel).productInfoBySkns(processContents.allgoods);

                data.content = guangProcess.pushGoodsInfo(processContents.finalDetail, goodsList, isApp);

                // 内容中的相关推荐和悬浮商品移到data层级
                let relatedRecoIndex = data.content.findIndex((cont) => {
                    return typeof cont.relatedReco !== 'undefined';
                });

                let collocationIndex = data.content.findIndex((cont) => {
                    return typeof cont.collocation !== 'undefined';
                });

                if (relatedRecoIndex > 0) {
                    data.goods = data.content[relatedRecoIndex].relatedReco;
                    data.content.splice(relatedRecoIndex, 1);
                }
                if (collocationIndex > 0) {
                    data.group = data.content[collocationIndex].collocation;
                    data.content.splice(collocationIndex, 1);
                }
                res.json(data);
            } else {
                return next();
            }
        }
    })().catch(next);
};

/**
 * 异步获取逛文章评论
 * @param {*} req
 * @param {*} res
 * @param {*} next
 */
const getComments = (req, res, next) => {
    let udid = req.sessionID || require('yoho-md5')(req.ip) || 'yoho';

    req.ctx(DetailModel).comments({
        article_id: req.query.article_id,
        page: req.query.page,
        udid: udid
    }).then(result => {
        return res.render('info/comments', {
            comments: result,
            layout: false
        });
    }).catch(next);
};

module.exports = {
    index,
    mini,
    foryoho,
    indexRedirect,
    getComments
};