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

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import digital.laboratory.platform.common.mybatis.security.service.DLPUser;
import digital.laboratory.platform.reagent.dto.WarehousingRecordFormDTO;
import digital.laboratory.platform.reagent.entity.*;
import digital.laboratory.platform.reagent.mapper.WarehousingRecordFormMapper;
import digital.laboratory.platform.reagent.service.*;
import digital.laboratory.platform.reagent.vo.WarehousingContentVO;
import digital.laboratory.platform.reagent.vo.WarehousingRecordFormVO;
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.Calendar;
import java.util.List;

/**
 * 签收记录表服务实现类
 *
 * @author Zhang Xiaolong created at  2023-03-10
 * @describe 签收记录表 服务实现类
 */
@Service
@SuppressWarnings("all")
public class WarehousingRecordFormServiceImpl extends ServiceImpl<WarehousingRecordFormMapper, WarehousingRecordForm> implements WarehousingRecordFormService {
    @Autowired
    private WarehousingRecordFormService warehousingRecordFormService;

    @Autowired
    private WarehousingContentService warehousingContentService;

    @Autowired
    private WarehousingBatchListService warehousingBatchListService;

    @Autowired
    private StorageRegistrationFormService storageRegistrationFormService;

    @Autowired
    private ReagentConsumableInventoryService reagentConsumableInventoryService;

    @Autowired
    private ReagentConsumablesService reagentConsumablesService;
    @Autowired
    private ReferenceMaterialService referenceMaterialService;
    @Autowired
    private LatticeFormService latticeFormService;

    @Autowired
    private StorageRoomFormService storageRoomFormService;

    @Autowired
    private CabinetFormService cabinetFormService;

    @Autowired
    private BatchDetailsService batchDetailsService;

    @Autowired
    private AcceptanceRecordFormService acceptanceRecordFormService;

    @Override//查看采购入库
    public WarehousingRecordFormVO getWarehousingRecordFormVO(String warehousingFormId) {

        WarehousingRecordForm byId = warehousingRecordFormService.getById(warehousingFormId);

        WarehousingRecordFormVO warehousingRecordFormVO = new WarehousingRecordFormVO();

        BeanUtils.copyProperties(byId, warehousingRecordFormVO);

        List<WarehousingContentVO> warehousingContentVOList = warehousingContentService.getWarehousingContentVOList(warehousingFormId);

        warehousingRecordFormVO.setWarehousingContentVOList(warehousingContentVOList);

        return warehousingRecordFormVO;
    }


