package com.huimv.beeboxs.controller;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huimv.beeboxs.common.utils.Result;
import com.huimv.beeboxs.entity.HiveBaseBeehive;
import com.huimv.beeboxs.entity.HiveBeehive;
import com.huimv.beeboxs.entity.HiveBeehiveStatus;
import com.huimv.beeboxs.entity.HiveWeight;
import com.huimv.beeboxs.service.IHiveBaseBeehiveService;
import com.huimv.beeboxs.service.IHiveBeehiveService;
import com.huimv.beeboxs.service.IHiveWeightService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

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

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2022-04-28
 */
@RestController
@RequestMapping("/hiveWeight")
@CrossOrigin
public class HiveWeightController {

    @Autowired
    IHiveBeehiveService beehiveService;

    @Autowired
    IHiveBaseBeehiveService baseBeehiveService;

    @Autowired
    IHiveWeightService weightService;

    @PostMapping("/list")
    public Result page(@RequestBody Map map){

        return weightService.searchList(map);
    }


//    @Scheduled(cron = "0 0 6 * * ? ")
    public void  saveWeight(){
        System.out.println("start");
        List<HiveBaseBeehive> type = baseBeehiveService.list(new QueryWrapper<HiveBaseBeehive>().eq("type", 2));

        List<HiveWeight> hiveWeights = new ArrayList<HiveWeight>();
        for (HiveBaseBeehive hiveBaseBeehive : type) {
            HiveWeight hiveWeight = new HiveWeight();

            HiveWeight weightEntity = weightService.getOne(new QueryWrapper<HiveWeight>().eq("ap_uid_hex", hiveBaseBeehive.getApUidHex()).orderByDesc("id").last("limit 1"));

            hiveWeight.setApUidHex(hiveBaseBeehive.getApUidHex());
            hiveWeight.setFarmId(hiveBaseBeehive.getFarmId());
            hiveWeight.setUidHex(hiveBaseBeehive.getUidHex());
            hiveWeight.setUpdateTime(new Date());
            hiveWeight.setWeight(hiveBaseBeehive.getWeight());

            String increment = hiveBaseBeehive.getWeight();
            if (ObjectUtil.isNotEmpty(weightEntity)){

                increment = (Double.parseDouble(hiveBaseBeehive.getWeight() )- Double.parseDouble(weightEntity.getWeight()))+"";
            }
            hiveWeight.setIncrement(increment);



            hiveWeights.add(hiveWeight);
        }

        weightService.saveBatch(hiveWeights);
    }


}
