/**
 * 资质
 */

import moment = require("moment");
import { OPERATIONALDATATYPE, TABLEID, TABLENAME } from "../config/enum/dbEnum";
import { operationalData, selectData } from "../data/operationalData";
import { EnterpriseAwardUpdateConfig, EnterpriseIPRUpdateConfig, EnterprisePatentUpdateConfig, EnterpriseQualificationUpdateConfig } from "../config/eccParam/enterprise";
import { eccFormParam } from "../util/verificationParam";
import { getMySqlMs, randomId } from "../tools/system";
import { BizError } from "../util/bizError";
import { ERRORENUM } from "../config/enum/errorEnum";
import * as enumConfig from "../config/enum/enum";
import { checkChange, extractData } from "../util/piecemeal";
import { changeEnumValue, eccEnumValue } from "../util/verificationEnum";
import { EnterpriseQualificationInfoResConfig } from "../config/splitResult/enterprise";


//------------------------------------------------荣誉奖项

/**
 * 荣誉奖项-列表
 * 回显
 * @param uscc 
 */
export async function enterpriseHonorInfo(eId) {
    let filesList = ["hId", "awardName", "awardingUnit", "awardTime", "awardLevel", "awardImg"];
    let iprList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业荣誉, {eId}, filesList);
    
    let dataList:any[] = [];
    iprList.forEach(item => {
        let {hId, awardName, awardingUnit, awardTime, awardLevel, awardImg} = item;
        dataList.push({
            hId,
            awardName,
            awardingUnit,
            awardTime: moment(awardTime).format("YYYY"),
            awardLevel:awardLevel,
            awardImg:JSON.parse(awardImg),
        });
    });

    return {dataList};
}



/**
 * 荣誉奖项-修改
 * @param uscc 企业统一信用代码
 * @param param 表单
 * @returns 
 */
export async function updateEnterpriseHonorInfo(eId, hId, param) {
    const FuncName = "企业修改荣誉奖项"
    eccFormParam(FuncName, EnterpriseAwardUpdateConfig, param );
    param.awardTime = getMySqlMs(param.awardTime);
    param.awardImg = JSON.stringify(param.awardImg);
    
    let filesList = [ "awardName", "awardingUnit", "awardTime", "awardLevel", "awardImg"];
    let iprInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业荣誉, {hId, eId}, filesList)
    if (!iprInfo || !iprInfo.awardName) throw new BizError(ERRORENUM.当前数据不存在); 
   
    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.企业荣誉, param, {hId, eId});
    
    return {isSuccess:true};
}


/**
 * 荣誉奖项-添加
 * @param uscc 企业统一信用代码
 * @param param 表单
 * @returns 
 */
export async function createEnterpriseHonorInfo(eId, param) {
    const FuncName = "企业创建荣誉奖项"
    eccFormParam(FuncName, EnterpriseAwardUpdateConfig, param );
   
    let addInfo = {
        eId,
        hId:randomId(TABLEID.企业荣誉),
        awardName:param.awardName,
        awardingUnit:param.awardingUnit,
        awardTime:getMySqlMs(param.awardTime),
        awardLevel:param.awardLevel,
        awardImg:JSON.stringify(param.awardImg),
    };

    await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.企业荣誉, addInfo, {});
    
    return {isSuccess:true};
}


/**
 * 荣誉奖项-删除
 * @param param0 
 * @returns 
 */
export async function deleteEnterpriseHonorInfo(eId, hId) {
    let filesList = [ "awardName", "awardingUnit", "awardTime", "awardLevel", "awardImg"];
    let iprInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业荣誉, {hId, eId}, filesList)
    if (!iprInfo || !iprInfo.awardName) throw new BizError(ERRORENUM.当前数据不存在);

    await operationalData(OPERATIONALDATATYPE.删除, TABLENAME.企业荣誉, {}, {hId, eId});
    
    return {isSuccess:true};
}


//=====================================================知识产权

/**
 * 知识产权信息-列表
 * 回显
 * @param uscc 
 */
