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

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 labelRouter from "./lable/router";
import * as blacklistRouter from "./blackList/router";
import * as msgActivityRouter from "./msgActivity/router";
import * as applyRouter from "./apply/router";
import * as asyncHandler from 'express-async-handler';
import { payCallback } from "../biz/member/cost";
import { checkUser } from "../middleware/user";
import { ADMINLV } from "../config/enum";

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);//导出路由
        // await initDoc(labelRouter.FirstName, labelRouter.Config, labelRouter.FirstRouter);//标签路由
        // await initDoc("2.0", labelRouter.Config, labelRouter.FirstRouter);//标签路由
        // await initDoc("2.0", blacklistRouter.Config, blacklistRouter.FirstRouter);//黑名单路由
        // await initDoc("2.0", msgActivityRouter.Config, msgActivityRouter.FirstRouter);//消息活动通知路由
        // await initDoc(applyRouter.FirstName, applyRouter.Config, applyRouter.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);//导出路由
    analysisRouter(httpServer, labelRouter.Config, labelRouter.FirstRouter, true);//标签相关
    analysisRouter(httpServer, blacklistRouter.Config, blacklistRouter.FirstRouter, true);//黑名单相关
    analysisRouter(httpServer, msgActivityRouter.Config, msgActivityRouter.FirstRouter, true);//消息活动通知
    analysisRouter(httpServer, applyRouter.Config, applyRouter.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, modelKey)));
            else  httpServer.post(firstRouter+subUrl, asyncHandler(routerFun(apiName, defaultParam, subUrl, param, bindBiz, notMiddleware, modelKey)));
        });   
    }
}
let permissionConfig = {
    "变更审批管理":{adminPermission:true, lv:ADMINLV.审批管理},
    "黑名单管理":{adminPermission:true, lv:ADMINLV.会员库},
    "微信支付":{adminPermission:false},
    "标签管理":{adminPermission:true, lv:ADMINLV.标签系统},
    "用户注册":{adminPermission:false},
    "登陆相关":{adminPermission:false},
    "会员库":{adminPermission:true, lv:ADMINLV.会员库},
    "审批管理":{adminPermission:true, lv:ADMINLV.审批管理},
    "会费管理":{adminPermission:true, lv:ADMINLV.会费管理},
    "会员管理":{adminPermission:true, lv:ADMINLV.变更管理},
    "权限管理":{adminPermission:true, lv:ADMINLV.管理设置},
    "个人首页展示":{adminPermission:false, lv:ADMINLV.会员库},
    "oss授权":{adminPermission:false},
    "消息通知":{adminPermission:false},
    "活动通知":{adminPermission:false},
    "会员个人页活动通知":{adminPermission:false},
    "发票管理":{adminPermission:true, lv:ADMINLV.发票管理},
    "会员个人页":{adminPermission:false},
    "会员导出":{adminPermission:true, lv:ADMINLV.会员库},
    "审批导出":{adminPermission:true, lv:ADMINLV.会员库},
    "学会概况_学会概括":{adminPermission:true, lv:ADMINLV.学会概况},
    "学会概况_学会领导":{adminPermission:true, lv:ADMINLV.学会概况},
    "学会概况_学会架构":{adminPermission:true, lv:ADMINLV.学会概况},
    "首页_专题系列":{adminPermission:true, lv:ADMINLV.首页},
    "品牌项目_学术研究":{adminPermission:true, lv:ADMINLV.品牌项目},
    "品牌项目_芳华杯":{adminPermission:true, lv:ADMINLV.品牌项目},
    "分支机构_机构管理":{adminPermission:true, lv:ADMINLV.分支机构},
    "通知公告_会议通知":{adminPermission:true, lv:ADMINLV.内容管理},
    "通知公告_活动通知":{adminPermission:true, lv:ADMINLV.内容管理},
    "通知公告_项目公告":{adminPermission:true, lv:ADMINLV.内容管理},
    "内容管理_banner管理":{adminPermission:true, lv:ADMINLV.内容管理},
    "内容管理_视频管理":{adminPermission:true, lv:ADMINLV.内容管理},
    "内容管理_文章管理":{adminPermission:true, lv:ADMINLV.内容管理},
    "党建工作_学习园地":{adminPermission:true, lv:ADMINLV.党建工作},
    "党建工作_主题教育":{adminPermission:true, lv:ADMINLV.党建工作},
    "党建工作_文字资料":{adminPermission:true, lv:ADMINLV.党建工作},
    "分支机构_机构管理_工作动态":{adminPermission:true, lv:ADMINLV.分支机构},
    "分支机构_机构管理_委员名单":{adminPermission:true, lv:ADMINLV.分支机构},
    "分支机构_机构管理_下载管理":{adminPermission:true, lv:ADMINLV.分支机构},
};

function routerFun(apiName, defaultParam, subUrl, param, bindBiz, notMiddleware, modelKey) {
    return async function (req, res) {
        //判断权限
        //modelKey
        let permissionInfo = permissionConfig[modelKey];
        if (permissionInfo) {
            let {adminPermission, lv} = permissionInfo;
            if (adminPermission && !req.adminInfomation) {
                //路由是管理员路由，用户不是管理员用户
                throw new BizError(ERRORENUM.权限错误);
            } else if(adminPermission && req.adminInfomation) {
                //路由是管理员路由，用户是管理员用户
                if (req.adminInfomation.adminLv.indexOf(lv) == -1 ) {
                    throw new BizError(ERRORENUM.权限错误);
                }
            }
            
        }
        
        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);
    }));
}
