package com.huimv.admin.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
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.GasThreshold;
import com.huimv.admin.entity.ProtThreshold;
import com.huimv.admin.mapper.ProtThresholdMapper;
import com.huimv.admin.mapper.SysAccountMultilevelMapper;
import com.huimv.admin.service.IProtThresholdService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
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;

/**
 * <p>
 * 环保阈值 服务实现类
 * </p>
 *
 * @author author
 * @since 2023-02-14
 */
@Service
public class ProtThresholdServiceImpl extends ServiceImpl<ProtThresholdMapper, ProtThreshold> implements IProtThresholdService {

    @Autowired
    private ProtThresholdMapper protThresholdMapper;
    @Autowired
    SysAccountMultilevelMapper sysAccountMultilevelMapper;
    @Override
    public Result list(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        String protType = paramsMap.get("protType");
        QueryWrapper<ProtThreshold> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("farm_id", farmId);
        List<ProtThreshold> protThresholdList = protThresholdMapper.selectList(queryWrapper);

        Integer userId = TokenSign.getMemberIdByJwtToken(httpServletRequest);
        List<Integer> userIds =sysAccountMultilevelMapper.getLowerLevel( userId,farmId);
        List<Integer> collect =new ArrayList<>();
        if (ObjectUtil.isNotEmpty(protThresholdList) &&StringUtils.isNotBlank(protThresholdList.get(0).getUserIds())){
            collect = Arrays.stream(protThresholdList.get(0).getUserIds().split(",")).map(Integer::valueOf).filter(userIds::contains).collect(Collectors.toList());
        }

        if (protThresholdList.size() == 0) {
            JSONObject jsonObject = new JSONObject();

            jsonObject.put("in", getProtThreshold());
            jsonObject.put("deal", getProtThreshold());
            jsonObject.put("out", getProtThreshold());
            jsonObject.put("userIds", new ArrayList<>());
            ProtThreshold protThreshold = new ProtThreshold();
            protThreshold.setFarmId(Integer.parseInt(farmId));
            protThreshold.setProtType(1);
            protThresholdMapper.insert(protThreshold);
            ProtThreshold protThreshold2 = new ProtThreshold();
            protThreshold2.setFarmId(Integer.parseInt(farmId));
            protThreshold2.setProtType(2);
            protThresholdMapper.insert(protThreshold2);
            ProtThreshold protThreshold3 = new ProtThreshold();
            protThreshold3.setFarmId(Integer.parseInt(farmId));
            protThreshold3.setProtType(3);
            protThresholdMapper.insert(protThreshold3);


            return new Result(ResultCode.SUCCESS, jsonObject);
        } else {
            JSONObject jsonObject = new JSONObject();
            for (int i = 0; i < protThresholdList.size(); i++) {
                if (protThresholdList.get(i).getProtType()==1) {
                    jsonObject.put("in", protThresholdList.get(i));
                } else if (protThresholdList.get(i).getProtType()==2) {
                    jsonObject.put("deal", protThresholdList.get(i));
                } else if (protThresholdList.get(i).getProtType()==3) {
                    jsonObject.put("out", protThresholdList.get(i));
                }
            }
            jsonObject.put("userIds",collect);
            return new Result(ResultCode.SUCCESS,jsonObject);
        }

    }