export async function enterpriseIPRInfo(eId:string) {
    let filesList = ["iprId", "year", "number"];
    let iprList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.知识产权, {eId}, filesList);

    let iprInfo = {};
    if (iprList && iprList.length) {
        iprList.forEach(item => {
            let yearStr = moment(item.year).format("YYYY");
            let {iprId, year, number} = item;
            if (!iprInfo[yearStr]) iprInfo[yearStr] = {};
            else number = number + iprInfo[yearStr].number;
            iprInfo[yearStr] = {
                iprId,
                year,
                yearStr:`${yearStr}年`,
                number
            };
        });
    }

    let dataList:any = [];
    for (let key in iprInfo) {
        let {iprId, year, yearStr, number} = iprInfo[key];
        dataList.push({
            iprId,
            year,
            yearStr,
            number
        })
    }

    //倒序
    dataList.sort(function(a, b) {
        return parseInt(moment(b.year).format("YYYY")) - parseInt(moment(a.year).format("YYYY"));
    });

    return {dataList};
}


export async function enterpriseIPRByType(eId:string, iprType:number) {
    let filesList = ["iprId", "year","number", "iprType","selectedValue","iprName", "iprUrl"];
    let selecParam:any = {eId};
    if (iprType == enumConfig.IPRTYPECLIENT.其他) {
        selecParam.iprType = {"%notIn%":[enumConfig.IPRTYPECLIENT.软件著作, enumConfig.IPRTYPECLIENT.海外专利, enumConfig.IPRTYPECLIENT.发明专利]};
    } else {
        selecParam.iprType = iprType;
    }
    
    let iprList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.知识产权, selecParam, filesList);

    let dataList:any[] = [];
    iprList.forEach(item => {
        let {iprId, year, number, iprType, selectedValue,iprName, iprUrl} = item;
        let yearStr = moment(year).format("YYYY");

        dataList.push({
            iprId,
            year,
            yearStr:`${yearStr}年`, 
            number:1,
            iprType:changeEnumValue(enumConfig.INTELLECTUALPROPERTYRIGHT, iprType),//新增知识产权类型
            selectedValue:iprType,//新增选中value
            iprName,//新增名称
            // iprUrl:JSON.stringify(iprUrl),//新增证材料证明
            iprUrl: iprUrl ? JSON.parse(iprUrl) : []//新增证材料证明

        }); 
    });

    //倒序
    dataList.sort(function(a, b) {
        return parseInt(moment(b.year).format("YYYY")) - parseInt(moment(a.year).format("YYYY"));
    });

    return {dataList};
}


/**
 * 知识产权信息-修改
 * @param uscc 企业统一信用代码
 * @param param 表单
 * @returns 
 */
export async function updateEnterpriseIPRInfo(eId, iprId, param) {
    const FuncName = "企业修改知识产权"
    eccFormParam(FuncName, EnterpriseIPRUpdateConfig, param );

    let filesList = ["year", "iprType", "iprName", "iprUrl"];
    let iprInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.知识产权, {iprId, eId}, filesList)
    if (!iprInfo || !iprInfo.year) throw new BizError(ERRORENUM.当前数据不存在); 

    // let disIprInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.知识产权, {year:getMySqlMs(param.year), eId}, ["eId", "iprId"])
    // if (disIprInfo && disIprInfo.eId && disIprInfo.iprId != iprId) throw new BizError(ERRORENUM.存在重复的年份数据); 
    
    /**修改字段 */
    let changeList = checkChange(param, iprInfo);
    if ( !changeList.length ) return {isSuccess:true};
   
    let addInfo = {
        year:getMySqlMs(param.year),
        iprType:param.iprType,//新增知识产权类型
        iprName:param.iprName,//新增名称
        // iprUrl:param.iprUrl,//新增证明材料
        iprUrl:JSON.stringify(param.iprUrl)//新增证明材料
    };

    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.知识产权, addInfo, {iprId});
    
    return {isSuccess:true};
}


/**
 * 知识产权信息-添加
 * @param uscc 企业统一信用代码
 * @param param 表单
 * @param iprUrl:'["XXX.png", "XXX.png"]'
 * @returns 
 */
