package com.yccrc.kede.service.impl;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yccrc.common.core.domain.entity.SysUser;
import com.yccrc.common.utils.PageUtils;
import com.yccrc.common.utils.SecurityUtils;
import com.yccrc.common.utils.StringUtils;
import com.yccrc.kede.domain.Attach;
import com.yccrc.kede.domain.Enterprise;
import com.yccrc.kede.domain.EnterpriseProject;
import com.yccrc.kede.domain.EnterpriseYearInfo;
import com.yccrc.kede.enums.AttachTypeEnum;
import com.yccrc.kede.mapper.EnterpriseProjectMapper;
import com.yccrc.kede.service.IAttachService;
import com.yccrc.kede.service.IEnterpriseProjectService;
import com.yccrc.kede.service.IEnterpriseService;
import com.yccrc.kede.service.IEnterpriseYearInfoService;
import com.yccrc.kede.vo.IndexRptVO;
import com.yccrc.kede.vo.ProjectHeadAddVO;
import com.yccrc.kede.vo.ProjectQueryVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
/**
 * @author pengzhiqiang
 * @description 针对表【enterprise_project】的数据库操作Service实现
 * @createDate 2023-07-26 15:44:00
 */
@Slf4j
@Service
public class EnterpriseProjectServiceImpl extends ServiceImpl<EnterpriseProjectMapper, EnterpriseProject>
        implements IEnterpriseProjectService {

    @Autowired
    private IEnterpriseService enterpriseService;
    @Autowired
    private IEnterpriseYearInfoService enterpriseYearInfoService;
    @Autowired
    private IAttachService attachService;

    @Override
    public Boolean saveProject(EnterpriseProject project) {
        try {
            SysUser user = SecurityUtils.getLoginUser().getUser();
            Enterprise enterprise = enterpriseService.getById(user.getScopeId());
            Integer entId = enterprise != null ? enterprise.getId() : null;
            String entName = enterprise != null ? enterprise.getEntName() : null;
            // 判断有没有当前年度企业基本信息
            long count = enterpriseYearInfoService.count(new LambdaQueryWrapper<EnterpriseYearInfo>()
                    .eq(EnterpriseYearInfo::getEntId, user.getScopeId())
                    .eq(EnterpriseYearInfo::getProjectYear, project.getProjectYear())
            );
            if (count < 1) {
                // 初始化一条年度企业基本信息数据
                enterpriseYearInfoService.save(new EnterpriseYearInfo(entId, entName,
                        project.getProjectYear(), enterprise.getAddress(), enterprise.getLinkName(), enterprise.getLinkPhone(), enterprise.getLinkMobile()));
            }
            // 新增项目申报
            LocalDate currentDate = LocalDate.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy");
            String nowYear = currentDate.format(formatter);

            project.setUserId(user.getUserId());
            project.setEntId(entId);
            project.setEntName(entName);
            project.setBackFlag(!nowYear.equals(project.getProjectYear()));
            if (project.getHeadAddVOList() != null && !project.getHeadAddVOList().isEmpty()) {
                project.setProjectJson(JSON.toJSONString(project.getHeadAddVOList()));
            }
            this.save(project);
        } catch (Exception e) {
            log.error("saveEnterpriseProject:{}", e.getMessage());
            return false;
        }
        return true;
    }

    @Override
    public Page<EnterpriseProject> selectList(ProjectQueryVO project) {
        QueryWrapper<EnterpriseProject> queryWrapper = new QueryWrapper<EnterpriseProject>()
                .eq(project.getEntId() != null, "a.ent_id", project.getEntId())
                .eq(project.getReportState() != null, "a.report_state", project.getReportState())
                .eq(project.getProvinceId() != null, "b.province_id", project.getProvinceId())
                .eq(project.getCityId() != null, "b.city_id", project.getCityId())
                .eq(project.getDistrictId() != null, "b.district_id", project.getDistrictId())
                .like(!StrUtil.isEmpty(project.getEntName()), "a.ent_name", project.getEntName())
                .like(!StrUtil.isEmpty(project.getProjectName()), "a.project_name", project.getProjectName())
                .like(!StrUtil.isEmpty(project.getLicense()), "b.license", project.getLicense())
                .like(!StrUtil.isEmpty(project.getProjectName()), "a.project_name", project.getEntName())
                .like(!StrUtil.isEmpty(project.getProjectNo()), "a.project_no", project.getProjectNo())
                .in(project.getYearList() != null && !project.getYearList().isEmpty(),
                        "a.project_year", project.getYearList())
                .orderByDesc("a.id");
        SysUser user = SecurityUtils.getLoginUser().getUser();
        switch (user.getUserType()) {
            case ADMIN:
                // 查看全部
                break;
            case ENT_ADMIN:
            case ENT_ADMIN_TECH:
            case ENT_ADMIN_FIN:
            case ENT_TECH:
            case ENT_FIN:
                queryWrapper.eq("ent_id", user.getScopeId());
                break;
            default:
                break;
        }
        Page<EnterpriseProject> page = baseMapper.selectPage(PageUtils.initPage(), queryWrapper);
        for (EnterpriseProject record : page.getRecords()) {
            // 财务进度
            int finTotal = 3;
            int finSize = attachService.lambdaQuery()
                    .eq(Attach::getAttachType, AttachTypeEnum.FINACIAL)
                    .eq(Attach::getDataId, record.getId())
                    .in(Attach::getFileType, "file4", "file5", "file8")
                    .list().size();
            record.setFinRate(finSize == 0 ? "0%" : NumberUtil.div(finSize * 100, finTotal, 2) + "%");
            // 技术进度:加计年度企业基本信息 + 企业研发项目情况表 + 技术人员上传1-7项相关文件
            int techTotal = 9 + 12 + 7;

            if (!record.getContractFlag()) {
                techTotal--;
            }
            if (!record.getAppraisalFlag()) {
                techTotal--;
            }
            // 附件
            int techSize = attachService.lambdaQuery()
                    .eq(Attach::getAttachType, AttachTypeEnum.FINACIAL)
                    .eq(Attach::getDataId, record.getId())
                    .in(Attach::getFileType, "file1", "file2", "file3", "file6",
                            record.getContractFlag() ? "file7" : "过滤file7数据", "file9",
                            record.getReportFlag() ? "file10" : "过滤file10数据")
                    .list().size();
            EnterpriseYearInfo one = enterpriseYearInfoService.getOne(new LambdaUpdateWrapper<EnterpriseYearInfo>()
                    .eq(EnterpriseYearInfo::getEntId, record.getEntId())
                    .eq(EnterpriseYearInfo::getProjectYear, record.getProjectYear()));
            if (one == null) {
                one = new EnterpriseYearInfo();
            }
            techSize += record.getTechNum() + one.getTotal();
            record.setTechRate(techSize == 0 ? "0%" : NumberUtil.div(techSize * 100, techTotal, 2) + "%");

            // 研发人数
            if (StringUtils.isNotBlank(record.getProjectJson())) {
                List<ProjectHeadAddVO> list = JSON.parseArray(record.getProjectJson(), ProjectHeadAddVO.class);
                record.setTechPersons(list.size());
            }
        }
        return page;
    }

    @Override
    public IndexRptVO rptProject() {
        QueryWrapper<Enterprise> queryWrapper = new QueryWrapper<Enterprise>();

        SysUser user = SecurityUtils.getLoginUser().getUser();
        switch (user.getUserType()) {
//			case ADMIN:
//				break;
            case GOV_PROV:
                queryWrapper.eq("b.province_id", user.getScopeId());
                break;
            case GOV_CITY:
                queryWrapper.eq("b.city_id", user.getScopeId());
                break;
            case GOV_DISTRI:
                queryWrapper.eq("b.district_id", user.getScopeId());
                break;

            case ENT_ADMIN:
            case ENT_ADMIN_TECH:
            case ENT_ADMIN_FIN:
            case ENT_TECH:
            case ENT_FIN:
                queryWrapper.eq("a.ent_id", user.getScopeId());
                break;
            default:
                break;
        }
        return baseMapper.rptProject(queryWrapper);
    }
}
