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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import digital.laboratory.platform.common.aop.annotation.DlpResultProc;
import digital.laboratory.platform.common.core.exception.ValidateCodeException;
import digital.laboratory.platform.common.mybatis.security.service.DLPUser;
import digital.laboratory.platform.common.security.util.SecurityUtils;
import digital.laboratory.platform.imr.convert.DrugHandingOverApplyConvert;
import digital.laboratory.platform.imr.dto.DrugHandingOverReviewDTO;
import digital.laboratory.platform.imr.entity.DrugCaseInfo;
import digital.laboratory.platform.imr.entity.DrugHandingOverApply;
import digital.laboratory.platform.imr.entity.DrugMaterialInfo;
import digital.laboratory.platform.imr.enums.DrugHandingOverApplyStatus;
import digital.laboratory.platform.imr.enums.DrugMaterialStatus;
import digital.laboratory.platform.imr.query.DrugHandingOverApplyQuery;
import digital.laboratory.platform.imr.service.DrugCaseInfoService;
import digital.laboratory.platform.imr.service.DrugHandingOverApplyService;
import digital.laboratory.platform.imr.mapper.DrugHandingOverApplyMapper;
import digital.laboratory.platform.imr.service.DrugMaterialInfoService;
import digital.laboratory.platform.imr.vo.DrugHandingOverApplyVO;
import digital.laboratory.platform.sys.entity.Drug;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author ChenJiangBao
* @description 针对表【b_drug_handing_over_apply(毒品库中关联的案事件信息)】的数据库操作Service实现
* @createDate 2025-01-08 17:30:46
*/
@Service
public class DrugHandingOverApplyServiceImpl extends ServiceImpl<DrugHandingOverApplyMapper, DrugHandingOverApply>
    implements DrugHandingOverApplyService{

    @Resource
    private DrugCaseInfoService drugCaseInfoService;

    @Resource
    private DrugMaterialInfoService drugMaterialInfoService;

    /**
     * 创建毒品送缴申请-委托单位操作
     * @return
     */
    @Override
    @DlpResultProc
    public DrugHandingOverApplyVO create() {
        DLPUser user = SecurityUtils.getUser();
        DrugHandingOverApply entity = new DrugHandingOverApply();
        entity.setHandingOverUser(user.getId());
        entity.setHandingOverOrg(user.getOrgId());
        entity.setApplyDate(LocalDateTime.now());
        entity.setStatus(DrugHandingOverApplyStatus.WAIT_HANDING_OVER.getStatus());
        if (super.save(entity)) {
            return DrugHandingOverApplyConvert.entityToVO(entity);
        }
        return null;
    }

    /**
     * 根据毒品送缴申请查询条件分页查询毒品送缴申请VO对象
     *
     * @param query 查询条件
     * @return 分页后的毒品送缴申请视图对象列表
     */
    @Override
    public IPage<DrugHandingOverApplyVO> voPage(DrugHandingOverApplyQuery query) {
        LambdaQueryWrapper<DrugHandingOverApply> lambdaQueryWrapper = appendQueryCriteria(query);
        Page<DrugHandingOverApply> page = super.page(new Page<>(query.getCurrent(), query.getSize()), lambdaQueryWrapper);

        IPage<DrugHandingOverApplyVO> voPage = new Page<>();
        BeanUtils.copyProperties(page, voPage, "records");
        voPage.setRecords(DrugHandingOverApplyConvert.entityToVOList(page.getRecords()));
        return voPage;
    }

    /**
     * 删除送缴申请
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(List<String> ids) {
        List<DrugHandingOverApply> drugHandingOverApplies = super.listByIds(ids);
        for (DrugHandingOverApply drugHandingOverApply : drugHandingOverApplies) {
            if (!drugHandingOverApply.getStatus().equals(DrugHandingOverApplyStatus.WAIT_HANDING_OVER.getStatus())) {
                throw new ValidateCodeException(String.format("id为 %s 的申请已经送缴，不能删除！"));
            }
        }

        if (super.removeByIds(ids)) {
            List<DrugCaseInfo> drugCaseInfoList = drugCaseInfoService.list(Wrappers.<DrugCaseInfo>lambdaQuery().in(DrugCaseInfo::getApplyId, ids));
            if (CollUtil.isNotEmpty(drugCaseInfoList)) {
                List<String> caseIdList = drugCaseInfoList.stream().map(DrugCaseInfo::getId).collect(Collectors.toList());
                drugCaseInfoService.removeByIds(caseIdList);
                List<DrugMaterialInfo> drugMaterialInfos = drugMaterialInfoService.list(Wrappers.<DrugMaterialInfo>lambdaQuery().in(DrugMaterialInfo::getCaseId, caseIdList));
                if (CollUtil.isNotEmpty(drugMaterialInfos)) {
                    drugMaterialInfoService.remove(Wrappers.<DrugMaterialInfo>lambdaQuery().in(DrugMaterialInfo::getCaseId, caseIdList));
                }
            }
        } else {
            return false;
        }
        return true;
    }

    /**
     * 审核送缴申请
     *
     * @param dto
     * @param user
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public DrugHandingOverApplyVO review(DrugHandingOverReviewDTO dto, DLPUser user) {
        DrugHandingOverApply byId = super.getById(dto.getId());
        if (byId == null) {
            throw new ValidateCodeException("数据不存在！");
        }
        if (!byId.getStatus().equals(DrugHandingOverApplyStatus.WAIT_ACCEPT.getStatus())) {
            throw new ValidateCodeException("该申请不在 [待审核] 状态！");
        }

        boolean update = super.update(Wrappers.<DrugHandingOverApply>lambdaUpdate()
                .eq(DrugHandingOverApply::getId, dto.getId())
                .set(DrugHandingOverApply::getReason, dto.getReason())
                .set(DrugHandingOverApply::getReviewer, user.getId())
                .set(DrugHandingOverApply::getReviewDate, LocalDateTime.now())
                .set(DrugHandingOverApply::getStatus,
                        dto.getIsPass() == 1 ? DrugHandingOverApplyStatus.AGREE_ACCEPT.getStatus() : DrugHandingOverApplyStatus.REJECT_ACCEPT.getStatus()
                )
        );
        if (update) {
            if (dto.getIsPass() == 1) {
                // 更新毒品检材状态
                drugMaterialInfoService.update(
                        Wrappers.<DrugMaterialInfo>lambdaUpdate()
                                .inSql(DrugMaterialInfo::getCaseId, String.format("SELECT case_id FROM b_drug_case_info WHERE apply_id = '%s'", dto.getId()))
                                .set(DrugMaterialInfo::getStatus, DrugMaterialStatus.WAIT_INBOUND.getStatus())
                );
            }
            return DrugHandingOverApplyConvert.entityToVO(super.getById(dto.getId()));
        }
        return null;
    }

    /**
     * 提交送缴申请
     * @param applyId
     * @return
     */
    @Override
    public boolean submit(String applyId) {
        DrugHandingOverApply preInfo = super.getById(applyId);
        if (preInfo == null) {
            throw new ValidateCodeException("数据不存在！");
        }
        if (!preInfo.getStatus().equals(DrugHandingOverApplyStatus.WAIT_HANDING_OVER.getStatus())) {
            throw new ValidateCodeException("该申请不在 [待提交] 状态！");
        }
        return super.update(Wrappers.<DrugHandingOverApply>lambdaUpdate()
                .eq(DrugHandingOverApply::getId, applyId)
                .set(DrugHandingOverApply::getHandingOverDate, LocalDateTime.now())
                .set(DrugHandingOverApply::getStatus, DrugHandingOverApplyStatus.WAIT_ACCEPT.getStatus())
        );
    }

    /**
     * 根据给定的查询条件构建LambdaQueryWrapper查询对象
     *
     * @param query 查询条件对象，包含时间范围类型、用户查询类型等
     * @return 构建的LambdaQueryWrapper查询对象
     */
    private LambdaQueryWrapper<DrugHandingOverApply> appendQueryCriteria(DrugHandingOverApplyQuery query) {
        DLPUser user = SecurityUtils.getUser();
        Integer timeRangeType = query.getTimeRangeType();
        Integer userQueryType = query.getUserQueryType();
        LambdaQueryWrapper<DrugHandingOverApply> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(!user.isStaff(), DrugHandingOverApply::getHandingOverOrg, user.getOrgId());
        // 受理单位不需要看待提交的申请
        lambdaQueryWrapper.ne(user.isStaff(), DrugHandingOverApply::getStatus, DrugHandingOverApplyStatus.WAIT_HANDING_OVER.getStatus());
        if (timeRangeType != null) {
            if (timeRangeType == 1) {
                lambdaQueryWrapper.ge(query.getStartDate() != null, DrugHandingOverApply::getApplyDate, query.getStartDate())
                        .le(query.getEndDate() != null, DrugHandingOverApply::getApplyDate, query.getEndDate());
            } else if (timeRangeType == 2) {
                lambdaQueryWrapper.ge(query.getStartDate() != null, DrugHandingOverApply::getHandingOverDate, query.getStartDate())
                        .le(query.getEndDate() != null, DrugHandingOverApply::getHandingOverDate, query.getEndDate());
            }
        }

        if (userQueryType != null) {
            if (userQueryType == 1) {
                lambdaQueryWrapper.eq(StrUtil.isNotBlank(query.getUserId()), DrugHandingOverApply::getHandingOverUser, query.getUserId());
            } else if (userQueryType == 2) {
                lambdaQueryWrapper.eq(StrUtil.isNotBlank(query.getUserId()), DrugHandingOverApply::getReviewer, query.getUserId());
            }
        }
        return lambdaQueryWrapper;
    }
}