export async function createEnterpriseIPRInfo(eId, param) {
    const FuncName = "企业创建知识产权"
    eccFormParam(FuncName, EnterpriseIPRUpdateConfig, param );

    // let iprInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.知识产权, {year:getMySqlMs(param.year), eId}, ["eId"])
    // if (iprInfo && iprInfo.eId) throw new BizError(ERRORENUM.存在重复的年份数据); 

    let addInfo = {
        eId,
        year:getMySqlMs(param.year),
        iprId:randomId(TABLEID.知识产权),
        iprType:param.iprType,//新增知识产权类型
        iprName:param.iprName,//新增名称
        // iprUrl:param.iprUrl//新增证明材料
        iprUrl:JSON.stringify(param.iprUrl),//新增证明材料
        number:1
    };

    await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.知识产权, addInfo, {});
    
    return {isSuccess:true};
}


export async function deleteEnterpriseIPRInfo(eId, iprId) {
    let filesList = ["year", "iprType",  "iprName", "iprUrl"];
    let iprInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.知识产权, {iprId, eId}, filesList)
    if (!iprInfo || !iprInfo.year) throw new BizError(ERRORENUM.当前数据不存在); 

    await operationalData(OPERATIONALDATATYPE.删除, TABLENAME.知识产权, {}, {iprId, eId});
    
    return {isSuccess:true};
}




//====================================专利

/**
 * 专利信息-列表
 * 回显
 * @param uscc 
 */
export async function enterprisePatentInfo(eId:string) {
    let filesList = ["pId", "year", "alienPatent", "classIPatent", "secondClassPatent", "thirdPentent"];
    let iprList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业专利表, {eId}, filesList);

    let dataList:any[] = [];
    iprList.forEach(item => {
        let {pId, year, number, alienPatent, classIPatent, secondClassPatent, thirdPentent} = item;
        dataList.push({
            pId,
            year,
            yearStr:moment(year).format("YYYY"),
            number,
            alienPatent,
            classIPatent,
            secondClassPatent,
            thirdPentent
        });
    });

    return {dataList};
}



/**
 * 专利信息-修改
 * @param uscc 企业统一信用代码
 * @param param 表单
 * @returns 
 */
export async function updateEnterprisePatentInfo(eId, pId, param) {
    const FuncName = "企业修改知识产权"
    eccFormParam(FuncName, EnterprisePatentUpdateConfig, param );

    let filesList = ["pId", "year", "alienPatent", "classIPatent", "secondClassPatent", "thirdPentent"];
    let iprInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业专利表, {pId, eId}, filesList)
    if (!iprInfo || !iprInfo.year) throw new BizError(ERRORENUM.当前数据不存在); 
    let disInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业专利表, {year:getMySqlMs(param.year), eId}, ["eId", "pId"])
    if (disInfo && disInfo.eId && disInfo.pId != pId) throw new BizError(ERRORENUM.存在重复的年份数据); 
    /**修改字段 */
    let changeList = checkChange(param, iprInfo);
    if ( !changeList.length ) return {isSuccess:true};
   
    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.企业专利表, param, {pId, eId});
    
    return {isSuccess:true};
}


/**
 * 专利信息-添加
 * @param uscc 企业统一信用代码
 * @param param 表单
 * @returns 
 */
export async function createEnterprisePatentInfo(eId, param) {
    const FuncName = "企业创建知识产权"
    eccFormParam(FuncName, EnterprisePatentUpdateConfig, param );
   
    let disInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业专利表, {year:getMySqlMs(param.year), eId}, ["eId"])
    if (disInfo && disInfo.eId) throw new BizError(ERRORENUM.存在重复的年份数据); 

    let addInfo = {
        eId,
        year:getMySqlMs(param.year),
        alienPatent:param.alienPatent,
        classIPatent:param.classIPatent,
        secondClassPatent:param.secondClassPatent,
        thirdPentent:param.thirdPentent,
        pId:randomId(TABLEID.企业专利表)
    };

    await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.企业专利表, addInfo, {});
    
    return {isSuccess:true};
}


/**
 * 专利信息-删除
 * @param param0 
 * @returns 
 */
export async function deleteEnterprisePatentInfo(eId, pId) {
    let filesList = ["pId", "year", "alienPatent", "classIPatent", "secondClassPatent", "thirdPentent"];
    let iprInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业专利表, {pId, eId}, filesList)
    if (!iprInfo || !iprInfo.year) throw new BizError(ERRORENUM.当前数据不存在);

    await operationalData(OPERATIONALDATATYPE.删除, TABLENAME.企业专利表, {}, {pId, eId});
    
    return {isSuccess:true};
}


