/**
 * 小程序端 企业用户的 企业基础信息
 * 作者：lxm
 */

import { EnterpriseQualificationUpdateConfig, EnterpriseUpdateBaseDataConfig, InitialTeamUpdateConfig } from "../../config/eccFormParamConfig";
import { ENTERPRISETEAM, INDUSTRY, LISTINGSITUATION, STATEENUM } from "../../config/enum";
import { ERRORENUM } from "../../config/errorEnum";
import { EnterpriseBaseConfig, EnterpriseInitialTeamConfig } from "../../config/splitResultConfig";
import * as enterpriseData from "../../data/enterprise/enterprise";
import { addMoneyEnterpriseInitialTeam, deleteMoneyEnterpriseInitialTeam, findEnterpriseInitialTeam, updateMoneyEnterpriseInitialTeam } from "../../data/enterprise/initialTeam";
import { findEnterpriseNewTeamData } from "../../data/enterprise/team";
import { getInitialTeamMemberId } from "../../tools/system";
import { BizError } from "../../util/bizError";
import { checkChange, checkDataHaveNull, extractData } from "../../util/piecemeal";
import { eccEnumValue } from "../../util/verificationEnum";
import { eccFormParam } from "../../util/verificationParam";

/**
 * 校验参数是否为空
 * @param param 参数 
 * @returns true就是空 
 */
function paramIsNull(param) {
    if (!param) return true;
    let isNull = false;
    if (typeof param == "object") {
        if (Array.isArray(param) ) isNull = param.length == 0;
        else isNull = Object.keys(param).length == 0;
    }
    else isNull = !param;

    return isNull;
}


/**
 * 获取首页基础信（首页顶端数据）
 * 知识产权，融资情况，企业资质 第一次进来会红，点开之后红点提示 会永久消失  2023-05-08
 * @param uscc 企业统一信用代码
 * @returns 
 */
export async function getHomePageHeaderData(uscc:string) {
    let enterpriseInfo = await enterpriseData.selectOneEnterpriseByParam({uscc});

    //企业名称
    let name = enterpriseInfo.name;

    let newTeamInfo = await findEnterpriseNewTeamData(uscc);
    let teamInfo = Object.keys(newTeamInfo).length > 0 ?  newTeamInfo : {doctor:0, master:0, undergraduate:0, juniorCollege:0, other:0 };

    //团队总数
    let memberCount = teamInfo.doctor + teamInfo.master+ teamInfo.undergraduate+ teamInfo.juniorCollege+ teamInfo.other;

    let initialTeam = enterpriseInfo.haveFirstClassTalent == STATEENUM.未选 ||  !enterpriseInfo.haveFirstClassTalent;//创始团队缺失 true=缺失 

    
    let qualification = !enterpriseInfo.tipsQualification; //企业资质缺失 true=缺失 需要标红
    let intellectualProperty = !enterpriseInfo.tipsIntellectualProperty;//知识产权缺失 true=缺失 需要标红
    let financing = !enterpriseInfo.tipsFinancingInfo; //融资情况缺失 true=缺失 需要标红

    let checkEnterpriseInfo = extractData(EnterpriseBaseConfig, enterpriseInfo, false);
    let baseInfo = checkDataHaveNull(checkEnterpriseInfo, true)

    return {
        name,
        memberCount,
        hiatus:{
            initialTeam,
            qualification,
            financing,
            intellectualProperty,
            baseInfo
        }
    }
}


/**
 * 修改创始团队信息
 * 修改 删除 添加  为一个接口 根据数据情况与老数据情况做匹配
 * @param uscc 企业统一信用代码
 * @param firstClassTalent 是否拥有国际一流人才
 * @param teams 创始团队信息
 * @returns isSuccess
 */
