/**
 * 孵化器看板
 */

import moment = require("moment");
import { OPERATIONALDATATYPE, TABLEID, TABLENAME } from "../config/enum/dbEnum";
import { BUILDING, CHANGESTATE, CHANGETYPE, DEGREE, EMIGRATIONTYPE, FUHUASTATE, INCOME, INDUSTRY, OFFLINEPROMOTION, ONLINEPROMOTION, PROMOTIONTYPE, STATE } from "../config/enum/enum";
import { operationalData, selectData, selectManyTableData } from "../data/operationalData";
import { getMySqlMs, randomId } from "../tools/system";
import { changeEnumValue } from "../util/verificationEnum";
import { eccFormParam } from "../util/verificationParam";
import { AdminRegisterAddConfig, YuYiBaseDataUpdateConfig } from "../config/eccParam/enterprise";
import { ERRORENUM } from "../config/enum/errorEnum";
import { BizError } from "../util/bizError";
import { extractData } from "../util/piecemeal";
import { EnterpriseApplyForConfig, YuYiBaseDataConfig } from "../config/splitResult/enterprise";


/**
 * 基本信息
 * @returns 
 */
export async function getBaseData() {
    let nowTime = getMySqlMs(new Date());

    let baseData = {
        fuhuaData:{ //孵化器数据
            // "总面积":0, //没有
            "孵化器总面积":0,
            "在孵面积":0,
            // "自用面积":0,
            "在孵企业":0,
            "迁出企业":0,
            "毕业企业":0,
            // "出租率": "", // 添加出租率字段
            // "园区面积":0,//新增
            // "产业规模": 0,
            // "总资产投入金额": 0,
            // "引入机构数量": 0,
            // "引入机构投资": 0,
        },
        fuhuaPinfen:0, //孵化器评分 没有该字段
        fuhuaInfo:{ //孵化器信息   
        },
        entryInfo: [], // 孵化器入驻信息
        promotionInfo: {} // 运营推广信息
    };

    let selectParam = { state:CHANGESTATE.已通过 };
    let araeParam = {column:["area", "unitPrice", "roomNumber", "rent", "startTime", "endTime"], where:{} };
    let zaifuTableInfo:any = {};
    zaifuTableInfo[TABLENAME.租赁信息] = araeParam;
    zaifuTableInfo[TABLENAME.企业孵化信息] = {column:["state", "startTime", "endTime"], where:{state:{"%ne%":FUHUASTATE.迁出}} };
    let zaifuResList = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, selectParam, ["eId"], zaifuTableInfo );
    
    if (zaifuResList) baseData.fuhuaData["在孵企业"] = zaifuResList.length;
    // zaifuResList.forEach( info => {
    //     info.enterprise_leases.forEach( lease => {
    //         baseData.fuhuaData["在孵面积"] += parseFloat(lease.area);
    //     })
    // })
    // 累加在孵面积（考虑租赁时间）
    zaifuResList.forEach(info => {
        info.enterprise_leases.forEach(lease => {
            // 确认租赁时间在有效范围内
            if (nowTime >= lease.startTime && nowTime <= lease.endTime) {
                baseData.fuhuaData["在孵面积"] += parseFloat(lease.area);
            }
        });
    });
    // baseData.fuhuaData["在孵面积占比"] = ((baseData.fuhuaData["在孵面积(㎡)"] / baseData.fuhuaData["总面积(㎡)"])*100).toFixed(2) + "%";

    /**迁出企业 */
    let qianchuList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业孵化信息, {state:FUHUASTATE.迁出}, {});
    if (qianchuList) baseData.fuhuaData["迁出企业"] = qianchuList.length;

    /**毕业企业 */
    // let biyeList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业孵化信息, {graduationTime:{"%ne%":null}}, {});
    let biyeList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业孵化信息, {moveOutType:EMIGRATIONTYPE.毕业迁出}, {});
    if (biyeList) baseData.fuhuaData["毕业企业"] = biyeList.length;
    
    /**孵化器信息 */
    let yuyiList = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.羽翼孵化器信息, {}, []);
    if (baseData.fuhuaData["在孵面积"] != yuyiList.zaifuArea) await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.羽翼孵化器信息, {zaifuArea:baseData.fuhuaData["在孵面积"]}, {yId:yuyiList.yId});
    
    if (yuyiList) {
        // baseData.fuhuaData["总面积"] = yuyiList.totalArea;
        baseData.fuhuaData["孵化器总面积"] = yuyiList.totalArea;
        // baseData.fuhuaData["在孵面积"] = yuyiList.zaifuArea;
        // baseData.fuhuaData["自用面积"] = yuyiList.ziyonArea;   
        // baseData.fuhuaData["园区面积"] = yuyiList.parkArea;//新增
        // baseData.fuhuaData["产业规模"] = yuyiList.industrialScale;
        // baseData.fuhuaData["总资产投入金额"] = yuyiList.totalAssetInvestmentAmount;
        // baseData.fuhuaData["引入机构数量"] = yuyiList.numberOfInstitutionsIntroduced;
        // baseData.fuhuaData["引入机构投资"] = yuyiList.introduceInstitutionalInvestment;
        // baseData.fuhuaData["出租率"] = yuyiList.rentRate;//出租率

        baseData.fuhuaInfo = {
            "运营名称":yuyiList.operateName,
            "孵化器名称":yuyiList.name,
            "统一社会信用代码":yuyiList.uscc,
            "注册时间":yuyiList.registerTime,
            "孵化级别":yuyiList.incubateLv,
            "孵化器认定时间":yuyiList.incubateTime,
            "孵化领域":yuyiList.incubateField,
            "机构性质":yuyiList.natureInstitution,
            "是否成立投资基金":yuyiList.fundedReserve,//
            "联系人":yuyiList.contacts,
            "负责人":yuyiList.personCharge,
            "手机号码":yuyiList.phone,
            "孵化器简介":yuyiList.synopsis,
        }
    }

    /**
     * 孵化器入驻信息
     */
    let entryList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.入驻信息表, {}, [`info_enterId`, `building`, `occupancyRate`, `enteredEnterprises`]);
    let entryInfo = {"1":{"入驻率":"", "入驻企业":""}, "3":{"入驻率":"", "入驻企业":""}, "4":{"入驻率":"", "入驻企业":""}};

    if (entryList.length) {
        entryList.forEach( info => {
            // let building = changeEnumValue(BUILDING, info.building);
            let building = info.building;
            if (!entryInfo[building]) {
                entryInfo[building] = { "入驻率": "", "入驻企业": "" };
            }
            entryInfo[building].入驻率 = info.occupancyRate;
            entryInfo[building].入驻企业 = info.enteredEnterprises;
        })
    }

    baseData.entryInfo = [];
    for (let key in entryInfo) {
        let dataList = [];
        for (let name in entryInfo[key]) {
            dataList.push({key:name, value:entryInfo[key][name]});
        }
        baseData.entryInfo.push({name:changeEnumValue(BUILDING, parseInt(key)), dataList});
    }

    /**
     * 运营推广(次数)
     */
    let promotionList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.运营推广信息表,{}, ["opId","promotionType", "promotionApp", "promotionNum"]);
    let promotionInfo = {"线上推广": {},  "线下推广": {}};
    if (promotionList.length) {
        promotionList.forEach( info => {
            let appStr = "";
            if (info.promotionType == PROMOTIONTYPE.线上推广) {
                appStr = changeEnumValue(ONLINEPROMOTION, info.promotionApp);
                promotionInfo["线上推广"][appStr] = info.promotionNum;
            } else if (info.promotionType == PROMOTIONTYPE.线下推广) {
                appStr = changeEnumValue(OFFLINEPROMOTION, info.promotionApp);
                promotionInfo["线下推广"][appStr] = info.promotionNum;
            }
        })
    }

    baseData.promotionInfo = {"线上推广": [],  "线下推广": []};
    for (let key in promotionInfo) {
        let infoData = promotionInfo[key];
        for (let name in infoData) {
            baseData.promotionInfo[key].push({key:name, value:infoData[name]});
        }
    }

    return {baseData};
}


