/**
 * 总路由入口
 *
 * 
 * */

import { ERRORENUM } from "../config/errorEnum";
import { getDoc, initDoc } from "../tools/reqResult";
import { BizError } from "../util/bizError";
import { eccFormParam, eccReqParamater } from "../util/verificationParam";
import * as portalRouter from "./portal/router";
import * as publicRouter from "./public/router";
import * as memberRouter from "./member/router";
import * as costRouter from "./cost/router";
import * as officalWebsiteRouter from "./officalWebsite/router";
import * as orderRouter from "./order/router";
import * as outPutRouter from "./outPut/routers";
import * as asyncHandler from 'express-async-handler';
import { payCallback } from "../biz/member/cost";
import { checkUser } from "../middleware/user";

const Look = false;//true更新文档

export async function setRouter(httpServer){
    if (Look) {
        await getDoc();
        await initDoc(portalRouter.FirstName, portalRouter.Config, portalRouter.FirstRouter);//网站编辑
        // await initDoc(publicRouter.FirstName, publicRouter.Config, publicRouter.FirstRouter);//公用组件
        // await initDoc(memberRouter.FirstName, memberRouter.Config, memberRouter.FirstRouter);//用户路由
        await initDoc(officalWebsiteRouter.FirstName, officalWebsiteRouter.Config, officalWebsiteRouter.FirstRouter);//官网路由
        // await initDoc(orderRouter.FirstName, orderRouter.Config, orderRouter.FirstRouter);//会费相关
        // await initDoc(costRouter.FirstName, costRouter.Config, costRouter.FirstRouter);//支付
        // await initDoc(outPutRouter.FirstName, outPutRouter.Config, outPutRouter.FirstRouter);//导出路由
    }
    analysisRouter(httpServer, portalRouter.Config, portalRouter.FirstRouter, true);//网站编辑
    analysisRouter(httpServer, publicRouter.Config, publicRouter.FirstRouter, false);//公用组件
    analysisRouter(httpServer, memberRouter.Config, memberRouter.FirstRouter, true);//用户路由
    analysisRouter(httpServer, officalWebsiteRouter.Config, officalWebsiteRouter.FirstRouter, false);//官网路由
    analysisRouter(httpServer, orderRouter.Config, orderRouter.FirstRouter, true);//会费相关
    analysisRouter(httpServer, costRouter.Config, costRouter.FirstRouter, true);//支付
    analysisRouter(httpServer, outPutRouter.Config, outPutRouter.FirstRouter, true);//导出路由
}


function analysisRouter(httpServer, config, firstRouter, haveMiddleware) {
    for (let modelKey in config) {
        config[modelKey].forEach(info => {
            let {apiName, defaultParam, subUrl, param, bindBiz, notMiddleware} = info;
            if (haveMiddleware && !notMiddleware) httpServer.post(firstRouter+subUrl, checkUser , asyncHandler(routerFun(apiName, defaultParam, subUrl, param, bindBiz, notMiddleware)));
            else  httpServer.post(firstRouter+subUrl, asyncHandler(routerFun(apiName, defaultParam, subUrl, param, bindBiz, notMiddleware)));
        });   
    }
}

function routerFun(apiName, defaultParam, subUrl, param, bindBiz, notMiddleware) {
    return async function (req, res) {
        let chackObjectList = [];
        let checkStringMap = {};
        let stringNotMustHaveKeys = [];
        
        let funcParam:any = {};
        funcParam.userId = req.headers.userId;

        for (let i = 0; i < param.length; i++) {
            let info:any = param[i];
            let {key, type} = param[i];
            if (info.isNull) stringNotMustHaveKeys.push(key);
            if (type == 'Object') {
                chackObjectList.push(param[i]);
                checkStringMap[key] = type;
            }
            else checkStringMap[key] = type; 
        }
        /**校验参数 */
        if (chackObjectList.length) {
            chackObjectList.forEach(item => {
                if (!req.body[item.key]) throw new BizError(ERRORENUM.参数错误, `${apiName}`, `缺少参数${item.key}`);
                eccFormParam(apiName, item.sub, req.body[item.key]);
                funcParam[item.key] = req.body[item.key];
            });
         }
        if (Object.keys(checkStringMap).length) {
            let eccResult = eccReqParamater(apiName, checkStringMap, req.body, stringNotMustHaveKeys);
            for (let key in eccResult) {
                funcParam[key] = eccResult[key];
            }
        }
        if (defaultParam) funcParam["defaultParam"] = defaultParam;
        let result = await bindBiz(funcParam);

        res.success(result);
    }
}


export async function setAdditionalRouter(httpServer) {
    httpServer.post('/manage/cost/pay/wechart/callback', asyncHandler(async (req, res) => {
        let result = await payCallback(req.body);
        res.success(result);
    }));
}
