package com.ningdatech.pmapi.projectdeclared.utils;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ningdatech.pmapi.fiscal.service.ICompanyFiscalCodeService;
import com.ningdatech.pmapi.projectdeclared.contants.ProjectCodeContant;
import com.ningdatech.pmapi.projectlib.model.dto.ProjectDTO;
import com.ningdatech.pmapi.projectlib.model.entity.Project;
import com.ningdatech.pmapi.projectlib.model.entity.ProjectCollection;
import com.ningdatech.pmapi.projectlib.service.IProjectCollectionService;
import com.ningdatech.pmapi.projectlib.service.IProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 生成项目编号工具类
 *
 * @author CMM
 * @since 2023/04/04 14:13
 */
@Component
public class GenerateProjectCodeUtil {
    @Autowired
    private ICompanyFiscalCodeService companyFiscalCodeService;

    @Autowired
    private IProjectService projectService;

    @Autowired
    private IProjectCollectionService projectCollectionService;

    public String generateProjectCode(ProjectDTO project){
        // 获取所属行政区划代码(9位)
        String areaCode = project.getAreaCode() + ProjectCodeContant.REGION_LAST_3;
        // 获取建设年度 (10-13)
        String year = Objects.nonNull(project.getProjectYear()) ? String.valueOf(project.getProjectYear())
                : String.valueOf(LocalDateTime.now().getYear());
        // 14-15 项目类型
        String projectType =  ProjectCodeContant.PROJECT_TYPE_PREFIX + project.getProjectType();
        // 16-20 项目序号00001
        Long max = projectService.count(Wrappers.lambdaQuery(Project.class)
                .eq(Project::getProjectYear,project.getProjectYear())
                .eq(Project::getNewest,Boolean.TRUE));
        Long maxCurrent = max + 1;
        String serialNumber = String.format(ProjectCodeContant.SHUZI_5,maxCurrent);
        // 生成20位的项目编号
        return areaCode + year + projectType + serialNumber;
    }

    public String generateProjectCode(ProjectCollection project){
        // 获取所属行政区划代码(9位)
        String areaCode = project.getAreaCode() + ProjectCodeContant.REGION_LAST_3;
        // 获取建设年度 (10-13)
        String year = Objects.nonNull(project.getProjectYear()) ? String.valueOf(project.getProjectYear())
                : String.valueOf(LocalDateTime.now().getYear());
        // 14-15 项目类型
        String projectType =  ProjectCodeContant.PROJECT_TYPE_PREFIX + project.getProjectType();
        // 16-20 项目序号00001
        Long max = projectService.count(Wrappers.lambdaQuery(Project.class)
                .eq(Project::getProjectYear,project.getProjectYear())
                .eq(Project::getNewest,Boolean.TRUE));
        Long maxCurrent = max + 1;
        String serialNumber = String.format(ProjectCodeContant.SHUZI_5,maxCurrent);
        // 生成20位的项目编号
        return areaCode + year + projectType + serialNumber;
    }
}
