package com.ningdatech.pmapi.safety.manage;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
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.exception.BizException;
import com.ningdatech.basic.function.VUtils;
import com.ningdatech.basic.model.PageVo;
import com.ningdatech.basic.util.CollUtils;
import com.ningdatech.pmapi.common.constant.BizConst;
import com.ningdatech.pmapi.common.constant.RegionConst;
import com.ningdatech.pmapi.projectlib.enumeration.ProjectStatusEnum;
import com.ningdatech.pmapi.projectlib.model.entity.Project;
import com.ningdatech.pmapi.projectlib.model.req.ProjectListReq;
import com.ningdatech.pmapi.projectlib.service.IProjectService;
import com.ningdatech.pmapi.safety.model.dto.PersonSafetyInfoDTO;
import com.ningdatech.pmapi.safety.model.dto.SupplierSafetyQualificationDTO;
import com.ningdatech.pmapi.safety.model.entity.PersonSafetyInfo;
import com.ningdatech.pmapi.safety.model.entity.SupplierSafetyQualification;
import com.ningdatech.pmapi.safety.model.vo.PersonSafetyInfoVO;
import com.ningdatech.pmapi.safety.model.vo.ProjectMonitorVO;
import com.ningdatech.pmapi.safety.model.vo.SafetyMonitorVO;
import com.ningdatech.pmapi.safety.model.vo.SupplierSafetyQualificationVO;
import com.ningdatech.pmapi.safety.service.IPersonSafetyInfoService;
import com.ningdatech.pmapi.safety.service.ISupplierSafetyQualificationService;
import com.ningdatech.pmapi.user.security.auth.model.UserInfoDetails;
import com.ningdatech.pmapi.user.util.LoginUserUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

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

/**
 * @Classname SafetyRiskManage
 * @Description
 * @Date 2023/8/2 9:17
 * @Author PoffyZhang
 */
@Component
@Slf4j
@AllArgsConstructor
public class SafetyRiskManage {

    private final IProjectService projectService;

    private final ISupplierSafetyQualificationService supplierSafetyQualificationService;

    private final IPersonSafetyInfoService personSafetyInfoService;

    /**
     * 列表
     * @param req
     * @return
     */
    public PageVo<ProjectMonitorVO> personMonitorList(ProjectListReq req) {
        LambdaQueryWrapper<Project> query = Wrappers.lambdaQuery(Project.class)
                .eq(Project::getNewest, Boolean.TRUE)
                .ge(Project::getStatus, ProjectStatusEnum.UNDER_CONSTRUCTION.getCode())
                .ne(Project::getStatus, ProjectStatusEnum.OPERATION.getCode())
                .eq(StringUtils.isNotBlank(req.getRegionCode()),Project::getAreaCode,req.getRegionCode())
                .like(StringUtils.isNotBlank(req.getProjectName()),Project::getProjectName,req.getProjectName())
                .like(StringUtils.isNotBlank(req.getBuildOrgName()),Project::getBuildOrgName,req.getBuildOrgName())
                .orderByDesc(Project::getUpdateOn);
        checkAuth(query,LoginUserUtil.loginUserDetail());
        Page<Project> page = projectService.page(req.page(), query);
        long total;
        if ((total = page.getTotal()) == 0) {
            return PageVo.empty();
        }
        List<ProjectMonitorVO> records = CollUtils.convert(page.getRecords(),
                p -> BeanUtil.copyProperties(p,ProjectMonitorVO.class));
        return PageVo.of(records, total);
    }

    /**
     * 权限控制
     * @param query
     * @param user
     */
    private void checkAuth(LambdaQueryWrapper<Project> query, UserInfoDetails user) {
        //如果是超管
        if(user.getSuperAdmin()){
            log.info(user.getUsername() + " 是超管,可以看所有项目");
        }else if(user.getRegionAdmin()){
            //如果是区域管理员
            log.info(user.getUsername() + " 是区管,可以看本区域" + user.getRegionCode() + "项目");
            if(!RegionConst.RC_LS.equals(user.getRegionCode())){
                //不是丽水市本级的话 就只看 自己区域的
                query.eq(Project::getAreaCode,user.getRegionCode());
            }
            //如果是市本级 就能看所有的
        }else if(user.getIsOrgAdmin()){
            //单位管理员
            log.info(user.getUsername() + " 是单位管理员,可以看单位 " + user.getEmpPosUnitName() + " 项目");
            query.eq(Project::getBuildOrgCode,user.getEmpPosUnitCode());
        }else{
            //其它角色全都看不见
            query.eq(Project::getId,0L);
        }
    }