export async function updateInitialTeamInfo(uscc:string, firstClassTalent:number, teams) {
    eccEnumValue("修改创始团队信息", "firstClassTalent", STATEENUM, firstClassTalent);
    if (firstClassTalent==STATEENUM.未选) throw new BizError(ERRORENUM.请先选择是否拥有, '修改创始团队信息 没有选是和否');
    /**校验参数 */
    if ( (firstClassTalent==STATEENUM.是 && !Array.isArray(teams)) || (firstClassTalent==STATEENUM.是 && !teams.length) ) {
        throw new BizError(ERRORENUM.参数错误, "修改创始团队信息", "缺少参数 teams");
    }
    if (!firstClassTalent) teams = [];

    teams.forEach((info, index) => {
        eccFormParam(`修改创始团队信息 下标:${index}`, InitialTeamUpdateConfig, info);
        eccEnumValue('修改创始团队信息', 'type', ENTERPRISETEAM, info.type);
        if (info.des.length > 200) throw new BizError(ERRORENUM.字数超过200限制, `修改创始团队信息 下标:${index}`);
    });

    //是否拥有国际人才这个字段在 企业表中 需要单独做更改
    let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(uscc);
    enterpriseInfo.haveFirstClassTalent = firstClassTalent;
    await enterpriseInfo.save();

    let enterpriseInitialTeamList = await findEnterpriseInitialTeam(uscc);
    
    /**匹配数据操作逻辑 */
    let newTeamIdList = [];//用于匹配新数据，老数据不在新数据中 判定为被删除
    teams.forEach(info => {
        if (info.id && info.id != "newdata") newTeamIdList.push(info.id);//todo
    });
    let deleteList = [];
    //老数据将出现在这个map里 用于与新数据id匹配，匹配id不在老数据中判定为添加操作
    let dataBaseTeamMap = {}; 
    enterpriseInitialTeamList.forEach(info => {
        dataBaseTeamMap[info.id] = info;
        if (newTeamIdList.indexOf(info.id) == -1 ) {
            deleteList.push(info);
        } 
    });

    let addList = [];
    let updateList = [];

    teams.forEach(info => {
        let {id} = info;
        let dataBaseInfo = dataBaseTeamMap[id]; 
        if (!dataBaseInfo) {//不存在老的id 判定为添加操作
            info.id = getInitialTeamMemberId(uscc, info.name);
            info.uscc = uscc;
            info.name = enterpriseInfo.name;
            addList.push(info);
        } else {
            //比对新老数据判断数据需不需要修改
            let changeList = checkChange(info, Object.assign({name:enterpriseInfo.name, uscc}, dataBaseInfo));
            if (changeList.length) updateList.push(info);
        }
    });

    /**修改数据 */
    if (addList.length) await addMoneyEnterpriseInitialTeam(addList);
    if (updateList.length) await updateMoneyEnterpriseInitialTeam(updateList);
    if (deleteList.length) await deleteMoneyEnterpriseInitialTeam(deleteList);

    return {isSuccess:true};
}


/**
 * 获取创始团队信息
 * 回显
 * @param uscc 企业统一信用代码
 * @returns initialTeam 团队列表  firstClassTalent 是否拥有国际一流人才
 */
export async function selectInitialTeamInfo(uscc:string) {
    let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(uscc);
    let firstClassTalent = enterpriseInfo.haveFirstClassTalent || STATEENUM.未选;

    let initialTeamList = await findEnterpriseInitialTeam(uscc);

    let initialTeam = [];

    initialTeamList.forEach(info => {
        let changeData = extractData(EnterpriseInitialTeamConfig, info, false);
        initialTeam.push(changeData);
    });
    
    return { initialTeam, firstClassTalent }; 
}


/**
 * 修改企业知识产权信息
 * @param uscc 企业统一信用代码
 * @param alienPatent 海外专利个数
 * @param classIPatent 一类专利个数
 * @param secondClassPatent 二类专利个数
 * @returns isSuccess
 */
