package com.jeeplus.test.cw.reportCancellApply.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.sys.domain.User;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.sys.utils.StringUtils;
import com.jeeplus.sys.utils.UserUtils;
import com.jeeplus.test.cw.projectRecords.domain.CwProjectRecords;
import com.jeeplus.test.cw.projectRecords.service.dto.CwProjectRecordsDTO;
import com.jeeplus.test.cw.projectRecords.service.mapstruct.CwProjectRecordsWrapper;
import com.jeeplus.test.cw.projectReport.domain.*;
import com.jeeplus.test.cw.projectReport.mapper.CwProjectInfoMapper;
import com.jeeplus.test.cw.projectReport.mapper.CwProjectReportCancelMapper;
import com.jeeplus.test.cw.projectReport.mapper.CwProjectReportMapper;
import com.jeeplus.test.cw.projectReport.mapper.ProjectReportWorkAttachmentMapper;
import com.jeeplus.test.cw.projectReport.service.dto.CwProjectReportDTO;
import com.jeeplus.test.cw.projectReport.service.dto.ProjectReportWorkAttachmentDTO;
import com.jeeplus.test.cw.projectReport.service.mapstruct.CwProjectReportFileWrapper;
import com.jeeplus.test.cw.reportCancellApply.domain.ReportCancellApply;
import com.jeeplus.test.cw.reportCancellApply.mapper.ReportCancellApplyMapper;
import com.jeeplus.test.cw.reportCancellApply.service.dto.ReportInfoDto;
import com.jeeplus.test.oss.domain.WorkAttachment;
import liquibase.pro.packaged.A;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author: 王强
 * @create: 2022-11-18 17:36
 **/
@Service
@Transactional
public class ReportCancellApplyService extends ServiceImpl<ReportCancellApplyMapper, ReportCancellApply> {

    @Resource
    private ReportCancellApplyMapper applyMapper;

    @Resource
    private CwProjectReportCancelMapper cancelMapper;

    @Resource
    private CwProjectInfoMapper infoMapper;

    @Resource
    private ProjectReportWorkAttachmentMapper attachmentMapper;

    @Resource
    private CwProjectReportMapper reportMapper;

    /**
     * 差选项目列表信息
     * @param page
     * @param projectReportData
     * @return
     * @throws Exception
     */
    public IPage<ReportInfoDto> getList(Page<ReportInfoDto> page, ReportInfoDto projectReportData) throws Exception{
        QueryWrapper<ReportInfoDto> queryWrapper = QueryWrapperGenerator.buildQueryCondition (projectReportData,ReportInfoDto.class);
        queryWrapper.eq("a.del_flag","0");
        queryWrapper.orderByDesc("a.create_date");
        //条件
        if (StringUtils.isNotEmpty(projectReportData.getProjectNumber())) {
            queryWrapper.like("d.project_number", projectReportData.getProjectNumber());
        }
        if (StringUtils.isNotEmpty(projectReportData.getProjectName())) {
            queryWrapper.like("d.project_name", projectReportData.getProjectName());
        }
        if (StringUtils.isNotEmpty(projectReportData.getProjectMasterId())) {
            queryWrapper.eq("d.project_master_id", projectReportData.getProjectMasterId());
        }
        if (StringUtils.isNotEmpty(projectReportData.getCreateBy().getId())) {
            queryWrapper.like("a.create_by", projectReportData.getCreateBy().getId());
        }
        //创建时间
        String[] contractDates = projectReportData.getContractDates();
        if (contractDates != null) {

            queryWrapper.between("a.create_date", contractDates[0], contractDates[1]);
        }
        IPage<ReportInfoDto> list = applyMapper.getList(page, queryWrapper);
        return list;
    }

    /**
     * 修改状态
     * @param data
     * @return
     */
    public String updateStatusById(ReportInfoDto data) {
        ReportCancellApply cwProjectRecords = new ReportCancellApply();
        BeanUtils.copyProperties(data, cwProjectRecords);
        applyMapper.update(cwProjectRecords, new QueryWrapper<ReportCancellApply>().lambda().eq(ReportCancellApply::getId, cwProjectRecords.getId()));
        return "操作成功";
    }

    public ReportInfoDto queryById(String id) {
        ReportInfoDto reportData = applyMapper.queryById(id);
        return reportData;
    }

    /**
     * 保存项目以及其他相关信息
     * @param reportData
     * @return
     * @throws Exception
     */
    public synchronized String saveForm(ReportInfoDto reportData) throws Exception{
        if (StringUtils.isNotEmpty(reportData.getId())){

            ReportCancellApply report = applyMapper.selectById(reportData.getId());
            if (report != null){
                reportData.setCreateBy(reportData.getCreateBy());
                return update(reportData);
            }
        }
        return add(reportData);

    }

