/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package com.unis.projectManagement.modular.pmProjectInfo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unis.projectManagement.modular.pmApplication.entity.PmApplication;
import com.unis.projectManagement.modular.pmApplication.mapper.PmApplicationMapper;
import com.unis.projectManagement.modular.pmProjectInfo.vo.PmProjectInfoPageVO;
import com.unis.projectManagement.modular.pmProjectInfoFile.entity.PmProjectInfoFile;
import com.unis.projectManagement.modular.pmProjectInfoFile.mapper.PmProjectInfoFileMapper;
import com.unis.projectManagement.modular.projectInfoPlan.entity.ProjectInfoPlan;
import com.unis.projectManagement.modular.projectInfoPlan.mapper.ProjectInfoPlanMapper;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.LocalDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.unis.common.enums.CommonSortOrderEnum;
import com.unis.common.exception.CommonException;
import com.unis.common.page.CommonPageRequest;
import com.unis.projectManagement.modular.pmProjectInfo.entity.PmProjectInfo;
import com.unis.projectManagement.modular.pmProjectInfo.mapper.PmProjectInfoMapper;
import com.unis.projectManagement.modular.pmProjectInfo.param.PmProjectInfoAddParam;
import com.unis.projectManagement.modular.pmProjectInfo.param.PmProjectInfoEditParam;
import com.unis.projectManagement.modular.pmProjectInfo.param.PmProjectInfoIdParam;
import com.unis.projectManagement.modular.pmProjectInfo.param.PmProjectInfoPageParam;
import com.unis.projectManagement.modular.pmProjectInfo.service.PmProjectInfoService;

import java.time.*;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 项目信息管理表Service接口实现类
 *
 * @author hjc
 * @date 2024/05/28 11:33
 **/
@Slf4j
@Service
public class PmProjectInfoServiceImpl extends ServiceImpl<PmProjectInfoMapper, PmProjectInfo> implements PmProjectInfoService {

    @Autowired
    private PmProjectInfoMapper pmProjectInfoMapper;

    @Autowired
    private PmApplicationMapper pmApplicationMapper;

    @Autowired
    private PmProjectInfoFileMapper pmProjectInfoFileMapper;

    @Autowired
    private ProjectInfoPlanMapper projectInfoPlanMapper;