    @Transactional
    @Override//录入入库明细
    public Boolean addFormById(List<WarehousingRecordFormDTO> warehousingRecordFormDTOList, DLPUser dlpUser) {

        boolean flag = true;

        int i = 0;
        //签收内容循环
        for (WarehousingRecordFormDTO warehousingRecordFormDTO : warehousingRecordFormDTOList) {

            WarehousingBatchList warehousingBatchList = new WarehousingBatchList();

            BeanUtils.copyProperties(warehousingRecordFormDTO, warehousingBatchList);

            warehousingBatchList.setWarehousingBatchListId(IdWorker.get32UUID().toUpperCase());

            warehousingBatchList.setDepositorId(dlpUser.getId());

            LambdaQueryWrapper<WarehousingBatchList> warehousingBatchListLambdaQueryWrapper = new LambdaQueryWrapper<>();

            warehousingBatchListLambdaQueryWrapper.eq(WarehousingBatchList::getWarehousingContentId, warehousingBatchList.getWarehousingContentId());
            //通过判断签收内容表里的签收批次表数量，进行批次字段的赋值
            warehousingBatchList.setBatch(warehousingBatchListService.list(warehousingBatchListLambdaQueryWrapper).size() + 1);

            WarehousingContent byId = warehousingContentService.getById(warehousingBatchList.getWarehousingContentId());

            byId.setWarehousingQuantity(byId.getWarehousingQuantity() + warehousingBatchList.getQuantity());

            if (byId.getWarehousingQuantity() > byId.getTotalQuantity()) {
                throw new RuntimeException(String.format("入库数量不能大于采购数量"));
            }

            if (warehousingContentService.updateById(byId) & warehousingBatchListService.save(warehousingBatchList)) {

                flag = true;
            } else {
                flag = false;
            }
            //入库登记表更新
            StorageRegistrationForm storageRegistrationForm = new StorageRegistrationForm();

            storageRegistrationForm.setStorageRegistrationFormId(IdWorker.get32UUID().toUpperCase());

            storageRegistrationForm.setReagentConsumableId(byId.getReagentConsumableId());

            storageRegistrationForm.setQuantity(warehousingBatchList.getQuantity());

            storageRegistrationForm.setRemarks(warehousingRecordFormDTO.getRemarks());

            storageRegistrationFormService.save(storageRegistrationForm);

            LambdaQueryWrapper<ReagentConsumableInventory> reagentConsumableInventoryLambdaQueryWrapper = new LambdaQueryWrapper<>();

            reagentConsumableInventoryLambdaQueryWrapper.eq(ReagentConsumableInventory::getReagentConsumableId, byId.getReagentConsumableId());

            ReagentConsumableInventory one = reagentConsumableInventoryService.getOne(reagentConsumableInventoryLambdaQueryWrapper);
            //录入仓库批次信息，仓库不存在该物品
            if (one == null) {

                ReagentConsumableInventory reagentConsumableInventory = new ReagentConsumableInventory();

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

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

                ReagentConsumables reagentConsumables = reagentConsumablesService.getOne(reagentConsumablesLambdaQueryWrapper);

                BeanUtils.copyProperties(reagentConsumables, reagentConsumableInventory);

                reagentConsumableInventory.setReagentConsumableInventoryId(IdWorker.get32UUID().toUpperCase());

                BatchDetails batchDetails = new BatchDetails();

                BeanUtils.copyProperties(warehousingBatchList, batchDetails);

                batchDetails.setBatchDetailsId(IdWorker.get32UUID().toUpperCase());

                batchDetails.setServiceStatus(1);

                batchDetails.setPurchaseTime(LocalDateTime.now());

                batchDetails.setReagentConsumableInventoryId(reagentConsumableInventory.getReagentConsumableInventoryId());

                if (reagentConsumableInventory.getTotalQuantity() == null) {

                    reagentConsumableInventory.setTotalQuantity(0);
                }

                if (reagentConsumableInventory.getCategory().equals("试剂") & reagentConsumableInventory.getCategory().equals("标准物质")) {

                    reagentConsumableInventory.setTotalQuantity(reagentConsumableInventory.getTotalQuantity() + batchDetails.getQuantity() * Integer.valueOf(reagentConsumableInventory.getPackagedCopies()));

                } else {

                    reagentConsumableInventory.setTotalQuantity(reagentConsumableInventory.getTotalQuantity() + batchDetails.getQuantity());
                }


                reagentConsumableInventory.setTotalQuantity(reagentConsumableInventory.getTotalQuantity() + batchDetails.getQuantity());
                //如果是标准物质，则赋值编号
                if (reagentConsumables.getCategory().equals("标准物质")) {

                    for (int j = 0; j < batchDetails.getQuantity(); j++) {

                        ReferenceMaterial referenceMaterial = new ReferenceMaterial();

                        referenceMaterial.setId(IdWorker.get32UUID().toUpperCase());

                        referenceMaterial.setReagentConsumableId(reagentConsumables.getReagentConsumableId());

                        referenceMaterial.setBatchDetailsId(batchDetails.getBatchDetailsId());

                        Calendar calendar = Calendar.getInstance();

                        int year = calendar.get(Calendar.YEAR);

                        LatticeForm latticeForm = latticeFormService.getById(warehousingRecordFormDTO.getLatticeId());

                        CabinetForm cabinetForm = cabinetFormService.getById(latticeForm.getCabinetFormId());

                        StorageRoomForm storageRoomForm = storageRoomFormService.getById(cabinetForm.getStorageRoomFormId());

                        String prefix = reagentConsumables.getEnglishName() + "-" + year + "-" + storageRoomForm.getFloor() + "-";

                        List<ReferenceMaterial> list = referenceMaterialService.list(Wrappers.<ReferenceMaterial>query()
                                .likeRight("number", prefix)
                                .orderByDesc("number"));

                        int newNo = 1;

                        if ((list != null) && (list.size() > 0)) {
                            ReferenceMaterial referenceMaterial1 = list.get(0);
                            String strMaxNo = StrUtil.removePrefixIgnoreCase(referenceMaterial1.getNumber(), prefix);
                            try {
                                int maxno = Integer.parseUnsignedInt(strMaxNo);
                                newNo = maxno + 1;
                            } catch (NumberFormatException e) {
                                // 如果后缀有非数字, 则无视之, 重头编码
                                newNo = 1;
                            }
                        }
                        referenceMaterial.setNumber(prefix + String.format("%02d", newNo));

                        referenceMaterialService.save(referenceMaterial);

                    }
                    reagentConsumableInventoryService.save(reagentConsumableInventory);

                    batchDetailsService.save(batchDetails);
                }
            } else {
                //如果仓库存在该物品
                LambdaQueryWrapper<ReagentConsumableInventory> reagentConsumableInventoryLambdaQueryWrapper1 = new LambdaQueryWrapper<>();

                reagentConsumableInventoryLambdaQueryWrapper1.eq(ReagentConsumableInventory::getReagentConsumableId, byId.getReagentConsumableId());

                ReagentConsumableInventory one1 = reagentConsumableInventoryService.getOne(reagentConsumableInventoryLambdaQueryWrapper1);

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

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

                ReagentConsumables reagentConsumables = reagentConsumablesService.getOne(reagentConsumablesLambdaQueryWrapper);

                BatchDetails batchDetails = new BatchDetails();

                BeanUtils.copyProperties(warehousingBatchList, batchDetails);

                batchDetails.setBatchDetailsId(IdWorker.get32UUID().toUpperCase());

                batchDetails.setServiceStatus(1);

                batchDetails.setPurchaseTime(LocalDateTime.now());

                batchDetails.setReagentConsumableInventoryId(one1.getReagentConsumableInventoryId());

                one1.setTotalQuantity(one1.getTotalQuantity() + batchDetails.getQuantity());

                if (one1.getCategory().equals("标准物质")) {

                    for (int j = 0; j < batchDetails.getQuantity(); j++) {

                        ReferenceMaterial referenceMaterial = new ReferenceMaterial();

                        referenceMaterial.setId(IdWorker.get32UUID().toUpperCase());

                        referenceMaterial.setReagentConsumableId(one1.getReagentConsumableId());

                        referenceMaterial.setBatchDetailsId(batchDetails.getBatchDetailsId());

                        Calendar calendar = Calendar.getInstance();

                        int year = calendar.get(Calendar.YEAR);

                        LatticeForm latticeForm = latticeFormService.getById(warehousingRecordFormDTO.getLatticeId());

                        CabinetForm cabinetForm = cabinetFormService.getById(latticeForm.getCabinetFormId());

                        StorageRoomForm storageRoomForm = storageRoomFormService.getById(cabinetForm.getStorageRoomFormId());

                        String prefix = reagentConsumables.getEnglishName() + "-" + year + "-" + storageRoomForm.getFloor() + "-";

                        List<ReferenceMaterial> list = referenceMaterialService.list(Wrappers.<ReferenceMaterial>query()
                                .likeRight("number", prefix)
                                .orderByDesc("number"));

                        int newNo = 1;

                        if ((list != null) && (list.size() > 0)) {
                            ReferenceMaterial referenceMaterial1 = list.get(0);
                            String strMaxNo = StrUtil.removePrefixIgnoreCase(referenceMaterial1.getNumber(), prefix);
                            try {
                                int maxno = Integer.parseUnsignedInt(strMaxNo);
                                newNo = maxno + 1;
                            } catch (NumberFormatException e) {
                                // 如果后缀有非数字, 则无视之, 重头编码
                                newNo = 1;
                            }
                        }
                        referenceMaterial.setNumber(prefix + String.format("%02d", newNo));

                        referenceMaterialService.save(referenceMaterial);

                    }
                    reagentConsumableInventoryService.updateById(one1);

                    batchDetailsService.save(batchDetails);

                }
            }
        }
        LambdaQueryWrapper<WarehousingContent> warehousingContentLambdaQueryWrapper = new LambdaQueryWrapper<>();

        String warehousingRecordFormId = warehousingContentService.getById(warehousingRecordFormDTOList.get(0).getWarehousingContentId()).getWarehousingRecordFormId();

        warehousingContentLambdaQueryWrapper.eq(WarehousingContent::getWarehousingRecordFormId, warehousingRecordFormId);

        List<WarehousingContent> list = warehousingContentService.list(warehousingContentLambdaQueryWrapper);

        WarehousingRecordForm warehousingRecordForm = warehousingRecordFormService.getById(warehousingRecordFormId);
//遍历采购内容，判断试剂耗材是否入库完毕
        for (WarehousingContent warehousingContent : list) {

            if (warehousingContent.getWarehousingQuantity() == warehousingContent.getTotalQuantity()) {

                LambdaQueryWrapper<WarehousingBatchList> warehousingBatchListLambdaQueryWrapper = new LambdaQueryWrapper<>();

                warehousingBatchListLambdaQueryWrapper.eq(WarehousingBatchList::getWarehousingContentId, warehousingContent.getWarehousingContentId());

                List<WarehousingBatchList> list1 = warehousingBatchListService.list(warehousingBatchListLambdaQueryWrapper);

                if (warehousingContent.getAcceptanceRecordFormId() == null) {

                    AcceptanceRecordForm acceptanceRecordForm = acceptanceRecordFormService.addForm(warehousingContent.getReagentConsumableId(), list1.get(0).getSupplierId());

                    warehousingContent.setAcceptanceRecordFormId(acceptanceRecordForm.getAcceptanceRecordFormId());

                    warehousingContentService.updateById(warehousingContent);
                }

                i = i + 1;
            }
        }
        //判断该清单所有试剂耗材是否入库完成
        if (i == list.size()) {
            warehousingRecordForm.setStatus(2);
        } else {
            warehousingRecordForm.setStatus(1);
        }

        warehousingRecordFormService.updateById(warehousingRecordForm);

        return flag;
    }

}



