import moment = require("moment");
import { FINANCINGROUNDS, RAS, RESEARCHTYPE, VISITDEMAND, VISITSTATE } from "../../../config/enum";
import * as enterpriseData from "../../../data/enterprise/enterprise";
import { changeEnumValue } from "../../../util/verificationEnum";
import * as labelData from "../../../data/label";
import * as financingData from "../../../data/fuHuaQi/monthTask/financing";
import * as dishonestPersonData from "../../../data/enterprise/dishonestPerson";
import * as illegalityData from "../../../data/enterprise/illegality";
import * as enterpriseRiskData from "../../../data/enterprise/enterpriseRisk";
import * as visitData from "../../../data/fuHuaQi/visit";
import * as demandData from "../../../data/fuHuaQi/demand";
import * as leaseData from "../../../data/lease";
import * as qualificationsData from "../../../data/enterprise/qualifications";

export async function portrait(uscc) {
    let eInfo = await enterpriseData.findEnterpriseByUscc(uscc);

    let labelList = await labelData.selectLabelList({});
    let labelMap = {};
    labelList.forEach(info => {
        labelMap[info.id] = info.labelName;
    })

    let label = [];
    eInfo.labels.forEach(info => {
        label.push({
            key:labelMap[info.labelId],
            color:"#b4d2ff",
            frameColor:"#1677FF",
            
        });
    });

    let zscqList = [];
    let zscqCount = 0;
    if (eInfo.intellectualProperty) {
        if (eInfo.intellectualProperty.alienPatent) {
            zscqList.push({key:"海外专利", value:eInfo.intellectualProperty.alienPatent});
            zscqCount += eInfo.intellectualProperty.alienPatent;
        }
        if (eInfo.intellectualProperty.classIPatent) {
            zscqList.push({key:"一类专利", value:eInfo.intellectualProperty.classIPatent});
            zscqCount += eInfo.intellectualProperty.classIPatent;
        }
        if (eInfo.intellectualProperty.secondClassPatent) {
            zscqList.push({key:"二类专利", value:eInfo.intellectualProperty.secondClassPatent});
            zscqCount += eInfo.intellectualProperty.secondClassPatent;
        }
    }

    let financingList = await financingData.findFinancingList({uscc});

    let rzqkCount = "-";
    let rzqkLunci = "-";
    let rzqkMap = {};
    let thisYear = new Date().getFullYear();
    for (let i = 4; i >= 0; i-- ) {
        let year = thisYear - i;
        rzqkMap[year] = 0;
    }
    if (financingList.length) {
        financingList.forEach(info => {
            let yearKey = new Date(info.timeToObtainInvestment).getFullYear();
            if (rzqkMap[yearKey] != undefined) {
                rzqkMap[yearKey] += info.financingAmount;
            }
        });
        rzqkLunci = changeEnumValue(FINANCINGROUNDS, financingList[financingList.length - 1].financingRounds)
        rzqkCount = `${financingList[financingList.length - 1].financingAmount}万`;
    }
    let rzqkList = [];
    for (let key in rzqkMap) {
        rzqkList.push({
            key, value:rzqkMap[key]
        });
    }


    let star = 0;
    let starStr = "-";
    let kcf = 0;
    let kcfpm = 0;
    let ejhy = eInfo.gbej || '-';

    if (eInfo.kcf) {
        ejhy = eInfo.kcf.subIndustry;
        kcf = eInfo.kcf.score;
        kcfpm = eInfo.kcf.industryRanking;

        if (eInfo.kcf.score && !isNaN(eInfo.kcf.score)) {
            star = Math.floor(parseInt(eInfo.kcf.score)/20);
            if (star < 3) {
                starStr = "优秀";
            } else starStr = "良好";
        }
    }

    let gqjgList = [];
    if (eInfo.guQuanJieGou) {
        eInfo.guQuanJieGou.forEach(info => {
            gqjgList.push({
                key:info.name,
                value:parseFloat(info.stockPercent)
            })
        })
    }

    let sxList = await dishonestPersonData.findList({uscc});
    let flfx = [];
    sxList.forEach(info => {
        flfx.push(`${info.actionRemark || ""} ${info.amount || ""} `);
    });

    let illegalityList = await illegalityData.findList({uscc});
    let jyqdxfx = [];
    illegalityList.forEach(info => {
        jyqdxfx.push(`${info.AddReason || ""}`);
    });

    let riskList = await enterpriseRiskData.findList({uscc});
    let glqyfx = [];
    riskList.forEach(info => {
        glqyfx.push(`${info.title || ""}`);
    });

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

    let qyxqList = [];
    demandList.forEach(info => {
        let label = [];
        info.demand.forEach(item => {
            label.push(changeEnumValue(VISITDEMAND, item))
        })

        qyxqList.push({
            time:moment(info.createTime).format("YYYY-MM-DD"),
            labelStr:changeEnumValue(VISITDEMAND, info.demand),
            label,
            desc:info.demandDesc
        })
    });

    let sysc = 0;
    let htzt = "-";
    let zjjn = "-";
    if (eInfo.leaseInfo) {
        if (eInfo.leaseInfo.rentEndTime) {
            sysc = moment(eInfo.leaseInfo.rentEndTime).diff(new Date().valueOf(), 'months');
            if (eInfo.leaseInfo.contractEndTime > new Date().valueOf()) {
                htzt = "签约企业";
            }else {
                htzt = "到期企业"
            }
            if (eInfo.leaseInfo.rentEndTime > new Date().valueOf()) {
                htzt = "正常缴纳";
            }else {
                htzt = "到期未缴"
            }
        }
    }
    let zlqkDataInfo = await leaseData.findOnceData({uscc});

    let zlqkList = [];
    if (zlqkDataInfo && zlqkDataInfo.rentPayment && Array.isArray(zlqkDataInfo.rentPayment)) {
        zlqkDataInfo.rentPayment.forEach(info => {
            zlqkList.push({
                time:moment(info.payStartTime).format("YYYY.MM.DD"),
                jnqx:`已缴纳${info.payLong}个月`,
                state:"已缴"
            });
        })
    };

    let qualificationsList = await qualificationsData.findList({uscc});

    let zzzcList = [];
    qualificationsList.forEach(info => {
        let itemTime = "-";
        if (info.startDate) itemTime = moment(info.startDate).format("YYYY.MM.DD")
        zzzcList.push({
            time:itemTime,
            name:info.name || "-",
            state:info.status || "-"
        })
    })


    let visitList = await visitData.findByParam({uscc});
    
    let qyzfList = [];
    visitList.forEach(info => {
        qyzfList.push({
            time:moment(info.visitTime).format("YYYY.MM.DD"),
            leaderName:info.leaderName,
            type:changeEnumValue(RESEARCHTYPE, info.researchType),
            desc:info.desc,
            state:changeEnumValue(VISITSTATE, info.state)
        });
    })

    let result = {
        enterpriseInfo:{
            name:eInfo.name,
            uscc:uscc,
            legalPerson:eInfo.legalPerson || "-",
            RAS:eInfo.RAS ? changeEnumValue(RAS, eInfo.RAS) : "-",
            logonTime:eInfo.logonTime ? moment(eInfo.logonTime).format("YYYY-MM-DD") : "-",
            firstIncubationTime:eInfo.firstIncubationTime ? moment(eInfo.firstIncubationTime).format("YYYY-MM-DD") : "-",
            zuZhiJiGouDaiMa:eInfo.zuZhiJiGouDaiMa,
            label
        },
        zscq:{
            count:zscqCount,
            dataList:zscqList,
        },
        rzqk:{
            befor:{
                count:rzqkCount,
                lunci:rzqkLunci
            },
            dataList:rzqkList,
        },
        qykcf:{
            ejhy,
            star,
            starStr,
            kcf,
            kcfpm
        },
        gqjg:gqjgList,
        qyfx:{
            flfx,
            jyqdxfx,
            glqyfx,
        },
        qyxq:{
            count:qyxqList.length,
            dataList:qyxqList,
        },
        zlqk:{
            sysc,
            htzt,
            zjjn,
            dataList:zlqkList
        },
        zzzc:{
            count:zzzcList.length,
            dataList:zzzcList
        },
        qyzf:{
            count:qyzfList.length,
            dataList:qyzfList
        },

    };

    return result
}


