/**
 * 种养
 */

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

/**
 * 种养列表-暂无使用
 * @param plantType 种养类型
 * @param selectStr 
 * @returns 
 */
export async function zhongYangDangQianList(zhongYangType:number, selectStr:string) {
    let funName = `当前种养列表`;
    eccEnumValue(funName, 'zhongYangType', ZHONGYANGTYPE, zhongYangType);

    let param = {
        plantType:{"$gte":zhongYangType, "$lt":zhongYangType+99},
        isEnd:0
    };
    let zyList = await zhongzhiData.selectToParam( param );
    
    let typeMap = {};
    zyList.forEach(info => {
        let {plantType} = info;
        typeMap[plantType] = {value:plantType, key:changeEnumValue(PLANTTYPE, plantType)};
    });
    let dataList = Object.values(typeMap);

    return {dataList};
}


/**
 * 种养列表-分页
 * @param zhongYangType 种养类型
 * @param dId 使用地块
 * @param plantTime 种养时间
 * @param pageNumber 
 * @returns 
 */
export async function zhongYangDangQianListToPage(zhongYangType:number, plantType:number, dId:number, plantTime:number, pageNumber:number) {
    let funName = `当前种养列表`;
    let param:any = { plantType:{"$gte":zhongYangType, "$lt":zhongYangType+99} };
    if (plantType) {
        eccEnumValue(funName, "plantType", PLANTTYPE, plantType);
        param.plantType = plantType;
    }
    if (dId) {
        param.dId = dId;
    }
    if (plantTime) {
        let selectStartTime = moment(plantTime).startOf('day').valueOf();
        let selectEndTime = moment(plantTime).endOf("day").valueOf();
        // let selectStartTime = moment(plantTime).valueOf();
        // let selectEndTime = moment(plantTime).valueOf();
        param.plantTime = {"$gte":selectStartTime, "$lte":selectEndTime};
    }
    
    /**获取地块名称 */
    let dikuaiList = await dikuaiData.selectToParam({});
    let diKuaiMap = {};
    dikuaiList.forEach(info => {
        let {dId, code, purpose} = info;
        diKuaiMap[dId] = {code, purpose};
    });

    let zyList = await zhongzhiData.findDataToParamToSortPage( param, {plantTime:-1}, pageNumber );
    let dataCount = await zhongzhiData.findDataToParamCouant(param);
    let dataList = [];
    zyList.forEach(info => {
        let code = "-";
        let purpose = "-"; 
        if (diKuaiMap[info.dId]) {
            code = diKuaiMap[info.dId].code;
            purpose = changeEnumValue(PURPOSE, diKuaiMap[info.dId].purpose);
        }
        let addInfo = {
            zId : info.zId,
            size : info.size,
            plantType : changeEnumValue(PLANTTYPE, info.plantType),
            code,
            plantTime:moment(info.plantTime).format("YYYY-MM-DD"),
            purpose,
            plantTimeNum:info.plantTime,
            ctTime:moment(info.ct).format("YYYY-MM-DD"),
        };
        dataList.push(addInfo);
    });

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

    return {dataList, dataCount};
}


/**
 * 删除种养
 * @param zId 
 * @returns 
 */
export async function deleteZhongYang(zId) {
    let zhongYangInfo = await zhongzhiData.selectOne({zId});
    if (!zhongYangInfo || !zhongYangInfo.zId) throw new BizError(ERRORENUM.数据不存在);

    await zhongzhiData.deleteData({zId});

    return successResult();
}


/**
 * 添加种养
 * @param reqUser 
 * @param param 
 * @returns 
 */
export async function addZhongYang(reqUser, param) {
    let funName = `添加种养`;
    eccFormParam(funName, ZhongYangConfig, param);
    eccEnumValue(funName, "plantType", PLANTTYPE, param.plantType);

    //校验地块大小是否符合扣除
    let dkInfo = await dikuaiData.selectOne({dId:param.dId});
    if (!dkInfo || !dkInfo.dId) throw new BizError(ERRORENUM.地块不存在);
    if (dkInfo.size < param.size) throw new BizError(ERRORENUM.地块大小不足);

    let addInfo = {
        zId:randomId(TABLENAME.种植表),
        size:param.size,//种植大小
        plantType:param.plantType,//
        dId:param.dId,//地块id
        plantTime:param.plantTime,//种植时间
        uId:reqUser.userId,
        isEnd:0,
        ct:new Date().valueOf()
    };

    await zhongzhiData.addData(addInfo);

    dkInfo.nullSize = dkInfo.size - param.size;
    dkInfo.useSize = dkInfo.useSize + param.size;
    await dkInfo.save();

    return successResult();
}


/**
 * 修改种养
 * @param reqUser 
 * @param zId 
 * @param param 
 * @returns 
 */
export async function updateZhongYang(reqUser, zId, param) {
    let funName = `修改种养`;
    eccFormParam(funName, ZhongYangConfig, param);
    eccEnumValue(funName, "plantType", PLANTTYPE, param.plantType);

    let dkInfo = await dikuaiData.selectOne({dId:param.dId});
    if (!dkInfo || !dkInfo.dId) throw new BizError(ERRORENUM.地块不存在);
    if (dkInfo.size < param.size) throw new BizError(ERRORENUM.地块大小不足);

    let zhongYangInfo = await zhongzhiData.selectOne({zId});

    zhongYangInfo.plantType = param.plantType;
    zhongYangInfo.dId = param.dId;
    zhongYangInfo.size = param.size;
    zhongYangInfo.plantTime = param.plantTime;

    await zhongYangInfo.save();

    return successResult();
}


/**
 * 种养回显
 * @param zId 
 * @returns 
 */
export async function zhognYangInfo(zId) {

    let dikuaiInfo = await zhongzhiData.selectOne({zId});
    let dataInfo = {
        plantType:dikuaiInfo.plantType,//编号
        dId:dikuaiInfo.dId,//地块id
        size:dikuaiInfo.size,//地块大小
        plantTime:dikuaiInfo.plantTime,//种植时间
    };

    return {dataInfo}
}


/**
 * 种养记录-暂无使用
 * @param zhongYangType 
 * @param selectStr 
 * @param plantType 
 * @param plantTime 
 * @param dId 
 * @returns 
 */
export async function zhongYangJiLu(zhongYangType:number, selectStr:string, plantType:number, plantTime:number, dId:string) {
    let funName = `种养记录`;
 
    let param:any = { plantType:{"$gte":zhongYangType, "$lt":zhongYangType+99} };
    if (plantType) {
        eccEnumValue(funName, "plantType", PLANTTYPE, plantType);
        param.plantType = plantType;
    }
    if (dId) {
        param.dId = dId;
    }
    if (plantTime) {
        let selectStartTime = moment(plantTime).startOf('day').valueOf();
        let selectEndTime = moment(plantTime).endOf("day").valueOf();
        param.plantTime = {"$gte":selectStartTime, "$lte":selectEndTime};
    }
    
    /**获取地块名称 */
    let dikuaiList = await dikuaiData.selectToParam({});
    let diKuaiMap = {};
    dikuaiList.forEach(info => {
        let {dId, code} = info;
        diKuaiMap[dId] = code;
    });

    let dbList = await zhongzhiData.selectToParam(param);
    let dataList = [];
    dbList.forEach(info => {
        dataList.push({
            plantType:changeEnumValue(PLANTTYPE, info.plantType),
            size:info.size,
            code:diKuaiMap[info.dId],
            plantTime:moment(info.plantTime).format("YYYY-MM-DD")
        })
    });

    return {dataList};
}


