/**
 * 企业自评
 */

import { OPERATIONALDATATYPE, TABLENAME } from "../config/enum/dbEnum";
import { STATE } from "../config/enum/enum";
import { paginateArray, selectData, selectManyTableData } from "../data/operationalData";



/**
 * 企业自评结果
 */
export async function enterpriseResults(enterpriseName:string, page:number) {
    // 1. 查询企业基本信息
    let selectParam:any = {}
    if (enterpriseName) selectParam.enterpriseName = {"%like%":enterpriseName};

    let manyTableInfo:any = {};
    manyTableInfo[TABLENAME.企业基础信息表] = {column:["eId", "enterpriseName"], where:selectParam };
    let enterpriseInfo = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.答题记录, {answerStatus:STATE.是}, ["garId"], manyTableInfo);
    // 获取企业及其答题记录ID
    let answerIdList = enterpriseInfo.map(info => info.garId);
    // let answerIdList = [];
    // enterpriseInfo.forEach( info => {
    //     answerIdList.push(info.garId);
    // });

    // 2. 获取答题记录总得分
    let answerRecords = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.答题记录, { garId: { "%in%": answerIdList } }, ["garId", "totalScore"] );
    // 3. 获取各分类得分
    let manyAnswerTableInfo:any = {};
    manyAnswerTableInfo[TABLENAME.高新企业创新能力评价答题] = { column:["answerType"], where:{} };
    let answerDetails = await selectManyTableData(
        OPERATIONALDATATYPE.多表联查,
        TABLENAME.答题记录明细,
        { garId: { "%in%": answerIdList } },
        ["garId", "gaId", "questionScore"],
        manyAnswerTableInfo
    );

    // 4. 处理数据，按企业分组并计算各分类得分
    let result = [];

    // 使用forEach遍历企业信息
    enterpriseInfo.forEach(enterprise => {
        // 1. 找出当前企业的答题记录
        let currentRecords = [];
        answerRecords.forEach(record => {
            if (record.garId === enterprise.garId) {
                currentRecords.push(record);
            }
        });
        
        // 2. 找出当前企业的答题明细
        let currentDetails = [];
        answerDetails.forEach(detail => {
            if (detail.garId === enterprise.garId) {
                currentDetails.push(detail);
            }
        });
        
        // 3. 初始化分类得分对象
        let categoryScores = {
            知识产权: 0,
            科技成果: 0,
            研发管理: 0,
            企业成长: 0
        };

        // 4. 计算各分类得分
        currentDetails.forEach(detail => {
            let category = detail.gaoxin_answer.answerType;
            if (categoryScores.hasOwnProperty(category)) {
                categoryScores[category] += parseInt(detail.questionScore) || 0;
            }
        });

        // 5. 构建结果对象并添加到结果数组
        result.push({
            garId:enterprise.garId,
            企业名称: enterprise.enterprise.enterpriseName,
            总得分: currentRecords[0]?.totalScore || 0,
            ...categoryScores
        });
    });

    
    let paginatedData = await paginateArray(result, page);
    let dataList = paginatedData.data;
    let dataCount = paginatedData.meta.totalItems;

    // let result = enterpriseInfo.map(enterprise => {
    //     /** filter方法：从数组中筛选出符合条件(相同garId)的元素 */
    //     // 1. 筛选当前企业的答题记录
    //     let records = answerRecords.filter(r => r.garId === enterprise.garId);
    //     // 2. 筛选当前企业的答题明细
    //     let details = answerDetails.filter(d => d.garId === enterprise.garId);
        
    //     // 初始化分类得分
    //     let categoryScores = {
    //         知识产权: 0,
    //         科技成果: 0,
    //         研发管理: 0,
    //         企业成长: 0
    //     };

    //     // 计算各分类得分
    //     details.forEach(detail => {
    //         let category = detail.gaoxin_answer.answerType;
    //         if (categoryScores.hasOwnProperty(category)) {
    //             categoryScores[category] += parseInt(detail.questionScore) || 0;
    //         }
    //     });

    //     return {
    //         企业名称: enterprise.enterprise.enterpriseName,
    //         总得分: records[0]?.totalScore || 0,
    //         ...categoryScores
    //     };
    // });

    return {dataList, dataCount};
}



/**
 * 获取企业答题详情
 * @param garId 答题记录ID
 * @param answerType 题目类型(知识产权/科技成果/研发管理/企业成长)
 * @returns 返回指定类型的答题详情数组
 */
