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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import digital.laboratory.platform.common.mybatis.security.service.DLPUser;
import digital.laboratory.platform.imr.dto.DestroyOutboundDTO;
import digital.laboratory.platform.imr.dto.ReturnOutboundDTO;
import digital.laboratory.platform.imr.entity.*;
import digital.laboratory.platform.imr.enums.OutboundType;
import digital.laboratory.platform.imr.feign.TransferFeignService;
import digital.laboratory.platform.imr.feign.dto.UpdateHolderDTO;
import digital.laboratory.platform.imr.mapper.*;
import digital.laboratory.platform.imr.service.SampleOutWarehouseService;
//import digital.laboratory.platform.common.seata.*;
import digital.laboratory.platform.imr.vo.OutSampleVO;
import digital.laboratory.platform.sys.entity.CellAndStoreSupplyData;
import digital.laboratory.platform.sys.feign.RemoteCabinetService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

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


@Service
@RequiredArgsConstructor
public class SampleOutWarehouseServiceImpl implements SampleOutWarehouseService {


    private final SampleStorageMapper storageMapper;


    private final RemoteCabinetService cabinetService;

    private final SampleOutboundRecordMapper outboundRecordMapper;


    private final TransferFeignService transferFeignService;


    private final SampleInboundAndOutboundTableMapper tableMapper;


    private final DestructionDetailMapper destructionDetailMapper;

    private final DestructionPublicityMapper publicityMapper;



    /**
     * 销毁出库
     *
     */
    @Override
    @GlobalTransactional
    public void destroyOutbound(DestroyOutboundDTO dto, DLPUser dlpUser) {

        //验证当前的样本id是否已经是待销毁状态
        for (String sampleId : dto.getSampleIds()) {
            SampleStorage storage = storageMapper.selectOne(new QueryWrapper<SampleStorage>().eq("sample_id", sampleId));
            if (storage.getEarlyWarning() != 2) {
                throw new RuntimeException(String.format("当前名称为" + storage.getName()) + "的样本不是审批通过的状态");
            }
             /*
            这里做一下销毁出库要查询公示判断
             */
            QueryWrapper<DestructionDetail> wrapper = new QueryWrapper<>();
            wrapper.eq("sample_id",sampleId);
            List<DestructionDetail> details = destructionDetailMapper.selectList(wrapper);

            if(details==null || details.size()==0){
                throw new RuntimeException("当前样本还未进行销毁公示");
            }else {
                for (DestructionDetail detail:details) {
                    OutSampleVO sampleVO = storageMapper.getSampleById(detail.getSampleId());
                    //查询样本看看是否已经发布
                    DestructionPublicity destructionPublicity = publicityMapper.selectById(detail.getDestructionId());
                    if(destructionPublicity.getStatus()==-1){
                        //没查询出或者未发布的
                        throw new RuntimeException("当前"+sampleVO.getName()+"样本还未进行销毁公示");
                    }
                }
            }

        }

        /*
        验证完后
        0.storage表修改为3出库
        1.出库记录
        2.出入库登记表
        3.添加流转记录
        4.修改样本状态
        5.持有人
         */

        for (String sampleId : dto.getSampleIds()) {
            //0.storage表修改为3出库
            SampleStorage storage = storageMapper.selectOne(new QueryWrapper<SampleStorage>().eq("sample_id", sampleId));
            storage.setStatus(3);//已经出库
            storage.setRecipientId(dlpUser.getId());//检材管理员就是接受人
            storage.setOutRepositoryDate(LocalDateTime.now());//出库时间
            storage.setIsReturn(-1);//不需要归还
            storageMapper.updateById(storage);

            //2.出库记录
            SampleOutboundRecord sampleOutboundRecord = new SampleOutboundRecord();
            sampleOutboundRecord.setId(IdWorker.get32UUID().toUpperCase());
            sampleOutboundRecord.setOutboundType(OutboundType.DESTRUCTION);//销毁出库
            sampleOutboundRecord.setName(storage.getName());//样本名称--方便搜索
            sampleOutboundRecord.setRecipientId(dlpUser.getId());//领取人id
            sampleOutboundRecord.setSampleId(sampleId);

            //后面的备注--当前样本已经销毁"+"销毁单位:"+xxx
            sampleOutboundRecord.setReason("检材销毁出库");//把出库原因设置为备注
            sampleOutboundRecord.setOutboundDate(LocalDateTime.now());//出库时间
            outboundRecordMapper.insert(sampleOutboundRecord);

//        2.修改样本出入库登记表--出库是修改操作先查询出sample对应的出入库登记表
            //程序文件中说明:检验时才填写出入库登记表
            QueryWrapper<SampleInboundAndOutboundTable> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("sample_id",sampleId);
            queryWrapper.isNull("out_warehouse_date");//出库日期的数据
            SampleInboundAndOutboundTable table = tableMapper.selectOne(queryWrapper);
            if(table != null){
                table.setOutboundSupervisor(dto.getSupervisor());//出库监督人
                table.setOutWarehouseDate(LocalDateTime.now());//出库时间
                tableMapper.updateById(table);
            }
/*          UpdateWrapper<SampleInboundAndOutboundTable> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("sample_id",sampleId);
            updateWrapper.isNull("appraiser_id");//鉴定人为空的数据
            updateWrapper.set("appraiser_id",null);//鉴定人
            updateWrapper.set("out_warehouse_date",LocalDateTime.now());//出库时间
            updateWrapper.set("remarks","当前样本已经出库销毁");//备注
            updateWrapper.set("return_time",null);//返回时间
            tableMapper.update(null,updateWrapper);*/

//            3.添加流转记录
            transferFeignService.addTransferByOut(sampleId,dlpUser.getId());
//            4.修改样本状态
            transferFeignService.updateStatus(sampleId,8);
            //5.持有人
            transferFeignService.updateSampleHolder(new UpdateHolderDTO(sampleId,dlpUser.getId()));

            ArrayList<String> sampleIds = new ArrayList<>();
            sampleIds.add(storage.getSampleId());
            CellAndStoreSupplyData cellAndStoreSupplyData = new CellAndStoreSupplyData();
            cellAndStoreSupplyData.setCellId(storage.getStorageCellId());
            cellAndStoreSupplyData.setCellStatus("1");
            cellAndStoreSupplyData.setStoreSupplyList(sampleIds);
        /*
        柜子新接口
         */
            //cabinetService.updateCabinet(dto.getCellId(),str,"1");
            ArrayList<CellAndStoreSupplyData> supplyData = new ArrayList<>();
            supplyData.add(cellAndStoreSupplyData);
            cabinetService.takeOrSaveGoodsFromCabinet(supplyData,-1);
        }
    }

