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

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.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import digital.laboratory.platform.common.mybatis.security.service.DLPUser;
import digital.laboratory.platform.imr.dto.DestructionPublicityDTO;
import digital.laboratory.platform.imr.entity.DestructionDetail;
import digital.laboratory.platform.imr.entity.DestructionPublicity;
import digital.laboratory.platform.imr.feign.TransferFeignService;
import digital.laboratory.platform.imr.mapper.DestructionDetailMapper;
import digital.laboratory.platform.imr.mapper.DestructionPublicityMapper;
import digital.laboratory.platform.imr.mapper.SampleApplyMapper;
import digital.laboratory.platform.imr.service.DestructionPublicityService;
import digital.laboratory.platform.imr.vo.DestructionPublicityVO;
import digital.laboratory.platform.imr.vo.OutSampleVO;
import digital.laboratory.platform.imr.vo.StatusSampleVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 服务实现类
 *
 * @author Zhang Xiaolong created at  2023-03-23
 * @describe  服务实现类
 */
@Service
@RequiredArgsConstructor
public class DestructionPublicityServiceImpl extends ServiceImpl<DestructionPublicityMapper, DestructionPublicity> implements DestructionPublicityService {


    private final DestructionPublicityMapper dpMapper;

    private final DestructionDetailMapper ddMapper;


    private final TransferFeignService transferFeignService;


    private final SampleApplyMapper asMapper;

    /**
     * 创建
     * @param dto
     * @param dlpUser
     * @return
     */
    @Override
    @Transactional
    public DestructionPublicityVO createPublicity(DestructionPublicityDTO dto, DLPUser dlpUser) {

        //创建主表(销毁与公示)
        DestructionPublicity publicity = new DestructionPublicity();
        publicity.setId(IdWorker.get32UUID().toUpperCase());
        publicity.setReviewerId(dto.getReviewerId());//审批人
        publicity.setRemarks(dto.getRemarks());//备注
        publicity.setStatus(-1);//创建默认未发布
        publicity.setDestroyCompany(dto.getDestroyCompany());//销毁单位
        publicity.setApplicantId(dlpUser.getId());//申请人--检材管理员
        publicity.setDestroyQuantity(dto.getSampleIds().size());//数量
        publicity.setDestroyDate(dto.getDestroyDate());//销毁时间
        dpMapper.insert(publicity);
        //创建副表(销毁样本明细)
        List<String> sampleIds = dto.getSampleIds();
        for (String sampleId : sampleIds) {
            DestructionDetail detail = new DestructionDetail();
            detail.setSampleId(sampleId);
            detail.setId(IdWorker.get32UUID().toUpperCase());
            detail.setDestructionId(publicity.getId());
            ddMapper.insert(detail);
        }
        return dpMapper.getPublicityVO(publicity.getId());
    }

    /**
     * 修改以当前页面为准
     * 所以对副表修改时先删除在添加
     * @param dto
     * @param dlpUser
     * @return
     */
    @Override
    @Transactional
    public DestructionPublicityVO updatePublicity(DestructionPublicityDTO dto, DLPUser dlpUser) {

        //先获取修改对象是否存在
        DestructionPublicity publicity = dpMapper.selectById(dto.getId());
        if(publicity==null){
            throw new RuntimeException(String.format("修改对象不存在"));
        }
        if(publicity.getStatus()!=-1){//未发布
            throw new RuntimeException(String.format("当前状态不可修改"));
        }
        //修改信息
        publicity.setRemarks(dto.getRemarks());
        publicity.setReviewerId(dto.getReviewerId());
        publicity.setDestroyDate(dto.getDestroyDate());
        publicity.setDestroyCompany(dto.getDestroyCompany());
        publicity.setDestroyQuantity(dto.getSampleIds().size());
        dpMapper.updateById(publicity);
        //先删除
        QueryWrapper<DestructionDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("destruction_id",publicity.getId());
        ddMapper.delete(wrapper);
        //再添加
        //副表
        List<String> sampleIds = dto.getSampleIds();
        for (String sampleId : sampleIds) {
            DestructionDetail detail = new DestructionDetail();
            detail.setSampleId(sampleId);
            detail.setId(IdWorker.get32UUID().toUpperCase());
            detail.setDestructionId(publicity.getId());
            ddMapper.insert(detail);
        }
        return dpMapper.getPublicityVO(dto.getId());
    }

    /**
     * 单个删除
     * @param id
     * @return
     */
    @Override
    @Transactional
    public void deleteOneById(String id) {

        //先通过id查询出
        DestructionPublicity destructionPublicity = dpMapper.selectById(id);
        if(destructionPublicity==null) {
            throw new RuntimeException(String.format("数据不存在"));
        }else if(destructionPublicity.getStatus()==1){//已经发布
            throw new RuntimeException(String.format("当前状态不可删除"));
        }

        //先删除副表
        QueryWrapper<DestructionDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("destruction_id",id);
        ddMapper.delete(wrapper);

        //删除主表数据
        dpMapper.deleteById(id);

    }

    /**
     * 销毁与公示分页查询
     * @param page
     * @param
     * @return
     */
    @Override
    public IPage<DestructionPublicityVO> getDestructionPublicityPage(Page<DestructionPublicity> page, QueryWrapper<DestructionPublicity> qw) {
        return dpMapper.getDestructionPublicityPage(page,qw);
    }

    /**
     * 查询单个
     * @param id
     * @return
     */
    @Override
    public DestructionPublicity getOneById(String id) {
        //先获取单个vo
        DestructionPublicityVO vo = dpMapper.getPublicityVO(id);
        if(vo==null) {
            throw new RuntimeException(String.format("数据不存在"));
        }
        //获取对应样本信息集合
        List<OutSampleVO> publicityDetail = ddMapper.getPublicityDetail(id);
        vo.setSampleVO(publicityDetail);

        return vo;
    }

    /**
     * 发布公示
     * @param id
     * @return
     */
    @Override
    public DestructionPublicity release(String id) {

        DestructionPublicity publicity = dpMapper.selectById(id);
        if(publicity==null){
            throw new RuntimeException(String.format("数据不存在"));
        }else if (publicity.getStatus()==1){
            throw new RuntimeException(String.format("当前公示已经发布"));
        }

        // 发布前判断当前样本是否已经在别的公示里面发布了
        QueryWrapper<DestructionDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("destruction_id",publicity.getId());
        List<DestructionDetail> details = ddMapper.selectList(wrapper);

        for (DestructionDetail detail : details) {
            StatusSampleVO sampleVO =  asMapper.getSampleInfo(detail.getSampleId());
            if(sampleVO.getStatus() == 11){
                throw new RuntimeException(String.format("名称为:"+sampleVO.getName()+"的样本已在别的公示中发布;请勿重复提交"));
            }
        }



        publicity.setStatus(1);//发布状态
        publicity.setReleaseDate(LocalDateTime.now());//发布时间

        dpMapper.updateById(publicity);


        for (DestructionDetail detail : details) {
            transferFeignService.updateStatus(detail.getSampleId(),11);//样本状态为已经发布销毁公示,待出库销毁
            //transferFeignService.updateSampleHolder(new UpdateHolderDTO(detail.getSampleId(),""));//当期持有人
        }


        /**
         * 调用分中心官网
         */

        return this.getOneById(id);
    }
}