/**
 * 走访逻辑
 */
import moment = require("moment");
import { FUHUASTATE, RESEARCHTYPE, VISITDEMAND, VISITENTERPRISETYPE, VISITSTATE } from "../../config/enum";
import * as visitData from "../../data/fuHuaQi/visit";
import * as demandData from "../../data/fuHuaQi/demand";
import * as enterpriseData from "../../data/enterprise/enterprise";
import * as trackData from "../../data/fuHuaQi/track";
import { changeEnumManyValue, changeEnumValue, eccEnumValue } from "../../util/verificationEnum";
import { BizError } from "../../util/bizError";
import { ERRORENUM } from "../../config/errorEnum";
import { getRandomId } from "../../tools/system";
import { eccFormParam } from "../../util/verificationParam";
import { AddVisitConfig } from "../../config/eccParam/fuHuaQi";


export async function visitStatisBase(fuHuaQiUscc:string) {

    let startMs = moment().startOf("y").valueOf();
    let lastYearMs = moment().subtract(1,'y').startOf("y").valueOf();

    let dangQianCount = await visitData.findCountByParam({ visitTime:{"$gt":startMs}, fuHuaQiUscc, state:VISITSTATE.走访安排});
    let liShiCount = await visitData.findCountByParam({ visitTime:{"$gt":startMs}, fuHuaQiUscc, state:VISITSTATE.完成});

    let lastYearCount = await visitData.findCountByParam({ visitTime:{"$gt":lastYearMs, "$lt":startMs}, state:VISITSTATE.完成, fuHuaQiUscc });
    let thisYearCount = dangQianCount + liShiCount;

    let yearToYear = 0;
    if (thisYearCount && lastYearCount) {
        yearToYear = Math.ceil((thisYearCount - lastYearCount) / lastYearCount * 100)
    }

    let dataInfo = {
        thisYearCount,
        yearToYear,
        dangQianCount,
        liShiCount
    };

    return {dataInfo};
}

export async function visitStatisTypeList(fuHuaQiUscc) {

    let startMs = moment().startOf("y").valueOf();
    // let dbList = await visitData.findByParam({ visitTime:{"$gt":startMs}, fuHuaQiUscc});

    let dbList = await demandData.findByParam({createTime:{"$gt":startMs}, fuHuaQiUscc});

    let typeMap = {};
    dbList.forEach(item => {
        let {enterpriseType, demand, uscc, enterpriseName} = item;
        let demandList = changeEnumManyValue(VISITDEMAND, demand);
        if (!typeMap[enterpriseName]) typeMap[enterpriseName] = {enterpriseName, uscc, demand:[] };

        demandList.forEach(itemKey => {
            if (typeMap[enterpriseName].demand.indexOf(itemKey) <= -1) {
                typeMap[enterpriseName].demand.push(itemKey);
            }
        })
    });

    let demanList = Object.values(typeMap);

    let now = new Date().valueOf();
    let selectzcparam = {
        "$or":[
            {"firstIncubationTime":{"$gt":now-(24*3600*90*1000) }},
            {"timeOfImmigration":{"$gt":now-(24*3600*90*1000) }}
        ]
    };

    let zcdbList = await enterpriseData.findEnterpriseList(selectzcparam);
    let zcList = [];
    zcdbList.forEach(info => {
        let createTime = "";
        if (info.firstIncubationTime)  createTime = moment(info.firstIncubationTime).format("YYYY-MM-DD");
        if (info.timeOfImmigration)  createTime = moment(info.timeOfImmigration).format("YYYY-MM-DD");
        zcList.push({
            uscc:info.uscc,
            enterpriseName:info.name,
            createTime
        });
    });

    let dataList = [
        {key:changeEnumValue(VISITENTERPRISETYPE, VISITENTERPRISETYPE.主动申报需求企业), count:demanList.length, list:demanList },
        {key:changeEnumValue(VISITENTERPRISETYPE, VISITENTERPRISETYPE.新入驻企业), count:zcList.length, list:zcList },
        {key:changeEnumValue(VISITENTERPRISETYPE, VISITENTERPRISETYPE.临近毕业企业), count:0, list:[] },
        {key:changeEnumValue(VISITENTERPRISETYPE, VISITENTERPRISETYPE.数据异常企业), count:0, list:[] },
    ];



    return {dataList};
}

