package com.ruoyi.business.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.domain.HwFenceArea;
import com.ruoyi.business.domain.HwFenceTarget;
import com.ruoyi.business.domain.VO.AlarmInfoVo;
import com.ruoyi.business.domain.VO.EleMonitorDeviceSumVo;
import com.ruoyi.business.domain.VO.ElectronicFenceVo;
import com.ruoyi.business.mapper.HwAlarmInfoMapper;
import com.ruoyi.business.mapper.HwFenceAreaMapper;
import com.ruoyi.business.mapper.HwFenceTargetMapper;
import com.ruoyi.common.core.constant.HwDictConstants;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.datascope.annotation.DataScope;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.business.mapper.HwElectronicFenceMapper;
import com.ruoyi.business.domain.HwElectronicFence;
import com.ruoyi.business.service.IHwElectronicFenceService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 电子围栏Service业务层处理
 *
 * @author xins
 * @date 2023-09-04
 */
@Service
public class HwElectronicFenceServiceImpl implements IHwElectronicFenceService {
    @Autowired
    private HwElectronicFenceMapper hwElectronicFenceMapper;

    @Autowired
    private HwFenceTargetMapper hwFenceTargetMapper;

    @Autowired
    private HwFenceAreaMapper hwFenceAreaMapper;

    @Autowired
    private HwAlarmInfoMapper hwAlarmInfoMapper;

    /**
     * 查询电子围栏
     *
     * @param electronicFenceId 电子围栏主键
     * @return 电子围栏
     */
    @Override
    public HwElectronicFence selectHwElectronicFenceByElectronicFenceId(Long electronicFenceId) {
        HwElectronicFence electronicFence = hwElectronicFenceMapper.selectHwElectronicFenceByElectronicFenceId(electronicFenceId);
        HwFenceArea queryFenceArea = new HwFenceArea();
        queryFenceArea.setElectronicFenceId(electronicFence.getElectronicFenceId());
        List<HwFenceArea> fenceAreas = hwFenceAreaMapper.selectHwFenceAreaList(queryFenceArea);
        JSONArray polygonJsonArr = new JSONArray();
        JSONArray circleJsonArr = new JSONArray();
        if (fenceAreas != null && !fenceAreas.isEmpty()) {
            int polygonIndex = 0;
            int circleIndex = 0;
            for (HwFenceArea fenceArea : fenceAreas) {
                String areaShapeFlag = fenceArea.getAreaShapeFlag();
                String areaRange = fenceArea.getAreaRange();
                if (areaShapeFlag.equals(HwDictConstants.AREA_SHAPE_FLAG_POLYGN)) {
                    String[] polygonRangePointsArr = areaRange.split("_");
                    for (String polygonRangePoint : polygonRangePointsArr) {
                        JSONObject polygonJson = new JSONObject();
                        polygonJson.put("longitude", new BigDecimal(polygonRangePoint.split(",")[0]));
                        polygonJson.put("latitude", new BigDecimal(polygonRangePoint.split(",")[1]));
                        polygonJson.put("index", polygonIndex);
                        polygonJsonArr.add(polygonJson);
                    }
                    polygonIndex++;

                } else if (areaShapeFlag.equals(HwDictConstants.AREA_SHAPE_FLAG_CIRCULA)) {
                    String[] circleRangePointsArr = areaRange.split(",");
                    JSONObject circleJson = new JSONObject();
                    JSONArray centerPointJsonArr = new JSONArray();
                    centerPointJsonArr.add(new BigDecimal(circleRangePointsArr[0]));
                    centerPointJsonArr.add(new BigDecimal(circleRangePointsArr[1]));
                    circleJson.put("center", centerPointJsonArr.toString());
                    circleJson.put("radius", new BigDecimal(circleRangePointsArr[2]));
                    circleJson.put("index", circleIndex);
                    circleJsonArr.add(circleJson);

                    circleIndex++;

                }
            }
        }
        electronicFence.setCircleAreaListStr(circleJsonArr.toString());
        electronicFence.setPolygonAreaListStr(polygonJsonArr.toString());
        return electronicFence;
    }