    @Override
    public Page<PmProjectInfoPageVO> page(PmProjectInfoPageParam param) {
       /* QueryWrapper<PmProjectInfo> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isAllNotEmpty(pmProjectInfoPageParam.getSortField(), pmProjectInfoPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(pmProjectInfoPageParam.getSortOrder());
            queryWrapper.orderBy(true, pmProjectInfoPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(pmProjectInfoPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(PmProjectInfo::getId);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);*/

        Page<PmProjectInfoPageVO> page = new Page<>(param.getCurrent(), param.getSize());
        Page<PmProjectInfoPageVO> pmProjectInfoPageVOPage = pmProjectInfoMapper.selectMyPage(page, param.getProjectType(), param.getProjectName());
        page.setTotal(pmProjectInfoPageVOPage.getRecords().size());
        return pmProjectInfoPageVOPage;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(PmProjectInfoAddParam pmProjectInfoAddParam) {

        //保存项目信息表
        PmProjectInfo pmProjectInfo = BeanUtil.toBean(pmProjectInfoAddParam, PmProjectInfo.class);
        this.save(pmProjectInfo);

        //保存计划进度表
        List<ProjectInfoPlan> projectInfoPlanList = pmProjectInfoAddParam.getProjectInfoPlanList();
        for (ProjectInfoPlan projectInfoPlan : projectInfoPlanList) {
            try {
                projectInfoPlanMapper.insert(projectInfoPlan);
            } catch (Exception e) {
                log.error("新增计划进度表失败,项目id为{},异常信息：{}", pmProjectInfo.getPmApplicationId(), e.getMessage());
                throw new CommonException("新增计划进度表失败,项目id为{}", pmProjectInfo.getPmApplicationId());
            }
        }

        //保存项目文件表
        List<PmProjectInfoFile> pmProjectInfoFileList = pmProjectInfoAddParam.getPmProjectInfoFileList();
        for (PmProjectInfoFile pmProjectInfoFile : pmProjectInfoFileList) {
            try {
                pmProjectInfoFileMapper.insert(pmProjectInfoFile);
            } catch (Exception e) {
                log.error("新增项目文件表失败,项目id为{},异常信息：{}", pmProjectInfoFile.getPmApplicationId(), e.getMessage());
                throw new CommonException("新增项目文件表失败,项目id为{}", pmProjectInfoFile.getPmApplicationId());
            }
        }

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(PmProjectInfoEditParam pmProjectInfoEditParam) {


        PmProjectInfo pmProjectInfo = this.queryEntity(pmProjectInfoEditParam.getId());
        BeanUtil.copyProperties(pmProjectInfoEditParam, pmProjectInfo);
        this.updateById(pmProjectInfo);
        //将之前的项目文件和计划进度数据删除
        pmProjectInfoFileMapper.delete(Wrappers.lambdaQuery(PmProjectInfoFile.class)
                .in(PmProjectInfoFile::getPmApplicationId, pmProjectInfo.getPmApplicationId()));
        projectInfoPlanMapper.delete(Wrappers.lambdaQuery(ProjectInfoPlan.class)
                .in(ProjectInfoPlan::getPmApplicationId, pmProjectInfo.getPmApplicationId()));

        //保存计划进度表
        List<ProjectInfoPlan> projectInfoPlanList = pmProjectInfoEditParam.getProjectInfoPlanList();
        for (ProjectInfoPlan projectInfoPlan : projectInfoPlanList) {
            try {
                projectInfoPlanMapper.insert(projectInfoPlan);
            } catch (Exception e) {
                log.error("新增计划进度表失败,项目id为{},异常信息：{}", pmProjectInfo.getPmApplicationId(), e.getMessage());
                throw new CommonException("新增计划进度表失败,项目id为{}", pmProjectInfo.getPmApplicationId());
            }
        }

        //保存项目文件表
        List<PmProjectInfoFile> pmProjectInfoFileList = pmProjectInfoEditParam.getPmProjectInfoFileList();
        for (PmProjectInfoFile pmProjectInfoFile : pmProjectInfoFileList) {
            try {
                pmProjectInfoFileMapper.insert(pmProjectInfoFile);
            } catch (Exception e) {
                log.error("新增项目文件表失败,项目id为{},异常信息：{}", pmProjectInfoFile.getPmApplicationId(), e.getMessage());
                throw new CommonException("新增项目文件表失败,项目id为{}", pmProjectInfoFile.getPmApplicationId());
            }
        }

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<PmProjectInfoIdParam> pmProjectInfoIdParamList) {

        PmProjectInfo pmProjectInfo = this.queryEntity(pmProjectInfoIdParamList.get(0).getId());

        //将之前的项目文件和计划进度数据删除
        pmProjectInfoFileMapper.delete(Wrappers.lambdaQuery(PmProjectInfoFile.class)
                .in(PmProjectInfoFile::getPmApplicationId, pmProjectInfo.getPmApplicationId()));

        projectInfoPlanMapper.delete(Wrappers.lambdaQuery(ProjectInfoPlan.class)
                .in(ProjectInfoPlan::getPmApplicationId, pmProjectInfo.getPmApplicationId()));

        // 执行删除
        this.removeByIds(CollStreamUtil.toList(pmProjectInfoIdParamList, PmProjectInfoIdParam::getId));

    }

    @Override
    public JSONObject detail(PmProjectInfoIdParam pmProjectInfoIdParam) {

        JSONObject jsonObject = new JSONObject();
        //获取项目信息
        PmProjectInfo pmProjectInfo = this.queryEntity(pmProjectInfoIdParam.getId());
        jsonObject.put("pmProjectInfo", pmProjectInfo);

        //获取项目申报信息
        PmApplication pmApplication = pmApplicationMapper.selectById(pmProjectInfo.getPmApplicationId());
        jsonObject.put("pmApplication", pmApplication);

        //获取计划进度信息
        List<ProjectInfoPlan> projectInfoPlanList = projectInfoPlanMapper.selectList(Wrappers.lambdaQuery(ProjectInfoPlan.class)
                .eq(ProjectInfoPlan::getPmApplicationId, pmProjectInfo.getPmApplicationId()));
        jsonObject.put("projectInfoPlanList", projectInfoPlanList);

        //获取项目文件信息
        List<PmProjectInfoFile> pmProjectInfoFileList = pmProjectInfoFileMapper.selectList(Wrappers.lambdaQuery(PmProjectInfoFile.class)
                .eq(PmProjectInfoFile::getPmApplicationId, pmProjectInfo.getPmApplicationId()));
        jsonObject.put("pmProjectInfoFileList", pmProjectInfoFileList);


        return jsonObject;

    }

    @Override
    public PmProjectInfo queryEntity(String id) {
        PmProjectInfo pmProjectInfo = this.getById(id);
        if (ObjectUtil.isEmpty(pmProjectInfo)) {
            throw new CommonException("项目信息管理表不存在，id值为：{}", id);
        }
        return pmProjectInfo;
    }

    /**
     * 新增时下拉-获取项目申报信息
     *
     * @author hjc
     * @date 2024/05/28 11:33
     */
    @Override
    public List<PmApplication> getPmApplication() {
        //查询申报通过的项目
      /*  return pmApplicationMapper.selectList(Wrappers.lambdaQuery(PmApplication.class)
                .eq(PmApplication::getStatus, 3));*/
        return pmApplicationMapper.selectGetPmApplication();
    }

    /**
     * 获取项目监督管理详情
     *
     * @author hjc
     * @date 2024/05/28 11:33
     */
    @Override
    public JSONObject getSuperviseDetail(PmProjectInfoIdParam pmProjectInfoIdParam) {
        JSONObject jsonObject = new JSONObject();
        //获取项目信息
        PmProjectInfo pmProjectInfo = this.queryEntity(pmProjectInfoIdParam.getId());
        jsonObject.put("pmProjectInfo", pmProjectInfo);

        //获取项目申报信息
        PmApplication pmApplication = pmApplicationMapper.selectById(pmProjectInfo.getPmApplicationId());
        jsonObject.put("pmApplication", pmApplication);

        //获取计划进度信息
        List<ProjectInfoPlan> projectInfoPlanList = projectInfoPlanMapper.selectList(Wrappers.lambdaQuery(ProjectInfoPlan.class)
                .eq(ProjectInfoPlan::getPmApplicationId, pmProjectInfo.getPmApplicationId()));

        ArrayList<ProjectInfoPlan> list = new ArrayList<>();

        for (ProjectInfoPlan projectInfoPlan : projectInfoPlanList) {
            //超期预警
            LocalDate localDate = LocalDate.now(); // 例如，这可以是任何LocalDate对象
            ZonedDateTime zdt = localDate.atStartOfDay(ZoneId.systemDefault());
            Instant instant = zdt.toInstant();
            Date now = Date.from(instant);
            //判断当前时间在结束时间之后  为超期
            if (now.after(projectInfoPlan.getScheduleEndDate())){

                long nowTime = now.getTime();
                long endTime = projectInfoPlan.getScheduleEndDate().getTime();
                long time = nowTime - endTime;
                long days = time / (24 * 60 * 60 * 1000);
                projectInfoPlan.setOverdueWarn(String.valueOf(days));

            }

            list.add(projectInfoPlan);

        }
        jsonObject.put("projectInfoPlanList", list);

        //获取项目文件信息
        List<PmProjectInfoFile> pmProjectInfoFileList = pmProjectInfoFileMapper.selectList(Wrappers.lambdaQuery(PmProjectInfoFile.class)
                .eq(PmProjectInfoFile::getPmApplicationId, pmProjectInfo.getPmApplicationId()));
        jsonObject.put("pmProjectInfoFileList", pmProjectInfoFileList);

        return jsonObject;
    }
}