//====================================资质认证

/**
 * 资质信息-回显
 * 回显
 * @param uscc 
 */
export async function enterpriseQualificationInfo(eId) {
    let qualificationData = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业资质, {eId}, []);
    
    // let qualificationList = [];
    // if (qualificationData.goPublicSector) {
    //     let qualification = JSON.parse(qualificationData.goPublicSector);
    //     for(let i = 0; i < qualification.length; i++){
    //         let qualificationType = changeEnumValue(enumConfig.LISTINGSITUATION, qualification[i]);
    //         qualificationList.push(qualificationType);
    //     }
    // }

    let result = {
        kxState: 0,
        kxTime: "",
        kxNumber: "",
        kxImg: [],
        zjtxState: 0,
        zjtxTime: "",
        zjtxImg: [],
        xjrState: 0,
        xjrTime: "",
        xjrImg: [],
        xjrPyState: 0,
        xjrPyTime: "",
        xjrPyImg: [],
        gxjsState: 0,
        gaoXinJiShuTime: "",
        gaoXinJiShuImg: [],
        listedState: 0,
        goPublicSector: [],
        goPublicTime: "",
        other: "",
    };
    if (qualificationData.qId) {
        result = {
            kxState: qualificationData.kxState || 0,//新增科小状态
            kxTime: qualificationData.kxTime,
            kxNumber: qualificationData.kxNumber || '',//新增科小编号
            kxImg: qualificationData.kxImg ? JSON.parse(qualificationData.kxImg) :[],//新增科编图片
            zjtxState: qualificationData.zjtxState || 0,
            zjtxTime: qualificationData.zjtxTime,
            zjtxImg: qualificationData.zjtxImg ? JSON.parse(qualificationData.zjtxImg) : [],//新增专精特新证书
            xjrState: qualificationData.xjrState || 0,
            xjrTime: qualificationData.xjrTime,
            xjrImg: qualificationData.xjrImg ? JSON.parse(qualificationData.xjrImg) : [],//新增小巨人证书
            xjrPyState: qualificationData.xjrPyState || 0,
            xjrPyTime: qualificationData.xjrPyTime,
            xjrPyImg: qualificationData.zjtxImg ? JSON.parse(qualificationData.xjrPyImg) : [],//新增小巨人培育证书
            gxjsState: qualificationData.gxjsState || 0,
            gaoXinJiShuTime: qualificationData.gaoXinJiShuTime,
            gaoXinJiShuImg: qualificationData.gaoXinJiShuImg ? JSON.parse(qualificationData.gaoXinJiShuImg) : [],//新增高新技术证书
            listedState: qualificationData.listedState || 0,
            goPublicSector: JSON.parse(qualificationData.goPublicSector) || [],
            goPublicTime: qualificationData.goPublicTime,
            // goPublicTime: qualificationData.goPublicTime ? moment(qualificationData.goPublicTime).valueOf() :  "",
            other: qualificationData.other || '',//新增其他
        };
    }

    return result;
}


/**
 * 资质信息-修改
 * @param uscc 企业统一信用代码
 * @param param 表单
 * @returns 
 */