export async function getOperateData(year) {
    let yearTime = moment(year, "YYYY").startOf('year').format("YYYY-MM-DD");
    console.log("yearTime:", yearTime);

    let operateData = {
        "当前在孵企业数": 0,
        // "在孵企业数变化趋势": [], // 修改：不再区分实体/虚拟
        "在孵企业数变化趋势": {
            "在孵企业": []
        },
        "毕业企业数变化趋势": {
            "毕业企业": []
        },
        "企业需求新增趋势": [],
        "在孵企业行业领域": [],
    };
    let qushiConf = { "01": 0, "02": 0, "03": 0, "04": 0, "05": 0, "06": 0, "07": 0, "08": 0, "09": 0, "10": 0, "11": 0, "12": 0 };

    /**在孵企业 */
    let fhColumn = ["fId", "eId", "startTime", "endTime", "state", "virtualCause", "virtualCauseDes", "moveOutType",
        "moveOutTrace", "moveOutCause", "moveOutTime", "graduationTime", ];
    let 在孵dbList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业孵化信息, {state: { "%between%": [FUHUASTATE.实体孵化, FUHUASTATE.虚拟孵化] }}, fhColumn);
    // 新增：统一统计每个月的数据
    let zaifuInfo = { ...qushiConf }; // 初始化每月数据为0
    在孵dbList.forEach(info => {
        let year = moment(info.startTime).format("YYYY");
        let month = moment(info.startTime).format("MM");

        if (year === moment(yearTime).format("YYYY")) {
            operateData.当前在孵企业数 += 1;
            zaifuInfo[month] += 1;
        }
    })

    operateData.在孵企业数变化趋势.在孵企业 = Object.keys(zaifuInfo)
        .map(key => ({ key, value: zaifuInfo[key].toString() }))
        .sort((a, b) => parseInt(a.key) - parseInt(b.key));


    /**毕业企业 */
    let biyeList = await selectData(
        OPERATIONALDATATYPE.查询多个,
        TABLENAME.企业孵化信息,
        { moveOutType: EMIGRATIONTYPE.毕业迁出 }, {}); // 只查毕业迁出的企业

    let biyeInfo = { ...qushiConf }; // 每月初始化为0

    biyeList.forEach(info => {
        let graduationTime = info.graduationTime || info.moveOutTime; // 如果graduationTime不存在用moveOutTime代替
        if (!graduationTime) return;

        let year = moment(graduationTime).format("YYYY");
        let month = moment(graduationTime).format("MM");

        if (year === moment(yearTime).format("YYYY")) {
            biyeInfo[month] += 1;
        }
    });

    operateData.毕业企业数变化趋势.毕业企业 = Object.keys(biyeInfo)
        .map(key => ({ key, value: biyeInfo[key].toString() }))
        // .sort((a, b) => a.key - b.key);
        .sort((a, b) => parseInt(a.key) - parseInt(b.key));
    
    //将 industry 字符串转换为数组
    let manyTableInfo: any = {}
    manyTableInfo[TABLENAME.企业孵化信息] = { column: ["fId", "eId", "startTime", "endTime", "state"], where: {} };
    manyTableInfo[TABLENAME.租赁信息] = { column: ["area", "startTime", "endTime"], where: {} };
    let fhdbList = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, { state: CHANGESTATE.已通过 }, ["industry", "eId"], manyTableInfo);
    
    let industryMap = {};
    fhdbList.forEach(info => {
        let { industry } = info;
        //行业领域分布
        if (industry) {
            let industryList = JSON.parse(industry);
            for (let i = 0; i < industryList.length; i++) {
                let industryStr = changeEnumValue(INDUSTRY, industryList[i]);
                if (!industryMap[industryStr]) industryMap[industryStr] = 0;
                industryMap[industryStr] += 1;
            }
        }
    })
    for (let key in INDUSTRY) {
        let anyKey: any = key;
        if (isNaN(anyKey)) {
            let keyStr = key;
            operateData.在孵企业行业领域.push({ key: keyStr, value: industryMap[keyStr] || 0 });
        }
    }
    
    /**企业需求新增趋势 */
    //获取所有企业服务表联查企业信息表 applyTime:申请服务时间
    let 企业服务dbList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业服务表, {applyTime: { "%gt%": yearTime }}, null);

    // 新增：统一统计每个月的数据
    let xuqiuInfo = { ...qushiConf }; // 初始化每月数据为0
    企业服务dbList.forEach(info => {
        let applyTime = info.applyTime;
        if (!applyTime) return;

        let year = moment(applyTime).format("YYYY");
        let month = moment(applyTime).format("MM");

        if (year === moment(yearTime).format("YYYY")) {
            xuqiuInfo[month] += 1;
        }
    });

    operateData.企业需求新增趋势 = Object.keys(xuqiuInfo)
        .map(key => ({ key, value: xuqiuInfo[key].toString() }))
        .sort((a, b) => parseInt(a.key) - parseInt(b.key));

    return { operateData };
}