    /**
     * 合同登记修改
     */
    @Transactional(rollbackFor = Exception.class)
    public String update(ReportInfoDto reportData) throws Exception{
        //获取当前登录人信息
        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        //修改
        ReportCancellApply report = new ReportCancellApply();
        BeanUtils.copyProperties(reportData, report);
        report.setUpdateBy(userDTO.getId());
        report.setUpdateDate(new Date());

        applyMapper.updateById(report);
        //修改报告管理的del_flag
        if (report.getStatus().equals("5")){
            //当审核通过的时候，删除新建行的newLine信息
            infoMapper.deleteById(report.getReportNewLineId());
            //删除新建行下的文件信息
            //删除work_attachment_id信息
            attachmentMapper.deleteByAttachMnentId(report.getReportNewLineId());
            //根据新建行id找到报告管理表id
            CwProjectInfoData newLineInfo = infoMapper.getNewLineInfoById(report.getReportNewLineId());
            if (StringUtils.isNotEmpty(newLineInfo.getReportId())){
                //根据报告管理id去新建行表中查数据，当没有数据的时候，报告表该条数据逻辑删除
                int count = infoMapper.getCountByReportId(newLineInfo.getReportId());
                if (count == 0){
                    //当没有数据的时候删除报告管理信息
                    reportMapper.deleteById(newLineInfo.getReportId());
                }
            }

            //向存放报废报告号表中添加数据
            CwProjectReportCancel cancel = new CwProjectReportCancel();
            cancel.setId(UUID.randomUUID().toString().replace("-", ""));
            cancel.setReportNo(reportData.getReportNo());
            cancelMapper.insert(cancel);
        }
        //驳回撤回操作
//        if (report.getStatus().equals("3") || report.getStatus().equals("4")){
//            //根据新建行id修改newLine的作废删除标记
//            infoMapper.updateSignById(report.getReportNewLineId(),"1");
//        }
//        CwProjectInfoData newLine = infoMapper.getById(report.getReportNewLineId());
//        //根据newLine的reportid找到报告表
//        CwProjectReport projectReport = reportMapper.selectById(newLine.getReportId());
//        if (report.getStatus().equals("2")){
//            projectReport.setDelFlag(1);
//            reportMapper.updateDelFlag(projectReport.getDelFlag(),projectReport.getId());
//        }else if (report.getStatus().equals("1") || report.getStatus().equals("4") || report.getStatus().equals("3")){
//            projectReport.setDelFlag(0);
//            reportMapper.updateDelFlag(projectReport.getDelFlag(),projectReport.getId());
//        }

        return report.getId();
    }

    /**
     * 新增
     */
    @Transactional(rollbackFor = Exception.class)
    public String add(ReportInfoDto reportData) throws Exception{
        //获取当前登录人信息
        UserDTO userDTO = UserUtils.getCurrentUserDTO();

        ReportCancellApply report = new ReportCancellApply();
        BeanUtils.copyProperties(reportData, report);
        if (ObjectUtil.isNotEmpty(report)) {
            if (StringUtils.isBlank(report.getCreateBy())) {
                report.setCreateBy(UserUtils.getCurrentUserDTO().getId());
                String id = UUID.randomUUID().toString().replace("-", "");
                report.setId(id);
            }
        }
        //根据新建行id修改newLine的作废删除标记
        infoMapper.updateSignById(report.getReportNewLineId(),"1");

        this.applyMapper.insert(report);
//        //向存放报废报告号表中添加数据
//        CwProjectReportCancel cancel = new CwProjectReportCancel();
//        cancel.setId(UUID.randomUUID().toString().replace("-", ""));
//        cancel.setReportNo(reportData.getReportNo());
//        cancelMapper.insert(cancel);
//        applyMapper.updateById(report);
//
//        //修改报告管理的del_flag
//        CwProjectInfoData newLine = infoMapper.getById(report.getReportNewLineId());
//        //根据newLine的reportid找到报告表
//        CwProjectReport projectReport = reportMapper.selectById(newLine.getReportId());
//        if (report.getStatus().equals("2")){
//            projectReport.setDelFlag(1);
//            reportMapper.updateDelFlag(projectReport.getDelFlag(),projectReport.getId());
//        }else if (report.getStatus().equals("1") || report.getStatus().equals("4") || report.getStatus().equals("3")){
//            projectReport.setDelFlag(0);
//            reportMapper.updateDelFlag(projectReport.getDelFlag(),projectReport.getId());
//        }

        return report.getId();
    }

    /**
     * 差选项目列表信息
     * @param page
     * @param reportInfoDto
     * @return
     * @throws Exception
     */
    public IPage<ReportInfoDto> findList(Page<ReportInfoDto> page, ReportInfoDto reportInfoDto) throws Exception{
        QueryWrapper<ReportInfoDto> queryWrapper = QueryWrapperGenerator.buildQueryCondition (reportInfoDto,ReportInfoDto.class);
        //获取当前登录人信息
        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        queryWrapper.eq("a.create_by",userDTO.getId());
        queryWrapper.eq("a.del_flag","0");
        queryWrapper.eq("a.status","5");
        queryWrapper.eq("b.delete_sign","0");
//        queryWrapper.eq("cw_re.review_status","5");
        queryWrapper.isNotNull("b.report_no");
        queryWrapper.orderByDesc("a.create_date");
        if (StringUtils.isNotEmpty(reportInfoDto.getProjectName())) {
            queryWrapper.like("c.project_name", reportInfoDto.getProjectName());
        }
        IPage<ReportInfoDto> list = applyMapper.findList(page, queryWrapper);

        return list;
    }

    public ResponseEntity deleteByIds(String ids) {
        String idArray[] =ids.split(",");
        //删除前先将报告文号给复原
        ArrayList<String> strings = Lists.newArrayList(idArray);
//        for (int i=0;i<strings.size();i++){
//            //修改新建行的del_flag为0，delete_sign为0
//            ReportCancellApply cancellApply = applyMapper.selectById(strings.get(i));
//            CwProjectInfoData infoData = infoMapper.getById(cancellApply.getReportNewLineId());
//            infoData.setDelFlag(0);
//            infoData.setDeleteSign("0");
//            infoMapper.updateById(infoData);
//            ReportInfoDto reportInfoDto = applyMapper.queryById(strings.get(i));
//            cancelMapper.deleteByReportNo(reportInfoDto.getReportNo());
//        }
        //将报告文号报废表的对应的报告文号给删除

        this.removeByIds (Lists.newArrayList (idArray));
        return ResponseEntity.ok ("删除成功");
    }
}
