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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.ioc.config.RestTemplateConfig;
import com.sky.ioc.entity.Cake;
import com.sky.ioc.entity.Indeicator;
import com.sky.ioc.entity.Label;
import com.sky.ioc.entity.domain.meeting.MeetingRecord;
import com.sky.ioc.entity.params.IocParam;
import com.sky.ioc.entity.params.IocTimeRange;
import com.sky.ioc.mapper.job.TokenMapper;
import com.sky.ioc.mapper.meeting.MeetingRecordMapper;
import com.sky.ioc.service.meeting.MeetingRecordService;
import com.sky.ioc.tool.DateUtil;
import com.sky.ioc.tool.MathUtils;
import com.sky.ioc.tool.ReturnMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

@Service
@Slf4j
public class MeetingRecordServiceImpl implements MeetingRecordService {

    @Resource
    private MeetingRecordMapper meetingRecordMapper;

    @Autowired
    TokenMapper tokenMapper;

    @Autowired
    RestTemplateConfig restTemplateConfig;

    final static  String MEETTING_RECORD_URL="/api/meeting/MEETING/record/list?pageNum=1&pageSize=1000";

    @Override
    public Map queryMeetingTreeList(IocParam iocParam) {
        LambdaQueryWrapper<MeetingRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ge(MeetingRecord::getStartTime, iocParam.getTimeRange().getStartDate());
        queryWrapper.le(MeetingRecord::getEndTime, iocParam.getTimeRange().getEndDate());
        List<MeetingRecord> meetingRecords = meetingRecordMapper.selectList(queryWrapper);
        Map collect = meetingRecords.stream().collect(Collectors.groupingBy(MeetingRecord::getFloor));
        for (Object key : collect.keySet()) {
            List<MeetingRecord> records = (List<MeetingRecord>) collect.get(key);
            Map<Integer, List<MeetingRecord>> map = records.stream().collect(Collectors.groupingBy(MeetingRecord::getRoomId));
            collect.put(key, map);
        }
        return collect;
    }

    @Override
    public List<MeetingRecord> queryMeetingList(IocParam iocParam) {
        LambdaQueryWrapper<MeetingRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ge(MeetingRecord::getStartTime, iocParam.getTimeRange().getStartDate());
        queryWrapper.le(MeetingRecord::getEndTime, iocParam.getTimeRange().getEndDate());
        List<MeetingRecord> meetingRecords = meetingRecordMapper.selectList(queryWrapper);
        return meetingRecords;
    }

    @Override
    public ReturnMsg getMeetingRecordList() {
        // 创建RestTemplate
        RestTemplate restTemplate = restTemplateConfig.build();
        // 发送GET请求
        String url = restTemplateConfig.addBaseUrl(MEETTING_RECORD_URL);
        ResponseEntity<Map> responseEntity = restTemplate.getForEntity(url, Map.class);
        // 获取响应对象里的 body 对象
        Map<String, Object> body = responseEntity.getBody();
        // 获取状态码
        Integer code = (Integer)body.get("code");
        // 获取响应信息
        String message = (String)body.get("msg");
        ThreadLocalRandom random = ThreadLocalRandom.current();
        if(code==200){
            ArrayList list = (ArrayList) body.get("rows");
            if(list!=null&&list.size()>0){
                meetingRecordMapper.delete(null);
                for (int i=0;i<list.size();i++){
                    LinkedHashMap json = (LinkedHashMap) list.get(i);
                    MeetingRecord meetingRecord = new MeetingRecord();
                    meetingRecord.setId((Integer) json.get("id"));
                    meetingRecord.setSubject((String) json.get("title"));
                    meetingRecord.setRoomId(Integer.parseInt(json.get("meetingRoomId").toString()));
                    String meetingDate = (String) json.get("meetingDate");
                    meetingRecord.setStartTime(meetingDate+" "+json.get("startTime"));
                    meetingRecord.setEndTime(meetingDate+" "+json.get("endTime"));
                    Long minutes = DateUtil.minutesBetween(meetingDate+" "+json.get("startTime"),meetingDate+" "+json.get("endTime"));
                    meetingRecord.setMinutes(minutes);
                    Integer personNum = random.nextInt(3,40);
                    meetingRecord.setPersonNum(personNum);
                    meetingRecord.setBookPerson((String) json.get("bookPerson"));
                    meetingRecord.setBookPhone((String) json.get("bookPhone"));
                    meetingRecordMapper.insert(meetingRecord);
                }
            }
            return ReturnMsg.ok();

        }else{
            log.info("获取会议记录数据："+message);
            return  ReturnMsg.fail(message);
        }

    }

