/**
 * 采收逻辑
 */
import { TABLENAME } from "../../config/dbEnum";
import { CaiShouConfig } from "../../config/eccParam";
import { PLANTTYPE, PURPOSE, ZHONGYANGTYPE } from "../../config/enum";
import { ERRORENUM } from "../../config/errorEnum";
import * as caishouData from "../../data/caishou";
import * as dikuaiData from "../../data/dikuai";
import * as zhongzhiData from "../../data/zhongzhi";
import { randomId, successResult } from "../../tools/system";
import { BizError } from "../../util/bizError";
import { changeEnumValue, eccEnumValue } from "../../util/verificationEnum";
import { eccFormParam } from "../../util/verificationParam";
import moment = require("moment");


/**
 * 添加采收
 * @param reqUser 
 * @param param 
 * @returns 
 */
export async function addCaiShou(reqUser, param) {
    let funName = `添加采收`;
    eccFormParam(funName, CaiShouConfig, param );
    eccEnumValue(funName, "plantType", PLANTTYPE, param.plantType);
    
    //修改种养
    let zhongyangParam = {isEnd:0, plantType:param.plantType, dId:param.dId};
    let zhongzhiList = await zhongzhiData.selectToParam(zhongyangParam);

    let sizeCount = 0;
    for (let i = 0; i < zhongzhiList.length; i++) {
        let {dId, size} = zhongzhiList[i];
        sizeCount += size;
    }

    //释放地块
    let diKuaiInfo = await dikuaiData.selectOne({dId:param.dId});
    diKuaiInfo.nullSize = diKuaiInfo.nullSize + sizeCount;
    diKuaiInfo.useSize = diKuaiInfo.useSize - sizeCount;
    await diKuaiInfo.save();

    let  csId = randomId(TABLENAME.采收);
    //改变种植面积
    await zhongzhiData.updateManyToParam({isEnd:0, plantType:param.plantType}, {isEnd:1, csId});

    //添加采收记录
    let addInfo = {
        csId,
        dIdList:param.dId,
        plantType:param.plantType,
        operationTime:param.operationTime,
        weight:param.weight,
        ct:new Date().valueOf(),
        createUser:reqUser.userId
    };
    await caishouData.addData(addInfo)

    return successResult();
}



/**
 * 采收列表
 * @param selectStr 
 * @param dId 
 * @param zhongYangType 
 * @param plantType 
 * @param operationTime 
 * @returns 
 */
export async function caiShouList(zhongYangType:number, dId:string, plantType:number, operationTime:number, pageNumber) {
    let funName = "采收列表";
    eccEnumValue(funName, "zhongYangType", ZHONGYANGTYPE, zhongYangType);

    let param:any = { plantType : {"$gte":zhongYangType, "$lt":zhongYangType+99} };
    if (plantType) {
        eccEnumValue(funName, "plantType", PLANTTYPE, plantType);
        param.plantType = plantType;
    }
    if (dId) {
        param.dIdList = {"$in":[dId]};
    }
    if (operationTime) {
        let startMs = moment(operationTime).startOf("day").valueOf();
        let endMs = moment(operationTime).endOf("day").valueOf();
        param.operationTime = {"$gte":startMs, "$lte":endMs};
    }

    let dikuaiList = await dikuaiData.selectToParam({});
    let diKuaiMap = {};
    dikuaiList.forEach(info => {
        let {dId, code, purpose} = info;
        diKuaiMap[dId] = {code, purpose};
    });

    let caishouList = await caishouData.findDataToParamToSortPage(param, {operationTime:-1}, pageNumber);
    let dataCount = await caishouData.findDataToParamCouant(param);
    let dataList = [];
    caishouList.forEach(item => {
        let {csId, plantType, dIdList, operationTime, weight, ct } = item;
        let dIds = dIdList;
        let didStr = "";
        let purpose = "-";
        dIds.forEach(dId => {
            didStr += `${diKuaiMap[dId].code} `;
            purpose = `${changeEnumValue(PURPOSE, diKuaiMap[dId].purpose)} `;
        });
        let operationTimeNum;
        if (operationTime) operationTimeNum = operationTime;
        else operationTimeNum = ct
        dataList.push({
            csId,
            plantType:changeEnumValue(PLANTTYPE, plantType),
            code:didStr || "-",
            purpose,
            operationTime:moment(operationTimeNum).format("YYYY-MM-DD"),
            weight,
            operationTimeNum,
            ctTime:moment(ct).format("YYYY-MM-DD"),
        });
    });

    dataList.sort( (a, b) => {
        return b.operationTimeNum - a.operationTimeNum;
    })

    return {dataList, dataCount}
}


/**
 * 采收回显
 * @param csId 
 * @returns 
 */
 export async function caishouInfo(csId) {
    let caishouInfo = await caishouData.findOne({csId});

    let dataInfo = {
        plantType:changeEnumValue(PLANTTYPE, caishouInfo.plantType),
        code:caishouInfo.dIdList[0] || "",
        operationTime:moment(caishouInfo.operationTime).format("YYYY-MM-DD"),
        weight:caishouInfo.weight
    };

    return dataInfo;
}


/**
 * 修改采收
 * @param reqUser 
 * @param csId 
 * @param param 
 * @returns 
 */
export async function updateCaiShou(reqUser, csId, param) {
    let funName = `修改采收`;
    eccFormParam(funName, CaiShouConfig, param );
    eccEnumValue(funName, "plantType", PLANTTYPE, param.plantType);

    let dikuaiList = await dikuaiData.selectToParam({});
    let diKuaiMap = {};
    dikuaiList.forEach(info => {
        let {dId, code} = info;
        diKuaiMap[dId] = code;
    });
    if (!diKuaiMap[param.dId]) throw new BizError(ERRORENUM.地块不存在, param.dIdList);

    let caiShouInfo = await caishouData.findOne({csId});

    caiShouInfo.plantType = param.plantType; //种植种类【枚举】 PLANTTYPE
    caiShouInfo.dIdList = param.dId;//地块id
    caiShouInfo.weight = param.weight;//采收重量
    caiShouInfo.operationTime = param.operationTime; //采收时间

    await caiShouInfo.save();

    return successResult();
}



/**
 * 删除采收
 * @param nzId 
 * @returns 
 */
export async function deleteCaiShou(csId) {
    let caishouInfo = await caishouData.findOne({csId});
    if (!caishouInfo || !caishouInfo.csId) throw new BizError(ERRORENUM.数据不存在);

    await caishouData.deleteData({csId});

    return successResult();
}



