package com.ningdatech.pmapi.projectlib.manage;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
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.function.VUtils;
import com.ningdatech.basic.model.PageVo;
import com.ningdatech.pmapi.common.constant.RegionConst;
import com.ningdatech.pmapi.common.helper.RegionCacheHelper;
import com.ningdatech.pmapi.projectdeclared.utils.GenerateProjectCodeUtil;
import com.ningdatech.pmapi.projectlib.model.dto.ProjectCollectionSaveDTO;
import com.ningdatech.pmapi.projectlib.model.entity.ProjectCollection;
import com.ningdatech.pmapi.projectlib.model.req.ProjectListReq;
import com.ningdatech.pmapi.projectlib.model.vo.ProjectCollectionVO;
import com.ningdatech.pmapi.projectlib.service.IProjectCollectionService;
import com.ningdatech.pmapi.sys.model.dto.RegionDTO;
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 ProjectCollectionManage
 * @Description
 * @Date 2023/6/25 9:13
 * @Author PoffyZhang
 */
@Component
@Slf4j
@AllArgsConstructor
public class ProjectCollectionManage {

    private final IProjectCollectionService collectionService;

    private final RegionCacheHelper regionCacheHelper;

    private final GenerateProjectCodeUtil generateProjectCodeUtil;

    /**
     * 项目归集
     * @param req
     * @return
     */
    public PageVo<ProjectCollectionVO> list(ProjectListReq req) {
        UserInfoDetails user = LoginUserUtil.loginUserDetail();
        String buildOrgCode = req.getBuildOrgCode();
        //如果是超管 可以看所有
        if(user.getSuperAdmin()){
            buildOrgCode = null;
        }

        Page<ProjectCollection> page = req.page();

        LambdaQueryWrapper<ProjectCollection> wrapper = Wrappers.lambdaQuery(ProjectCollection.class)
                .like(StringUtils.isNotBlank(req.getProjectName()), ProjectCollection::getProjectName, req.getProjectName())
                .like(StringUtils.isNotBlank(req.getBuildOrg()), ProjectCollection::getBuildOrg, req.getBuildOrg())
                .eq(Objects.nonNull(buildOrgCode), ProjectCollection::getBuildOrgCode, buildOrgCode);
        //处理 行政区域
        if(StringUtils.isNotBlank(req.getRegionCode())){
            List<RegionDTO> regions = regionCacheHelper.listChildren(req.getRegionCode(), req.getRegionLevel());

            if(CollUtil.isNotEmpty(regions)){
                wrapper.in(ProjectCollection::getAreaCode,regions.stream().map(RegionDTO::getRegionCode).collect(Collectors.toList()));
            }
        }

        collectionService.page(page,wrapper);

        if(0L == page.getTotal()){
            return PageVo.empty();
        }

        List<ProjectCollectionVO> res = page.getRecords().stream()
                .map(record -> {
                    ProjectCollectionVO vo = BeanUtil.copyProperties(record, ProjectCollectionVO.class);
                    vo.setArea(regionCacheHelper.getDisplayName(record.getAreaCode(), RegionConst.RL_COUNTY));
                    return vo;
                })
                .collect(Collectors.toList());

        return PageVo.of(res,page.getTotal());
    }

    /**
     * 项目归集详情
     * @param id
     * @return
     */
    public ProjectCollectionVO detail(Long id) {
        ProjectCollection projectCollection = collectionService.getById(id);

        return BeanUtil.copyProperties(projectCollection,ProjectCollectionVO.class);
    }

    /**
     * 保存
     * @param dto
     * @return
     */
    public String save(ProjectCollectionSaveDTO dto) {
        UserInfoDetails user = LoginUserUtil.loginUserDetail();

        ProjectCollection projectCollection = BeanUtil.copyProperties(dto,ProjectCollection.class);
        if(Objects.nonNull(dto.getId())){
            ProjectCollection old = collectionService.getById(dto.getId());
            VUtils.isTrue(Objects.isNull(old)).throwMessage("该项目归集不存在！");
            projectCollection.setId(dto.getId());
        }else{
            projectCollection.setProjectCode(generateProjectCodeUtil.generateProjectCode(projectCollection));
            projectCollection.setCreateBy(user.getUsername());
            projectCollection.setCreateOn(LocalDateTime.now());
        }

        projectCollection.setUpdateBy(user.getUsername());
        projectCollection.setUpdateOn(LocalDateTime.now());
        if(collectionService.saveOrUpdate(projectCollection)){
            return "保存成功";
        }
        return "保存失败";
    }

    /**
     * 删除
     * @param id
     * @return
     */
    public String delete(Long id) {
        ProjectCollection projectCollection = collectionService.getById(id);

        VUtils.isTrue(Objects.isNull(projectCollection)).throwMessage("该项目归集不存在 删除失败");

        if(collectionService.removeById(id)){
            return "删除成功";
        }
        return "删除失败";
    }
}