/**
 * 根据传入的年份生成当前年份与目标年份之间的所有年份列表
 * @param targetYear 传入的年份
 * @returns 
 */
export function getYearList(targetYear) {
    const currentYear = new Date().getFullYear();
  
    // 生成目标年份与当前年份之间的年份列表
    const startYear = Math.min(targetYear, currentYear);
    const endYear = Math.max(targetYear, currentYear);
    let years = [];
    for (let year = startYear; year <= endYear; year++) {
        years.push(year);
    }

    // 如果结果不足5年，返回近5年列表
    if (years.length < 5) {
        years = [];
        for (let year = currentYear - 4; year <= currentYear; year++) {
        years.push(year);
        }
    }

    // 确保输出顺序始终为时间正序
    years.sort((a, b) => {
        return a - b;
    })

    return years;
}


export async function getRiskData() {
    let yj = {
        高风险: 0,
        中低风险: 0,
        关注: 0
    }
    let riskEnterprises: any[] = [];
    let fhColumn = ["enterpriseName", "industry", "eId", "shijiaoziben"];
    //获取所有企业孵化信息
    let manyTableInfo: any = {}
    // manyTableInfo[TABLENAME.企业孵化信息] = { column: ["fId", "eId", "startTime", "endTime", "state"], where: { state: FUHUASTATE.实体孵化 } };
    manyTableInfo[TABLENAME.企业孵化信息] = { column: ["fId", "eId", "moveOutTime", "moveOutType"], where: {} };
    // manyTableInfo[TABLENAME.企业经营信息] = { column: ["annual"], where: {} };
    let fhdbList = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, {state: CHANGESTATE.已通过}, fhColumn, manyTableInfo);

    let manageList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业经营信息, {}, ["annual", "eId"]);

    let map = {};
    manageList.forEach(info => {
        map[info.eId] = 1;
    });

    fhdbList.forEach(info => {
        let riskLevel = "";
        if (info.enterprise_fuhuas[0].moveOutType == EMIGRATIONTYPE.违约退租 || info.enterprise_fuhuas[0].moveOutType == EMIGRATIONTYPE.到期退租) {
            yj.高风险 += 1;
            riskLevel = "高风险";
            riskEnterprises.push([info.enterpriseName, riskLevel]);
        } else if (!map[info.eId]) {
            yj.中低风险 += 1;
            riskLevel = "中低风险";
            riskEnterprises.push([info.enterpriseName, riskLevel]);
        }
    });

    let yujiData = [];
    for (let key in yj) {
        yujiData.push({key, value:yj[key]});
    }

    return {
        yujiData,
        riskEnterprises
    };
}

