/**
 * 在谈在跟
 */

import * as verificationEnumTools from "../util/verificationEnum";
import * as configEnum from "../config/enum";
import * as industryEnum from "../config/enum/industryEnum";
import * as negotiationData from "../data/negotiation";
import { checkChange, extractData } from "../util/piecemeal";
import * as splitResultConfig from '../config/splitResultConfig';
import { eccFormParam } from "../util/verificationParam";
import { NegotiationAddConfig, NegotiationUpdateConfig } from "../config/eccParam/admin";
import { randomId } from "../tools/system";
import { TABLEID } from "../config/enum/dbEnum";
import { BizError } from "../util/bizError";
import { ERRORENUM } from "../config/errorEnum";
import moment from "moment";


/**
 * 在谈在跟-列表
 * @param name 企业名称
 * @param industry 行业领域
 * @param progressStatus 进展情况
 * @param primaryContact 负责人、首谈人
 * @param contactDepartment 对接部门
 * @param page 页
 */
export async function negotiationList(name:string, industry, progressStatus:number, primaryContact:string, contactDepartment:string, page:number) {
    let selectParam:any = {};
    if (name) {
        selectParam.name = {"$regex":`${name}`};
    }
    if (industry && industry.length > 0) {
        verificationEnumTools.eccEnumValue('管理后台获取在谈在跟列表', 'industry', industryEnum.ALLINDUSTRY, industry);
        selectParam.industry = {"$in":industry};
    }
    if (progressStatus) {
        verificationEnumTools.eccEnumValue('管理后台获取在谈在跟列表', 'progressStatus', configEnum.PROGRESSSTATUS, progressStatus);
        selectParam.progressStatus = progressStatus;
    }
    if (primaryContact) {
        selectParam.primaryContact = {"$regex":`${primaryContact}`};
    }
    if (contactDepartment) {
        selectParam.contactDepartment = {"$regex":`${contactDepartment}`};
    }
    /**需要用到的查询数据 */
    let negotiationDbList = await negotiationData.findNegotiationListToPage(selectParam, (page - 1) * 10);
    let count = await negotiationData.findNegotiationCount(selectParam);//符合查询条件的数据总数

    /**组合返回结果 */
    let dataList = [];
    negotiationDbList.forEach( info => {
        /**截取返回数据 */
        let changeData:any = extractData(splitResultConfig.negotiationListConfig, info, true);

        /**将枚举值转为字符 */
        let industry = [];
        if (changeData.industry && changeData.industry.length > 0) {
            industry.push(verificationEnumTools.changeEnumValue(industryEnum.ALLINDUSTRY, changeData.industry))
        }
        changeData.industry = industry;

        //细分行业领域
        let subDivide = [];
        if (changeData.subDivide && changeData.subDivide.length > 0) {
            // 数组处理
            let subDivideValue = verificationEnumTools.changeEnumValue(industryEnum.SUBDIVIDE, changeData.subDivide);
            if (subDivideValue) {
                subDivide.push(subDivideValue);
            }
        }
        changeData.subDivide = subDivide;

        // changeData.registrationStatus = verificationEnumTools.changeEnumValue(configEnum.REGISTRATIONSTATUS, changeData.registrationStatus);
        changeData.progressStatus = verificationEnumTools.changeEnumValue(configEnum.PROGRESSSTATUS, changeData.progressStatus);

        dataList.push(changeData);
    })

    return {count, dataList};
}


/**
 * 在谈在跟-新增
 * @param uscc 
 * @param param 
 */
export async function negotiationCreate(param) {
    /**校验表单参数 */
    eccFormParam("管理后台新增在谈在跟企业", NegotiationAddConfig, param);
    /**校验枚举 */
    if (param.industry && param.industry.length > 0) {
        verificationEnumTools.eccEnumValue('管理后台新增在谈在跟', 'industry', industryEnum.ALLINDUSTRY, param.industry);
    }
    if (param.subDivide && param.subDivide.length > 0) {
        verificationEnumTools.eccEnumValue('管理后台新增在谈在跟', 'subDivide', industryEnum.SUBDIVIDE, param.subDivide);
    }
    // verificationEnumTools.eccEnumValue('管理后台新增在谈在跟', 'registrationStatus', configEnum.REGISTRATIONSTATUS, param.registrationStatus);

    let enterpriseInfo = await negotiationData.findNegotiationByParam({name:param.name});
    if (enterpriseInfo && enterpriseInfo.name)  throw new BizError(ERRORENUM.该企业已存在, `${param.name}已经在库中存在`);

    let negotiationInfo = {
        id: randomId(TABLEID.在跟在谈),
        name: param.name,
        industry: param.industry,
        subDivide: param.subDivide,
        // registrationStatus: param.registrationStatus,
        progressStatus: param.progressStatus,
        primaryContact: param.primaryContact,
        contactDepartment: param.contactDepartment,
        progressDetails: param.progressDetails,
        createTime:new Date().valueOf(),
    }

    await negotiationData.createDataByParam(negotiationInfo);

    return {isSuccess:true};
}


/**
 * 在谈在跟-回显
 * @param uscc 
 */
export async function negotiationInfo(id:string) {
    /**校验企业 */
    let negotiationDbInfo = await negotiationData.findNegotiationByParam({id});
    if (!negotiationDbInfo || !negotiationDbInfo.id) throw new BizError(ERRORENUM.未找到数据, `库中不存在id=${id}这个企业`);

    /**将枚举值转为字符 */
    // let industry = [];
    // if (negotiationDbInfo.industry && negotiationDbInfo.industry.length > 0) {
    //     industry.push(verificationEnumTools.changeEnumValue(industryEnum.ALLINDUSTRY, negotiationDbInfo.industry))
    // }

    let dataInfo = {
        name: negotiationDbInfo.name,
        industry: negotiationDbInfo.industry,
        subDivide: negotiationDbInfo.subDivide,
        // registrationStatus: negotiationDbInfo.registrationStatus,
        progressStatus: negotiationDbInfo.progressStatus,
        primaryContact: negotiationDbInfo.primaryContact,
        contactDepartment: negotiationDbInfo.contactDepartment,
        progressDetails: negotiationDbInfo.progressDetails,
    };

    return {dataInfo};
}


