package com.huimv.produce.produce.controller;


import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huimv.common.utils.Result;
import com.huimv.common.utils.ResultCode;
import com.huimv.produce.produce.entity.ProdProduce;
import com.huimv.produce.produce.service.IProdProduceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author astupidcoder
 * @since 2021-11-25
 */
@RestController
@RequestMapping("/prodProduce")
public class ProdProduceController {

    @Autowired
    private IProdProduceService prodProduceService;
    private String[] fullDataType = new String[]{"avg_farrow_1", "avg_farrow_2", "avg_farrow_3", "avg_weight", "break_grice", "break_rate", "breed_rate",
            "fatpig_rate", "grice_rate", "nest_times", "piglet_rate", "psy"};
    private String[] fullDataType1 = new String[]{"平均窝产仔猪", "平均窝产活仔数", "平均窝产正常仔数", "平均窝断奶重", "窝断奶仔猪数", "7日断配率", "配种分娩率",
            "肥猪成活率", "产房成活率", "年产窝数", "保育成活率", "PSY"};

    @GetMapping("/listProducee")
    public Result listProducee(@RequestParam(name = "farmId") Integer farmId) {
        Date now = new Date();
        List<ProdProduce> list = prodProduceService.list(new QueryWrapper<ProdProduce>().eq("farm_id", farmId).eq("year", DateUtil.year(now)).eq("month", DateUtil.month(now) + 1));
        Map map = new HashMap();
        JSONArray stockTypeJa = new JSONArray();
        for (ProdProduce prodProduce : list) {
            String stockType = prodProduce.getStockType();
            stockTypeJa.add(stockType);
            map.put(stockType, prodProduce);
        }
        //结果完整性检查
        checkFullResult(map, stockTypeJa);
        return new Result(ResultCode.SUCCESS, map);
    }
    //结果完整性检查
    public void checkFullResult(Map map, JSONArray stockTypeJa) {
        for(int a=0;a<fullDataType.length;a++){
            boolean isExist = false;
            for (int b = 0; b < stockTypeJa.size(); b++) {
                if (stockTypeJa.getString(b).trim().equalsIgnoreCase(fullDataType[a])) {
                    isExist = true;
                    break;
                }
            }
            if (!isExist) {
                JSONObject newJo = new JSONObject();
                newJo.put("stockQuantity","0");
                newJo.put("stockType",fullDataType[a]);
                newJo.put("stockName",fullDataType1[a]);
                map.put(fullDataType[a],newJo);
            }
        }
    }

    @PostMapping("/listImportance")
    public Result listImportance(@RequestBody Map<String, String> map) {

        return prodProduceService.listImportance(map);
    }
}
