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

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
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.inspection.dto.EntrustInfoDto;
import digital.laboratory.platform.inspection.entity.AssignmentInfo;
import digital.laboratory.platform.inspetion.api.entity.EntrustInfo;
import digital.laboratory.platform.inspetion.api.entity.SampleInfo;
import digital.laboratory.platform.inspection.mapper.EntrustInfoMapper;
import digital.laboratory.platform.inspection.service.AssignmentInfoService;
import digital.laboratory.platform.inspection.service.EntrustInfoService;
import digital.laboratory.platform.inspection.service.SampleInfoService;
import digital.laboratory.platform.inspetion.api.entity.MaterialDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/*
 *@title EntrustInfoServiceImpl
 *@description
 *@author xy
 *@version 1.0
 *@create 2023/12/7 15:31
 */
@Service
@Slf4j
public class EntrustInfoServiceImpl extends ServiceImpl<EntrustInfoMapper, EntrustInfo> implements EntrustInfoService {

    @Resource
    private SampleInfoService sampleInfoService;

    @Resource
    private AssignmentInfoService assignmentInfoService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public EntrustInfo addEntrustInfo(EntrustInfoDto entrustInfo) {
        List<MaterialDto> materialList = entrustInfo.getMaterialList();

        if (StringUtils.isBlank(entrustInfo.getId())) {
            entrustInfo.setId(IdWorker.get32UUID());
            log.info("保存对象entrustInfo的ID为空，由系统生成一个给它使用 {}", entrustInfo.getId());
        }
        if (entrustInfo.getMaterialType().equals("1")) {
            entrustInfo.setBusinessType("10002");
        } else if (entrustInfo.getMaterialType().equals("0")) {
            entrustInfo.setBusinessType("10001");
        }
        //读取检材信息
        if (materialList != null && materialList.size() > 0) {
            ArrayList<SampleInfo> sampleInfos = new ArrayList<>();
            for (MaterialDto material : materialList) {
                SampleInfo sampleInfo = new SampleInfo();
                sampleInfoService.copy(sampleInfo, material, 0);
                sampleInfo.setBusinessId(entrustInfo.getId());
                sampleInfo.setBusinessType(entrustInfo.getBusinessType());
                sampleInfos.add(sampleInfo);
            }
            sampleInfoService.saveBatch(sampleInfos);
        }
        entrustInfo.setStatus(0);
        boolean ret = this.save(entrustInfo);
        if (ret) {
            log.info("{} 保存成功", entrustInfo);
            return entrustInfo;
        } else {
            log.info("{} 保存失败", entrustInfo);
            return null;
        }
    }

    @Override
    public EntrustInfo updateEntrustInfo(EntrustInfo entrustInfo) {
        if (entrustInfo.getSource() == 0) {
            throw new RuntimeException(String.format("数据是其他系统推送录入的，不能修改"));
        }
        boolean ret = this.updateById(entrustInfo);
        if (ret) {
            return entrustInfo;
        } else {
            return null;
        }
    }

    @Override
    public Boolean deleteEntrustInfo(String id) {
        List<AssignmentInfo> assignmentInfoList = assignmentInfoService.list(Wrappers.<AssignmentInfo>lambdaQuery().eq(AssignmentInfo::getBusinessId, id));
        if (assignmentInfoList.size() > 0) {
            throw new RuntimeException(String.format("当前业务已被分配，无法删除!"));
        }
        return this.removeById(id);
    }