/**
 * 价值分析
 */
export async function getWorthDate() {
    let worthData = {
        "TXP":[], //纳税趋势(万元)
        "financing":[], //融资金额趋势
        "jiuye":[] //就业人数趋势
    }
    let qushiConf = {"01":0, "02":0, "03":0, "04":0, "05":0, "06":0, "07":0, "08":0, "09":0, "10":0, "11":0, "12":0};

    /**纳税趋势 */
    let nashuiList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业经营信息, {}, {});
    let minNaShuiYear = Math.min( ...nashuiList.map(item => new Date(item.investmentDate).getFullYear()) );
    if (!nashuiList.length) minNaShuiYear = new Date().getFullYear();
    let nashuiYear = getYearList(minNaShuiYear);

    for(let i = 0; i < nashuiYear.length; i++) {
        let nashui = 0;
        nashuiList.forEach( info => {
            let parsedStartTime = moment(info.annual);
            if (parsedStartTime.isValid() && parsedStartTime.year() === nashuiYear[i]) {
                nashui += parseFloat(info.TXP);
            }
        })

        worthData.TXP.push({key:nashuiYear[i], value:nashui.toString()});
    }

    //X轴排序
    worthData.TXP.sort( (a, b) => {
        return a.key - b.key;
    })


    /**融资额趋势分析 */
    let 融资情况 = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业融资, {}, []);
    let minYear = Math.min( ...融资情况.map(item => new Date(item.investmentDate).getFullYear()) );
    if (!融资情况.length) minYear = new Date().getFullYear();
    let year = getYearList(minYear);
    for(let i = 0; i < year.length; i++) {
        let 融资金额 = 0;
        融资情况.forEach(info => {
            let 融资日期 = moment(info.investmentDate);
            if (融资日期.isValid() && 融资日期.year() === year[i]) {
                融资金额 += parseFloat(info.financingAmount || 0);
            }
        });
        worthData.financing.push({key:year[i], value:融资金额});
    }

    /**就业人数趋势 */
    let 参保记录 = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.参保记录, {}, {});
    let minJiuyeYear = Math.min( ...参保记录.map(item => new Date(item.investmentDate).getFullYear()) );
    if (!参保记录.length) minJiuyeYear = new Date().getFullYear();
    let jiuyeyear = getYearList(minJiuyeYear);
    for(let i = 0; i < jiuyeyear.length; i++) {
        let 就业人数 = 0;
        参保记录.forEach(info => {
            let 参保日期 = moment(info.annual);
            if (参保日期.isValid() && 参保日期.year() === jiuyeyear[i]) {
                if (info.zhuanKe) {
                    就业人数 += parseInt(info.zhuanKe);
                }
                if (info.benKe) {
                    就业人数 += parseInt(info.benKe);
                }
                if (info.shuoshi) {
                    就业人数 += parseInt(info.shuoshi);
                }
                if (info.boShi) {
                    就业人数 += parseInt(info.boShi);
                }
                if (info.boshiyishang) {
                    就业人数 += parseInt(info.boshiyishang);
                }
                if (info.qiTa) {
                    就业人数 += parseInt(info.qiTa);
                }
            }
        });
        worthData.jiuye.push({key:jiuyeyear[i], value:就业人数.toString()});
    }

    //X轴排序
    worthData.jiuye.sort( (a, b) => {
        return a.key - b.key;
    })

    return worthData;
}