    @Override
    public List<HwElectronicFence> selectElectronicByScene(Long sceneId) {
        return hwElectronicFenceMapper.selectElectronicByScene(sceneId);
    }

    @Override
    public List<ElectronicFenceVo> selectEleTypeNums(Long sceneId) {
        List<ElectronicFenceVo> electronicFenceVos = new ArrayList<>();
        HwElectronicFence queryElectronicFence = new HwElectronicFence();
        queryElectronicFence.setSceneId(sceneId);
        List<HwElectronicFence> electronicFenceList = hwElectronicFenceMapper.selectHwElectronicFenceList(queryElectronicFence);
        electronicFenceList.forEach(electronicFence -> {
            HwFenceArea queryFenceArea = new HwFenceArea();
            queryFenceArea.setElectronicFenceId(electronicFence.getElectronicFenceId());
            List<HwFenceArea> fenceAreas = hwFenceAreaMapper.selectHwFenceAreaList(queryFenceArea);
            for (HwFenceArea fenceArea : fenceAreas) {
                ElectronicFenceVo e = new ElectronicFenceVo();
                String fenceType = electronicFence.getFenceType();
                String areaShapeFlag = fenceArea.getAreaShapeFlag();
                String areaRange = fenceArea.getAreaRange();
                Integer deviceCount = 0;
                if (fenceType.equals(HwDictConstants.FENCE_TYPE_DEVICE)
                        || fenceType.equals(HwDictConstants.FENCE_TYPE_MONITOR_UNIT)) {
                    deviceCount = hwElectronicFenceMapper.selectDeviceCount(electronicFence.getElectronicFenceId());
                }

                if (fenceType.equals(HwDictConstants.FENCE_TYPE_MONITOR_UNIT)) {
                    deviceCount = hwElectronicFenceMapper.selectDeviceCountByMonitorUnit(electronicFence.getElectronicFenceId());

                } else if (fenceType.equals(HwDictConstants.FENCE_TYPE_SCENE)) {
                    deviceCount = hwElectronicFenceMapper.selectDeviceCountByScene(electronicFence.getSceneId());
                }

                if (areaShapeFlag.equals(HwDictConstants.AREA_SHAPE_FLAG_POLYGN)) {
                    String[] areaRangeArr = areaRange.split("_");
                    List<ElectronicFenceVo.AreaPoint> points = new ArrayList<ElectronicFenceVo.AreaPoint>();
                    for (String areaR : areaRangeArr) {
                        String[] areaRArr = areaR.split(",");
                        ElectronicFenceVo.AreaPoint p = new ElectronicFenceVo.AreaPoint();
                        p.setLongitude(Double.valueOf(areaRArr[0]));
                        p.setLatitude(Double.valueOf(areaRArr[1]));
                        points.add(p);
                    }
                    e.setAreaPoints(points);

                } else if (areaShapeFlag.equals(HwDictConstants.AREA_SHAPE_FLAG_CIRCULA)) {
                    String[] areaRangeArr = areaRange.split(",");
                    ElectronicFenceVo.AreaPoint p = new ElectronicFenceVo.AreaPoint();
                    p.setLongitude(Double.valueOf(areaRangeArr[0]));
                    p.setLatitude(Double.valueOf(areaRangeArr[1]));

                    e.setCenterPoint(p);
                    e.setRadius(Double.valueOf(areaRangeArr[2]));
                }

                AlarmInfoVo alarmInfoVo = hwAlarmInfoMapper.selectAlarmCountByFenceArea(fenceArea.getFenceAreaId());
                e.setAbnormalCount(alarmInfoVo.getAlarmCount());
                e.setAreaShapeFlag(areaShapeFlag);
                e.setDeviceCount(deviceCount);
                electronicFenceVos.add(e);
            }
        });

        return electronicFenceVos;
    }