export async function visitAlendarStatis(fuHuaQiUscc:string) {
    let startMs = moment().startOf("month").valueOf();
    
    let shengYuCount = await visitData.findCountByParam({ visitTime:{"$gt":startMs}, fuHuaQiUscc, state:VISITSTATE.走访安排});
    let leiJiCount = await visitData.findCountByParam({ visitTime:{"$gt":startMs}, fuHuaQiUscc, state:VISITSTATE.完成});
    let thisMonthCount = shengYuCount + leiJiCount;

    let rate = 0;
    if (leiJiCount && thisMonthCount) {
        rate = Math.ceil(leiJiCount / thisMonthCount * 100)
    }

    let dataInfo = {
        shengYuCount,
        leiJiCount,
        rate
    };

    return {dataInfo};
}


export async function visitCalendarList(fuHuaQiUscc) {

    let startMs = moment().startOf("w").valueOf();
    let endMs = startMs + (24* 3600* 1000 * 7);
    let dbList = await visitData.findByParam({ visitTime:{"$gt":startMs, "$lt":endMs}, fuHuaQiUscc});

   
    let typeMap = {};

    dbList.forEach(item => {
        let {visitTime, accompany, leaderName, id, enterpriseName} = item;
        
        let dateStr = moment(visitTime).format("YYYY-MM-DD");
        if (!typeMap[dateStr]) typeMap[dateStr] = [];

        typeMap[dateStr].push({
            accompany,//陪同人员
            leaderName,//出席领导
            id,
            enterpriseName,
            time:moment(visitTime).format("HH:mm")
        });
    });


    let dataList = [];

    for (let key in typeMap) {
        let itemList = typeMap[key]
        dataList.push({
            dateKey:key,
            subList:itemList
        });
    }

    dataList.sort( (a, b) => {return new Date(a.dateKey).valueOf()- new Date(b.dateKey).valueOf()});

    return {dataList};
}

/**
 * 添加走访安排
 * @param fuHuaQiUscc 
 * @param param 
 */
export async function visitAdd(fuHuaQiUscc:string, param) {
    eccFormParam("添加走访安排", AddVisitConfig, param);
    eccEnumValue("添加走访按排", "researchType", RESEARCHTYPE, param.researchType);

    let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(param.uscc);
    if (!enterpriseInfo || !enterpriseInfo.uscc) throw new BizError(ERRORENUM.目标数据不存在)

    let addInfo = {
        id:getRandomId("zf"),
        fuHuaQiUscc,
        enterpriseName:enterpriseInfo.name,
        uscc:param.uscc,
        visitTime:param.visitTime,
        accompany:param.accompany,
        leaderName:param.leaderName,
        researchType:param.researchType,
        desc:param.desc,
        state:VISITSTATE.走访安排,//1=初始状态  2=取消 3=完成  VISITSTATE
        createTime:new Date().valueOf(),
        enterpriseType:VISITENTERPRISETYPE.主动申报需求企业//VISITENTERPRISETYPE
    };

    await visitData.createDataByParam(addInfo);

    return {isSuccess:true};
}


export async function visitInfo(id:string) {
    let visitInfo = await visitData.findOne({id});

    let dataInfo = {
        enterpriseName:visitInfo.enterpriseName,
        uscc:visitInfo.uscc,
        visitTime:visitInfo.visitTime,
        accompany:visitInfo.accompany,
        leaderName:visitInfo.leaderName,
        researchType:changeEnumValue( RESEARCHTYPE, visitInfo.researchType),
        desc:visitInfo.desc,
        createTime:new Date().valueOf(),
        enterpriseType:changeEnumValue(VISITENTERPRISETYPE, visitInfo.enterpriseType)
    };

    return {dataInfo};
}