    /**
     * 退还出库
     * @param dto
     * @param dlpUser
     */
    @Override
    @GlobalTransactional
    public void returnOutbound(ReturnOutboundDTO dto, DLPUser dlpUser) {

        for (String sampleId : dto.getSampleIds()) {
            SampleStorage storage = storageMapper.selectOne(new QueryWrapper<SampleStorage>().eq("sample_id", sampleId));
            if(storage==null){
                throw new RuntimeException("当前样本未找到在仓库信息");
            }else if (storage.getStatus()!=2) {
                throw new RuntimeException(String.format("当前名称为" + storage.getName()) + "的样本不是审批通过的状态");
            }


            /*
              0.修改当前storage表状态
              1.流转记录表
              2.修改样本当前状态
              3.出库记录
             */
            //0.修改当前storage表状态
            storage.setIsReturn(-1);//不需要归还
            storage.setOutRepositoryDate(LocalDateTime.now());//出库时间
            storage.setRecipientId(dlpUser.getId());//领取人
            storage.setStatus(3);//已经出库
            storageMapper.updateById(storage);

            //1.流转记录表
            transferFeignService.addTransferByOut(sampleId,dlpUser.getId());

            //2.修改sample状态(已经退还出库)
            transferFeignService.updateStatus(sampleId,10);//退还出库

            //3.出库记录
            SampleOutboundRecord sampleOutboundRecord = new SampleOutboundRecord();
            sampleOutboundRecord.setId(IdWorker.get32UUID().toUpperCase());
            sampleOutboundRecord.setOutboundType(OutboundType.RETURN);//退还出库
            sampleOutboundRecord.setName(storage.getName());//样本名称--方便搜索
            sampleOutboundRecord.setRecipientId(dto.getReturnInstitution());//这里把退还单位设置到领取人id中
            sampleOutboundRecord.setSampleId(sampleId);
            sampleOutboundRecord.setReason(dto.getRemark());//备注
            sampleOutboundRecord.setOutboundDate(LocalDateTime.now());//出库时间
            outboundRecordMapper.insert(sampleOutboundRecord);

            //出入库登记表supervisor
            QueryWrapper<SampleInboundAndOutboundTable> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("sample_id",sampleId);
            queryWrapper.isNull("out_warehouse_date");//出库日期的数据
            SampleInboundAndOutboundTable table = tableMapper.selectOne(queryWrapper);
            if(table != null){
                table.setOutboundSupervisor(dto.getSupervisor());//出库监督人
                table.setOutWarehouseDate(LocalDateTime.now());//出库时间
                tableMapper.updateById(table);
            }
            ArrayList<String> sampleIds = new ArrayList<>();
            sampleIds.add(storage.getSampleId());
            CellAndStoreSupplyData cellAndStoreSupplyData = new CellAndStoreSupplyData();
            cellAndStoreSupplyData.setCellId(storage.getStorageCellId());
            cellAndStoreSupplyData.setCellStatus("1");
            cellAndStoreSupplyData.setStoreSupplyList(sampleIds);
        /*
        柜子新接口
         */
            //cabinetService.updateCabinet(dto.getCellId(),str,"1");
            ArrayList<CellAndStoreSupplyData> supplyData = new ArrayList<>();
            supplyData.add(cellAndStoreSupplyData);
            cabinetService.takeOrSaveGoodsFromCabinet(supplyData,-1);
        }
    }
}
