import xFetch from '../utils/xFetch';

var express = require('express');

export const PRODUCT_STATUS = {
    '-9': '草稿',
    0: '已删除',
    1: '未发布',
    5: '预热中',
    11: '募集中',
    17: '已暂停',
    21: '已封账',
    31: '已成立',
}

export const productStatusToString = status => {
    return PRODUCT_STATUS[status] || '未定义';
};

export function formatMoney(money = 0) {
    let ret;
    if (isNaN(money)) {
        ret = '0';
    } else if (money >= 1E10) {
        ret = (money / 1E10) + '亿';
    } else if (money >= 1E6) {
        ret = (money / 1E6) + '万';
    } else {
        ret = (money / 1E2);
    }
    return ret;
}


export const leftPad = num => {
    return num >= 10 ? num : ('0' + num);
};

export const formatDateTime = (time = 0, format = 'YYYY-MM-DD hh:mm:ss') => {
    const date = new Date(time);
    const data = {
        YYYY: date.getFullYear(),
        MM: leftPad(date.getMonth() + 1),
        DD: leftPad(date.getDate()),
        hh: leftPad(date.getHours()),
        mm: leftPad(date.getMinutes()),
        ss: leftPad(date.getSeconds())
    };
    return format.replace(/[A-Za-z]+/g, metch => {
        return data[metch];
    });
};


module.exports = function (req, res, next) {
    Promise.all([
        xFetch('https://m.fudou6.com/api/1.0/cate/cates.json'),
        xFetch('https://m.fudou6.com/api/1.0/prod/detail.json?itemId=' + req.params.id)
    ]).then((arr)=> {
        const {pCates} = arr[0];
        const {item} = arr[1];



        if (!item || !pCates) {
            var err = new Error('Not Found');
            err.status = 404;
            next(err);
        }


        pCates.forEach(cate=> {
            cate.subCates.forEach(scate=> {
                if (scate.id == item.categoryId) {
                    item.categoryName = scate.name;
                    item.categoryParentId = cate.id;
                    item.categroyParentName = cate.name;
                }
            });
        });

        item.elements = JSON.parse(item.elements);

        Object.keys(item.elements).forEach(key=>{
            //console.log('%s\t%s\t%s', key, item.elements[key][0], item.elements[key][1]);
            item.elements[key] = item.elements[key][1];
        });

        item.commissionAlg = JSON.parse(item.commissionAlg);

        item.commissionAlg = item.commissionAlg.map(it=> {
            const {sy, yj} = (it.result || {});
            return {
                rowspan:item.commissionAlg.length,
                range: (it.min ? formatMoney(it.min)+' ≤ ':'') + ' x ' + (it.max ? ' < '+formatMoney(it.max) : ''),
                min: it.min,
                max: it.max,
                sy, yj
            };
        });

        item.fundRaisedStartTimeString = item.fundRaisedStartTime && formatDateTime(item.fundRaisedStartTime);
        item.fundRaisedEndTimeString = item.fundRaisedEndTime && formatDateTime(item.fundRaisedEndTime);



        item.statusString = productStatusToString(item.status);

        //募集目标
        item.fundRaisedTargetString = formatMoney(item.fundRaisedTarget);
        //已募集
        item.fundRaisedOverString = formatMoney(item.fundRaisedOver);
        item.fundRaisedPercentage = item.fundRaisedOver / item.fundRaisedTarget * 100;
        //募集剩余
        item.fundRaisedSurplus = Math.max(item.fundRaisedTarget - item.fundRaisedOver, 0);

        item.fundRaisedSurplusString = formatMoney(item.fundRaisedSurplus);
        //最小投资
        item.minimumAmountString = formatMoney(item.minimumAmount);

        //console.log(item);

        res.render('product', {
            navProducts:'active',
            styles:['product'],
            scripts:['utils','product'],
            ...item
        });

    }).catch(err=> {
        console.log(err);
        next(err);
    });

};
