package com.jeeplus.finance.reportCancellApply.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.common.TokenProvider;
import com.jeeplus.common.constant.CacheNames;
import com.jeeplus.common.redis.RedisUtils;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.finance.projectReport.domain.CwProjectInfoData;
import com.jeeplus.finance.projectReport.domain.CwProjectReportCancel;
import com.jeeplus.finance.projectReport.domain.CwProjectReportData;
import com.jeeplus.finance.projectReport.mapper.CwProjectInfoMapper;
import com.jeeplus.finance.projectReport.mapper.CwProjectReportCancelMapper;
import com.jeeplus.finance.projectReport.mapper.CwProjectReportMapper;
import com.jeeplus.finance.projectReport.mapper.ProjectReportWorkAttachmentMapper;
import com.jeeplus.finance.projectReport.service.CwProjectReportService;
import com.jeeplus.finance.reportCancellApply.domain.ReportCancellApply;
import com.jeeplus.finance.reportCancellApply.mapper.ReportCancellApplyMapper;
import com.jeeplus.finance.reportCancellApply.service.dto.ReportInfoDto;
import com.jeeplus.flowable.feign.IFlowableApi;
import com.jeeplus.sys.domain.User;
import com.jeeplus.sys.feign.IRoleApi;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.service.dto.RoleDTO;
import com.jeeplus.sys.service.dto.UserDTO;
//import com.jeeplus.sys.utils.UserUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
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;

    @Autowired
    private IFlowableApi flowTaskService;

    @Resource
    private CwProjectReportService projectReportService;


    /**
     * 差选项目列表信息
     * @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");
        //条件
        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.getProjectMaster2Id())) {
            queryWrapper.eq("d.real_header", projectReportData.getProjectMaster2Id());
        }
        if (StringUtils.isNotEmpty(projectReportData.getProjectMasterName())) { // 项目经理1筛选
            queryWrapper.like("g.id", projectReportData.getProjectMasterName());
        }
        if (StringUtils.isNotEmpty(projectReportData.getProjectMaster2Name())) { // 项目经理2筛选
            queryWrapper.like("k.id", projectReportData.getProjectMaster2Name());
        }
        if (StringUtils.isNotEmpty(projectReportData.getCreateBy().getId())) {
            queryWrapper.like("a.create_by_id", projectReportData.getCreateBy().getId());
        }
        //创建时间
        String[] contractDates = projectReportData.getContractDates();
        if (contractDates != null) {

            queryWrapper.between("a.create_time", contractDates[0], contractDates[1]);
        }
        // 如果当前用户是部门主任，则可以查看部门所有的项目、自己创建的项目以及所属项目组的项目
        // 如果当前用户是员工，则可以查看自己创建的项目以及所属项目组的项目
        StringBuilder officeIds = new StringBuilder();
//        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        List<String> manageOfficeIdList= Lists.newArrayList();

        /*//获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken ( ));
        //获取当前登录人所属角色
        //若是评估部门主任，则仅展示部门主任信息
        //若是评估员工，则仅展示自己的数据信息
        List<RoleDTO> roleDTOList = userDTO.getRoleDTOList();
        for (RoleDTO roleDTO : roleDTOList) {
            //根据角色id查询角色信息
            RoleDTO roleDTOById = SpringUtil.getBean(IRoleApi.class).getRoleDTOById(roleDTO.getId());
            if("cwyg".equals(roleDTOById.getEnName()) && "兴光会计员工".equals(roleDTOById.getName())){
                queryWrapper.eq("a.create_by_id", userDTO.getId());
                break;
            }else if("cw_bmzr".equals(roleDTOById.getEnName()) && "兴光会计部门主任".equals(roleDTOById.getName())){
                queryWrapper.eq("sumo.user_id", userDTO.getId());
                break;
            }else if("zkbyg".equals(roleDTOById.getEnName()) && "质控部员工".equals(roleDTOById.getName())){
                queryWrapper.eq("cw_rev.review_by", userDTO.getId());
                break;
            }
        }*/

        long l1 = System.currentTimeMillis();
        IPage<ReportInfoDto> list = applyMapper.getList(page, queryWrapper,officeIds.toString());
        long l2 = System.currentTimeMillis();
        System.out.println("报告作废列表查询service方法消耗时间:" + (l2-l1));
        list.getRecords().stream().forEach(i -> {
            // 复核
            if (StringUtils.isNotBlank(i.getTaskId()) && StringUtils.isNotBlank(i.getStatus())) {
                if ("2".equals(i.getStatus())) { // “审核中”的数据要获取数据审核人
                    i.setAuditUserIds(flowTaskService.getTaskAuditUsers(i.getTaskId()));  // 获取数据审核人
                }
            }
        });
        long l3 = System.currentTimeMillis();
        System.out.println("报告作废列表查询service方法获取审核人数据消耗时间:" + (l3-l2));
