package com.sky.ioc.service.space.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.ioc.entity.Indeicator;
import com.sky.ioc.entity.Label;
import com.sky.ioc.entity.domain.space.*;
import com.sky.ioc.entity.params.IocParam;
import com.sky.ioc.mapper.AccessSpaceMapper;
import com.sky.ioc.mapper.BuildingSpaceMapper;
import com.sky.ioc.mapper.MeetingMapper;
import com.sky.ioc.mapper.space.BuildingFloorMapper;
import com.sky.ioc.mapper.space.BuildingRoomMapper;
import com.sky.ioc.mapper.space.BuildingStationMapper;
import com.sky.ioc.service.space.SpaceService;
import com.sky.ioc.tool.DateUtil;
import com.sky.ioc.tool.GeneralMethod;
import com.sky.ioc.tool.MathUtils;
import com.sky.ioc.tool.ReturnMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

/**
 * TODO  空间
 *
 * @Description
 * @Author LunCe
 * @Date 2023/2/22 11:44
 **/
@Service
public class SpaceServiceImpl implements SpaceService {

    @Autowired
    BuildingSpaceMapper buildingSpaceMapper;

    @Autowired
    AccessSpaceMapper accessSpaceMapper;

    @Autowired
    MeetingMapper meetingMapper;

    @Autowired
    BuildingStationMapper buildingStationMapper;

    @Autowired
    BuildingFloorMapper buildingFloorMapper;

    @Autowired
    BuildingRoomMapper buildingRoomMapper;