export async function updateEnterpriseQualificationInfo(eId, param) {
    const FuncName = "企业修改资质信息";
   
    eccFormParam(FuncName, EnterpriseQualificationUpdateConfig, param );

    if (param.goPublicSector) eccEnumValue(FuncName, 'goPublicSector', enumConfig.LISTINGSITUATION, param.goPublicSector);
        
    let filesList = ["eId", "kxState","kxTime","kxNumber","kxImg", "zjtxState","zjtxTime","zjtxImg",
        "xjrState", "xjrTime","xjrImg","xjrPyState", "xjrPyTime","xjrPyImg",
        "gxjsState","gaoXinJiShuTime","gaoXinJiShuImg","listedState", "goPublicTime", "goPublicSector","other"];

    let iprInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业资质, {eId}, filesList)

    /**修改字段 */
    // filesList.forEach(keyStr => {
    //     if (keyStr == "goPublicSector" || keyStr == "kxState" || keyStr == "zjtxState" 
    //         || keyStr == "xjrState" || keyStr == "xjrPyState" || keyStr == "gxjsState" || keyStr == "listedState" 
    //     ) return;
    //     if (!param[keyStr]) delete param[keyStr]
    // });

    param.kxNumber = param.kxNumber ? param.kxNumber : null;
    param.goPublicSector = param.goPublicSector ? JSON.stringify(param.goPublicSector) : "[]";
    param.kxImg = param.kxImg ? JSON.stringify(param.kxImg) : "[]";
    param.zjtxImg = param.zjtxImg ? JSON.stringify(param.zjtxImg) : "[]";
    param.xjrImg = param.xjrImg ? JSON.stringify(param.xjrImg) : "[]";
    param.xjrPyImg = param.xjrPyImg ? JSON.stringify(param.xjrPyImg) : "[]";
    param.gaoXinJiShuImg = param.gaoXinJiShuImg ? JSON.stringify(param.gaoXinJiShuImg) : "[]";
    param.kxTime = param.kxTime ? getMySqlMs(param.kxTime) : null;
    param.zjtxTime = param.zjtxTime ? getMySqlMs(param.zjtxTime) : null;
    param.xjrTime = param.xjrTime ? getMySqlMs(param.xjrTime) : null;
    param.xjrPyTime = param.xjrPyTime ? getMySqlMs(param.xjrPyTime) : null;
    param.gaoXinJiShuTime = param.gaoXinJiShuTime ? getMySqlMs(param.gaoXinJiShuTime) : null;
    param.goPublicTime = param.goPublicTime ? getMySqlMs(param.goPublicTime) : null;

    if (!iprInfo || !iprInfo.eId) {
        param.qId = randomId(TABLEID.企业资质);
        param.eId = eId;
        await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.企业资质, param, {});
    } else {
        if (param && Object.keys(param).length > 0) {
            await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.企业资质, param, {eId});
        }
    }
    
    return {isSuccess:true};
}


// export async function updateEnterpriseQualificationInfo(eId, param) {
//     const FuncName = "企业修改资质信息";
   
//     // 验证参数
//     eccFormParam(FuncName, EnterpriseQualificationUpdateConfig, param);
    
//     // 处理上市板块枚举值
//     if (param.goPublicSector) {
//         eccEnumValue(FuncName, 'goPublicSector', enumConfig.LISTINGSITUATION, param.goPublicSector);
//     }

//     // 查询现有数据
//     let filesList = [
//         "eId", "kxState", "kxTime", "kxNumber", "kxImg", 
//         "zjtxState", "zjtxTime", "zjtxImg",
//         "xjrState", "xjrTime", "xjrImg", "xjrPyState", "xjrPyTime", "xjrPyImg",
//         "gxjsState", "gaoXinJiShuTime", "gaoXinJiShuImg", "listedState", "goPublicTime", "goPublicSector", "other"
//     ];

//     let iprInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业资质, { eId }, filesList);
//     if (!iprInfo || !iprInfo.eId) throw new BizError(ERRORENUM.当前数据不存在);

//     // 构建需要更新的字段
//     let addInfo: any = {};

//     // 处理图片字段
//     const imageFields = ["kxImg", "zjtxImg", "xjrImg", "xjrPyImg", "gaoXinJiShuImg"];
//     imageFields.forEach(field => {
//         if (param[field] && param[field].length > 0) {
//             addInfo[field] = JSON.stringify(param[field]);
//         }
//     });

//     // 处理其他字段
//     const otherFields = [
//         "kxState", "kxTime", "kxNumber", 
//         "zjtxState", "zjtxTime", 
//         "xjrState", "xjrTime", "xjrPyTime", 
//         "gxjsState", "gaoXinJiShuTime", 
//         "listedState", "goPublicTime", "goPublicSector", "other"
//     ];
//     otherFields.forEach(field => {
//         if (param[field] !== undefined) {
//             addInfo[field] = param[field];
//         }
//     });

//     // 特殊处理 goPublicSector
//     if (param.goPublicSector && Array.isArray(param.goPublicSector)) {
//         addInfo.goPublicSector = JSON.stringify(param.goPublicSector);
//     }

//     // 更新数据库
//     if (Object.keys(addInfo).length > 0) {
//         await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.企业资质, addInfo, { eId });
//     }
    
//     return { isSuccess: true };
// }