    @Override
    public ReturnMsg getMeetingRecordTotal(IocTimeRange timeRange) {
        Indeicator indeicator = new Indeicator();
        List<JSONObject> objects = new ArrayList<>();
        objects.add(new JSONObject());
        objects.add(new JSONObject());
        objects.add(new JSONObject());
        objects.add(new JSONObject());
        objects.add(new JSONObject());
        objects.add(new JSONObject());
        Integer days = DateUtil.daysBetween(timeRange.getStartDate(),timeRange.getEndDate());
        //总会议数
        Long totalMeeting = meetingRecordMapper.countByTime(timeRange);
        //总会议人次
        Long totalPerson = meetingRecordMapper.totalPersonByTime(timeRange);
        //总会议时长
        Long totalMinutes = meetingRecordMapper.totalMinutesByTime(timeRange);
        double avgMeeting = MathUtils.division(totalMeeting,days,2);
        double avgPerson = MathUtils.division(totalMeeting,totalPerson,2);
        double avgMinutes = MathUtils.division(totalMinutes,totalMeeting,2);
        objects.get(0).put("value", totalMeeting);
        objects.get(1).put("value", avgMeeting);
        objects.get(2).put("value", totalPerson);
        objects.get(3).put("value", avgPerson);
        objects.get(4).put("value", totalMinutes);
        objects.get(5).put("value", avgMinutes);
        indeicator.setList(objects);
        return ReturnMsg.ok(indeicator);
    }

    /**
     * 统计总次数
     * */
    @Override
    public ReturnMsg getMeetingAnalysissTimes(IocTimeRange iocTimeRange) {
        String[] param = {"times"};
        String startStr = iocTimeRange.getStartDate();
        String endStr = iocTimeRange.getEndDate();
        List<String> list = DateUtil.getBetweenDays(startStr, endStr);
        String[] labKey = list.toArray(new String[0]);
        List<Label> labels1 = new ArrayList<>();
        for (int i = 0; i < labKey.length; i++) {
            Label label = new Label();
            JSONObject jsonObject = new JSONObject();
            IocTimeRange iocTimeRange1 = new IocTimeRange();
            iocTimeRange1.setStartDate(labKey[i]+" 00:00:00");
            iocTimeRange1.setEndDate(labKey[i]+" 23:59:00");
            long times = meetingRecordMapper.countByTime(iocTimeRange1);
            jsonObject.put(param[0],times);
            label.setJsonObject(jsonObject);
            label.setLabel(labKey[i]);
            labels1.add(label);
        }
        return ReturnMsg.ok(labels1);
    }
    /**
     * 统计总人次
     * */
    @Override
    public ReturnMsg getMeetingAnalysissPerson(IocTimeRange iocTimeRange) {
        String[] param = {"person"};
        String startStr = iocTimeRange.getStartDate();
        String endStr = iocTimeRange.getEndDate();
        List<String> list = DateUtil.getBetweenDays(startStr, endStr);
        String[] labKey = list.toArray(new String[0]);
        List<Label> labels1 = new ArrayList<>();
        for (int i = 0; i < labKey.length; i++) {
            Label label = new Label();
            JSONObject jsonObject = new JSONObject();
            IocTimeRange iocTimeRange1 = new IocTimeRange();
            iocTimeRange1.setStartDate(labKey[i]+" 00:00:00");
            iocTimeRange1.setEndDate(labKey[i]+" 23:59:00");
            long person = meetingRecordMapper.totalPersonByTime(iocTimeRange1);
            jsonObject.put(param[0],person);
            label.setJsonObject(jsonObject);
            label.setLabel(labKey[i]);
            labels1.add(label);
        }
        return ReturnMsg.ok(labels1);
    }
    /**
     * 统计总时长
     * */
    @Override
    public ReturnMsg getMeetingAnalysissMinutes(IocTimeRange iocTimeRange) {
        String[] param = {"minutes"};
        String startStr = iocTimeRange.getStartDate();
        String endStr = iocTimeRange.getEndDate();
        List<String> list = DateUtil.getBetweenDays(startStr, endStr);
        String[] labKey = list.toArray(new String[0]);
        List<Label> labels1 = new ArrayList<>();
        for (int i = 0; i < labKey.length; i++) {
            Label label = new Label();
            JSONObject jsonObject = new JSONObject();
            IocTimeRange iocTimeRange1 = new IocTimeRange();
            iocTimeRange1.setStartDate(labKey[i]+" 00:00:00");
            iocTimeRange1.setEndDate(labKey[i]+" 23:59:00");
            long minutes = meetingRecordMapper.totalMinutesByTime(iocTimeRange1);
            jsonObject.put(param[0],minutes);
            label.setJsonObject(jsonObject);
            label.setLabel(labKey[i]);
            labels1.add(label);
        }
        return ReturnMsg.ok(labels1);
    }

