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

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.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import digital.laboratory.platform.common.mybatis.security.service.DLPUser;
import digital.laboratory.platform.reagent.dto.AuditAndApproveDTO;
import digital.laboratory.platform.reagent.dto.ComplianceCheckDTO;
import digital.laboratory.platform.reagent.entity.*;
import digital.laboratory.platform.reagent.mapper.ComplianceCheckMapper;
import digital.laboratory.platform.reagent.service.*;
import digital.laboratory.platform.reagent.vo.ComplianceCheckVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * (符合性检查记录表)服务实现类
 *
 * @author Zhang Xiaolong created at  2023-03-10
 * @describe (符合性检查记录表) 服务实现类
 */
@Service
public class ComplianceCheckServiceImpl extends ServiceImpl<ComplianceCheckMapper, ComplianceCheck> implements ComplianceCheckService {

    @Autowired
    private ComplianceCheckService complianceCheckService;
    @Autowired
    private ReagentConsumableInventoryService reagentConsumableInventoryService;

    @Autowired
    private BatchDetailsService batchDetailsService;

    @Autowired
    private BlacklistService blacklistService;

    @Autowired
    private ReagentConsumablesService reagentConsumablesService;


    @Override
    public IPage<ComplianceCheckVO> getComplianceCheckVOPage(IPage<ComplianceCheck> page, QueryWrapper<ComplianceCheck> qw) {

        IPage<ComplianceCheckVO> complianceCheckVOPage = baseMapper.getComplianceCheckVOPage(page, qw);

        List<ComplianceCheckVO> records = complianceCheckVOPage.getRecords();

        for (ComplianceCheckVO record : records) {

            LambdaQueryWrapper<ReagentConsumables> reagentConsumablesLambdaQueryWrapper = new LambdaQueryWrapper<>();

            reagentConsumablesLambdaQueryWrapper.eq(ReagentConsumables::getReagentConsumableId,record.getReagentConsumableId());

            ReagentConsumables one = reagentConsumablesService.getOne(reagentConsumablesLambdaQueryWrapper);

            record.setReagentConsumableName(one.getReagentConsumableName());
        }

        return complianceCheckVOPage;
    }

    @Override
    public List<ComplianceCheckVO> getComplianceCheckVOList(QueryWrapper<ComplianceCheck> qw) {
        List<ComplianceCheckVO> complianceCheckVOList = baseMapper.getComplianceCheckVOList(qw);
        return complianceCheckVOList;
    }

    @Override//通过ID查询符合性检查记录
    public ComplianceCheckVO getComplianceCheckVO(String complianceCheckId) {

        ComplianceCheckVO complianceCheckVO = baseMapper.getComplianceCheckVO(complianceCheckId);

        LambdaQueryWrapper<ReagentConsumables> reagentConsumablesLambdaQueryWrapper = new LambdaQueryWrapper<>();

        reagentConsumablesLambdaQueryWrapper.eq(ReagentConsumables::getReagentConsumableId,complianceCheckVO.getReagentConsumableId());

        ReagentConsumables one = reagentConsumablesService.getOne(reagentConsumablesLambdaQueryWrapper);

        complianceCheckVO.setReagentConsumableName(one.getReagentConsumableName());

        return complianceCheckVO;

    }


    @Transactional
    @Override//新增符合性检查
    public ComplianceCheck addCheck(ComplianceCheckDTO complianceCheckDTO, DLPUser dlpUser) {

        ComplianceCheck complianceCheck = new ComplianceCheck();

        complianceCheck.setComplianceCheckId(IdWorker.get32UUID().toUpperCase());

        BeanUtils.copyProperties(complianceCheckDTO, complianceCheck);

        if (complianceCheckService.save(complianceCheck)) {
            return complianceCheck;
        } else {
            throw new RuntimeException(String.format("保存失败"));
        }

    }

    @Override//手动新增符合性检查
    public List<ComplianceCheck> addCheckList(List<ComplianceCheckDTO> list, DLPUser dlpUser) {

        List<ComplianceCheck> complianceChecks = new ArrayList<>();

        for (ComplianceCheckDTO complianceCheckDTO : list) {

            ComplianceCheck complianceCheck = complianceCheckService.addCheck(complianceCheckDTO, dlpUser);

            complianceChecks.add(complianceCheck);
        }
        if (complianceChecks != null) {
            return complianceChecks;
        } else throw new RuntimeException(String.format("保存失败"));
    }