export async function visitUpdateState(id, state:number) {
    if ( !( state == 3 || state == 2 ) ) throw new BizError(ERRORENUM.参数错误);
    
    let visitInfo = await visitData.findOne({id});
    if (!visitInfo || !visitInfo.id) throw new BizError(ERRORENUM.目标数据不存在);

    visitInfo.state = state;
    await visitInfo.save();

    return {isSuccess:true}
}


export async function visitTrackAdd(fuHuaQiUscc:string, uscc:string, trackType:number, content:string) {
    eccEnumValue("添加服务追踪", "trackType", VISITENTERPRISETYPE, trackType)

    let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(uscc);
    if (!enterpriseInfo || !enterpriseInfo.uscc) throw new BizError(ERRORENUM.目标数据不存在);

    let addInfo = {
        id:getRandomId("track"),//标识
        fuHuaQiUscc,//孵化器uscc
        uscc,//企业uscc
        enterpriseName:enterpriseInfo.enterpriseName,
        trackType,//跟踪类型 VISITENTERPRISETYPE
        content,//内容
        createTime:new Date().valueOf()
    };

    await trackData.createDataByParam(addInfo);

    return {isSuccess:true}
}

export async function visitTrackList(uscc) {

    let dbList = await trackData.findByParam({uscc});

    let dataList = [];
    let enterpriseName = "";
    dbList.forEach(item => {
        let trackType = changeEnumManyValue(VISITDEMAND, item.trackType);
        enterpriseName = item.enterpriseName;
        dataList.push({
            id:item.id,
            trackType,
            time:moment(item.createTime).format("YYYY.MM.DD"),
            content:item.content
        });
    })

    return {dataList, enterpriseName};
}



export async function visitLogStatis(fuHuaQiUscc:string, year:number) {
    let startMs = moment(`${year}-01-01 00:00:00`).valueOf();
    let endMs = moment(`${year}-01-01 00:00:00`).add(1,'y').valueOf();
    let lastStartMs = moment(`${year}-01-01 00:00:00`).subtract(1, 'y').valueOf();

    let thisYearParma = { visitTime:{"$gt":startMs, "$lt":endMs}, fuHuaQiUscc, state:VISITSTATE.完成};
    let dangQianCount = await visitData.findCountByParam(thisYearParma);

    let lastYearParma = { visitTime:{"$gt":lastStartMs, "$lt":startMs}, fuHuaQiUscc, state:VISITSTATE.完成};
    let liShiCount = await visitData.findCountByParam(lastYearParma);

    let rate = 0;
    if (dangQianCount && liShiCount) {
        rate = Math.ceil((dangQianCount - liShiCount) / liShiCount * 100)
    }


    return {dataInfo:{rate, thisYearCount:dangQianCount}};
}


export async function visitLogList(fuHuaQiUscc:string, year:number) {
    let startMs = moment(`${year}-01-01 00:00:00`).valueOf();
    let endMs = moment(`${year}-01-01 00:00:00`).add(1,'y').valueOf();
    let dbList = await visitData.findByParam({ visitTime:{"$gt":startMs, "$lt":endMs}, state:{"$gt":VISITSTATE.走访安排},  fuHuaQiUscc});

    let monthMap = {};

    dbList.forEach(item => {
        let {state, enterpriseName, id, visitTime} = item;

        let monthNumber = moment(visitTime).format("M");

        if (!monthMap[monthNumber]) {
            monthMap[monthNumber] = {count:0, dataList:[]};
        }

        if (state == VISITSTATE.完成) monthMap[monthNumber].count += 1;
        monthMap[monthNumber].dataList.push({
            enterpriseName,
            id,
            state:changeEnumValue(VISITSTATE, state),
            visitTime:moment(visitTime).format("YYYY/MM/DD HH:mm")
        });
    });

    let dataList = [];
    for (let key in monthMap) {
        dataList.push({
            key,
            count:monthMap[key].count,
            list:monthMap[key].dataList
        });
    }

    return {dataList}
}