    /**
     * 查询电子围栏列表
     *
     * @param hwElectronicFence 电子围栏
     * @return 电子围栏
     */
    @Override
    public List<HwElectronicFence> selectHwElectronicFenceList(HwElectronicFence hwElectronicFence) {
        return hwElectronicFenceMapper.selectHwElectronicFenceList(hwElectronicFence);
    }

    /**
     * 新增电子围栏
     *
     * @param hwElectronicFence 电子围栏
     * @return 结果
     */
    @Override
    @Transactional
    public int insertHwElectronicFence(HwElectronicFence hwElectronicFence) {
        hwElectronicFence.setFencePushFlag("0");
        hwElectronicFence.setFenceType("3");
        hwElectronicFence.setCreateTime(DateUtils.getNowDate());
        int rows = hwElectronicFenceMapper.insertHwElectronicFence(hwElectronicFence);
        this.batchInsertFenceArea(hwElectronicFence);
        return rows;
    }

    private void batchInsertFenceArea(HwElectronicFence hwElectronicFence) {
        Long electronicFenceId = hwElectronicFence.getElectronicFenceId();
        String polygonAreaListStr = hwElectronicFence.getPolygonAreaListStr();
        String circleAreaListStr = hwElectronicFence.getCircleAreaListStr();
        List<HwFenceArea> fenceAreaList = new ArrayList<>();
        if (polygonAreaListStr != null) {
            JSONArray polygonAreaJsonArray = JSON.parseArray(polygonAreaListStr);
            Map<Integer, JSONArray> polygonAreaJsonMap = new HashMap<>();
            for (Object polygonAreaObj : polygonAreaJsonArray) {
                JSONObject polygonAreaJson = (JSONObject) polygonAreaObj;
                Integer polygonAreaIndex = polygonAreaJson.getInteger("index");
                JSONArray polygonAreaArr = polygonAreaJsonMap.get(polygonAreaIndex);
                if (polygonAreaArr == null) {
                    polygonAreaArr = new JSONArray();
                    polygonAreaArr.add(polygonAreaJson);
                    polygonAreaJsonMap.put(polygonAreaIndex, polygonAreaArr);
                } else {
                    polygonAreaArr.add(polygonAreaJson);
                }
            }

            //每个key有一个区域，多个点
            for (Map.Entry<Integer, JSONArray> entry : polygonAreaJsonMap.entrySet()) {
                JSONArray polygonPointList = entry.getValue();
                StringBuilder areaRange = new StringBuilder();
                int i = 0;
                for (Object polygonPointObj : polygonPointList) {
                    JSONObject polygonPointJson = (JSONObject) polygonPointObj;
                    if (i > 0) {
                        areaRange.append("_");
                    } else {
                        i++;
                    }
                    areaRange.append(polygonPointJson.getString("longitude")).append(",").append(polygonPointJson.getString("latitude"));
                }
                HwFenceArea polygonArea = new HwFenceArea();
                polygonArea.setElectronicFenceId(electronicFenceId);
                polygonArea.setAreaShapeFlag(HwDictConstants.AREA_SHAPE_FLAG_POLYGN);
                polygonArea.setAreaRange(areaRange.toString());
                fenceAreaList.add(polygonArea);
            }
        }
        if (circleAreaListStr != null) {
            JSONArray circleAreaJsonArray = JSON.parseArray(circleAreaListStr);
            Map<Integer, JSONArray> circleAreaJsonMap = new HashMap<>();
            for (Object circleAreaObj : circleAreaJsonArray) {
                JSONObject circleAreaJson = (JSONObject) circleAreaObj;
                Integer circleAreaIndex = circleAreaJson.getInteger("index");
                JSONArray circleAreaArr = circleAreaJsonMap.get(circleAreaIndex);
                if (circleAreaArr == null) {
                    circleAreaArr = new JSONArray();
                    circleAreaArr.add(circleAreaJson);
                    circleAreaJsonMap.put(circleAreaIndex, circleAreaArr);
                } else {
                    circleAreaArr.add(circleAreaJson);
                }
            }

            //每个key有一个区域，多个点
            for (Map.Entry<Integer, JSONArray> entry : circleAreaJsonMap.entrySet()) {
                JSONArray circlePointList = entry.getValue();
                StringBuilder areaRange = new StringBuilder();
                int j = 0;
                for (Object circlePointObj : circlePointList) {
                    JSONObject circlePointJson = (JSONObject) circlePointObj;
                    if (j > 0) {
                        areaRange.append(",");
                    } else {
                        j++;
                    }
                    JSONArray centerPointArr = circlePointJson.getJSONArray("center");
                    BigDecimal longitude = (BigDecimal) centerPointArr.get(0);
                    BigDecimal latitude = (BigDecimal) centerPointArr.get(1);
                    areaRange.append(longitude).append(",")
                            .append(latitude).append(",")
                            .append(circlePointJson.getString("radius"));
                }
                HwFenceArea polygonArea = new HwFenceArea();
                polygonArea.setElectronicFenceId(electronicFenceId);
                polygonArea.setAreaShapeFlag(HwDictConstants.AREA_SHAPE_FLAG_CIRCULA);
                polygonArea.setAreaRange(areaRange.toString());
                fenceAreaList.add(polygonArea);
            }

        }

        if (!fenceAreaList.isEmpty()) {
            for (HwFenceArea area : fenceAreaList) {
                hwFenceAreaMapper.insertHwFenceArea(area);
            }
        }
    }

