package com.usky.fire.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usky.common.core.bean.CommonPage;
import com.usky.common.core.util.HttpUtils;
import com.usky.common.core.util.StringUtils;
import com.usky.common.mybatis.core.AbstractCrudService;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.fire.domain.BaseUserCompany;
import com.usky.fire.domain.MhPostInspect;
import com.usky.fire.mapper.MhPostInspectMapper;
import com.usky.fire.service.BaseUserCompanyService;
import com.usky.fire.service.MhPostInspectService;
import com.usky.fire.service.config.webScoket.WsSessionManager;
import com.usky.fire.service.util.OnlineMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;

/**
 * <p>
 * 查岗信息 服务实现类
 * </p>
 *
 * @author JCB
 * @since 2022-08-24
 */
@Service
public class MhPostInspectServiceImpl extends AbstractCrudService<MhPostInspectMapper, MhPostInspect> implements MhPostInspectService {

    @Autowired
    private BaseUserCompanyService baseUserCompanyService;

    @Override
    public CommonPage<MhPostInspect> postInspectRecordList(String companyId, Integer pageNum, Integer pageSize) {
        IPage<MhPostInspect> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<MhPostInspect> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.select(MhPostInspect::getId, MhPostInspect::getInspectStatus, MhPostInspect::getInspectTime,
                MhPostInspect::getSpentTime, MhPostInspect::getReplyTime)
                .eq(MhPostInspect::getCompanyId, companyId)
                .orderByDesc(MhPostInspect::getId);
        page = this.page(page, queryWrapper);
        if (page.getTotal() > 0) {
            for (int i = 0; i < page.getRecords().size(); i++) {
                if (page.getRecords().get(i).getInspectStatus() == 1) {
                    page.getRecords().get(i).setInspectStatusName("已响应");
                    String spentDate = String.format("%0" + 2 + "d", page.getRecords().get(i).getSpentTime() / 60) + ":" + String.format("%0" + 2 + "d", page.getRecords().get(i).getSpentTime() % 60);
//                    String spentDate = page.getRecords().get(i).getSpentTime() / 60 + ":" + page.getRecords().get(i).getSpentTime() % 60;
                    page.getRecords().get(i).setSpentDate(spentDate);
                } else {
                    //查岗时间与当前时间差
                    long data1 = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
                    long data2 = page.getRecords().get(i).getInspectTime().toEpochSecond(ZoneOffset.of("+8"));
                    long time = data1 - data2;
                    if (time < 600) {
                        page.getRecords().get(i).setInspectStatusName("等待响应");
                        page.getRecords().get(i).setCountdown(600 - time);
                    } else {
                        page.getRecords().get(i).setInspectStatusName("离岗");
                        page.getRecords().get(i).setSpentDate("超时未响应");
                    }
                }
            }
        }
        return new CommonPage<>(page.getRecords(), page.getTotal(), pageSize, pageNum);
    }

    @Override
    public Map<String, Object> postInspectRecordStatistics(String companyId) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String spentTime = "--:--";
        Integer answeredCount = 0;
        Integer notAnsweredCount = 0;
        Integer count = 0;
        Date date = new Date();
        String startTime = OnlineMethod.getDateTime(date, 7);
        String endTime = format.format(date);
        if (StringUtils.isNotBlank(companyId)) {
            Integer spentTimeAvg = baseMapper.mhPostInspectStatistics(" AVG(spent_time) ", 1, startTime, endTime, null, companyId);
            if (spentTimeAvg == null) {
                spentTimeAvg = 0;
            }
            answeredCount = baseMapper.mhPostInspectStatistics(" count(*) ", 1, startTime, endTime, null, companyId);
            notAnsweredCount = baseMapper.mhPostInspectStatistics(" count(*) ", 0, startTime, endTime, null, companyId);
            count = answeredCount + notAnsweredCount;

            spentTime = String.format("%0" + 2 + "d", spentTimeAvg / 60) + ":" + String.format("%0" + 2 + "d", spentTimeAvg % 60);
//            spentTime = spentTimeAvg / 60 + ":" + spentTimeAvg % 60;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("spentTimeAvg", spentTime);
        map.put("count", count);
        map.put("answeredCount", answeredCount);
        map.put("notAnsweredCount", notAnsweredCount);
        return map;
    }

    @Override
    @Transactional
    public MhPostInspect postInspectPush(MhPostInspect mhPostInspect) {
        mhPostInspect.setInspectCode(UUID.randomUUID().toString().replaceAll("-", ""));
        mhPostInspect.setInspectTime(LocalDateTime.now());
        mhPostInspect.setInspectStatus(0);
        mhPostInspect.setCreator(SecurityUtils.getUsername());
        mhPostInspect.setCreateTime(LocalDateTime.now());
        this.save(mhPostInspect);
        //查岗时间与当前时间差
        long data1 = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
        long data2 = mhPostInspect.getInspectTime().toEpochSecond(ZoneOffset.of("+8"));
        long time = data1 - data2;
        mhPostInspect.setCountdown(600 - time);
        String message = JSONObject.toJSONString(mhPostInspect);
        List<BaseUserCompany> userCompanyList = baseUserCompanyService.userCompanyList(mhPostInspect.getCompanyId());
        for (int i = 0; i < userCompanyList.size(); i++) {
            this.webSocketPush(new TextMessage(message), userCompanyList.get(i).getUserId());
        }
        return mhPostInspect;
    }


    @Override
    public void webSocketPush(final TextMessage message, Integer userId) {
        Set<Map.Entry<String, WebSocketSession>> entrySet = WsSessionManager.SESSION_POOL.entrySet();
        for (Map.Entry<String, WebSocketSession> entry : entrySet) {
            String[] split = entry.getKey().split("-");
            String url = String.valueOf(entry.getValue().getUri());
            String userId1 = OnlineMethod.getFieldValue(url, "userId").replaceAll(" ", "");
            Integer userId2 = Integer.parseInt(userId1);
            if (userId == userId2) {
                final WebSocketSession webSocketSession = entry.getValue();
                //判断连接是否仍然打开的
                if (webSocketSession.isOpen()) {
                    //开启多线程发送消息（效率高）
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                if (webSocketSession.isOpen()) {
                                    webSocketSession.sendMessage(message);
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();

                }
            }
        }
    }

    @Override
    public void postInspectAnswerRequest() {
        String url = "http://172.16.120.165:13200/prod-api/service-fire/postInspect/postInspectAnswerRecept";
        String res = null;
        try {
            res = HttpUtils.get(url, null);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (StringUtils.isNotBlank(res)) {
            JSONObject jsonObj = JSONObject.parseObject(res);
            String userStr = jsonObj.getString("data");
            if (StringUtils.isNotBlank(userStr) && !userStr.equals("[]")) {
                List<MhPostInspect> mhPostInspectList = JSON.parseArray(userStr, MhPostInspect.class);
                for (int i = 0; i < mhPostInspectList.size(); i++) {
                    this.updateById(mhPostInspectList.get(i));
                }
            }
        }
    }
}