//企业需求相关
export async function visitDemandList(fuHuaQiUscc, demand) {
    /**找目标月入库的数据 */
    let enterpriseCount = await enterpriseData.findEnterpriseCount({fuHuaQiUscc});

    // let startMs = moment().startOf("y").valueOf();
    let param:any = { fuHuaQiUscc};
    if (demand && demand.length) {
        param.demand = {"$in":demand}
    }

    let dbList = await demandData.findByParam(param);
    let dataList = [];
    dbList.forEach(item => {
        let demand = changeEnumManyValue(VISITDEMAND, item.demand)
        dataList.push({
            enterpriseName:item.enterpriseName,
            id:item.id,
            demand,
            uscc:item.uscc
        });
    })

    return {enterpriseCount, dataList}
}


export async function visitDemandAdd(fuHuaQiUscc, uscc, demand, demandDesc) {

    eccEnumValue("添加企业需求", "demand", VISITDEMAND, demand);

    let enterprsieInfo = await enterpriseData.findEnterpriseByUscc(uscc);
    if (!enterprsieInfo || !enterprsieInfo.uscc) {
        throw new BizError(ERRORENUM.该企业不存在)
    }

    let addInfo = {
        id:getRandomId("qyxq"),
        fuHuaQiUscc,
        uscc,//企业uscc
        enterpriseName:enterprsieInfo.name,
        createTime:new Date().valueOf(),
        enterpriseType:VISITENTERPRISETYPE.主动申报需求企业,//VISITENTERPRISETYPE
        demand,//企业需求
        demandDesc
    }

    await demandData.createDataByParam(addInfo);

    return {isSuccess:true};
}

export async function visitDemandEnterpriseInfo(uscc) {

    let dbList = await demandData.findByParam({uscc});

    let enterpriseName = "";
    let dataList = [];
    dbList.forEach(item => {
        let demand = changeEnumManyValue(VISITDEMAND, item.demand)
        enterpriseName = item.enterpriseName;
        uscc = item.uscc;
        dataList.push({
            id:item.id,
            uscc:item.uscc,
            demand,
            time:moment(item.createTime).format("YYYY.MM.DD"),
            demandDesc:item.demandDesc
        });
    })

    return {dataList,uscc, enterpriseName};
}

export async function visitDemandDelete(id) {

    let item = await demandData.findOne({id});
    if (!item || !item.id) throw new BizError(ERRORENUM.未找到数据);

    await demandData.removeOneData(id);

    return {isSuccess:true};
}

//============企业端

/**
 * 企业需求列表
 * @param fuHuaQiUscc 
 * @param demand 
 * @returns 
 */
export async function enterpriseVisitDemandList(uscc:string) {
    let dbList = await demandData.findByParam({uscc});
    let dataList = [];
    dbList.forEach(item => {
        let demand = changeEnumManyValue(VISITDEMAND, item.demand)
        dataList.push({
            demandDesc:item.demandDesc,
            id:item.id,
            demand,
            time:moment(item.createTime).format("YYYY-MM-DD")
        });
    })

    return {dataList}
}


export async function enterpriseAddDemand(uscc, demand, demandDesc) {
    eccEnumValue("添加企业需求", "demand", VISITDEMAND, demand);

    let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(uscc)

    let enterprsieInfo = await enterpriseData.findEnterpriseByUscc(uscc);
    if (!enterprsieInfo || !enterprsieInfo.uscc) {
        throw new BizError(ERRORENUM.该企业不存在)
    }

    let addInfo = {
        id:getRandomId("qyxq"),
        fuHuaQiUscc:enterpriseInfo.fuHuaQiUscc,
        uscc,//企业uscc
        enterpriseName:enterprsieInfo.name,
        createTime:new Date().valueOf(),
        enterpriseType:VISITENTERPRISETYPE.数据异常企业,//VISITENTERPRISETYPE
        demand,//企业需求
        demandDesc
    }

    await demandData.createDataByParam(addInfo);

    return {isSuccess:true};
}