    @Override//删除符合性检查
    public Boolean delCheckById(String complianceCheckId) {

        return complianceCheckService.removeById(complianceCheckId);
    }

    @Transactional
    @Override//录入结论
    public ComplianceCheck editCheckById(ComplianceCheckDTO complianceCheckDTO) {

        ComplianceCheck byId = complianceCheckService.getById(complianceCheckDTO.getComplianceCheckId());

        if (complianceCheckDTO.getInspectionScheme() == null) {
            throw new RuntimeException(String.format("请先制定检查方案"));
        }
        byId.setExaminationConclusion(complianceCheckDTO.getExaminationConclusion());

        String nonconformingItem = byId.getNonconformingItem();

        byId.setDateOfInspection(LocalDateTime.now());

        if (nonconformingItem != null) {
            //若存在不合格项目，将其添加至黑名单
            BatchDetails batchDetails = batchDetailsService.getById(complianceCheckDTO.getBatchDetailsId());

            blacklistService.addListById(byId.getReagentConsumableId(), batchDetails.getSupplierId());

            if (complianceCheckService.updateById(byId)) {
                return byId;
            } else throw new RuntimeException(String.format("录入失败"));
        }
        return byId;
    }

    @Override//录入方案
    public ComplianceCheck addScheme(ComplianceCheckDTO complianceCheckDTO) {

        ComplianceCheck byId = complianceCheckService.getById(complianceCheckDTO.getComplianceCheckId());

        byId.setInspectionScheme(complianceCheckDTO.getInspectionScheme());

        if (complianceCheckService.updateById(byId)) {
            return byId;
        } else return null;

    }

    @Override//提交符合性检查
    public ComplianceCheck commitCheck(ComplianceCheckDTO complianceCheckDTO, DLPUser dlpUser) {

        String complianceCheckId = complianceCheckDTO.getComplianceCheckId();

        ComplianceCheck byId = complianceCheckService.getById(complianceCheckId);

        if (byId != null) {

            byId.setStatus(1);

            if (complianceCheckService.updateById(byId)) {
                return byId;
            } else {
                return null;
            }
        } else {
            ComplianceCheck complianceCheck = complianceCheckService.addCheck(complianceCheckDTO, dlpUser);
            complianceCheck.setStatus(1);

            if (complianceCheckService.updateById(complianceCheck)) {
                return complianceCheck;
            } else return null;
        }
    }

    @Override//一级审核
    public ComplianceCheck primaryAuditCheck(AuditAndApproveDTO auditAndApproveDTO, DLPUser dlpUser) {

        ComplianceCheck byId = complianceCheckService.getById(auditAndApproveDTO.getUuId());

        if (byId.getStatus() != 1) {
            throw new RuntimeException(String.format("当前状态不可审核"));
        }

        byId.setAuditOpinionOfPrimary(auditAndApproveDTO.getAuditOpinion());

        byId.setAuditResultOfPrimary(auditAndApproveDTO.getAuditResult());

        byId.setAuditTimeOfPrimary(LocalDateTime.now());

        byId.setPrimaryAuditorId(dlpUser.getId());

        if (complianceCheckService.updateById(byId)) {
            return byId;
        } else {
            return null;
        }
    }

    @Override//二级审核
    public ComplianceCheck secondaryAuditCheck(AuditAndApproveDTO auditAndApproveDTO, DLPUser dlpUser) {

        ComplianceCheck byId = complianceCheckService.getById(auditAndApproveDTO.getUuId());

        if (byId.getStatus() != 1) {
            throw new RuntimeException(String.format("当前状态不可审核"));
        }

        byId.setAuditOpinionOfSecondary(auditAndApproveDTO.getAuditOpinion());

        byId.setAuditResultOfSecondary(auditAndApproveDTO.getAuditResult());

        byId.setAuditTimeOfSecondary(LocalDateTime.now());

        byId.setSecondaryAuditorId(dlpUser.getId());

        byId.setStatus(2);

        if (complianceCheckService.updateById(byId)) {
            return byId;
        } else {
            return null;
        }
    }
}