/**
 * 在谈在跟-修改
 * @param uscc 
 * @param param 
 */
export async function negotiationUpdate(id:string, param) {
    /**校验参数 */
    eccFormParam("管理后台修改在谈在跟企业", NegotiationUpdateConfig, param);

    /**校验枚举 */
    verificationEnumTools.eccEnumValue('管理后台修改在谈在跟企业', 'industry', industryEnum.ALLINDUSTRY, param.industry);
    verificationEnumTools.eccEnumValue('管理后台修改在谈在跟企业', 'subDivide', industryEnum.SUBDIVIDE, param.subDivide);
    // verificationEnumTools.eccEnumValue('管理后台修改在谈在跟企业', 'registrationStatus', configEnum.REGISTRATIONSTATUS, param.registrationStatus);
    verificationEnumTools.eccEnumValue('管理后台修改在谈在跟企业', 'progressStatus', configEnum.PROGRESSSTATUS, param.progressStatus);

    /**校验企业 */
    let negotiationDbInfo = await negotiationData.findNegotiationByParam({id});
    if (!negotiationDbInfo || !negotiationDbInfo.id) throw new BizError(ERRORENUM.未找到数据, `库中不存在id=${id}这个企业`);

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

    await negotiationDbInfo.save();

    return {isSuccess:true};
}


/**
 * 在谈在跟-删除
 * @param id 
 */
export async function negotiationDelete(id:string) {
    let negotiationDbInfo = await negotiationData.findNegotiationByParam({id});
    if (!negotiationDbInfo || !negotiationDbInfo.name) throw new BizError(ERRORENUM.未找到数据, `库中不存在id=${id}这个企业`);

    await negotiationData.removeOneData(id);

    return {isSuccess:true};
}


/**
 * 导出在谈在跟企业信息列表
 * @param name 企业名称
 * @param industry 行业领域
 * @param progressStatus 进展情况
 * @param primaryContact 负责人、首谈人
 * @param contactDepartment 对接部门
 * @returns 二维数组，第一行为表头，后续行为数据
 */
export async function outPutNegotiationData(name:string, industry:string[], progressStatus:number, primaryContact:string, contactDepartment:string, id:string[]) {
    /** 拼接查询条件 */
    let selectParam: any = {};
    if (name) {
        selectParam.name = {"$regex": `${name}`};
    }
    if (industry && industry.length > 0) {
        verificationEnumTools.eccEnumValue('管理后台导出在谈在跟列表', 'industry', industryEnum.ALLINDUSTRY, industry);
        selectParam.industry = {"$in": industry};
    }
    if (progressStatus) {
        verificationEnumTools.eccEnumValue('管理后台导出在谈在跟列表', 'progressStatus', configEnum.PROGRESSSTATUS, progressStatus);
        selectParam.progressStatus = progressStatus;
    }
    if (primaryContact) {
        selectParam.primaryContact = {"$regex": `${primaryContact}`};
    }
    if (contactDepartment) {
        selectParam.contactDepartment = {"$regex": `${contactDepartment}`};
    }
    if (id) {
        selectParam.id = {"$in": id};
    }

    /** 查询在谈在跟数据 */
    let negotiationDbList = await negotiationData.findNegotiationListByParam(selectParam);

    /** 表头定义 */
    const titleList = [
        "企业名称",
        "行业领域",
        "细分行业领域",
        "进展情况",
        "负责人/首谈人",
        "对接部门",
        "进度详情",
        "创建时间"
    ];

    /** 字段映射 */
    const keyList = [
        "name",
        "industry",
        "subDivide",
        "progressStatus",
        "primaryContact",
        "contactDepartment",
        "progressDetails",
        "createTime"
    ];

    let dataList = [titleList]; // 第一行为表头

    negotiationDbList.forEach(info => {
        /** 提取数据 */
        let changeData: any = extractData(splitResultConfig.negotiationListConfig, info, true);

        /** 枚举值转文本 */
        let industryText = [];
        if (changeData.industry && changeData.industry.length > 0) {
            industryText.push(verificationEnumTools.changeEnumValue(industryEnum.ALLINDUSTRY, changeData.industry));
        }
        changeData.industry = industryText.join("、") || "未选择";
        changeData.subDivide = verificationEnumTools.changeEnumValue(industryEnum.SUBDIVIDE, changeData.subDivide) || "未选择";
        // changeData.registrationStatus = verificationEnumTools.changeEnumValue(configEnum.REGISTRATIONSTATUS, changeData.registrationStatus) || "未选择";
        changeData.progressStatus = verificationEnumTools.changeEnumValue(configEnum.PROGRESSSTATUS, changeData.progressStatus) || "未选择";

        /** 时间格式化 */
        changeData.createTime = info.createTime ? moment(info.createTime).format("YYYY-MM-DD HH:mm:ss") : "-";

        /** 生成一行数据 */
        let row = [];
        keyList.forEach(key => {
            let value = changeData[key];
            if (value === null || value === undefined || value === "") {
                value = "-";
            }
            // 确保值是字符串类型
            if (Array.isArray(value)) {
                value = value.join("、");
            }
            row.push(value);
        });

        dataList.push(row);
    });

    return dataList;
}