export async function updateIntellectualProperty(uscc:string, alienPatent:number, classIPatent:number, secondClassPatent:number) {
    let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(uscc);

    enterpriseInfo.intellectualProperty = {alienPatent, classIPatent, secondClassPatent};

    if (!enterpriseInfo.tipsIntellectualProperty ) {
        enterpriseInfo.tipsIntellectualProperty = true;
    }

    await enterpriseInfo.save();

    return {isSuccess:true}
}


/**
 * 查询企业专利信息 
 * 回显
 * @param uscc 企业统一信用代码
 * @returns 
 */
export async function selectIntellectualProperty(uscc:string) {
    let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(uscc);

    let intellectualProperty = {alienPatent:0, classIPatent:0, secondClassPatent:0};

    if (!paramIsNull(enterpriseInfo.intellectualProperty)) {
        intellectualProperty = enterpriseInfo.intellectualProperty;
    }

    return intellectualProperty;
}


/**
 * 获取企业资质信息
 * @param uscc 企业统一信用代码
 * @returns 
 */
export async function selectQualification(uscc:string) {
    let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(uscc);

    let defaultQualification = {
        isHighTech:false,//是否是高新技术企业
        highTechMs:0,//高新技术认证时间戳
        isZjtx:false,//是否专精特新企业
        zjtxMs:0,//专精特新认证时间戳
        isXjrpy:false,//是否小巨人培育企业
        xjrpyMs:0,//小巨人培育企业时间戳
        isXjr:false,//是否是小巨人企业
        xjrMs:0,//小巨人企业认证时间
        beOnTheMarket:[],//上市情况
        isBeOnTheMarket:false
    };
    
    return enterpriseInfo.qualification || defaultQualification;
}


/**
 * 修改企业资质
 * @param uscc 企业统一信用代码
 * @returns 
 */
export async function updateQualification(uscc:string, param) {
    eccFormParam("修改企业资质", EnterpriseQualificationUpdateConfig, param);

    if (param.isBeOnTheMarket) {
        if (!param.beOnTheMarket.length) throw new BizError(ERRORENUM.参数错误, '修改企业资质', '缺失 beOnTheMarket  ')
        eccEnumValue("修改企业资质", "beOnTheMarket", LISTINGSITUATION, param.beOnTheMarket );
    } else param.beOnTheMarket = [];

    let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(uscc);

    enterpriseInfo.qualification = JSON.parse(JSON.stringify(param) );

    if (!enterpriseInfo.tipsQualification ) {
        enterpriseInfo.tipsQualification = true;
    }

    await enterpriseInfo.save();
    
    return {isSuccess:true};
}


/**
 * 获取企业基本信息
 * 回显
 * @param uscc 
 */
export async function enterpriseBaseInfo(uscc:string) {
    let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(uscc);

    let updateInfo = extractData(EnterpriseBaseConfig, enterpriseInfo, false);

    return updateInfo;
}


/**
 * 修改我的企业信息
 * @param uscc 企业统一信用代码
 * @param param 表单
 * @returns 
 */
export async function updateEnterpriseBaseInfo(uscc:string, param) { 
    eccFormParam("企业修改我的信息", EnterpriseUpdateBaseDataConfig, param );
    eccEnumValue('企业修改我的信息', 'industry', INDUSTRY, param.industry);

    let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(uscc);

    /**修改字段 */
    let changeList = checkChange(param, enterpriseInfo);
    if ( !changeList.length ) throw new BizError(ERRORENUM.数据无更新, `${param.uscc}数据无更新`);
    changeList.forEach(key => {
        if (key != "uscc" && key != "name") {
            enterpriseInfo[key] = param[key];
        }
    });

    await enterpriseInfo.save();
    
    return {isSuccess:true};
}


/**
 * 获取资讯列表
 * @param uscc 预留好 后期做推荐的参数
 * 
 */
async function getInformationList(uscc:string) {

    let list = [];

    
}