    @Override
    public ReturnMsg getMeetingCakeMinutes(IocTimeRange iocTimeRange) {
        List<Cake> lists = new ArrayList<>();
        Cake cake30 = new Cake();
        Cake cake60 = new Cake();
        Cake cake90 = new Cake();
        Cake cake120 = new Cake();
        Cake cake150 = new Cake();
        Cake cake180 = new Cake();
        cake30.setName("30分钟以内");
        cake60.setName("30-60分钟");
        cake90.setName("60-90分钟");
        cake120.setName("90-120分钟");
        cake150.setName("120-150分钟");
        cake180.setName("150分钟以上");
        Long minutes30 = meetingRecordMapper.selectCount(new LambdaQueryWrapper<MeetingRecord>()
                .lt(MeetingRecord::getMinutes,30));
        Long minutes60 = meetingRecordMapper.selectCount(new LambdaQueryWrapper<MeetingRecord>()
                .ge(MeetingRecord::getMinutes,30)
                .lt(MeetingRecord::getMinutes,60));
        Long minutes90 = meetingRecordMapper.selectCount(new LambdaQueryWrapper<MeetingRecord>()
                .ge(MeetingRecord::getMinutes,60).lt(MeetingRecord::getMinutes,90));
        Long minutes120 = meetingRecordMapper.selectCount(new LambdaQueryWrapper<MeetingRecord>()
                .ge(MeetingRecord::getMinutes,90).lt(MeetingRecord::getMinutes,120));
        Long minutes150 = meetingRecordMapper.selectCount(new LambdaQueryWrapper<MeetingRecord>()
                .ge(MeetingRecord::getMinutes,120).lt(MeetingRecord::getMinutes,150));
        Long minutes180 = meetingRecordMapper.selectCount(new LambdaQueryWrapper<MeetingRecord>()
                .ge(MeetingRecord::getMinutes,150));
        cake30.setValue(minutes30);
        cake60.setValue(minutes60);
        cake90.setValue(minutes90);
        cake120.setValue(minutes120);
        cake150.setValue(minutes150);
        cake180.setValue(minutes180);
        lists.add(cake30);
        lists.add(cake60);
        lists.add(cake90);
        lists.add(cake120);
        lists.add(cake150);
        lists.add(cake180);
        return ReturnMsg.ok(lists);
    }

    @Override
    public ReturnMsg getMeetingCakePerson(IocTimeRange iocTimeRange) {
        List<Cake> lists = new ArrayList<>();
        Cake cake4 = new Cake();
        Cake cake8 = new Cake();
        Cake cake12 = new Cake();
        Cake cake16 = new Cake();
        Cake cake20 = new Cake();
        Cake cakeMore = new Cake();
        cake4.setName("4人以内");
        cake8.setName("4-8人");
        cake12.setName("8-12人");
        cake16.setName("12-16人");
        cake20.setName("16-20人");
        cakeMore.setName("20人以上");
        Long person4 = meetingRecordMapper.selectCount(new LambdaQueryWrapper<MeetingRecord>()
                .lt(MeetingRecord::getPersonNum,4));
        Long person8 = meetingRecordMapper.selectCount(new LambdaQueryWrapper<MeetingRecord>()
                .ge(MeetingRecord::getPersonNum,4)
                .lt(MeetingRecord::getPersonNum,8));
        Long person12 = meetingRecordMapper.selectCount(new LambdaQueryWrapper<MeetingRecord>()
                .ge(MeetingRecord::getPersonNum,8).lt(MeetingRecord::getPersonNum,12));
        Long person16 = meetingRecordMapper.selectCount(new LambdaQueryWrapper<MeetingRecord>()
                .ge(MeetingRecord::getPersonNum,12).lt(MeetingRecord::getPersonNum,16));
        Long person20 = meetingRecordMapper.selectCount(new LambdaQueryWrapper<MeetingRecord>()
                .ge(MeetingRecord::getPersonNum,16).lt(MeetingRecord::getPersonNum,20));
        Long personMore = meetingRecordMapper.selectCount(new LambdaQueryWrapper<MeetingRecord>()
                .ge(MeetingRecord::getPersonNum,20));
        cake4.setValue(person4);
        cake8.setValue(person8);
        cake12.setValue(person12);
        cake16.setValue(person16);
        cake20.setValue(person20);
        cakeMore.setValue(personMore);
        lists.add(cake4);
        lists.add(cake8);
        lists.add(cake12);
        lists.add(cake16);
        lists.add(cake20);
        lists.add(cakeMore);
        return ReturnMsg.ok(lists);
    }
}