//========================================================================管委会端

export async function gwhVisitAlendarStatis(year:number) {
    let startMs = moment(`${year}-01-01 00:00:00`).valueOf();
    let endMs = moment(`${year}-01-01 00:00:00`).add(1,'y').valueOf();
    let lastStartMs = moment(`${year}-01-01 00:00:00`).subtract(1, 'y').valueOf();

    let thisYearParma = { visitTime:{"$gt":startMs, "$lt":endMs}, state:{"$gt":VISITSTATE.走访安排}};
    let dangQianCount = await visitData.findCountByParam(thisYearParma);

    let lastYearParma = { visitTime:{"$gt":lastStartMs, "$lt":startMs}, state:{"$gt":VISITSTATE.走访安排}};
    let liShiCount = await visitData.findCountByParam(lastYearParma);

    let rate = 0;
    if (dangQianCount && liShiCount) {
        rate = Math.ceil((dangQianCount - liShiCount) / liShiCount * 100)
    }
    
    let anPaiCount = await visitData.findCountByParam({ visitTime:{"$gt":startMs, "$lt":endMs}, state:VISITSTATE.走访安排});
    let jiLuCount = await visitData.findCountByParam({ state:{"$gt":VISITSTATE.走访安排}});

    let dataInfo = {
        thisYearCount:dangQianCount,
        anPaiCount,
        jiLuCount,
        rate//同比
    };

    return {dataInfo};
}

export async function gwhVisitCalendarList() {
    let startMs = moment().startOf("w").valueOf();
    let endMs = startMs + (24* 3600* 1000 * 7);
    let dbList = await visitData.findByParam({ visitTime:{"$gt":startMs, "$lt":endMs} });
   
    let typeMap = {};

    dbList.forEach(item => {
        let {visitTime, accompany, leaderName, id, enterpriseName} = item;
        
        let dateStr = moment(visitTime).format("YYYY-MM-DD");
        if (!typeMap[dateStr]) typeMap[dateStr] = [];

        typeMap[dateStr].push({
            accompany,//陪同人员
            leaderName,//出席领导
            id,
            enterpriseName,
            time:moment(visitTime).format("HH:mm")
        });
    });

    let dataList = [];
    for (let key in typeMap) {
        let itemList = typeMap[key]
        dataList.push({
            dateKey:key,
            subList:itemList
        });
    }

    dataList.sort( (a, b) => {return new Date(a.dateKey).valueOf()- new Date(b.dateKey).valueOf()});

    return {dataList};
}

export async function gwhvisitAdd(fuHuaQiUscc:string, param) {
    eccFormParam("添加走访安排", AddVisitConfig, param);
    eccEnumValue("添加走访按排", "researchType", RESEARCHTYPE, param.researchType);

    let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(param.uscc);
    if (!enterpriseInfo || !enterpriseInfo.uscc) throw new BizError(ERRORENUM.目标数据不存在)

    let addInfo = {
        id:getRandomId("zf"),
        fuHuaQiUscc,
        enterpriseName:enterpriseInfo.name,
        uscc:param.uscc,
        visitTime:param.visitTime,
        accompany:param.accompany,
        leaderName:param.leaderName,
        researchType:param.researchType,
        desc:param.desc,
        state:VISITSTATE.走访安排,//1=初始状态  2=取消 3=完成  VISITSTATE
        createTime:new Date().valueOf(),
        enterpriseType:VISITENTERPRISETYPE.临近毕业企业//VISITENTERPRISETYPE
    };

    await visitData.createDataByParam(addInfo);

    return {isSuccess:true};
}

