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.EnergyWarningThreshold;
import com.huimv.admin.mapper.EnergyWarningThresholdMapper;
import com.huimv.admin.mapper.SysAccountMultilevelMapper;
import com.huimv.admin.service.IEnergyWarningThresholdService;
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 EnergyWarningThresholdServiceImpl extends ServiceImpl<EnergyWarningThresholdMapper, EnergyWarningThreshold> implements IEnergyWarningThresholdService {

    @Autowired
    private EnergyWarningThresholdMapper warningThresholdMapper;
    @Autowired
    SysAccountMultilevelMapper sysAccountMultilevelMapper;

    @Override
    public Result list(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        QueryWrapper<EnergyWarningThreshold> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("farm_id", farmId);
        List<EnergyWarningThreshold> energyWarningThresholds = warningThresholdMapper.selectList(queryWrapper);

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

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

                jsonObject.put("renChen",    getData());
                jsonObject.put("chanFang",    getData());
                jsonObject.put("baoYu",    getData());
                jsonObject.put("yuFei",    getData());
                jsonObject.put("houBei",    getData());
                jsonObject.put("geLi",    getData());
            return new Result(ResultCode.SUCCESS, jsonObject);
        } else {
            JSONObject jsonObject = new JSONObject();
            for (int i = 0; i < energyWarningThresholds.size(); i++) {
                if ("1".equals(energyWarningThresholds.get(i).getOther1())) {
                    jsonObject.put("renChen", energyWarningThresholds.get(i));
                } else if ("2".equals(energyWarningThresholds.get(i).getOther1())) {
                    jsonObject.put("chanFang", energyWarningThresholds.get(i));
                } else if ("3".equals(energyWarningThresholds.get(i).getOther1())) {
                    jsonObject.put("baoYu", energyWarningThresholds.get(i));
                } else if ("4".equals(energyWarningThresholds.get(i).getOther1())) {
                    jsonObject.put("yuFei", energyWarningThresholds.get(i));
                } else if ("5".equals(energyWarningThresholds.get(i).getOther1())) {
                    jsonObject.put("houBei", energyWarningThresholds.get(i));
                } else if ("6".equals(energyWarningThresholds.get(i).getOther1())) {
                    jsonObject.put("geLi", energyWarningThresholds.get(i));
                }
            }
            jsonObject.put("userIds", collect);
            return new Result(ResultCode.SUCCESS, jsonObject);
        }

    }

    private JSONObject getData() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("maxWater", 0);
        jsonObject.put("maxElectricity", 0);
        jsonObject.put("maxFeed", 0);
        jsonObject.put("maxGas", 0);
        return jsonObject;
    }

    @Override
    public Result add(HttpServletRequest httpServletRequest, List<EnergyWarningThreshold> energyWarningThresholds) {
        for (EnergyWarningThreshold energyWarningThreshold : energyWarningThresholds) {
            if (ObjectUtil.isNotEmpty(energyWarningThreshold)) {

                Integer farmId = energyWarningThreshold.getFarmId();
                String userIds = energyWarningThreshold.getUserIds();
                QueryWrapper<EnergyWarningThreshold> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("farm_id", farmId).eq("other1", energyWarningThreshold.getOther1());
                EnergyWarningThreshold energyWarningThreshold1 = warningThresholdMapper.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 = energyWarningThreshold1.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);

                EnergyWarningThreshold threshold = new EnergyWarningThreshold();
                threshold.setMaxWater(energyWarningThreshold.getMaxWater());
                threshold.setMaxElectricity(energyWarningThreshold.getMaxElectricity());
                threshold.setMaxFeed(energyWarningThreshold.getMaxFeed());
                threshold.setMaxGas(energyWarningThreshold.getMaxGas());
                threshold.setUserIds(oldUsersIds.stream().map(String::valueOf).collect(Collectors.joining(",")));

                if (ObjectUtil.isEmpty(energyWarningThreshold1)) {
                    warningThresholdMapper.insert(threshold);
                } else {
                    threshold.setId(energyWarningThreshold.getId());
                    warningThresholdMapper.updateById(threshold);
                }
            }
        }
        return new Result(ResultCode.SUCCESS,"修改成功");
    }
}
