package net.lab1024.sa.admin.module.business.wms.shipping.pick.service.impl;

import com.amazonaws.partitions.PartitionRegionImpl;
import jakarta.annotation.Resource;
import net.lab1024.sa.admin.module.business.wms.receive.asn.constant.AsnOrderStatusEnum;
import net.lab1024.sa.admin.module.business.wms.receive.asn.domain.entity.AsnEntity;
import net.lab1024.sa.admin.module.business.wms.receive.asnDetail.domain.entity.AsnDetailEntity;
import net.lab1024.sa.admin.module.business.wms.shipping.pick.constant.PickOrderStatusEnum;
import net.lab1024.sa.admin.module.business.wms.shipping.pick.domain.entity.PickEntity;
import net.lab1024.sa.admin.module.business.wms.shipping.pick.domain.form.PickAddForm;
import net.lab1024.sa.admin.module.business.wms.shipping.pick.domain.form.PickUpdateForm;
import net.lab1024.sa.admin.module.business.wms.shipping.pick.manager.PickManager;
import net.lab1024.sa.admin.module.business.wms.shipping.pick.service.PickQueryService;
import net.lab1024.sa.admin.module.business.wms.shipping.pick.service.PickService;
import net.lab1024.sa.admin.module.business.wms.shipping.pickDetail.domain.entity.PickDetailEntity;
import net.lab1024.sa.admin.module.business.wms.shipping.pickDetail.manager.PickDetailManager;
import net.lab1024.sa.admin.module.business.wms.shipping.pickDetail.service.PickDetailQueryService;
import net.lab1024.sa.admin.util.JoinerResult;
import net.lab1024.sa.admin.util.ResponseDTOUtil;
import net.lab1024.sa.base.common.code.UserErrorCode;
import net.lab1024.sa.base.common.domain.ResponseDTO;
import net.lab1024.sa.base.common.exception.BusinessException;
import net.lab1024.sa.base.common.util.SmartBeanUtil;
import net.lab1024.sa.base.module.support.datatracer.constant.DataTracerTypeEnum;
import net.lab1024.sa.base.module.support.datatracer.service.DataTracerService;
import net.lab1024.sa.base.module.support.serialnumber.constant.SerialNumberIdEnum;
import net.lab1024.sa.base.module.support.serialnumber.service.SerialNumberService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class PickServiceImpl implements PickService {

    @Resource
    private PickManager pickManager;

    @Resource
    private PickDetailManager pickDetailManager;

    @Resource
    private PickQueryService pickQueryService;

    @Resource
    private PickDetailQueryService pickDetailQueryService;

    @Resource
    private SerialNumberService serialNumberService;

    @Resource
    private DataTracerService dataTracerService;

    /**
     * 添加
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<PickEntity> add(PickAddForm addForm) {
        PickEntity exitPick = pickQueryService.queryByCustomerNumber(addForm.getCustomerNumber());
        if (exitPick != null) {
            throw new BusinessException(addForm.getCustomerNumber() + "客户订单号已存在");
        }
        //自动生成出库编号
        addForm.setPickNumber(serialNumberService.generate(SerialNumberIdEnum.PICK));
        //默认已创建
        addForm.setStatus(PickOrderStatusEnum.CREATED.getValue());
        PickEntity pickEntity = SmartBeanUtil.copy(addForm, PickEntity.class);
        pickManager.save(pickEntity);

        //操作记录
        dataTracerService.addTrace(pickEntity.getPickId(), DataTracerTypeEnum.PICK, "新建出库单：" + pickEntity.getPickNumber(), null, pickEntity);

        return ResponseDTO.ok(pickEntity);
    }

    /**
     * 更新
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<PickEntity> update(PickUpdateForm updateForm) {
        PickEntity exitPick = pickQueryService.queryByCustomerNumber(updateForm.getCustomerNumber());
        if (exitPick != null && !exitPick.getPickId().equals(updateForm.getPickId())) {
            throw new BusinessException(updateForm.getCustomerNumber() + "客户订单号已存在");
        }
        PickEntity pickEntity = SmartBeanUtil.copy(updateForm, PickEntity.class);
        pickManager.updateById(pickEntity);

        //业务操作记录
        dataTracerService.addTrace(updateForm.getPickId(), DataTracerTypeEnum.PICK, "编辑出库单：" + pickEntity.getPickNumber(), exitPick, pickEntity);

        return ResponseDTO.ok(pickEntity);
    }

    /**
     * 批量删除
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<String> batchDelete(List<Long> idList) {
        if (CollectionUtils.isEmpty(idList)) {
            return ResponseDTO.userErrorParam(UserErrorCode.PARAM_ERROR.getMsg());
        }
        JoinerResult resultMsg = JoinerResult.createJoiner();

        //查询批量订单
        List<PickEntity> pickList = pickQueryService.queryByPickIds(idList);

        //将订单按状态分组；已创建的一组；非已创建的一组。
        Map<Boolean, List<PickEntity>> partitionedAsnList = pickList.stream()
                .collect(Collectors.partitioningBy(pick -> PickOrderStatusEnum.CREATED.getValue().equals(pick.getStatus())));
        //已创建的订单允许删除
        List<PickEntity> createAsnList = partitionedAsnList.get(true);
        //出库单集合
        List<Long> pickIds = createAsnList.stream().map(PickEntity::getPickId).toList();
        //根据出库单ID集合查询出库明细
        List<PickDetailEntity> details = pickDetailQueryService.queryPickDetailByPickIds(pickIds);
        if (CollectionUtils.isNotEmpty(details)) {
            pickDetailManager.removeBatchByIds(details);
        }
        if (CollectionUtils.isNotEmpty(createAsnList)) {
            Set<String> pickCodes = createAsnList.stream().map(PickEntity::getPickNumber).collect(Collectors.toSet());
            pickManager.removeBatchByIds(createAsnList);
            resultMsg.getSussMsg().add(pickCodes + "订单删除成功");
        }

        //非已创建的订单不允许删除
        List<PickEntity> noCreateAsnList = partitionedAsnList.get(false);
        if (CollectionUtils.isNotEmpty(noCreateAsnList)) {
            Set<String> pickCodes = noCreateAsnList.stream().map(PickEntity::getPickNumber).collect(Collectors.toSet());
            resultMsg.getErrorMsg().add(pickCodes + "订单不允许删除");
        }

        return ResponseDTOUtil.buildResponseDTO(resultMsg);
    }

    /**
     * 单个删除
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<String> delete(Long pickId) {
        if (pickId == null) {
            return ResponseDTO.userErrorParam(UserErrorCode.PARAM_ERROR.getMsg());
        }
        PickEntity asn = pickManager.getById(pickId);
        String status = asn.getStatus();
        // 只有已创建的订单才允许删除
        if (!PickOrderStatusEnum.CREATED.getValue().equals(status)) {
            return ResponseDTO.userErrorParam(AsnOrderStatusEnum.getDescByValue(status) + "的订单不允许删除");
        }
        List<PickDetailEntity> details = pickDetailQueryService.queryPickDetailByPickId(pickId);
        if (CollectionUtils.isNotEmpty(details)) {
            pickDetailManager.removeBatchByIds(details);
        }
        pickManager.removeById(pickId);
        return ResponseDTO.ok();
    }
}