//        List<UserDTO> allUserInfo = SpringUtil.getBean(IUserApi.class).getAllUserInfo();
        List<UserDTO> allUserInfo = (List<UserDTO>) RedisUtils.getInstance().get(CacheNames.USER_CACHE_USER_ALL_INFO);
        if (null == allUserInfo || allUserInfo.size() == 0) {
            allUserInfo = SpringUtil.getBean(IUserApi.class).getAllUserInfo();
        }
        List<UserDTO> finalAllUserInfo = allUserInfo;
        list.getRecords().forEach(li -> {
            if (StringUtils.isBlank(li.getProjectMasterName())){
                //根据项目经理1的id去查项目经理去名称
                if (StringUtils.isNotBlank(li.getProjectMasterId())){
                    UserDTO matchingUser = null;
                    for (UserDTO user : finalAllUserInfo) {
                        if (li.getProjectMasterId().equals(user.getId())) {
                            matchingUser = user;
                            break;
                        }
                    }
                    if (matchingUser != null) {
                        String projectMasterName = matchingUser.getName(); // Assuming the property name is "userName"
                        li.setProjectMasterName(projectMasterName);
                    }
                }
            } else if (StringUtils.isBlank(li.getProjectMaster2Name())) {
                if (StringUtils.isNotBlank(li.getProjectMaster2Id())){
                    UserDTO matchingUser = null;
                    for (UserDTO user : finalAllUserInfo) {
                        if (li.getProjectMaster2Id().equals(user.getId())) {
                            matchingUser = user;
                            break;
                        }
                    }
                    if (matchingUser != null) {
                        String projectMasterName = matchingUser.getName(); // Assuming the property name is "userName"
                        li.setProjectMaster2Name(projectMasterName);
                    }
                }
            }
        });
        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);
        if (ObjectUtil.isNotEmpty(reportData) && StringUtils.isNotBlank(reportData.getReportNo())) {
            String reportId = applyMapper.queryReportIdByReportNo(reportData.getReportNo());
            if (StringUtils.isNotBlank(reportId)) {
                CwProjectReportData cwProjectReportData = projectReportService.queryContainDelById(reportId);
                reportData.setReportDetail(cwProjectReportData);
            }
        }
        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 = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        //修改
        ReportCancellApply report = new ReportCancellApply();
        BeanUtils.copyProperties(reportData, report);
        report.setUpdateById(userDTO.getId());
        report.setUpdateTime(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.getCreateById())) {
                report.setCreateById(SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken()).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);
        // 查询当前作废表中有效的报告文号  获取这些报告文号所属new_line表id
        List<ReportCancellApply> reportCancellApplies = this.list(new QueryWrapper<>());
        if (CollectionUtil.isNotEmpty(reportCancellApplies)) {
            List<String> newLineIdList = reportCancellApplies.stream().filter(item -> {
                if (StringUtils.isNotBlank(item.getReportNewLineId())) {
                    return true;
                }
                return false;
            }).map(ReportCancellApply::getReportNewLineId).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(newLineIdList)) {
                queryWrapper.notIn("b.id",newLineIdList);
            }
        }
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        queryWrapper.eq("a.create_by_id",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_time");
        if (StringUtils.isNotEmpty(reportInfoDto.getProjectName())) {
            queryWrapper.like("c.project_name", reportInfoDto.getProjectName());
        }

        /*//获取当前登录人所属角色
        //若是评估部门主任，则仅展示部门主任信息
        //若是评估员工，则仅展示自己的数据信息
        List<RoleDTO> roleDTOList = userDTO.getRoleDTOList();
        for (RoleDTO roleDTO : roleDTOList) {
            //根据角色id查询角色信息
            RoleDTO roleDTOById = SpringUtil.getBean(IRoleApi.class).getRoleDTOById(roleDTO.getId());
            if("cwyg".equals(roleDTOById.getEnName()) && "兴光会计员工".equals(roleDTOById.getName())){
                queryWrapper.eq("a.create_by_id", userDTO.getId());
                break;
            }else if("cw_bmzr".equals(roleDTOById.getEnName()) && "兴光会计部门主任".equals(roleDTOById.getName())){
                queryWrapper.eq("sumo.user_id", userDTO.getId());
                break;
            }else if("zkbyg".equals(roleDTOById.getEnName()) && "质控部员工".equals(roleDTOById.getName())){
                queryWrapper.eq("cw_rev.review_by", userDTO.getId());
                break;
            }else if("szfbdagly".equals(roleDTOById.getEnName()) && "苏州分部档案管理员".equals(roleDTOById.getName())){
                queryWrapper.eq("d.office_id", "1613800824395530242");
                break;
            }
        }*/

        IPage<ReportInfoDto> list = applyMapper.findList(page, queryWrapper);

        return list;
    }

    public ResponseEntity deleteByIds(String ids) {
        String idArray[] =ids.split(",");
        //删除前先将报告文号以及相关信息给复原
        ArrayList<String> strings = Lists.newArrayList(idArray);
        strings.stream().forEach(cancId->{
            // 根据作废数据id查询作废信息
            ReportCancellApply byId = this.getById(cancId);
            // 根据new_line表id复原新建行new_line表的信息
            infoMapper.saveById(byId.getReportNewLineId());
            // 根据new_line表id找到报告管理表id
            CwProjectInfoData newLineInfo = infoMapper.getNewLineInfoById(byId.getReportNewLineId());
            //根据报告管理表id复原报告管理表数据
            reportMapper.saveById(newLineInfo.getReportId());
            //存放报废报告号表中删除复原的数据（cw_project_report_cancel）根据报告文号
            cancelMapper.deleteByReportNo(newLineInfo.getReportNo());
        });
        // 根据id删除作废表中的数据（cw_project_report_cancell_apply）（根据id批量删除）
        this.removeByIds (strings);
        return ResponseEntity.ok ("删除成功");
    }

    public CwProjectReportData queryByNo(String no) {
        CwProjectReportData cwProjectReportData = new CwProjectReportData();
        if (StringUtils.isNotBlank(no)) {
            String reportId = applyMapper.queryReportIdByReportNo(no);
            if (StringUtils.isNotBlank(reportId)) {
                cwProjectReportData = projectReportService.queryById(reportId);
            }
        }
        return cwProjectReportData;
    }
}
