package digital.laboratory.platform.imr.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import digital.laboratory.platform.common.mybatis.security.service.DLPUser;
import digital.laboratory.platform.imr.dto.ReviewApprovalDTO;
import digital.laboratory.platform.imr.dto.ReviewSampleDetail;
import digital.laboratory.platform.imr.entity.SampleApply;
import digital.laboratory.platform.imr.entity.SampleApplyDetailed;
import digital.laboratory.platform.imr.entity.SampleStorage;
import digital.laboratory.platform.imr.enums.ApplyStatus;
//import digital.laboratory.platform.imr.entity.enums.SampleStatus;
import digital.laboratory.platform.imr.feign.TransferFeignService;
import digital.laboratory.platform.imr.mapper.SampleApplyDetailedMapper;
import digital.laboratory.platform.imr.mapper.SampleApplyMapper;
import digital.laboratory.platform.imr.mapper.SampleStorageMapper;
import digital.laboratory.platform.imr.service.ReviewApprovalService;
import digital.laboratory.platform.imr.service.SampleApplyService;
import digital.laboratory.platform.imr.vo.SampleApplyVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class ReviewApprovalServiceImpl implements ReviewApprovalService {



    private final SampleApplyMapper sampleApplyMapper;

    private final SampleApplyDetailedMapper detailedMapper;


    private final SampleApplyService sampleApprovalService;


    private final TransferFeignService transferFeignService;


    private final SampleStorageMapper sampleStorageMapper;


    /**
     * 一级审核员审核
     * @param dto
     * @param dlpUser
     * @return
     */
    @Override
    @Transactional
    public SampleApplyVO firstAudit(ReviewApprovalDTO dto, DLPUser dlpUser) {

        //查找对应的申请
        SampleApply sampleApply = sampleApplyMapper.selectById(dto.getApplyId());
        if(sampleApply == null){
            throw new RuntimeException("当前数据不存在");
        } else if (sampleApply.getApplyType()==1) {//外带申请
            if(sampleApply.getApplicationStatus()!=ApplyStatus.FIRST_LEVEL){
                throw new RuntimeException("当前数据不是待一级审核状态");
            }
        }
        //判断无误
        sampleApply.setFirstAuditDate(LocalDateTime.now());//时间
        sampleApply.setFirstAuditOpinion(dto.getOpinion());//意见
        sampleApply.setFirstAuditorId(dlpUser.getId());//一级审核员

        QueryWrapper<SampleApplyDetailed> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("apply_id",dto.getApplyId());
        List<SampleApplyDetailed> applyDetailed = detailedMapper.selectList(queryWrapper);
        ArrayList<String> idList = new ArrayList<>();
        List<ReviewSampleDetail> sampleDetails = dto.getReviewSampleDetails();

        if(dto.getStatus()==-1){//点击不通过按钮;勾选的数据为不通过

            //循环有的
            for (ReviewSampleDetail detail:sampleDetails) {
                //传值为不通过样本
                SampleApplyDetailed sampleApplyDetailed = detailedMapper.selectById(detail.getId());
                sampleApplyDetailed.setStatus(-1);
                detailedMapper.updateById(sampleApplyDetailed);
                idList.add(detail.getId());
            }
            //循环没有的
            QueryWrapper<SampleApplyDetailed> not = queryWrapper.notIn("id", idList);
            List<SampleApplyDetailed> detaileds = detailedMapper.selectList(not);
            if(!detaileds.isEmpty()) {
                for (SampleApplyDetailed detail : detaileds) {
                    detail.setStatus(1);//没有传值的为不通过
                    detailedMapper.updateById(detail);
                }
                sampleApply.setApplicationStatus(ApplyStatus.SECOND_LEVEL);
            }else {
                sampleApply.setApplicationStatus(ApplyStatus.FIRST_LEVEL_FAIL);
                for (ReviewSampleDetail detail:sampleDetails) {
                    //申请不通过的要恢复状态
                    SampleApplyDetailed sampleApplyDetailed = detailedMapper.selectById(detail.getId());
                    if(sampleApply.getApplyType()==2){
                        transferFeignService.updateStatus(sampleApplyDetailed.getSampleId(),2);
                    }else {
                        transferFeignService.updateStatus(sampleApplyDetailed.getSampleId(),1);
                    }
                }
            }
        }else {
            //循环有的
            for (ReviewSampleDetail detail:sampleDetails) {
                //传值为通过样本
                SampleApplyDetailed sampleApplyDetailed = detailedMapper.selectById(detail.getId());
                sampleApplyDetailed.setStatus(1);
                detailedMapper.updateById(sampleApplyDetailed);
                idList.add(detail.getId());
            }
            //循环没有的
            QueryWrapper<SampleApplyDetailed> not = queryWrapper.notIn("id", idList);
            List<SampleApplyDetailed> detaileds = detailedMapper.selectList(not);
            if(!detaileds.isEmpty()) {
                for (SampleApplyDetailed detail : detaileds) {
                    detail.setStatus(-1);//没有传值的为不通过
                    detailedMapper.updateById(detail);
                }
            }
            sampleApply.setApplicationStatus(ApplyStatus.SECOND_LEVEL);
        }

        /*QueryWrapper<SampleApplyDetailed> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("apply_id",dto.getApplyId());
        List<SampleApplyDetailed> applyDetailed = detailedMapper.selectList(queryWrapper);


        if(dto.getReviewSampleDetails().isEmpty()){
            //如果传值为空说明全部不通过
            sampleApply.setApplicationStatus(ApplyStatus.FIRST_LEVEL_FAIL);
            for (SampleApplyDetailed detailed:applyDetailed) {
                detailed.setStatus(-1);//不通过
                detailedMapper.updateById(detailed);
            }
        }else {
            //传值对应的样本状态为通过;没有的则为不通过
            sampleApply.setApplicationStatus(ApplyStatus.SECOND_LEVEL);
            ArrayList<String> idList = new ArrayList<>();

            for (ReviewSampleDetail reviewSampleDetail : dto.getReviewSampleDetails()) {
                SampleApplyDetailed detailed = detailedMapper.selectById(reviewSampleDetail.getId());
                detailed.setStatus(1);//通过
                detailedMapper.updateById(detailed);
                idList.add(reviewSampleDetail.getId());
            }
            QueryWrapper<SampleApplyDetailed> not = queryWrapper.notIn("id", idList);
            List<SampleApplyDetailed> detaileds = detailedMapper.selectList(not);
            if(detaileds!=null) {
                for (SampleApplyDetailed detail : detaileds) {
                    detail.setStatus(-1);//没有传值的为不通过
                    detailedMapper.updateById(detail);
                }
            }
        }*/
        sampleApplyMapper.updateById(sampleApply);

        return sampleApprovalService.getDetail(dto.getApplyId());
    }

    /**
     * 二级审核
     * @param dto
     * @param dlpUser
     * @return
     */
    @Override
    public SampleApplyVO secondaryAudit(ReviewApprovalDTO dto, DLPUser dlpUser) {
        //查找对应的申请
        SampleApply sampleApply = sampleApplyMapper.selectById(dto.getApplyId());
        if(sampleApply == null){
            throw new RuntimeException(String.format("当前数据不存在"));
        } else if (sampleApply.getApplyType()==1) {//外带申请
            if(sampleApply.getApplicationStatus()!=ApplyStatus.SECOND_LEVEL){
                throw new RuntimeException(String.format("当前数据不是待二级审核状态"));
            }
        }
        //判断无误
        sampleApply.setSecondaryAuditDate(LocalDateTime.now());//时间
        sampleApply.setSecondaryAuditOpinion(dto.getOpinion());//意见
        sampleApply.setSecondaryAuditorId(dlpUser.getId());//二级级审核员


        QueryWrapper<SampleApplyDetailed> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("apply_id",dto.getApplyId());
        List<SampleApplyDetailed> applyDetailed = detailedMapper.selectList(queryWrapper);
        ArrayList<String> idList = new ArrayList<>();
        List<ReviewSampleDetail> sampleDetails = dto.getReviewSampleDetails();

        if(dto.getStatus()==-1){//点击不通过按钮;勾选的数据为不通过

            //循环有的
            for (ReviewSampleDetail detail:sampleDetails) {
                //传值为不通过样本
                SampleApplyDetailed sampleApplyDetailed = detailedMapper.selectById(detail.getId());
                sampleApplyDetailed.setStatus(-1);
                detailedMapper.updateById(sampleApplyDetailed);
                idList.add(detail.getId());
            }
            //循环没有的
            QueryWrapper<SampleApplyDetailed> not = queryWrapper.notIn("id", idList);
            List<SampleApplyDetailed> detaileds = detailedMapper.selectList(not);
            if(!detaileds.isEmpty()) {
                for (SampleApplyDetailed detail : detaileds) {
                    detail.setStatus(1);//没有传值的为不通过
                    detailedMapper.updateById(detail);
                }
                sampleApply.setApplicationStatus(ApplyStatus.PENDING_APPROVAL);
            }else {
                sampleApply.setApplicationStatus(ApplyStatus.SECOND_LEVEL_FAIL);
                for (ReviewSampleDetail detail:sampleDetails) {
                    //申请不通过的要恢复状态
                    SampleApplyDetailed sampleApplyDetailed = detailedMapper.selectById(detail.getId());
                    if(sampleApply.getApplyType()==2){
                        transferFeignService.updateStatus(sampleApplyDetailed.getSampleId(),2);
                    }else {
                        transferFeignService.updateStatus(sampleApplyDetailed.getSampleId(),1);
                    }
                }

            }
        }else {
            //循环有的
            for (ReviewSampleDetail detail:sampleDetails) {
                //传值为通过样本
                SampleApplyDetailed sampleApplyDetailed = detailedMapper.selectById(detail.getId());
                sampleApplyDetailed.setStatus(1);
                detailedMapper.updateById(sampleApplyDetailed);
                idList.add(detail.getId());
            }
            //循环没有的
            QueryWrapper<SampleApplyDetailed> not = queryWrapper.notIn("id", idList);
            List<SampleApplyDetailed> detaileds = detailedMapper.selectList(not);
            if(detaileds!=null) {
                for (SampleApplyDetailed detail : detaileds) {
                    detail.setStatus(-1);//没有传值的为不通过
                    detailedMapper.updateById(detail);
                }
            }
            sampleApply.setApplicationStatus(ApplyStatus.PENDING_APPROVAL);
        }
        sampleApplyMapper.updateById(sampleApply);
        return sampleApprovalService.getDetail(dto.getApplyId());
    }



    @Override
    @Transactional
    public SampleApplyVO approval(ReviewApprovalDTO dto, DLPUser dlpUser) {
        //查找对应的申请
        SampleApply sampleApply = sampleApplyMapper.selectById(dto.getApplyId());
        if(sampleApply == null){
            throw new RuntimeException(String.format("当前数据不存在"));
        }else if(sampleApply.getApplicationStatus()!=ApplyStatus.PENDING_APPROVAL){
            throw new RuntimeException(String.format("当前数据不是待审批状态"));
        }
        //判断无误
        sampleApply.setApprovalDate(LocalDateTime.now());//时间
        sampleApply.setApproverOpinion(dto.getOpinion());//意见
        sampleApply.setApproverId(dlpUser.getId());//审批人


        QueryWrapper<SampleApplyDetailed> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("apply_id",dto.getApplyId());
        List<SampleApplyDetailed> applyDetailed = detailedMapper.selectList(queryWrapper);
        ArrayList<String> idList = new ArrayList<>();
        List<ReviewSampleDetail> sampleDetails = dto.getReviewSampleDetails();

        if(dto.getStatus()==-1){//点击不通过按钮;勾选的数据为不通过

            //循环有的
            for (ReviewSampleDetail detail:sampleDetails) {
                //传值为不通过样本
                SampleApplyDetailed sampleApplyDetailed = detailedMapper.selectById(detail.getId());
                sampleApplyDetailed.setStatus(-1);
                if(sampleApply.getApplyType()==2){
                    transferFeignService.updateStatus(sampleApplyDetailed.getSampleId(),2);
                }else {
                    transferFeignService.updateStatus(sampleApplyDetailed.getSampleId(),1);
                }
                detailedMapper.updateById(sampleApplyDetailed);
                idList.add(detail.getId());
            }
            //循环没有的
            QueryWrapper<SampleApplyDetailed> not = queryWrapper.notIn("id", idList);
            List<SampleApplyDetailed> detaileds = detailedMapper.selectList(not);
            if(!detaileds.isEmpty()) {
                for (SampleApplyDetailed detail : detaileds) {
                    detail.setStatus(1);//没有传值的为不通过
                    detailedMapper.updateById(detail);
                    if(sampleApply.getApplyType()==2){//如果是销毁申请需要改变预警状态
                        UpdateWrapper<SampleStorage> updateWrapper = new UpdateWrapper<>();
                        updateWrapper.eq("sample_id",detail.getSampleId());
                        updateWrapper.set("early_warning",2);//销毁预警状态修改为2--通过审核审批
                        sampleStorageMapper.update(null,updateWrapper);
                        transferFeignService.updateStatus(detail.getSampleId(),7);//样本状态为待销毁
                    }else {
                        //外带申请需要恢复状态
                        transferFeignService.updateStatus(detail.getSampleId(),1);
                    }
                }
                sampleApply.setApplicationStatus(ApplyStatus.APPROVED);
            }else {
                sampleApply.setApplicationStatus(ApplyStatus.APPROVAL_FAILED);
            }
        }else {//点击通过按钮
            //循环有的
            for (ReviewSampleDetail detail:sampleDetails) {
                //传值为通过样本
                SampleApplyDetailed sampleApplyDetailed = detailedMapper.selectById(detail.getId());
                sampleApplyDetailed.setStatus(1);
                detailedMapper.updateById(sampleApplyDetailed);
                idList.add(detail.getId());

                if(sampleApply.getApplyType()==2){//如果是销毁申请需要改变预警状态
                    UpdateWrapper<SampleStorage> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("sample_id",sampleApplyDetailed.getSampleId());
                    updateWrapper.set("early_warning",2);//销毁预警状态修改为2--通过审核审批
                    sampleStorageMapper.update(null,updateWrapper);
                    transferFeignService.updateStatus(sampleApplyDetailed.getSampleId(),7);//样本状态为待销毁
                }else {
                    //外带申请需要恢复状态
                    transferFeignService.updateStatus(sampleApplyDetailed.getSampleId(),1);
                }
            }
            //循环没有的
            QueryWrapper<SampleApplyDetailed> not = queryWrapper.notIn("id", idList);
            List<SampleApplyDetailed> detaileds = detailedMapper.selectList(not);
            if(!detaileds.isEmpty()) {
                for (SampleApplyDetailed detail : detaileds) {
                    detail.setStatus(-1);//没有传值的为不通过
                    detailedMapper.updateById(detail);
                    if(sampleApply.getApplyType()==2){
                        transferFeignService.updateStatus(detail.getSampleId(),2);
                    }else {
                        transferFeignService.updateStatus(detail.getSampleId(),1);
                    }
                }
            }
            sampleApply.setApplicationStatus(ApplyStatus.APPROVED);
        }
        sampleApplyMapper.updateById(sampleApply);
        return sampleApprovalService.getDetail(dto.getApplyId());
    }

}
