package com.usky.fire.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
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.exception.BusinessException;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.fire.domain.BaseCompany;
import com.usky.fire.domain.DemReportInfo;
import com.usky.fire.mapper.BaseCompanyMapper;
import com.usky.fire.mapper.DemReportInfoMapper;
import com.usky.fire.service.DemReportInfoService;
import com.usky.common.mybatis.core.AbstractCrudService;
import com.usky.fire.service.vo.CompanyDataVo;
import com.usky.fire.service.vo.DemReportInfoIdVo;
import com.usky.fire.service.vo.DemReportInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 报告信息表 服务实现类
 * </p>
 *
 * @author han
 * @since 2023-03-02
 */
@Slf4j
@Service
public class DemReportInfoServiceImpl extends AbstractCrudService<DemReportInfoMapper, DemReportInfo> implements DemReportInfoService {

    @Autowired
    private BaseCompanyMapper baseCompanyMapper;

    @Override
    public CommonPage<DemReportInfo> reportInfoList(String companyId, String sourceType, Integer pageNum, Integer pageSize) {
        IPage<DemReportInfo> page = new Page<>(pageNum, pageSize);

        String organization = null;
        try {
            organization = SecurityUtils.getLoginUser().getSysUser().getRemark();
        } catch (Exception e) {
            log.error("获取remake失败", e);
            return ToCommonPage(page);
        }

        if (StringUtils.isBlank(organization)) {
            throw new BusinessException("当前登录账号非消防重点单位，请联系管理员！");
        }

        LambdaQueryWrapper<BaseCompany> queryWrapper3 = Wrappers.lambdaQuery();
        queryWrapper3.select(BaseCompany::getCompanyId)
                .eq(BaseCompany::getOrganization, organization);
        String companyId1 = null;
        try {
            companyId1 = baseCompanyMapper.selectOne(queryWrapper3).getCompanyId();
        } catch (Exception e) {
            return ToCommonPage(page);
        }

        if (StringUtils.isBlank(companyId)) {
            companyId = companyId1;
        }

        LambdaQueryWrapper<DemReportInfo> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(DemReportInfo::getCompanyId, companyId);
        if ("2".equals(sourceType)) {
            queryWrapper.eq(DemReportInfo::getReportStatus, 1)
                    .orderByDesc(DemReportInfo::getId);
        } else {
            queryWrapper.orderByDesc(DemReportInfo::getId);
        }
        page = this.page(page, queryWrapper);

        return ToCommonPage(page);
    }

    @Override
    public List<DemReportInfoVo> reportInfoAdd(DemReportInfoVo demReportInfoVo) {
        List<DemReportInfoVo> list = new ArrayList<>();
        List<CompanyDataVo> companyList = demReportInfoVo.getCompanyList();
        Calendar now = Calendar.getInstance();
        if (CollectionUtils.isNotEmpty(companyList)) {
            List<String> companyIdList = new ArrayList<>();
            for (int i = 0; i < companyList.size(); i++) {
                companyIdList.add(companyList.get(i).getCompanyId());
            }
            List<DemReportInfo> list2 = new ArrayList<>();
            LambdaQueryWrapper<DemReportInfo> queryWrapper1 = Wrappers.lambdaQuery();
            queryWrapper1.select(DemReportInfo::getId, DemReportInfo::getCompanyId)
                    .in(DemReportInfo::getCompanyId, companyIdList)
                    .eq(DemReportInfo::getStatisticsTime, now.get(Calendar.YEAR) + "-" + now.get(Calendar.MONTH)).groupBy(DemReportInfo::getCompanyId);
            list2 = this.list(queryWrapper1);
            for (int i = 0; i < companyList.size(); i++) {
                for (int j = 0; j < list2.size(); j++) {
                    if (companyList.get(i).getCompanyId().equals(list2.get(j).getCompanyId())) {
                        DemReportInfoVo demReportInfoVo1 = new DemReportInfoVo();
                        demReportInfoVo1.setId(list2.get(j).getId());
                        demReportInfoVo1.setCompanyName(companyList.get(i).getCompanyName());
                        demReportInfoVo1.setCompanyId(companyList.get(i).getCompanyId());
                        list.add(demReportInfoVo1);
                    }
                }
            }
        }
        return list;
    }

    @Transactional
    @Override
    public void propelsReport(DemReportInfoIdVo demReportInfoIdVo) {
        List<Integer> reportInfoIdList = demReportInfoIdVo.getReportIdList();
        if (CollectionUtils.isNotEmpty(reportInfoIdList)) {
            for (int i = 0; i < reportInfoIdList.size(); i++) {
                DemReportInfo demReportInfo = new DemReportInfo();
                demReportInfo.setId(reportInfoIdList.get(i));
                demReportInfo.setReportStatus(1);
                demReportInfo.setSendTime(LocalDateTime.now());
                this.updateById(demReportInfo);
            }
        }
    }

    @Override
    public List<DemReportInfo> reportById(Integer id) {
        LambdaQueryWrapper<DemReportInfo> queryWrapper1 = Wrappers.lambdaQuery();
        queryWrapper1.select(DemReportInfo::getId, DemReportInfo::getReportPath)
                .eq(DemReportInfo::getId, id);
        List<DemReportInfo> list2 = this.list(queryWrapper1);
        return list2;
    }

    @Override
    public void updateReadStatus(Integer id) {
        String remark = null;
        try {
            remark = SecurityUtils.getLoginUser().getSysUser().getRemark();
        } catch (NullPointerException e) {
            log.error("获取remake失败", e);
            return;
        }

        String companyId = null;
        LambdaQueryWrapper<BaseCompany> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.select(BaseCompany::getCompanyId)
                .eq(BaseCompany::getOrganization, remark);
        BaseCompany baseCompany = baseCompanyMapper.selectOne(queryWrapper);
        if (baseCompany != null) {
            companyId = baseCompany.getCompanyId();
        } else {
            log.warn("未查询到与组织[{}]匹配的公司信息", remark);
            return;
        }

        DemReportInfo report = this.getOne(Wrappers.<DemReportInfo>lambdaQuery()
                .eq(DemReportInfo::getId, id));
        if (report == null) {
            log.warn("报告ID[{}]不存在，无法更新已读状态", id);
            return;
        }

        String reportCompanyId = report.getCompanyId();
        if (!Objects.equals(reportCompanyId, companyId)) {
            log.warn("报告ID[{}]所属公司[{}]与当前用户公司[{}]不匹配，无权限更新",
                    id, reportCompanyId, companyId);
            return;
        }

        if (report.getIsRead() == 0) {
            report.setReadTime(LocalDateTime.now());
            report.setIsRead(1);
            this.updateById(report);
            log.info("报告ID[{}]已更新为已读状态", id);
        } else {
            log.info("报告ID[{}]非第一次阅读，无需更新", id);
        }
    }
}
