/**
 * 销售
 */
import { TABLENAME } from "../../config/dbEnum";
import { XiaoShouConfig } from "../../config/eccParam";
import { PLANTTYPE, XIAOSHOUQUXIANG } from "../../config/enum";
import * as xiaoshouData from "../../data/xiaoshou";
import { randomId, successResult } from "../../tools/system";
import { changeEnumValue, eccEnumValue } from "../../util/verificationEnum";
import { eccFormParam } from "../../util/verificationParam";
import moment = require("moment");

/**
 * 添加销售
 * @param reqUser 
 * @param param 
 * @returns 
 */
export async function addXiaoShou(reqUser, param) {
    let funName = `添加销售`;
    eccFormParam(funName, XiaoShouConfig, param );
    eccEnumValue(funName, "quXiang", XIAOSHOUQUXIANG, param.quXiang);
    eccEnumValue(funName, "plantType", PLANTTYPE, param.plantType);
    
    let addInfo = {
        xsId:randomId(TABLENAME.销售),
        quXiang:param.quXiang,
        plantType:param.plantType,
        operationTime:param.operationTime,
        weight:param.weight,
        ct:new Date().valueOf(),
        createUser:reqUser.userId
    };

    await xiaoshouData.addData(addInfo)

    return successResult();
}


/**
 * 销售列表
 * @param selectStr 
 * @param quXiang 
 * @param plantType 
 * @param operationTime 
 * @returns 
 */
export async function xiaoShouList(selectStr:string, quXiang:string, plantType:number, operationTime:number) {
    let funName = "销售列表";
    let param:any = {};
    if (plantType) {
        eccEnumValue(funName, "plantType", PLANTTYPE, plantType);
        param.plantType = plantType;
    }
    if (quXiang) {
        eccEnumValue(funName, "quXiang", XIAOSHOUQUXIANG, quXiang);
        param.quXiang = quXiang;
    }
    if (operationTime) {
        let startMs = moment(operationTime).startOf("day").valueOf();
        let endMs = moment(operationTime).endOf("day").valueOf();
        param.useTime = {"$gte":startMs, "$lte":endMs};
    }

    let nongShiList = await xiaoshouData.selectToParam(param);
    let dataList = [];
    nongShiList.forEach(item => {
        let {plantType, quXiang, operationTime, weight } = item;
        
        dataList.push({
            plantType:changeEnumValue(PLANTTYPE, plantType),
            quXiang:changeEnumValue(XIAOSHOUQUXIANG, quXiang),
            operationTime:moment(operationTime).format("YYYY-MM-DD"),
            weight,
            operationTimeNum:operationTime
        });
    });

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

    return {dataList}
}