export async function getAnswerDetails(garId: string, answerType: string) {
    // 1. 查询答题记录明细
    let manyTableInfo: any = {};
    manyTableInfo[TABLENAME.高新企业创新能力评价答题] = {
        column: ["subject", "sort", "answerType"],
        where: { answerType }
    };
    
    let details = await selectManyTableData(
        OPERATIONALDATATYPE.多表联查,
        TABLENAME.答题记录明细,
        { garId },
        ["gadId", "gaId", "options", "questionScore"],
        manyTableInfo
    );
    
    // 2. 查询选项数据(用于获取选项文本)
    let optionPromises = details.map(detail => 
        selectData(
            OPERATIONALDATATYPE.查询多个,
            TABLENAME.高新企业创新能力评价选项,
            { gaId: detail.gaId },
            ["goId", "option", "answer"]
        )
    );
    let optionResults = await Promise.all(optionPromises);
    
    // 3. 处理数据，构建返回结果
    let result = [];
    if (answerType == "企业成长") {
        result = details.map((detail, index) => {
            // 获取当前题目的选项
            let options = optionResults[index] as Array<{ goId: number; answer: string }> | undefined;
            // let options = optionResults[index];
            // 解析用户选择的选项ID
            let selectedOptionIds = JSON.parse(detail.options || "[]");
            
            // 查找用户选择的选项文本
            let selectedOptions = (options as Array<{ goId: number; answer: string }>)
            .filter(opt => selectedOptionIds.includes(opt.goId))
            .map(opt => opt.answer)
            .join(", ");
            // let selectedOptions = options.filter(opt => 
            //     selectedOptionIds.includes(opt.goId)
            // ).map(opt => opt.answer).join(", ");
            
            return {
                版块: detail.gaoxin_answer.answerType,
                序号: detail.gaoxin_answer.sort,
                题目名称: detail.gaoxin_answer.subject,
                选项: selectedOptions || "-",  // 如果没有选择则显示"-"
                得分: detail.questionScore || 0
            };
        });
    } else {
        result = details.map((detail, index) => {
            // 获取当前题目的选项
            let options = optionResults[index] as Array<{ goId: number; answer: string }> | undefined;
            // let options = optionResults[index];
            // 解析用户选择的选项ID
            let selectedOptionIds = JSON.parse(detail.options || "[]");
            
            // 查找用户选择的选项文本
            let selectedOptions = (options as Array<{ goId: number; answer: string }>)
            .filter(opt => selectedOptionIds.includes(opt.goId))
            .map(opt => opt.answer)
            .join(", ");
            // let selectedOptions = options.filter(opt => 
            //     selectedOptionIds.includes(opt.goId)
            // ).map(opt => opt.answer).join(", ");
            
            return {
                版块: detail.gaoxin_answer.answerType,
                序号: detail.gaoxin_answer.sort,
                题目名称: detail.gaoxin_answer.subject,
                选项: selectedOptions || "-",  // 如果没有选择则显示"-"
                得分: detail.questionScore || 0
            };
        });
    }

    result.sort( (a, b) => {
        return a.序号 - b.序号;
    })
    
    return result;
}


/**
 * 查询所有企业的租房补贴资格评估列表
 * @param enterpriseName 企业名称筛选条件（可选）
 * @returns 企业评估结果列表
 */
 export async function getHousingSubsidyEligibilityList(enterpriseName:string, page:number) {
    // 1. 构建查询条件
    let selectParam:any = {}
    if (enterpriseName) selectParam.enterpriseName = {"%like%":enterpriseName};

    // 2. 多表联查：企业信息 + 最新答题记录
    let manyTableInfo: any = {};
    manyTableInfo[TABLENAME.企业基础信息表] = {
        column: ["eId", "enterpriseName"],
        where: selectParam
    };
    // 获取企业及其最新答题记录（按答题时间降序）
    let enterprises = await selectManyTableData(
        OPERATIONALDATATYPE.多表联查, TABLENAME.租房补贴答题记录, {answerStatus:STATE.是}, ["zarId", "eId", "totalScore"],
        manyTableInfo
    );

    // 3. 如果没有企业数据，直接返回空数组
    if (enterprises.length === 0) {
        return [];
    }

    // 4. 获取所有答题记录明细及相关题目信息
    let zarIds = enterprises.map(e => e.zarId);
    let detailTableInfo: any = {};
    detailTableInfo[TABLENAME.租房补贴企业自评] = {
        column: ["zaId", "answerType", "subject", "sort"],
        where: {},
        order: [["sort", "ASC"]]
    };
    let allDetails = await selectManyTableData(
        OPERATIONALDATATYPE.多表联查,
        TABLENAME.租房补贴答题记录明细,
        { zarId: {"%in%":zarIds} },
        ["zadId", "zarId", "zaId", "options"],
        detailTableInfo
    );

    let result = [];
    // 5. 按企业分组处理数据
    enterprises.forEach( enterprise => {
        // 筛选该企业的答题明细
        let details = allDetails.filter(d => d.zarId === enterprise.zarId);

        // 初始化结果对象
        let eligibility: any = {
            企业名称: enterprise.enterprise.enterpriseName,
            是否有研发费用: "",
            是否有缴纳社保: "",
            是否有软著等知识产权: "",
            是否认定科小或创新型中小企业: "",
            是否符合租房补贴申请: enterprise.totalScore === 1 ? "符合" : "不符合",
        };

        // 处理每个答题明细
        details.forEach( detail => {
            // 将answerType作为键，转换options为"是"/"否"
            eligibility[detail.zufang_answer.answerType] = detail.options === 1 ? "是" : "否";
        })
        
        if (details.length >= 4) {
            result.push(eligibility);
        }
    })

    let paginatedData = await paginateArray(result, page);
    let dataList = paginatedData.data;
    let dataCount = paginatedData.meta.totalItems;

    return {dataList, dataCount};
}








