import { TABLENAME } from "../../config/dbEnum";
import { CaiShouConfig, NongShiConfig } from "../../config/eccParam";
import { NONGSHITYPE, PLANTTYPE } from "../../config/enum";
import * as nongshiData from "../../data/nongshi";
import * as dikuaiData from "../../data/dikuai";
import { getMySqlMs, randomId, successResult } from "../../tools/system";
import { changeEnumValue, eccEnumValue } from "../../util/verificationEnum";
import { eccFormParam } from "../../util/verificationParam";
import moment = require("moment");
import { BizError } from "../../util/bizError";
import { ERRORENUM } from "../../config/errorEnum";

/**
 * 添加农事
 * @param reqUser 
 * @param param 
 * @returns 
 */
export async function addNongShi(reqUser, param) {
    let funName = `添加农事`;
    eccFormParam(funName, NongShiConfig, param );
    eccEnumValue(funName, "nsType", NONGSHITYPE, param.nsType);
    //确保添加时地块还在
    let dikuaiList = await dikuaiData.selectToParam({});
    let diKuaiMap = {};
    dikuaiList.forEach(info => {
        let {dId, code} = info;
        diKuaiMap[dId] = code;
    });
    if (!diKuaiMap[param.dIdList]) throw new BizError(ERRORENUM.地块不存在, param.dIdList);

    let addInfo = {
        nsId:randomId(TABLENAME.农事),
        nsType:param.nsType,
        dIdList:[param.dIdList],
        operationTime:param.operationTime,
        ct:new Date().valueOf()
    };
    await nongshiData.addData(addInfo)

    return successResult();
}

/**
 * 农事列表
 * @param selectStr 
 * @param dId 
 * @param nsType 
 * @param operationTime 
 * @returns 
 */
export async function nongShiList(selectStr:string, dId:string, nsType:number, operationTime:number) {
    let funName = "农事列表";
    let param:any = {};
    if (nsType) {
        eccEnumValue(funName, "nsType", NONGSHITYPE, nsType);
        param.nsType = nsType;
    }
    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} = info;
        diKuaiMap[dId] = code;
    });

    let nongShiList = await nongshiData.selectToParam(param);
    let dataList = [];
    nongShiList.forEach(item => {
        let {nsType, dIdList, operationTime } = item;
        let didStr = "";
        dIdList.forEach(dId => {
            didStr += `${diKuaiMap[dId]} `;
        });
        dataList.push({
            nsType:changeEnumValue(NONGSHITYPE, nsType),
            dIdList:didStr,
            operationTime:moment(operationTime).format("YYYY-MM-DD"),
            operationTimeNum:operationTime
        });
    });

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

    return {dataList}
}