    @Override
    public IPage<EntrustInfo> getEntrustPageList(Page page, Integer status, EntrustInfo entrustInfo, String keywords) {
        IPage ret = this.page(page, Wrappers.<EntrustInfo>lambdaQuery()
                .and(StringUtils.isNotBlank(keywords), qw -> qw.like(EntrustInfo::getAcceptNo, keywords).or()
                        .like(EntrustInfo::getCaseName, keywords))
                .eq(StringUtils.isNotBlank(entrustInfo.getAcceptNo()), EntrustInfo::getAcceptNo, entrustInfo.getAcceptNo())
                .eq(StringUtils.isNotBlank(entrustInfo.getEntrustDepartment()), EntrustInfo::getEntrustDepartment, entrustInfo.getEntrustDepartment())
                .eq(entrustInfo.getSource() != null, EntrustInfo::getSource, entrustInfo.getSource())
                .eq(StringUtils.isNotBlank(entrustInfo.getId()), EntrustInfo::getId, entrustInfo.getId())
                .like(StringUtils.isNotBlank(entrustInfo.getCaseName()), EntrustInfo::getCaseName, entrustInfo.getCaseName())
                .eq(entrustInfo.getStatus() != null, EntrustInfo::getStatus, status)
                .last("ORDER BY CAST(SUBSTRING_INDEX(accept_no,'-',1) AS UNSIGNED)DESC,CAST(SUBSTRING_INDEX(accept_no,'-',-1) AS UNSIGNED) DESC"));
        List<EntrustInfo> records = ret.getRecords();
        for (EntrustInfo info : records) {
            List<AssignmentInfo> list = assignmentInfoService.list(Wrappers.<AssignmentInfo>lambdaQuery().eq(AssignmentInfo::getBusinessId, info.getId()));
            if (list.size() > 0) {
                info.setIsDistribution(true);
            } else {
                info.setIsDistribution(false);
            }
            if (info.getBusinessType().equals("10001")) {
                info.setBusinessTypeName("缴获物案件");
            } else {
                info.setBusinessTypeName("生物样本案件");
            }
        }
        return ret;
    }

    @Override
    public List<EntrustInfo> getEntrustList(EntrustInfo entrustInfo) {
        List<EntrustInfo> retList = this.list(Wrappers.<EntrustInfo>lambdaQuery()
                .eq(StringUtils.isNotBlank(entrustInfo.getAcceptNo()), EntrustInfo::getAcceptNo, entrustInfo.getAcceptNo())
                .eq(StringUtils.isNotBlank(entrustInfo.getEntrustDepartment()), EntrustInfo::getEntrustDepartment, entrustInfo.getEntrustDepartment())
                .eq(entrustInfo.getSource() != null, EntrustInfo::getSource, entrustInfo.getSource())
                .like(StringUtils.isNotBlank(entrustInfo.getCaseName()), EntrustInfo::getCaseName, entrustInfo.getCaseName())
                .eq(StringUtils.isNotBlank(entrustInfo.getId()), EntrustInfo::getId, entrustInfo.getId())
                .orderByDesc(EntrustInfo::getUpdateTime));
        for (EntrustInfo info : retList) {
            List<AssignmentInfo> list = assignmentInfoService.list(Wrappers.<AssignmentInfo>lambdaQuery().eq(AssignmentInfo::getBusinessId, info.getId()));
            if (list.size() > 0) {
                info.setIsDistribution(true);
            } else {
                info.setIsDistribution(false);
            }
            if (info.getBusinessType().equals("10001")) {
                info.setBusinessTypeName("NPS案件");
            } else {
                info.setBusinessTypeName("生物样本案件");
            }
        }
        return retList;
    }

    /**
     * 如果存在，返回true，否则返回false
     *
     * @param id
     * @return
     */
    @Override
    public Boolean checkExist(String id) {
        List<EntrustInfo> retList = this.list(Wrappers.<EntrustInfo>lambdaQuery()
                .eq(EntrustInfo::getId, id));
        if (retList.size() > 0) {
            return true;
        } else {
            return false;
        }
    }

    //检查是否具有重复的编号
    @Override
    public boolean checkRepeatNo(String accept, String id) {
        if (StringUtils.isNotBlank(id)) {
            return true;
        }
        EntrustInfo entrustInfo = this.getOne(Wrappers.<EntrustInfo>lambdaQuery().eq(EntrustInfo::getAcceptNo, accept));
        return entrustInfo == null ? true : false;
    }


}
