/**
 * 租赁
 */

import moment = require("moment");
import { findEnterpriseByUscc, findEnterpriseCount, findEnterpriseList } from "../../data/enterprise/enterprise";
import { AREAUNIT, CONTRACTTYPE, FUHUASTATE, RENTTYPE, ZLSTATETYPE, ZLSTATISTYPE } from "../../config/enum";
import { eccFormParam } from "../../util/verificationParam";
import * as eccFormParamConfig from "../../config/eccParam/fuHuaQi";
import * as leaseData from "../../data/lease";

export async function zlHomeStatis(fhqUscc:string) {
    let count = await findEnterpriseCount({fuHuaQiUscc:fhqUscc});
    let enterpriseList = await findEnterpriseList({fuHuaQiUscc:fhqUscc});

    let htjjdq = 0;
    let htdqwq = 0;
    let zjjjdq = 0;
    let zjdqwq = 0;
    const Now = new Date().valueOf();

    enterpriseList.forEach(info => {
        let {leaseInfo} = info;
        if (!leaseInfo.contractStartTime || !leaseInfo.rentStartTime) {
            if (!leaseInfo.contractStartTime) {
                htdqwq += 1;
            }
            if  (!leaseInfo.rentStartTime) {
                zjdqwq += 1;
            } 
        } else {
            if ((leaseInfo.contractEndTime - Now) < 0) {
                htdqwq += 1;
            } else if ( (leaseInfo.contractEndTime - Now) > 0 && (leaseInfo.contractEndTime - Now) < (3600 * 24 * 1000 * 30)) {
                htjjdq += 1;
            }

            if ((leaseInfo.rentEndTime - Now) < 0) {
                zjdqwq += 1;
            } else if ( (leaseInfo.rentEndTime - Now) > 0 && (leaseInfo.rentEndTime - Now) < (3600 * 24 * 1000 * 30)) {
                zjjjdq += 1;
            }

        }
    });


    let dataInfo = {
        count,
        subList:[
            {key:"合同即将到期", value:htjjdq},
            {key:"合同到期未续签", value:htdqwq},
            {key:"租金即将到期", value:zjjjdq},
            {key:"租金到期未续签", value:zjdqwq}
        ]
    };

    return {dataInfo};
}

export async function zlHomeList(fhqUscc:string, enterpriseName, htstats, stats, zjstats) {
    let now = new Date().valueOf();
    let param:any = {fuHuaQiUscc:fhqUscc};
    if (enterpriseName) param.name = {"$regex":enterpriseName};
    if (htstats) {
        if (htstats == CONTRACTTYPE.签约企业 ) {
            param["leaseInfo.contractStartTime"] = {"$lt":now};
            param["leaseInfo.contractEndTime"] = {"$gt":now};
        } else {
            param["$or"] = [
                { "leaseInfo.contractStartTime":null},
                { "leaseInfo.contractStartTime":{"$gt":now} },
                { "leaseInfo.contractEndTime":{"$lt":now} }
            ];
            param["$or"].push();
        } 
    }
    if (zjstats) {
        if (zjstats == RENTTYPE.暂未到期 ) {
            param["leaseInfo.rentStartTime"] = {"$lt":now};
            param["leaseInfo.rentEndTime"] = {"$gt":now+(30*3600*24*1000)};
        } else if (zjstats == RENTTYPE.即将到期){
            param["leaseInfo.rentStartTime"] = {"$lt":now};
            param["leaseInfo.rentEndTime"] = {"$lt":now+(30*3600*24*1000), "$gt":now};
        } else {
            param["$or"] = [
                { "leaseInfo":null},
                { "leaseInfo.rentStartTime":{"$gt":now} },
                { "leaseInfo.rentStartTime":{"$lt":now} }
            ];
            param["$or"].push();
        } 
    }
    if (stats) {
        if (stats == FUHUASTATE.迁出 ) param.state = FUHUASTATE.迁出;
        else param.state = {"$ne":FUHUASTATE.迁出};
    }

    let enterpriseList = await findEnterpriseList(param);
    const Now = new Date().valueOf();

    let dataList = [];
    enterpriseList.forEach(info => {
        let {leaseInfo} = info;
        let htstats = "";//合同状态
        if (!leaseInfo || !leaseInfo.contractStartTime) {
            htstats = "到期未签"
        } else {
            if ((leaseInfo.contractEndTime - Now) < 0) {
                 htstats = "到期未签";
            } else {
                htstats = "签约企业";
            }
        }
        
        let zjstats = "";//租金状态
        let syzlsj = 0;//剩余租赁时间
        if (!leaseInfo || !leaseInfo.rentEndTime) {
            zjstats = "到期未缴"
        } else {
            if (leaseInfo.rentEndTime < Now) {
                zjstats = "到期未缴";
            }
            else if ( leaseInfo.rentStartTime < Now && (leaseInfo.rentEndTime - Now) < (3600 * 24 * 1000 * 30))  {
                zjstats = "即将到期";
            } else {
                zjstats = "暂未到期";
            }

            
            syzlsj = moment(leaseInfo.rentEndTime).diff(Now, 'd');
            syzlsj = syzlsj <= 0 ? 0 : syzlsj;
        }

        
        let stats = info.state == FUHUASTATE.迁出 ? "迁出" : "非迁出";//企业状态
        dataList.push({
            uscc:info.uscc,
            enterpriseName:info.name,//企业名称
            stats,//企业状态
            htstats,//合同状态
            zjstats,//租金状态
            syzlsj,//剩余租赁时间
        });
    });

    return {dataList};
}

