import { TABLENAME } from "../../config/dbEnum";
import { CaiShouConfig, NongShiAdminConfig } from "../../config/eccParam";
import { NONGSHITYPE, PLANTTYPE, PURPOSE } 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, NongShiAdminConfig, 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(nsType:number, dId:string, operationTime:number, pageNumber: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, purpose} = info;
        diKuaiMap[dId] = {code, purpose};
    });

    let nongShiList = await nongshiData.findDataToParamToSortPage(param, {operationTime:-1}, pageNumber);
    let dataCount = await nongshiData.findDataToParamCouant({});
    let dataList = [];
    nongShiList.forEach(item => {
        let {nsId, nsType, dIdList, operationTime } = item;
        let dIds = dIdList;
        let didStr = "";
        let purpose = "";
        dIds.forEach(dId => {
            didStr += `${diKuaiMap[dId].code} `;
            purpose += `${changeEnumValue(PURPOSE, diKuaiMap[dId].purpose)} `;
        });

        dataList.push({
            nsId,
            nsType:changeEnumValue(NONGSHITYPE, nsType),
            // dIdList:didStr,
            operationTime:moment(operationTime).format("YYYY-MM-DD"),
            operationTimeNum:operationTime,
            code:didStr,
            purpose,
        });
    });

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

    return {dataList, dataCount}
}


/**
 * 农事回显
 * @param nzId 
 * @returns 
 */
export async function nongShiInfo(nsId) {
    let nongShiInfo = await nongshiData.findOne({nsId});

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

    let didStr = "";
    let purpose = "";
    nongShiInfo.dIdList.forEach(dId => {
        didStr += `${diKuaiMap[dId].code} `;
        purpose += `${changeEnumValue(PURPOSE, diKuaiMap[dId].purpose)} `;
    });

    let dataInfo = {
        nsType:changeEnumValue(NONGSHITYPE, nongShiInfo.nsType),
        operationTime:moment(nongShiInfo.operationTime).format("YYYY-MM-DD"),
        code:didStr,
        purpose
    };

    return dataInfo;
}


/**
 * 修改农事
 * @param reqUser 
 * @param nzId 
 * @param param 
 * @returns 
 */
export async function updateNongShi(reqUser, nsId, param) {
    let funName = `修改农事`;
    eccFormParam(funName, NongShiAdminConfig, param );
    eccEnumValue(funName, "nsType", NONGSHITYPE, param.nsType);

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

    let nongShiInfo = await nongshiData.findOne({nsId});

    nongShiInfo.nsType = param.nsType;//农资类型
    nongShiInfo.dIdList = param.dIdList;//地块id
    nongShiInfo.operationTime = param.operationTime; //操作时间

    await nongShiInfo.save();

    return successResult();
}


/**
 * 删除农事
 * @param nzId 
 * @returns 
 */
export async function deleteNongShi(nsId) {
    let nongShiInfo = await nongshiData.findOne({nsId});
    if (!nongShiInfo || !nongShiInfo.nsId) throw new BizError(ERRORENUM.数据不存在);

    await nongshiData.deleteData({nsId});

    return successResult();
}


