package com.yeejoin.amos.boot.module.ymt.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.module.ymt.api.dto.AlertMsgDto;
import com.yeejoin.amos.boot.module.ymt.api.dto.AlertPaperInfoDto;
import com.yeejoin.amos.boot.module.ymt.api.dto.KV;
import com.yeejoin.amos.boot.module.ymt.api.dto.MsgLogDto;
import com.yeejoin.amos.boot.module.ymt.api.entity.MsgLog;
import com.yeejoin.amos.boot.module.ymt.api.enums.TerminalTypeEnum;
import com.yeejoin.amos.boot.module.ymt.api.mapper.MsgLogMapper;
import com.yeejoin.amos.boot.module.ymt.api.service.IMsgLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;

import java.util.LinkedList;
import java.util.List;

/**
 * 消息流水表服务实现类
 *
 * @author system_generator
 * @date 2022-04-20
 */
@Service
public class MsgLogServiceImpl extends BaseService<MsgLogDto, MsgLog, MsgLogMapper> implements IMsgLogService {

    Logger logger = LoggerFactory.getLogger(MsgLogServiceImpl.class);

    @Autowired
    AlertCalledServiceImpl alertCalledService;

    @Autowired
    TzsCitInfoServiceImpl citInfoService;

    /**
     * 分页查询
     */
    public Page<MsgLogDto> queryForMsgLogPage(Page<MsgLogDto> page) {
        return this.queryForPage(page, null, false);
    }

    /**
     * 列表查询 示例
     */
    public List<MsgLogDto> queryForMsgLogList() {
        return this.queryForList("", false);
    }

    public List<MsgLogDto> queryForWebMsgLogList(String terminalType) {
        return this.queryForList("", false, terminalType);
    }

    public List<AlertMsgDto> queryForAlertMsg(List<String> regionCodes) {
        List<AlertMsgDto> alertMsgDtoList = Lists.newArrayList();
        // 查询电梯警情预报消息
        List<AlertPaperInfoDto> alertPaperInfoDtoList = alertCalledService.getAlertPaperInfoList(alertCalledService.authRegionCodeList(regionCodes), false);
        if (!ValidationUtil.isEmpty(alertPaperInfoDtoList)) {
            alertPaperInfoDtoList.forEach(msg -> {
                AlertMsgDto alertMsgDto = new AlertMsgDto();
                alertMsgDto.setBody(msg.getAddress() + "发生" + msg.getAlarmType() + "事件");
                alertMsgDto.setFrom("elevator");
                alertMsgDto.setRelationId(String.valueOf(msg.getAlertId()));
                alertMsgDto.setTime(msg.getCallTime());
                alertMsgDto.setType(msg.getAlarmType());

                alertMsgDtoList.add(alertMsgDto);
            });
        }
//        // 查询气瓶预警消息
//        LambdaQueryWrapper<MsgLog> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(MsgLog::getTerminalType, "WEB");
//        //企业根据企业名称筛选，监管机构根据区域筛选
//        ReginParams reginParams = citInfoService.getReginParams();
//        if(!"company".equals(reginParams.getCompany().getLevel())){
//            wrapper.like(MsgLog::getRegionCode,reginParams.getCompany().getRegionCode());
//        } else {
//            wrapper.eq(MsgLog::getCompanyName,reginParams.getCompany().getCompanyName());
//        }
//        List<MsgLog> msgLogList = this.list(wrapper);
//        if (!ValidationUtil.isEmpty(msgLogList)) {
//            msgLogList.forEach(msg -> {
//                AlertMsgDto alertMsgDto = new AlertMsgDto();
//                alertMsgDto.setBody(msg.getBody());
//                alertMsgDto.setFrom("cylinder");
//                alertMsgDto.setRelationId(String.valueOf(msg.getSequenceNbr()));
//                alertMsgDto.setTime(msg.getSendTime());
//                alertMsgDto.setType(msg.getMsgTypeName());
//
//                alertMsgDtoList.add(alertMsgDto);
//            });
//        }
        return alertMsgDtoList;
    }

    public Integer countByTerminalType(String terminalType) {
        return this.list(new LambdaQueryWrapper<MsgLog>().eq(StringUtils.hasText(terminalType), MsgLog::getTerminalType, terminalType)).size();
    }

    public Page<MsgLogDto> queryForMsgLogByTerminalTypePage(Page<MsgLogDto> page, String terminalType, Boolean isRead, String sendTimeStart, String sendTimeEnd, String msgType, String body) {
        Page<MsgLog> msgLogPage = new Page<>(page.getCurrent(), page.getSize());
        LambdaQueryWrapper<MsgLog> wrapper = new LambdaQueryWrapper<>();
        //企业根据企业名称筛选，监管机构根据区域筛选
        ReginParams reginParams = citInfoService.getReginParams();
        if(!"company".equals(reginParams.getCompany().getLevel())){
            wrapper.like(MsgLog::getRegionCode,reginParams.getCompany().getRegionCode());
        } else {
          wrapper.eq(MsgLog::getCompanyName,reginParams.getCompany().getCompanyName());
        }

        if (!StringUtils.hasText(terminalType)) {
            terminalType = TerminalTypeEnum.TERMINAL_TYPE_WEB.getCode();
        }
        wrapper.eq(MsgLog::getTerminalType, terminalType);
//        wrapper.eq(isRead != null, MsgLog::getIsRead, isRead);
        wrapper.ge(StringUtils.hasText(sendTimeStart), MsgLog::getSendTime, sendTimeStart);
        wrapper.le(StringUtils.hasText(sendTimeEnd), MsgLog::getSendTime, sendTimeEnd);
        wrapper.eq(StringUtils.hasText(msgType), MsgLog::getMsgType, msgType);
        wrapper.eq(MsgLog::getIsDelete, 0);
        wrapper.orderByDesc(MsgLog::getSendTime);
        wrapper.like(StringUtils.hasText(body), MsgLog::getBody, body);
        page(msgLogPage, wrapper);
        LinkedList<MsgLogDto> msgLogDtos = new LinkedList<>();
        for (MsgLog record : msgLogPage.getRecords()) {
            MsgLogDto msgLogDto = new MsgLogDto();
            BeanUtils.copyProperties(record, msgLogDto);
            msgLogDtos.add(msgLogDto);
        }
        page.setRecords(msgLogDtos);
        return page;
    }

    public List<KV> getType() {
        return getBaseMapper().getMsgType();
    }

    public boolean allRead() {
        LambdaUpdateWrapper<MsgLog> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(MsgLog::getIsRead, 0).set(MsgLog::getIsRead, 1);
        return update(wrapper);
    }

    public boolean deleteByIds(List<Long> longs) {
        LambdaUpdateWrapper<MsgLog> wrapper = new LambdaUpdateWrapper<>();
        wrapper.in(MsgLog::getSequenceNbr, longs).set(MsgLog::getIsDelete, 1);
        return update(wrapper);
    }

}