export async function enterprisPortrait(uscc) {
    let eInfo = await enterpriseData.findEnterpriseByUscc(uscc);

    let labelList = await labelData.selectLabelList({});
    let labelMap = {};
    labelList.forEach(info => {
        labelMap[info.id] = info.labelName;
    })

    let label = [];
    eInfo.labels.forEach(info => {
        label.push({
            key:labelMap[info.labelId],
            color:"#b4d2ff",
            frameColor:"#1677FF",
            
        });
    });

    let zscqList = [];
    let zscqCount = 0;
    if (eInfo.intellectualProperty) {
        if (eInfo.intellectualProperty.alienPatent) {
            zscqList.push({key:"海外专利", value:eInfo.intellectualProperty.alienPatent});
            zscqCount += eInfo.intellectualProperty.alienPatent;
        }
        if (eInfo.intellectualProperty.classIPatent) {
            zscqList.push({key:"一类专利", value:eInfo.intellectualProperty.classIPatent});
            zscqCount += eInfo.intellectualProperty.classIPatent;
        }
        if (eInfo.intellectualProperty.secondClassPatent) {
            zscqList.push({key:"二类专利", value:eInfo.intellectualProperty.secondClassPatent});
            zscqCount += eInfo.intellectualProperty.secondClassPatent;
        }
    }

    let financingList = await financingData.findFinancingList({uscc});

    let rzqkCount = "-";
    let rzqkLunci = "-";
    let rzqkMap = {};
    let thisYear = new Date().getFullYear();
    for (let i = 4; i >= 0; i-- ) {
        let year = thisYear - i;
        rzqkMap[year] = 0;
    }
    if (financingList.length) {
        financingList.forEach(info => {
            let yearKey = new Date(info.timeToObtainInvestment).getFullYear();
            if (rzqkMap[yearKey] != undefined) {
                rzqkMap[yearKey] += info.financingAmount;
            }
        });
        rzqkLunci = changeEnumValue(FINANCINGROUNDS, financingList[financingList.length - 1].financingRounds)
        rzqkCount = `${financingList[financingList.length - 1].financingAmount}万`;
    }
    let rzqkList = [];
    for (let key in rzqkMap) {
        rzqkList.push({
            key, value:rzqkMap[key]
        });
    }

    let star = 0;
    let starStr = "-";
    let kcf = 0;
    let kcfpm = 0;
    let ejhy = eInfo.gbej || '-';

    if (eInfo.kcf) {
        ejhy = eInfo.kcf.subIndustry;
        kcf = eInfo.kcf.score;
        kcfpm = eInfo.kcf.industryRanking;

        if (eInfo.kcf.score && !isNaN(eInfo.kcf.score)) {
            star = Math.floor(parseInt(eInfo.kcf.score)/20);
            if (star < 3) {
                starStr = "优秀";
            } else starStr = "良好";
        }
    }

    let gqjgList = [];
    if (eInfo.guQuanJieGou) {
        eInfo.guQuanJieGou.forEach(info => {
            gqjgList.push({
                key:info.name,
                value:parseFloat(info.stockPercent)
            })
        })
    }

    let sxList = await dishonestPersonData.findList({uscc});
    let flfx = [];
    sxList.forEach(info => {
        flfx.push(`${info.actionRemark || ""} ${info.amount || ""} `);
    });

    let illegalityList = await illegalityData.findList({uscc});
    let jyqdxfx = [];
    illegalityList.forEach(info => {
        jyqdxfx.push(`${info.AddReason || ""}`);
    });

    let riskList = await enterpriseRiskData.findList({uscc});
    let glqyfx = [];
    riskList.forEach(info => {
        glqyfx.push(`${info.title || ""}`);
    });

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

    let qyxqList = [];
    demandList.forEach(info => {
        let label = [];
        info.demand.forEach(item => {
            label.push(changeEnumValue(VISITDEMAND, item))
        })

        qyxqList.push({
            time:moment(info.createTime).format("YYYY-MM-DD"),
            labelStr:changeEnumValue(VISITDEMAND, info.demand),
            label,
            desc:info.demandDesc
        })
    });

    let sysc = 0;
    let htzt = "-";
    let zjjn = "-";
    if (eInfo.leaseInfo) {
        if (eInfo.leaseInfo.rentEndTime) {
            sysc = moment(eInfo.leaseInfo.rentEndTime).diff(new Date().valueOf(), 'months');
            if (eInfo.leaseInfo.contractEndTime > new Date().valueOf()) {
                htzt = "签约企业";
            }else {
                htzt = "到期企业"
            }
            if (eInfo.leaseInfo.rentEndTime > new Date().valueOf()) {
                htzt = "正常缴纳";
            }else {
                htzt = "到期未缴"
            }
        }
    }
    let zlqkDataInfo = await leaseData.findOnceData({uscc});

    let zlqkList = [];
    if (zlqkDataInfo && zlqkDataInfo.rentPayment && Array.isArray(zlqkDataInfo.rentPayment)) {
        zlqkDataInfo.rentPayment.forEach(info => {
            zlqkList.push({
                time:moment(info.payStartTime).format("YYYY.MM.DD"),
                jnqx:`已缴纳${info.payLong}个月`,
                state:"已缴"
            });
        })
    };

    let qualificationsList = await qualificationsData.findList({uscc});

    let zzzcList = [];
    qualificationsList.forEach(info => {
        let itemTime = "-";
        if (info.startDate) itemTime = moment(info.startDate).format("YYYY.MM.DD")
        zzzcList.push({
            time:itemTime,
            name:info.name || "-",
            state:info.status || "-"
        })
    })


    let visitList = await visitData.findByParam({uscc});
    
    let qyzfList = [];
    visitList.forEach(info => {
        qyzfList.push({
            time:moment(info.visitTime).format("YYYY.MM.DD"),
            leaderName:info.leaderName,
            type:changeEnumValue(RESEARCHTYPE, info.researchType),
            desc:info.desc,
            state:changeEnumValue(VISITSTATE, info.state)
        });
    })

    let result = {
        enterpriseInfo:{
            name:eInfo.name,
            uscc:uscc,
            legalPerson:eInfo.legalPerson || "-",
            RAS:eInfo.RAS ? changeEnumValue(RAS, eInfo.RAS) : "-",
            logonTime:eInfo.logonTime ? moment(eInfo.logonTime).format("YYYY-MM-DD") : "-",
            firstIncubationTime:eInfo.firstIncubationTime ? moment(eInfo.firstIncubationTime).format("YYYY-MM-DD") : "-",
            zuZhiJiGouDaiMa:eInfo.zuZhiJiGouDaiMa,
            label
        },
        zscq:{
            count:zscqCount,
            dataList:zscqList,
        },
        rzqk:{
            befor:{
                count:rzqkCount,
                lunci:rzqkLunci
            },
            dataList:rzqkList,
        },
        qykcf:{
            ejhy,
            star,
            starStr,
            kcf,
            kcfpm
        },
        gqjg:gqjgList,
        qyfx:{
            flfx,
            jyqdxfx,
            glqyfx,
        },
        qyxq:{
            count:qyxqList.length,
            dataList:qyxqList,
        },
        zlqk:{
            sysc,
            htzt,
            zjjn,
            dataList:zlqkList
        },
        zzzc:{
            count:zzzcList.length,
            dataList:zzzcList
        },
        qyzf:{
            count:qyzfList.length,
            dataList:qyzfList
        },

    };

    return result;
}