export async function gwhVisitInfo(id:string) {
    let visitInfo = await visitData.findOne({id});

    let dataInfo = {
        enterpriseName:visitInfo.enterpriseName,
        uscc:visitInfo.uscc,
        visitTime:visitInfo.visitTime,
        accompany:visitInfo.accompany,
        leaderName:visitInfo.leaderName,
        researchType:changeEnumValue( RESEARCHTYPE, visitInfo.researchTyp),
        desc:visitInfo.desc,
        createTime:new Date().valueOf(),
        enterpriseType:changeEnumValue(VISITENTERPRISETYPE, visitInfo.enterpriseType)
    };

    return {dataInfo};
}

export async function gwhVisitLogStatis(year:number) {
    let startMs = moment(`${year}-01-01 00:00:00`).valueOf();
    let endMs = moment(`${year}-01-01 00:00:00`).add(1,'y').valueOf();
    let lastStartMs = moment(`${year}-01-01 00:00:00`).subtract(1, 'y').valueOf();

    let thisYearParma = { visitTime:{"$gt":startMs, "$lt":endMs}, state:{"$gt":VISITSTATE.走访安排}};
    let dangQianCount = await visitData.findCountByParam(thisYearParma);

    let lastYearParma = { visitTime:{"$gt":lastStartMs, "$lt":startMs}, state:{"$gt":VISITSTATE.走访安排}};
    let liShiCount = await visitData.findCountByParam(lastYearParma);

    let rate = 0;
    if (dangQianCount && liShiCount) {
        rate = Math.ceil((dangQianCount - liShiCount) / liShiCount * 100)
    }

    return {dataInfo:{rate, thisYearCount:dangQianCount}};
}

export async function gwhVisitLogList(year:number) {
    let startMs = moment(`${year}-01-01 00:00:00`).valueOf();
    let endMs = moment(`${year}-01-01 00:00:00`).add(1,'y').valueOf();
    let dbList = await visitData.findByParam({ visitTime:{"$gt":startMs, "$lt":endMs}, state:{"$gt":VISITSTATE.走访安排} });

    let monthMap = {};

    dbList.forEach(item => {
        let {state, enterpriseName, id, visitTime} = item;

        let monthNumber = moment(visitTime).format("M");

        if (!monthMap[monthNumber]) {
            monthMap[monthNumber] = {count:0, dataList:[]};
        }

        monthMap[monthNumber].count += 1;
        monthMap[monthNumber].dataList.push({
            enterpriseName,
            id,
            state:changeEnumValue(VISITSTATE, state),
            visitTime:moment(visitTime).format("YYYY/MM/DD HH:mm")
        });
    });

    let dataList = [];
    for (let key in monthMap) {
        dataList.push({
            key,
            count:monthMap[key].count,
            list:monthMap[key].dataList
        });
    }

    return {dataList}
}


export async function gwhVisitHomeStatis() {
    let startMs = moment().startOf("m").valueOf();
    
    let shengYuCount = await visitData.findCountByParam({ visitTime:{"$gt":startMs}, state:VISITSTATE.走访安排});
    let leiJiCount = await visitData.findCountByParam({ visitTime:{"$gt":startMs}, state:{"$ne":VISITSTATE.走访安排}});
    let thisMonthCount = shengYuCount + leiJiCount;

    let rate = 0;
    if (leiJiCount && thisMonthCount) {
        rate = Math.ceil(leiJiCount / thisMonthCount * 100)
    }

    let dataInfo = {
        shengYuCount,
        leiJiCount,
        rate
    };

    return {dataInfo};
}


export async function getEnterpriseForSelect() {
    /**找到该孵化器下已经提交入库的企业列表 */
    let enterpriseList = await enterpriseData.findSubmittedEnterpriseAllList();

    /**拼接返回 */
    let dataList = [];
    enterpriseList.forEach( info => {
        if (info.state != FUHUASTATE.迁出) {
            dataList.push({
                name:info.name,
                uscc:info.uscc,
                logonAddress:info.logonAddress, 
                operatingAddress:info.operatingAddress
            });
        }
    });
    
    return dataList;
}