    /**
     * TODO  智能看板 -- 楼宇态势
     *
     * @Description
     * @Return com.sky.ioc.tool.ReturnMsg
     * @Author LunCe
     * @date 2023/2/22 11:45
     */
    @Override
    public ReturnMsg getBuildingSituation() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("builtArea", 32277);
        jsonObject.put("layersInt", 21);
        jsonObject.put("serviceLife", 15);
        jsonObject.put("constructionPeriod", 15);
        jsonObject.put("companyNum", 5);
        return ReturnMsg.ok(jsonObject);
    }

    @Override
    public ReturnMsg getFloorCoreIndicators(IocParam iocParam) {
        Indeicator indeicator = new Indeicator();
        List<JSONObject> objects = indeicator.getList();
        BuildingSpace buildingSpace = null;
        String floorCode = "";
        BuildingFloor floor = null;
        if(iocParam.getFloorId()==null){
            buildingSpace = buildingSpaceMapper.getSumByTier();
        }else{
            buildingSpace = buildingSpaceMapper.getByTier(iocParam);
            floorCode = iocParam.getFloorId()+"F";
            if(iocParam.getFloorId()<0){
                floorCode = "B"+Math.abs(iocParam.getFloorId());
            }
            floor = buildingFloorMapper.selectOne(new LambdaQueryWrapper<BuildingFloor>().eq(BuildingFloor::getCode,floorCode));
        }
        Integer result =0;
        Long totalStation = 0l;
        List<BuildingRoom> rooms = null;
        if(floor!=null){
            rooms = buildingRoomMapper.selectList(new LambdaQueryWrapper<BuildingRoom>().eq(BuildingRoom::getFloorId,floor.getId()));
        }else{
            if(iocParam.getFloorId()==null){
                rooms = buildingRoomMapper.selectList(null);
            }
        }
        if(rooms!=null&&rooms.size()>0){
            List<Integer> ids = rooms.stream().map(BuildingRoom::getId).collect(Collectors.toList());
            totalStation = buildingStationMapper.selectCount(new LambdaQueryWrapper<BuildingStation>().in(BuildingStation::getRoomId,ids));
            Long usedStation = buildingStationMapper.selectCount(new LambdaQueryWrapper<BuildingStation>().in(BuildingStation::getRoomId,ids)
                    .eq(BuildingStation::getStatus,2));
            // 创建一个数值格式化对象
            NumberFormat numberFormat = NumberFormat.getInstance();
            // 设置精确到小数点后2位
            numberFormat.setMaximumFractionDigits(0);
            if (totalStation>0) {
                result = Integer.parseInt(numberFormat.format((float) usedStation / (float) totalStation * 100));
            }
        }
        if (buildingSpace != null) {
            objects.get(0).put("value",result);
            objects.get(1).put("value", totalStation);
            objects.get(2).put("value", buildingSpace.getWorkArea());
            objects.get(3).put("value", buildingSpace.getMeetingArea());
            objects.add(new JSONObject());
            objects.get(4).put("value", buildingSpace.getOtherArea());
        } else {
            objects.get(0).put("value", result);
            objects.get(1).put("value", totalStation);
            objects.get(2).put("value", 0);
            objects.get(3).put("value", 0);
            objects.add(new JSONObject());
            objects.get(4).put("value", 0);
        }

        indeicator.setList(objects);
        return ReturnMsg.ok(indeicator);
    }

    @Override
    public ReturnMsg getAccessPersonnel(IocParam iocParam) {
        List<AccessSpace> list = accessSpaceMapper.getByTier(iocParam);
        return ReturnMsg.ok(list);
    }

    @Override
    public ReturnMsg getFloorList(IocParam iocParam) {
        List<BuildingSpace> list = buildingSpaceMapper.getListByTier(iocParam);
        List<Map<String, String>> lists = new ArrayList<>();
        for (BuildingSpace buildingSpace:list) {
                Map<String, String> map = new HashMap();
                map.put("floor",buildingSpace.getTier()+"");
                map.put("leader",buildingSpace.getLeadArea()+"");
                map.put("meeting",buildingSpace.getMeetingArea()+"");
                map.put("work",buildingSpace.getWorkArea()+"");
                map.put("print",buildingSpace.getPrintArea()+"");
                lists.add(map);
        }
        return ReturnMsg.ok(lists);
    }

    @Override
    public ReturnMsg getMeetingCoreIndicators(IocParam iocParam) {
        Indeicator indeicator = new Indeicator();
        List<JSONObject> objects = indeicator.getList();
        DecimalFormat decimalFormat = new DecimalFormat("#.0");
        ThreadLocalRandom random = ThreadLocalRandom.current();
        Double saturation = meetingMapper.getSaturationByFloorId(iocParam);
        Double used = meetingMapper.getUsedByFloorId(iocParam);
        Double cost = meetingMapper.getCostByFloorId(iocParam);
        Double person_cost = meetingMapper.getPersonCostByFloorId(iocParam);
        cost = Double.valueOf(decimalFormat.format(cost));
        person_cost = Double.valueOf(decimalFormat.format(person_cost));
        double compare = random.nextDouble(-1, 1);
        compare = Double.parseDouble(decimalFormat.format(compare));
        objects.get(0).put("value", Double.valueOf(decimalFormat.format(saturation)));
        objects.get(0).put("compare", compare);

        objects.get(1).put("value", Double.valueOf(decimalFormat.format(used)));
        objects.get(1).put("compare", compare);

        objects.get(2).put("value", cost);
        objects.get(2).put("compare", compare);

        objects.get(3).put("value", person_cost);
        objects.get(3).put("compare", compare);
        indeicator.setWorthAttention("饱和度良好");
        indeicator.setList(objects);
        return ReturnMsg.ok(indeicator);
    }


    @Override
    public ReturnMsg getConferenceRoomInfo(IocParam iocParam) {
        return null;
    }

    @Override
    public ReturnMsg getMeetingCostTrend(IocParam iocParam) {
        String[] param = {"shichang", "bangong", "chanpin", "zhihui", "yewu", "qita"};
        String startStr = iocParam.getTimeRange().getStartDate();
        String endStr = iocParam.getTimeRange().getEndDate();
        List<String> lists = DateUtil.getBetweenDays(startStr, endStr);
        String[] labKey = lists.toArray(new String[0]);
        List<Label> labels1 = GeneralMethod.getInstance().dataGeneration(param, labKey);
        return ReturnMsg.ok(labels1);
    }

    @Override
    public ReturnMsg getSpaceInfo(IocParam iocParam) {
        String[] param = {"administrativeArea", "leisureArea"};
        String startStr = iocParam.getTimeRange().getStartDate();
        String endStr = iocParam.getTimeRange().getEndDate();
        List<String> lists = DateUtil.getBetweenDays(startStr, endStr);
        String[] labKey = lists.toArray(new String[0]);
        List<Label> labels1 = GeneralMethod.getInstance().dataGeneration(param, labKey);
        return ReturnMsg.ok(labels1);
    }

    @Override
    public ReturnMsg getSpaceCoreIndicators(IocParam iocParam) {
        Indeicator indeicator = new Indeicator();
        List<JSONObject> objects = indeicator.getList();
        ThreadLocalRandom random = ThreadLocalRandom.current();
        DecimalFormat decimalFormat = new DecimalFormat("#.0");
        double result = 0;
        Long totalStation = buildingStationMapper.selectCount(new LambdaQueryWrapper<BuildingStation>().eq(BuildingStation::getIsDel,0));
        Long usedStation = buildingStationMapper.selectCount(new LambdaQueryWrapper<BuildingStation>().eq(BuildingStation::getIsDel,0).eq(BuildingStation::getStatus,2));
        result = MathUtils.division(usedStation,totalStation,2);
        Long flowStation = buildingStationMapper.selectCount(new LambdaQueryWrapper<BuildingStation>().eq(BuildingStation::getIsDel,0).eq(BuildingStation::getIsBlock,1));
        Long fixedStation = buildingStationMapper.selectCount(new LambdaQueryWrapper<BuildingStation>().eq(BuildingStation::getIsDel,0).eq(BuildingStation::getIsBlock,0));
        int meettingUsed = random.nextInt(10, 100);
        int playCount = random.nextInt(100, 500);
        int workCount = random.nextInt(300, 1000);
        while (playCount > workCount) {
            playCount = random.nextInt(100, 500);
        }
        float compare = (float) Math.random();
        compare = Float.parseFloat(decimalFormat.format(compare));

        objects.get(0).put("value", result);
        objects.get(0).put("compare", compare);

        objects.get(1).put("value", meettingUsed);
        objects.get(1).put("compare", compare);

        objects.get(2).put("value", flowStation);
        objects.get(2).put("compare", compare);

        objects.get(3).put("value", fixedStation);
        objects.get(3).put("compare", compare);
        objects.add(new JSONObject());
        objects.get(4).put("value", playCount + "/" + workCount);
        objects.get(4).put("compare", compare);

        indeicator.setWorthAttention("会议室使⽤率过低，建议考虑改变空间类型");
        indeicator.setList(objects);
        return ReturnMsg.ok(indeicator);
    }

    @Override
    public ReturnMsg getSpaceOverview() {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("total", 18);
        jsonObject.put("occupancy", 14);
        jsonObject.put("percentage", 0.77);

        JSONObject jsonObject2 = new JSONObject();
        jsonObject2.put("total", 274);
        jsonObject2.put("occupancy",160 );
        jsonObject2.put("percentage", 0.58);

        JSONObject jsonObject3 = new JSONObject();
        jsonObject3.put("total", 2440);
        jsonObject3.put("occupancy", 940);
        jsonObject3.put("percentage", 0.38);
        jsonArray.add(jsonObject);
        jsonArray.add(jsonObject2);
        jsonArray.add(jsonObject3);


        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("data", jsonArray);
        return ReturnMsg.ok(jsonObject1);
    }
}