// ============================== 管理后台操作 ======================================
/**
 * 雨艺孵化器数据回显
 */
// export async function getYuYiFuHua() {
//     let yuyiInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.羽翼孵化器信息, {uscc:"91310115069312504K"}, []);
//     let dataInfo:any = extractData(YuYiBaseDataConfig, yuyiInfo);
//     //兼容一下唯一一个number
//     // dataInfo.enterpriseNum = dataInfo.enterpriseNum || 0;

//     return {dataInfo};
// }
export async function getYuYiFuHua() {
    // 1. 获取羽翼孵化器基本信息
    let yuyiInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.羽翼孵化器信息, {uscc: "91310115069312504K"}, []);
    let dataInfo: any = extractData(YuYiBaseDataConfig, yuyiInfo);

    // 2. 获取孵化器入驻信息
    let entryList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.入驻信息表, {}, [`info_enterId`, `building`, `occupancyRate`, `enteredEnterprises`]);
    let entryInfo = {"1": {"入驻率": "", "入驻企业": ""}, "3": {"入驻率": "", "入驻企业": ""}, "4": {"入驻率": "", "入驻企业": ""}};

    if (entryList.length) {
        entryList.forEach(info => {
            // let building = changeEnumValue(BUILDING, info.building);
            let building = info.building;
            if (!entryInfo[building]) {
                entryInfo[building] = { "入驻率": "", "入驻企业": "" };
            }
            entryInfo[building].入驻率 = info.occupancyRate;
            entryInfo[building].入驻企业 = info.enteredEnterprises;
        });
    }

    // 3. 获取运营推广（次数）信息
    let promotionList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.运营推广信息表, {}, ["opId", "promotionType", "promotionApp", "promotionNum"]);
    let promotionInfo = {"线上推广": {}, "线下推广": {}};

    if (promotionList.length) {
        promotionList.forEach(info => {
            let appStr = "";
            if (info.promotionType == PROMOTIONTYPE.线上推广) {
                appStr = changeEnumValue(ONLINEPROMOTION, info.promotionApp);
                promotionInfo["线上推广"][appStr] = info.promotionNum;
            } else if (info.promotionType == PROMOTIONTYPE.线下推广) {
                appStr = changeEnumValue(OFFLINEPROMOTION, info.promotionApp);
                promotionInfo["线下推广"][appStr] = info.promotionNum;
            }
        });
    }

    // 4. 将 entryInfo 和 promotionInfo 可以合并到 dataInfo 中
    // dataInfo.entryInfo = entryInfo;
    // dataInfo.promotionInfo = promotionInfo;

    // 4. 组装返回数据
    return {
        dataInfo,
        entryInfo,
        promotionInfo
    };
}

