package com.ningdatech.carapi.safe.manage;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ningdatech.basic.model.PageVo;
import com.ningdatech.basic.util.CollUtils;
import com.ningdatech.carapi.common.aop.BuildChildrenRegionWrapper;
import com.ningdatech.carapi.common.constant.UserRoleTypeEnum;
import com.ningdatech.carapi.common.contants.DefValConstants;
import com.ningdatech.carapi.common.util.CodeUtil;
import com.ningdatech.carapi.datascope.aop.LambdaDataScope;
import com.ningdatech.carapi.safe.entity.NdSecurityAdvisory;
import com.ningdatech.carapi.safe.entity.NdSecurityNoticeSaveReq;
import com.ningdatech.carapi.safe.model.dto.SecurityAdvisoryPageQuery;
import com.ningdatech.carapi.safe.model.vo.NdSecurityAdvisoryVO;
import com.ningdatech.carapi.safe.service.INdSecurityAdvisoryService;
import com.ningdatech.carapi.sys.helper.RegionsCacheHelper;
import com.ningdatech.carapi.user.security.auth.model.UserInfoDetails;
import com.ningdatech.carapi.user.util.LoginUserUtil;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author CMM
 * @description
 * @since 2022/11/16 16:00
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class SecurityAdvisoryManage {
    private final INdSecurityAdvisoryService ndSecurityAdvisoryService;
    private final RegionsCacheHelper regionsCacheHelper;

    public PageVo<NdSecurityAdvisoryVO> buildWrapper(SecurityAdvisoryPageQuery securityAdvisoryPageQuery) {
        // Page<NdSecurityAdvisory> page = securityAdvisoryPageQuery.page();

        UserInfoDetails userInfoDetails = LoginUserUtil.loginUserDetail();
        Long roleId = userInfoDetails.getRoleId();

        Integer pageNumber = securityAdvisoryPageQuery.getPageNumber();
        Integer pageSize = securityAdvisoryPageQuery.getPageSize();
        LambdaQueryWrapper<NdSecurityAdvisory> wrapper = Wrappers.lambdaQuery(NdSecurityAdvisory.class);
        // SecurityAdvisoryManage context = (SecurityAdvisoryManage) AopContext.currentProxy();
        List<NdSecurityAdvisory> securityAdvisoryList =
            ndSecurityAdvisoryService.dataScopeList(wrapper, securityAdvisoryPageQuery);
        // 省里上传的文件，下级账号也要能看到
        if (!UserRoleTypeEnum.SYSTEM_ADMIN_ROLE_ID.getId().equals(roleId)) {
            List<NdSecurityAdvisory> securityAdvisories = ndSecurityAdvisoryService
                    .list(Wrappers.lambdaQuery(NdSecurityAdvisory.class).isNotNull(NdSecurityAdvisory::getRegionId)
                            .eq(NdSecurityAdvisory::getRegionId, DefValConstants.ZJREGION_ID)
                            .eq(Objects.nonNull(securityAdvisoryPageQuery.getAdvisoryDate()),NdSecurityAdvisory::getAdvisoryDate,
                                    securityAdvisoryPageQuery.getAdvisoryDate()));
            securityAdvisoryList.addAll(securityAdvisories);
        }

        if (CollUtil.isEmpty(securityAdvisoryList)) {
            return PageVo.empty();
        }

        List<NdSecurityAdvisory> records = securityAdvisoryList.stream()
                .skip((long)(pageNumber - 1) * pageSize)
                .limit(pageSize).collect(Collectors.toList());

        // context.searAdvisory(page, wrapper, securityAdvisoryPageQuery);

        List<NdSecurityAdvisoryVO> data = CollUtils.convert(records, e -> {
            NdSecurityAdvisoryVO vo = BeanUtil.copyProperties(e, NdSecurityAdvisoryVO.class);
            CodeUtil.searchRegionName(vo);
            return vo;
        });
        return PageVo.of(data, securityAdvisoryList.size());
    }

    @LambdaDataScope(wrapperIndex = 1)
    @BuildChildrenRegionWrapper(wrapperIndex = 1, entityIndex = 2)
    public void searAdvisory(Page<NdSecurityAdvisory> page, LambdaQueryWrapper<NdSecurityAdvisory> wrapper,
        SecurityAdvisoryPageQuery securityAdvisoryPageQuery) {
        LocalDateTime time = securityAdvisoryPageQuery.getAdvisoryDate();
        if (Objects.nonNull(time)) {
            wrapper.ge(NdSecurityAdvisory::getAdvisoryDate, time).lt(NdSecurityAdvisory::getAdvisoryDate,
                time.plusMonths(1));
        }
        wrapper.orderBy(Boolean.TRUE, Boolean.FALSE, NdSecurityAdvisory::getAdvisoryDate);
        ndSecurityAdvisoryService.page(page, wrapper);
    }

    public void saveSecurityNotice(NdSecurityNoticeSaveReq req) {
        NdSecurityAdvisory ndSecurityAdvisory = BeanUtil.copyProperties(req, NdSecurityAdvisory.class);
        ndSecurityAdvisory.setCreateBy(LoginUserUtil.getUserId());
        ndSecurityAdvisory.setCreateOn(LocalDateTime.now());
        ndSecurityAdvisory.setRegionId(req.getRegionId());
        ndSecurityAdvisory.setRegionName(regionsCacheHelper.getDisplayName(req.getRegionId()));
        ndSecurityAdvisory.setAdvisoryDate(req.getYearMonth());
        ndSecurityAdvisory.setFileId(req.getFileId());
        ndSecurityAdvisory.setAdvisoryFileName(req.getFileName());
        ndSecurityAdvisory.setCompanyId(LoginUserUtil.loginUserDetail().getCompanyId());
        ndSecurityAdvisoryService.save(ndSecurityAdvisory);
    }

    public void deleteSecurityNotice(Long id) {
        ndSecurityAdvisoryService.deleteById(id);
    }

    public void incrementDownCount(Long id) {
        ndSecurityAdvisoryService.incrementDownCount(id);
    }
}