    private JSONObject getProtThreshold() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("cod1", 0);
        jsonObject.put("cod2", 0);
        jsonObject.put("ph1", 0);
        jsonObject.put("ph2", 0);
        jsonObject.put("nh3n1", 0);
        jsonObject.put("nh3n2", 0);
        jsonObject.put("tp1", 0);
        jsonObject.put("tp2", 0);
        jsonObject.put("tn1", 0);
        jsonObject.put("tn2", 0);
        jsonObject.put("flow1", 0);
        jsonObject.put("flow2", 0);
        jsonObject.put("userIds", 0);
        jsonObject.put("dataType", 0);
        jsonObject.put("other2", 0);
        jsonObject.put("other3", 0);
        return jsonObject;
    }

    @Override
    public Result add(HttpServletRequest httpServletRequest, List<ProtThreshold> protThresholds) {
        for (ProtThreshold protThreshold : protThresholds) {
            if (ObjectUtil.isNotEmpty(protThreshold)) {

                Integer farmId = protThreshold.getFarmId();
                String userIds = protThreshold.getUserIds();
                QueryWrapper<ProtThreshold> queryWrapper = new QueryWrapper<>();
                 queryWrapper.eq("farm_id", protThreshold.getFarmId()).eq("prot_type",protThreshold.getProtType());
                ProtThreshold threshold = protThresholdMapper.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 = threshold.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);

                ProtThreshold protThreshold1 = new ProtThreshold();
                protThreshold1.setProtType(protThreshold.getProtType());
                protThreshold1.setFarmId(protThreshold.getFarmId());
                protThreshold1.setCod1(protThreshold.getCod1());
                protThreshold1.setCod2(protThreshold.getCod2());
                protThreshold1.setPh1(protThreshold.getPh1());
                protThreshold1.setPh2(protThreshold.getPh2());
                protThreshold1.setNh3n1(protThreshold.getNh3n1());
                protThreshold1.setNh3n2(protThreshold.getNh3n2());
                protThreshold1.setTp1(protThreshold.getTp1());
                protThreshold1.setTp2(protThreshold.getTp2());
                protThreshold1.setTn1(protThreshold.getTn1());
                protThreshold1.setTn2(protThreshold.getTn2());
                protThreshold1.setFlow1(protThreshold.getFlow1());
                protThreshold1.setFlow2(protThreshold.getFlow2());
                protThreshold1.setOther2(protThreshold.getOther2());//低ph中较大的ph=6.5
                protThreshold1.setOther3(protThreshold.getOther3());//ph=6
                protThreshold1.setUserIds(oldUsersIds.stream().map(String::valueOf).collect(Collectors.joining(",")));
                protThreshold1.setDataType(protThreshold.getDataType());


                if (Double.parseDouble(protThreshold.getCod2()) <= Double.parseDouble(protThreshold.getCod1())) {
                    return new Result(10001, "Cod红色预警浓度不能低于橙色预警浓度",false);
                } else if (Double.parseDouble(protThreshold.getPh2()) <= Double.parseDouble(protThreshold.getPh1())) {
                    return new Result(10001, "高值ph红色预警浓度不能低于橙色预警浓度",false);
                } else if (Double.parseDouble(protThreshold.getOther3()) >= Double.parseDouble(protThreshold.getOther2())) {
                    return new Result(10001, "低值ph红色预警浓度不能低于橙色预警浓度",false);
                } else if (Double.parseDouble(protThreshold.getNh3n2()) <= Double.parseDouble(protThreshold.getNh3n1())) {
                    return new Result(10001, "NH3NH2红色预警浓度不能低于橙色预警浓度",false);
                } else if (Double.parseDouble(protThreshold.getTp2()) <= Double.parseDouble(protThreshold.getTp1())) {
                    return new Result(10001, "TP红色预警浓度不能低于橙色预警浓度",false);
                } else if (Double.parseDouble(protThreshold.getTn2()) <= Double.parseDouble(protThreshold.getTn1())) {
                    return new Result(10001, "TN红色预警浓度不能低于橙色预警浓度",false);
                } else if (Double.parseDouble(protThreshold.getFlow2()) <= Double.parseDouble(protThreshold.getFlow1())) {
                    return new Result(10001, "流量红色预警浓度不能低于橙色预警浓度",false);
                } else {

                    if (ObjectUtil.isEmpty(threshold)) {
                        protThresholdMapper.insert(protThreshold1);
                    } else {
                        protThreshold1.setId(protThreshold.getId());
                        protThresholdMapper.updateById(protThreshold1);
                    }
                }

            }
        }
            return new Result(ResultCode.SUCCESS, "修改成功");
    }
}
