package com.huimv.admin.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.huimv.admin.common.token.TokenSign;
import com.huimv.admin.common.utils.Result;
import com.huimv.admin.common.utils.ResultCode;
import com.huimv.admin.entity.EnvWarningThreshold;
import com.huimv.admin.entity.SysAccountMultilevel;
import com.huimv.admin.mapper.EnvWarningThresholdMapper;
import com.huimv.admin.mapper.SysAccountMultilevelMapper;
import com.huimv.admin.service.IEnvWarningThresholdService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huimv.admin.service.ISysAccountMultilevelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2023-02-13
 */
@Service
public class EnvWarningThresholdServiceImpl extends ServiceImpl<EnvWarningThresholdMapper, EnvWarningThreshold> implements IEnvWarningThresholdService {

    @Autowired
    EnvWarningThresholdMapper envWarningThresholdMapper;
    @Autowired
    SysAccountMultilevelMapper sysAccountMultilevelMapper;
    @Override
    public Result list(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");

        Integer userId = TokenSign.getMemberIdByJwtToken(httpServletRequest);
        List<Integer> userIds =sysAccountMultilevelMapper.getLowerLevel( userId,farmId);
        List<Integer> collect =new ArrayList<>();
        QueryWrapper<EnvWarningThreshold> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("farm_id", farmId);
        EnvWarningThreshold envWarningThreshold = envWarningThresholdMapper.selectOne(queryWrapper);
        JSONObject jsonObject = new JSONObject();
        String userIds1 = "";
        if (ObjectUtil.isNotEmpty(envWarningThreshold)){
            userIds1 = envWarningThreshold.getUserIds();
        }
        if (StringUtils.isNotBlank(userIds1)){
            collect = Arrays.stream(userIds1.split(",")).map(Integer::valueOf).filter(userIds::contains).collect(Collectors.toList());
        }

        if (ObjectUtil.isEmpty(envWarningThreshold)) {
            jsonObject.put("maxTem", 0);
            jsonObject.put("minTem", 0);
            jsonObject.put("maxHum", 0);
            jsonObject.put("minHum", 0);
            jsonObject.put("maxNh3", 0);
            jsonObject.put("maxCo", 0);
            jsonObject.put("userIds", null);
        } else {
            jsonObject.put("maxTem", envWarningThreshold.getMaxTem());
            jsonObject.put("minTem", envWarningThreshold.getMinTem());
            jsonObject.put("maxHum", envWarningThreshold.getMaxHum());
            jsonObject.put("minHum", envWarningThreshold.getMinHum());
            jsonObject.put("maxNh3", envWarningThreshold.getMaxNh3());
            jsonObject.put("maxCo", envWarningThreshold.getMaxCo());
            jsonObject.put("userIds", collect);
        }
        return new Result(ResultCode.SUCCESS,jsonObject);
    }

    @Override
    public Result add(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String userIds = paramsMap.get("userIds");
        String farmId = paramsMap.get("farmId");
        String maxTem = paramsMap.get("maxTem");
        String minTem = paramsMap.get("minTem");
        /*String maxHum = paramsMap.get("maxHum");
        String minHum = paramsMap.get("minHum");*/
        String maxNh3= paramsMap.get("maxNh3");
        String maxCo = paramsMap.get("maxCo");

        QueryWrapper<EnvWarningThreshold> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("farm_id", farmId);
        EnvWarningThreshold envWarningThreshold = envWarningThresholdMapper.selectOne(queryWrapper);

        //去掉属于该人物的id
        Integer userId = TokenSign.getMemberIdByJwtToken(httpServletRequest);
        //下属id
        List<Integer> lowerLevelIds = sysAccountMultilevelMapper.getLowerLevel( userId,farmId);
        //上传id
        List<Integer> uoloadIds = new ArrayList<>();
        if (StringUtils.isNotBlank(userIds)){
            uoloadIds = Arrays.stream(userIds.split(",")).map(Integer::valueOf).collect(Collectors.toList());
        }
        //现有id
        String oldUserIds = envWarningThreshold.getUserIds();
        List<Integer> oldUsersIds = new ArrayList<>();
        if (StringUtils.isNotBlank(oldUserIds)){
            oldUsersIds = Arrays.stream(oldUserIds.split(",")).map(Integer::valueOf).collect(Collectors.toList());
        }
        // 现有 -下属 + 上传
        oldUsersIds.removeAll(lowerLevelIds);
        oldUsersIds.addAll(uoloadIds);


        EnvWarningThreshold threshold = new EnvWarningThreshold();
      /*  threshold.setMaxHum(maxHum);
        threshold.setMinHum(minHum);*/
        threshold.setMaxTem(maxTem);
        threshold.setMinTem(minTem);
        threshold.setMaxNh3(maxNh3);
        threshold.setMaxCo(maxCo);
        threshold.setUserIds( oldUsersIds.stream().map(String::valueOf).collect(Collectors.joining(",")));
        threshold.setFarmId(Integer.parseInt(farmId));

        if (Double.parseDouble(maxTem) < Double.parseDouble(minTem)) {
            return new Result(10001, "最高温度不能小于最低温度", false);
        } /*else if (Integer.parseInt(maxHum) < Integer.parseInt(minHum)) {
            return new Result(10001, "最高湿度不能小于最低湿度", false);
        } */else {
            if (ObjectUtil.isEmpty(envWarningThreshold)) {
                envWarningThresholdMapper.insert(threshold);
            } else {
                threshold.setId(envWarningThreshold.getId());
                envWarningThresholdMapper.updateById(threshold);
            }
        }
        return Result.SUCCESS();
    }
}