export async function zlHomeSelectList(fhqUscc:string, type:number) {
    let enterpriseList = await findEnterpriseList({fuHuaQiUscc:fhqUscc});
    const Now = new Date().valueOf();

    let dataMap = {};
    enterpriseList.forEach(info => {
        let {leaseInfo} = info;
        switch (type) {
            case 1: 
                if (!dataMap["到期未签"]) dataMap["到期未签"] = 0;
                if (!dataMap["签约企业"]) dataMap["签约企业"] = 0;
                if (!leaseInfo || !leaseInfo.contractStartTime) {
                    dataMap["到期未签"] += 1;
                } else {
                    let keyStr = "";
                    if ((leaseInfo.contractEndTime - Now) < 0) {
                        keyStr = "到期未签";
                    }  else {
                        keyStr = "签约企业";
                    }

                    if (!dataMap[keyStr]) dataMap[keyStr] = 0;
                    dataMap[keyStr] += 1;
                }
            break;
            case 2:
                if (!dataMap["到期未缴"]) dataMap["到期未缴"] = 0;
                if (!dataMap["暂未到期"]) dataMap["暂未到期"] = 0;
                if (!dataMap["即将到期"]) dataMap["即将到期"] = 0;
                if (!leaseInfo || !leaseInfo.rentStartTime) {
                    dataMap["到期未缴"] += 1;
                } else {
                    let zjStr = "";
                    if (leaseInfo.rentEndTime < Now) {
                        zjStr = "到期未缴";
                    } else if ( leaseInfo.rentStartTime < Now && (leaseInfo.rentEndTime - Now) < (3600 * 24 * 1000 * 30))  {
                        zjStr = "即将到期";
                    }  else  {
                        zjStr = "暂未到期";
                    }
                    if (!dataMap[zjStr]) dataMap[zjStr] = 0;
                    dataMap[zjStr] += 1;
                }
            break;
            case 3:
                let fhStr = "";
                if (info.state == FUHUASTATE.迁出) {
                    fhStr = "迁出";
                } else {
                    fhStr = "在孵企业";
                }
                if (!dataMap[fhStr]) dataMap[fhStr] = 0;
                dataMap[fhStr] += 1;
            break;

        }
      
    });


    let dataList = [];
    for (let key in dataMap) {
        let value = 0;
        let count = dataMap[key];
        if (type == ZLSTATISTYPE.合同) {
            value = CONTRACTTYPE[key];
        } else if(type == ZLSTATISTYPE.租金) {
            value = RENTTYPE[key];
        } else if (type == ZLSTATISTYPE.企业状态) {
            value = ZLSTATETYPE[key];
        }
        dataList.push({
            key,
            value,
            count
        });
    }

    return {dataList};
}


export async function zlInfo(uscc:string) {
    let enterpriseInfo = await findEnterpriseByUscc(uscc);
    let leaseInfo = await leaseData.findOnceData({uscc});

    let dataInfo:any = {uscc, enterpriseName:enterpriseInfo.enterpriseName};
    if (!leaseInfo || !leaseInfo.uscc) {
        dataInfo.contractStartTime = 0;
        dataInfo.contractEndTime = 0;
        dataInfo.contractLong = "";
        dataInfo.contractState = "签约企业";
        dataInfo.price = 0;
        dataInfo.area = 0;
        dataInfo.rentPayment = [];
        dataInfo.address = "";
        dataInfo.areaUnit = AREAUNIT.面积;
    } else {
        dataInfo.contractStartTime = leaseInfo.contractStartTime;
        dataInfo.contractEndTime = leaseInfo.contractEndTime;
        dataInfo.contractLong = leaseInfo.contractLong;
        dataInfo.contractState = "签约企业";
        dataInfo.price = leaseInfo.price;
        dataInfo.area = leaseInfo.area;
        dataInfo.rentPayment = leaseInfo.rentPayment;
        dataInfo.address = leaseInfo.address;
        dataInfo.areaUnit = leaseInfo.areaUnit || AREAUNIT.面积;
    }

    return {dataInfo};
}

export async function zlUpdate(uscc:string, param) {
    eccFormParam("更新租赁信息", eccFormParamConfig.ZlUpdateConfig, param);
    if (param.rentPayment) {
        param.rentPayment.forEach((info, index) => {
            eccFormParam("更新租赁信息 租金缴纳情况"+index, eccFormParamConfig.ZlRentPaymentUpdateConfig, info);
        })
    }

    let leaseInfo = await leaseData.findOnceData({uscc});
    let enterpriseInfo = await findEnterpriseByUscc(uscc);
    if (!leaseInfo || !leaseInfo.uscc) {//添加
        param.uscc = uscc;
        param.enterpriseName = enterpriseInfo.enterpriseName;
        await leaseData.createData(param);        
    } else {
        for (let key in param) {
            leaseInfo[key] = param[key];
        }
        await leaseInfo.save();
    }

    let rentStartTime = new Date( param.rentPayment[0].payStartTime );
    let rentEndTime = moment( param.rentPayment[param.rentPayment.length -1].payStartTime).add( param.rentPayment[param.rentPayment.length -1].payLong, 'M');

    enterpriseInfo.leaseInfo = {
        contractStartTime:param.contractStartTime,//合同开始时间
        contractEndTime:param.contractEndTime,//合同结束时间
        rentStartTime,//租金开始时间
        rentEndTime,//租金结束时间
    };

    await enterpriseInfo.save();

    return {isSuccess:true};
}

