package com.huimv.beeboxs.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huimv.beeboxs.common.token.TokenSign;
import com.huimv.beeboxs.common.utils.Result;
import com.huimv.beeboxs.common.utils.ResultCode;
import com.huimv.beeboxs.entity.*;
import com.huimv.beeboxs.entity.vo.OpenDto;
import com.huimv.beeboxs.service.*;
import com.huimv.beeboxs.session.AccessToken;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/hive")
public class OpenCotroller {

    @Autowired
    ILoginService iLoginService;

    @Autowired
    IHiveBaseStationService baseStation;

    @Autowired
    IHiveBaseBeehiveService baseBeehiveService;
    @Autowired
    IBaseHiveFarmService baseHiveFarmService;

    @Autowired
    IHiveWarningService hiveWarningService;

    @PostMapping("/getHiveWarning")
    public  Result getHiveWarning(@RequestBody Map<String,String> map){
        String areaId = map.get("areaId");
        if (StringUtils.isBlank(areaId)){
            return new Result(ResultCode.SUCCESS,null);
        }
        List<BaseHiveFarm> location = baseHiveFarmService.list(new QueryWrapper<BaseHiveFarm>().like("location", areaId));
        if (ObjectUtil.isEmpty(location)){
            return new Result(ResultCode.SUCCESS,null);
        }
        List<Integer> farmIds = new ArrayList<>();
        for (BaseHiveFarm baseHiveFarm : location) {
            farmIds.add( baseHiveFarm.getId());
        }
        List endList = new ArrayList();
        List<HiveWarning> list = hiveWarningService.list(new QueryWrapper<HiveWarning>().in("farm_id", farmIds).orderByDesc("event_time").last("LIMIT 10"));
        for (HiveWarning hiveWarning : list) {
            String deviceIdHex = hiveWarning.getDeviceIdHex();
            HiveBaseBeehive uidHex = baseBeehiveService.getOne(new QueryWrapper<HiveBaseBeehive>().eq("uid_hex", deviceIdHex));

            OpenDto openDto = new OpenDto();
            openDto.setContent(hiveWarning.getMsgType());
            openDto.setDeviceName(uidHex.getTagName());
            openDto.setEventTime(hiveWarning.getEventTime());
            openDto.setEventType(hiveWarning.getEventType());
            endList.add(openDto);
        }

        return new Result(ResultCode.SUCCESS,endList);
    }

    @PostMapping("/getHiveCount")
    public  Result getHiveCount(@RequestBody Map<String,String> map){
        String areaId = map.get("areaId");
        if (StringUtils.isBlank(areaId)){
            Map endMap = new HashMap();
            endMap.put("stationNum",0);
            endMap.put("onStationNum",0);
            endMap.put("offStationNum",0);


            return new Result(ResultCode.SUCCESS,endMap);
        }
        List<BaseHiveFarm> location = baseHiveFarmService.list(new QueryWrapper<BaseHiveFarm>().like("location", areaId));
        if (ObjectUtil.isEmpty(location)){
            Map endMap = new HashMap();
            endMap.put("stationNum",0);
            endMap.put("onStationNum",0);
            endMap.put("offStationNum",0);


            return new Result(ResultCode.SUCCESS,endMap);
        }
        List<Integer> farmIds = new ArrayList<>();
        for (BaseHiveFarm baseHiveFarm : location) {
            farmIds.add( baseHiveFarm.getId());
        }
        QueryWrapper<HiveBaseBeehive> wrapper = new QueryWrapper<>();

        wrapper.in("farm_id",farmIds);
        wrapper.eq("type",2);

        int stationNum = baseBeehiveService.count(wrapper);

        wrapper.eq("tag_state",0);
        int onStationNum = baseBeehiveService.count(wrapper);


        Map endMap = new HashMap();
        endMap.put("stationNum",stationNum);
        endMap.put("onStationNum",onStationNum);
        endMap.put("offStationNum",stationNum -onStationNum);


        return new Result(ResultCode.SUCCESS,endMap);
    }



    @GetMapping("/token")
    public  Result token(@RequestParam(name = "account") String account,
                        @RequestParam(name = "password") String password,
                        HttpServletRequest req){

//        String code = map.get("code");

        String remoteHost = req.getRemoteHost();
        Result result = iLoginService.loginMultilevel(account, password);
        if(result.getCode() == 10000){

            SysAccountMultilevel accountEntity = (SysAccountMultilevel) result.getData();
            Integer id = accountEntity.getId();


            AccessToken accessToken = new AccessToken();
            accessToken.setCreated(new Date());
            accessToken.setAccountName(account);
            accessToken.setCode(result.getCode());
            accessToken.setMessage(result.getMessage());
            accessToken.setFarmId(accountEntity.getFarmIds());
            String token = TokenSign.sign(account,id,accountEntity.getFarmIds());
            accessToken.setToken(token);

            accessToken.setId(id);
            accessToken.setLoginIp(remoteHost);
            accessToken.setType(accountEntity.getType());
            return new Result(ResultCode.SUCCESS,accessToken);
        }
        return  result;
    }

    @GetMapping("/station/list")
    public  Result stationList(@RequestParam(name = "pageNo") String pageNo,
                        @RequestParam(name = "pageSize") String pageSize,
                        @RequestParam(name = "netstatus") String netstatus,
                        HttpServletRequest req){
        String farmIds = TokenSign.getFarmIds(req);
        if (StringUtils.isNotBlank(farmIds)){
            String[] split = farmIds.split(",");

           return baseStation.openPage(pageNo,pageSize,netstatus,split);

        }else {
            return new Result(10001,"账号未绑定牧场",false);
        }
    }

    @GetMapping("/station/data/{id}")
    public  Result stationData(@RequestParam(name = "stationId",required = false) String stationId,
                        @PathVariable("id") String id){

        if (StringUtils.isNotBlank(stationId)){

            return new Result(ResultCode.SUCCESS,  baseStation.getOne(new QueryWrapper<HiveBaseStation>().eq("ap_uid_hex",stationId)));
        }else {
            return new Result(10001,"该基站不存在",false);
        }
    }


    //获取某个基站下蜂箱列表接口
    @GetMapping("/beehive/list/{stationId}")
    public  Result beehiveList( @PathVariable("stationId") String stationId){


        if (StringUtils.isNotBlank(stationId)){

            return new Result(ResultCode.SUCCESS,  baseBeehiveService.list(new QueryWrapper<HiveBaseBeehive>().eq("ap_uid_hex",stationId)));
        }else {
            return new Result(10001,"该基站不存在",false);
        }
    }

    //获取某个蜂箱详细数据接口
    @GetMapping("/beehive/data/{beehiveId}")
    public  Result beehiveData( @PathVariable("beehiveId") String beehiveId){


        if (StringUtils.isNotBlank(beehiveId)){

            return new Result(ResultCode.SUCCESS,  baseBeehiveService.getOne(new QueryWrapper<HiveBaseBeehive>().eq("uid_hex",beehiveId)));
        }else {
            return new Result(10001,"该基站不存在",false);
        }
    }



}