    /**
     * 修改电子围栏
     *
     * @param hwElectronicFence 电子围栏
     * @return 结果
     */
    @Override
    public int updateHwElectronicFence(HwElectronicFence hwElectronicFence) {
        HwFenceArea queryFenceArea = new HwFenceArea();
        queryFenceArea.setElectronicFenceId(hwElectronicFence.getElectronicFenceId());
        List<HwFenceArea> dbFenceAreaList = hwFenceAreaMapper.selectHwFenceAreaList(queryFenceArea);
        for (HwFenceArea dbFenceArea : dbFenceAreaList) {
            hwFenceAreaMapper.deleteHwFenceAreaByFenceAreaId(dbFenceArea.getFenceAreaId());
        }
        this.batchInsertFenceArea(hwElectronicFence);
        hwElectronicFence.setUpdateTime(DateUtils.getNowDate());
        return hwElectronicFenceMapper.updateHwElectronicFence(hwElectronicFence);
    }

    /**
     * 批量删除电子围栏
     *
     * @param electronicFenceIds 需要删除的电子围栏主键
     * @return 结果
     */
    @Override
    public int deleteHwElectronicFenceByElectronicFenceIds(Long[] electronicFenceIds) {
        return hwElectronicFenceMapper.deleteHwElectronicFenceByElectronicFenceIds(electronicFenceIds);
    }

    /**
     * 删除电子围栏信息
     *
     * @param electronicFenceId 电子围栏主键
     * @return 结果
     */
    @Override
    public int deleteHwElectronicFenceByElectronicFenceId(Long electronicFenceId) {
        return hwElectronicFenceMapper.deleteHwElectronicFenceByElectronicFenceId(electronicFenceId);
    }


    /**
     * 查询电子围栏列表Join场景
     *
     * @param hwElectronicFence 电子围栏
     * @return 电子围栏
     */
    @Override
    @DataScope(tenantAlias = "hef")
    public List<HwElectronicFence> selectHwElectronicFenceJoinList(HwElectronicFence hwElectronicFence) {
        return hwElectronicFenceMapper.selectHwElectronicFenceJoinList(hwElectronicFence);
    }

}