    public SafetyMonitorVO personMonitorDetail(String projectCode) {
        SafetyMonitorVO vo = new SafetyMonitorVO();
        Project project = projectService.getOne(Wrappers.lambdaQuery(Project.class)
                .eq(Project::getNewest, Boolean.TRUE)
                .eq(Project::getProjectCode, projectCode)
                .last(BizConst.LIMIT_1));

        if(Objects.isNull(project)){
            return null;
        }

        List<SupplierSafetyQualification> ssq = supplierSafetyQualificationService.list(Wrappers.lambdaQuery(SupplierSafetyQualification.class)
                .eq(SupplierSafetyQualification::getProjectCode, projectCode));
        if(CollUtil.isNotEmpty(ssq)){
            vo.setSupplierSafetyQualification(ssq.stream()
                    .map(s -> BeanUtil.copyProperties(s, SupplierSafetyQualificationVO.class))
                    .collect(Collectors.toList()));
        }

        List<PersonSafetyInfo> psi = personSafetyInfoService.list(Wrappers.lambdaQuery(PersonSafetyInfo.class)
                .eq(PersonSafetyInfo::getProjectCode, projectCode));
        if(CollUtil.isNotEmpty(psi)){
            vo.setPersonSafetyInfo(psi.stream()
                    .map(p -> BeanUtil.copyProperties(p, PersonSafetyInfoVO.class))
                    .collect(Collectors.toList()));
        }

        return vo;
    }

    public JSONObject operationnMonitorSearch(String projectCode) {
        return null;
    }

    /**
     * 保存 供应商安全资质
     * @param dtos
     * @return
     */
    public String supplierSafetyQualificationSave(List<SupplierSafetyQualificationDTO> dtos) {
        if(CollUtil.isEmpty(dtos)){
            return "数据为空";
        }

        UserInfoDetails user = LoginUserUtil.loginUserDetail();

        String projectCode = dtos.get(0).getProjectCode();
        if(StringUtils.isBlank(projectCode)){
            throw new BizException("参数有误!");
        }
        supplierSafetyQualificationService.remove(Wrappers.lambdaQuery(SupplierSafetyQualification.class)
                .eq(SupplierSafetyQualification::getProjectCode, projectCode));

        Integer sucessNum = 0;
        for(SupplierSafetyQualificationDTO dto : dtos){
            projectCode = dto.getProjectCode();
            Project project = projectService.getOne(Wrappers.lambdaQuery(Project.class)
                    .eq(Project::getNewest, Boolean.TRUE)
                    .eq(Project::getProjectCode, projectCode)
                    .last(BizConst.LIMIT_1));

            VUtils.isTrue(Objects.isNull(project)).throwMessage("此项目并不存在!");

            SupplierSafetyQualification entity = BeanUtil.copyProperties(dto, SupplierSafetyQualification.class);
            entity.setCreateBy(user.getUsername());
            entity.setCreateOn(LocalDateTime.now());
            entity.setProjectId(project.getId());
            entity.setUpdateBy(user.getUsername());
            entity.setUpdateOn(LocalDateTime.now());
            if(supplierSafetyQualificationService.save(entity)){
                sucessNum ++;
            }
        }

        return "保存成功" + sucessNum + "条";
    }

    public String personMonitorSave(List<PersonSafetyInfoDTO> dtos) {
        if(CollUtil.isEmpty(dtos)){
            return "数据为空";
        }

        UserInfoDetails user = LoginUserUtil.loginUserDetail();

        String projectCode = dtos.get(0).getProjectCode();
        if(StringUtils.isBlank(projectCode)){
            throw new BizException("参数有误!");
        }
        personSafetyInfoService.remove(Wrappers.lambdaQuery(PersonSafetyInfo.class)
                .eq(PersonSafetyInfo::getProjectCode, projectCode));

        Integer sucessNum = 0;
        for(PersonSafetyInfoDTO dto : dtos){
            projectCode = dto.getProjectCode();
            Project project = projectService.getOne(Wrappers.lambdaQuery(Project.class)
                    .eq(Project::getNewest, Boolean.TRUE)
                    .eq(Project::getProjectCode, projectCode)
                    .last(BizConst.LIMIT_1));

            VUtils.isTrue(Objects.isNull(project)).throwMessage("此项目并不存在!");

            PersonSafetyInfo entity = BeanUtil.copyProperties(dto, PersonSafetyInfo.class);
            entity.setCreateBy(user.getUsername());
            entity.setCreateOn(LocalDateTime.now());
            entity.setProjectId(project.getId());
            entity.setUpdateBy(user.getUsername());
            entity.setUpdateOn(LocalDateTime.now());
            if(personSafetyInfoService.save(entity)){
                sucessNum ++;
            }
        }

        return "保存成功" + sucessNum + "条";
    }
}