/**
 * 雨艺孵化器基本信息修改
 * @param yId 
 * @param entryInfo {"1号楼":{入驻率:"", 入驻企业:""}, ......}
 * @param promotionInfo {"线上推广":{"活动宣讲":0, "三方机构合作":0}, "线下推广":{"活动宣讲":0, "三方机构合作":0}}
 */
export async function updateYuYi(yId, param) {
    const FuncName = "雨艺孵化器基本信息修改";
    eccFormParam(FuncName, YuYiBaseDataUpdateConfig, param);
    let yuyiInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.羽翼孵化器信息, {yId}, []);
    if (!yuyiInfo || !yuyiInfo.yId) {
        throw new BizError(ERRORENUM.数据不存在);
    }

    let enterInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.入驻信息表, {info_enterId:yuyiInfo.info_enterId}, [`info_enterId`, `building`, `occupancyRate`, `enteredEnterprises`]);
    if (!enterInfo || !enterInfo.info_enterId) {
        throw new BizError(ERRORENUM.数据不存在);
    }
    // let promotiondbInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.运营推广信息表, {opId:yuyiInfo.opId}, ["opId", "promotionType", "promotionApp", "promotionNum"]);
    // if (!promotiondbInfo || !promotiondbInfo.opId) {
    //     throw new BizError(ERRORENUM.数据不存在);
    // }

    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.羽翼孵化器信息, param, {yId});
    
    let  entryInfo = param.entryInfo;
    for (let key in entryInfo) {
        let 入驻信息updateInfo = {occupancyRate:entryInfo[key].入驻率, enteredEnterprises:entryInfo[key].入驻企业};
        let updateParam = {building:key}
        await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.入驻信息表, 入驻信息updateInfo, updateParam);
    }
    let promotionInfo = param.promotionInfo
    for (let key in promotionInfo) {
        for (let app in promotionInfo[key]) {
            let updateInfo = {promotionNum:promotionInfo[key][app]};
            let updateParam:any = {promotionType:PROMOTIONTYPE[key]}
            if (PROMOTIONTYPE[key] == PROMOTIONTYPE.线上推广) {
                updateParam.promotionApp = ONLINEPROMOTION[app];
            } else if (PROMOTIONTYPE[key] == PROMOTIONTYPE.线下推广) {
                updateParam.promotionApp = OFFLINEPROMOTION[app];
            }
            let 运营推广dbInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.运营推广信息表, updateParam, ["opId", "promotionType", "promotionApp", "promotionNum"]); 
            if (!Object.keys(运营推广dbInfo).length) {
                if (updateInfo.promotionNum) {
                    let addInfo = {
                        opId:randomId(TABLENAME.运营推广信息表),
                        promotionType:updateParam.promotionType,
                        promotionApp:updateParam.promotionApp,
                        promotionNum:updateInfo.promotionNum || ""
                    };
                    await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.运营推广信息表, addInfo, {});
                }
            } else {
                await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.运营推广信息表, {promotionNum:promotionInfo[key][app]}, updateParam);
            }
        }
    }

    return {isSuccess:true};
}







