package com.ningdatech.carapi.analysis.manage;

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

import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ningdatech.basic.exception.BizException;
import com.ningdatech.basic.model.PageVo;
import com.ningdatech.basic.util.CollUtils;
import com.ningdatech.carapi.analysis.entity.IndustryStandards;
import com.ningdatech.carapi.analysis.entity.req.IndustryStandardsListReq;
import com.ningdatech.carapi.analysis.entity.req.IndustryStandardsSaveReq;
import com.ningdatech.carapi.analysis.entity.vo.IndustryStandardsListVo;
import com.ningdatech.carapi.analysis.service.IIndustryStandardsService;
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.datascope.contants.LambdaDataScopeTypeEnum;
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 cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;

/**
 * <p>
 * IndustryStandardsManage
 * </p>
 *
 * @author WendyYang
 * @since 10:24 2022/10/15
 */
@Component
@RequiredArgsConstructor
public class IndustryStandardsManage {

    private final IIndustryStandardsService industryStandardsService;

    public PageVo<IndustryStandardsListVo> list(IndustryStandardsListReq req) {
        Integer pageNumber = req.getPageNumber();
        Integer pageSize = req.getPageSize();

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

        LambdaQueryWrapper<IndustryStandards> query = Wrappers.lambdaQuery(IndustryStandards.class);
        IndustryStandardsManage context = (IndustryStandardsManage) AopContext.currentProxy();
        context.buildQuery(query,req);

        List<IndustryStandards> standardsList = industryStandardsService.list(query);
        // 省级部门上传的文件(上传企业所属区域为省级)，按照文件类型，下级账号也要能看到
        if (!UserRoleTypeEnum.SYSTEM_ADMIN_ROLE_ID.getId().equals(roleId)) {
            List<IndustryStandards> standards = industryStandardsService.list(Wrappers.lambdaQuery(IndustryStandards.class)
                    .eq(IndustryStandards::getRegionId, DefValConstants.ZJREGION_ID)
                    .eq(IndustryStandards::getType,req.getType()));
            standardsList.addAll(standards);
        }

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

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

        //Page<IndustryStandards> page = industryStandardsService.page(req.page(), query);

        List<IndustryStandardsListVo> data = CollUtils.convert(records, w -> {
            IndustryStandardsListVo vo = BeanUtil.copyProperties(w, IndustryStandardsListVo.class);
            CodeUtil.searchCompanyNameAndRegionName(vo);
            return vo;
        });
        return PageVo.of(data, standardsList.size());
    }
    @LambdaDataScope
    public void buildQuery(LambdaQueryWrapper<IndustryStandards> query,IndustryStandardsListReq req) {
        query.orderByDesc(IndustryStandards::getId).eq(IndustryStandards::getType, req.getType())
            .like(StrUtil.isNotBlank(req.getFileName()), IndustryStandards::getName, req.getFileName())
            .ge(req.getStartTime() != null, IndustryStandards::getCreateOn, req.getStartTime())
            .le(req.getEndTime() != null, IndustryStandards::getCreateOn, req.getEndTime());
    }

    public void save(IndustryStandardsSaveReq req) {
        IndustryStandards industryStandards = BeanUtil.copyProperties(req, IndustryStandards.class);
        industryStandards.setCreateBy(LoginUserUtil.getUserId());
        industryStandards.setCreateOn(LocalDateTime.now());
        industryStandards.setRegionId(LoginUserUtil.loginUserDetail().getRegionId());
        industryStandards.setCompanyId(LoginUserUtil.loginUserDetail().getCompanyId());
        industryStandardsService.save(industryStandards);
    }

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

    public void deleteStandardFile(Long id, Long roleId) {

        LambdaQueryWrapper<IndustryStandards> wrapper = Wrappers.lambdaQuery(IndustryStandards.class);
        IndustryStandardsManage context = (IndustryStandardsManage) AopContext.currentProxy();
        context.buildStandardFileQuery(wrapper, id);
        IndustryStandards standards = industryStandardsService.getOne(wrapper);
        if (Objects.isNull(standards)){
            throw new BizException("文件无法删除!");
        }
        // IndustryStandards standards = industryStandardsService.getById(id);
        // 如果文件是省级部门上传的文件，只有省级管理员角色可以删除
        Long regionId = standards.getRegionId();
        if (Objects.nonNull(regionId) &&
                DefValConstants.ZJREGION_ID.equals(regionId)){
            // 判断登录用户角色是否为省管理员
            if (!UserRoleTypeEnum.SYSTEM_ADMIN_ROLE_ID.getId().equals(roleId)){
                throw new BizException("您没有权限删除该文件!");
            }
        }
        industryStandardsService.deleteById(id);
    }
    @LambdaDataScope(type = LambdaDataScopeTypeEnum.ALL)
    public void buildStandardFileQuery(LambdaQueryWrapper<IndustryStandards> wrapper, Long id) {
        wrapper.eq(IndustryStandards::getId,id);
    }
}
