package com.openhis.workflow.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.core.common.utils.DateUtils;
import com.core.common.utils.SecurityUtils;
import com.openhis.common.constant.CommonConstants;
import com.openhis.common.enums.DelFlag;
import com.openhis.common.enums.DispenseStatus;
import com.openhis.common.enums.SupplyType;
import com.openhis.workflow.domain.SupplyDelivery;
import com.openhis.workflow.domain.SupplyRequest;
import com.openhis.workflow.mapper.SupplyDeliveryMapper;
import com.openhis.workflow.service.ISupplyDeliveryService;

/**
 * 供应发放管理Service业务层处理
 *
 * @author system
 * @date 2025-02-20
 */
@Service
public class SupplyDeliveryServiceImpl extends ServiceImpl<SupplyDeliveryMapper, SupplyDelivery>
    implements ISupplyDeliveryService {

    /**
     * 根据单据，发放物品
     *
     * @param supplyRequestList 单据信息
     * @param now 当前时间
     * @return 发放详情
     */
    @Override
    public List<SupplyDelivery> createCompletedSupplyDelivery(List<SupplyRequest> supplyRequestList, Date now) {

        List<SupplyDelivery> deliveryList = new ArrayList<>();
        // 根据申请单据生成发放单据
        for (SupplyRequest supplyRequest : supplyRequestList) {
            SupplyDelivery supplyDelivery = new SupplyDelivery();
            supplyDelivery
                // 请求id
                .setRequestId(supplyRequest.getId())
                // 发放状态：已发放
                .setStatusEnum(DispenseStatus.COMPLETED.getValue())
                // 单据类型
                .setTypeEnum(supplyRequest.getTypeEnum())
                // 发放项目所在表
                .setItemTable(supplyRequest.getItemTable())
                // 发放物品id
                .setItemId(supplyRequest.getItemId())
                // 物品单位
                .setUnitCode(supplyRequest.getUnitCode())
                // 发放数量
                .setQuantity(supplyRequest.getItemQuantity())
                // 批次号
                .setLotNumber(supplyRequest.getLotNumber())
                // 追溯码
                .setTraceNo(supplyRequest.getTraceNo())
                // 供应商id
                .setSupplierId(supplyRequest.getSupplierId())
                // 审批人
                .setPractitionerId(supplyRequest.getApplicantId())
                // 发放时间
                .setOccurrenceTime(now)
                // 接收位置
                .setReceiverId(supplyRequest.getPurposeLocationId())
                // 接收时间
                .setReceiveTime(now)
                // 生产日期
                .setOccurrenceStartTime(supplyRequest.getStartTime())
                // 失效日期
                .setOccurrenceEndTime(supplyRequest.getEndTime());
            deliveryList.add(supplyDelivery);
            // 新增发放单据
            baseMapper.insert(supplyDelivery);
        }
        return deliveryList;
    }

    /**
     * 校验(已经审批通过的单号(发放状态是已完成),不能再重复审批通过)
     *
     * @param supplyReqIdList 供应申请id列表
     */
    @Override
    public boolean supplyDeliveryValidation(List<Long> supplyReqIdList) {

        // 根据请求id查询发放状态
        List<SupplyDelivery> deliveryList = baseMapper.selectList(new LambdaQueryWrapper<SupplyDelivery>()
            .eq(SupplyDelivery::getDeleteFlag, DelFlag.NO.getCode()).in(SupplyDelivery::getRequestId, supplyReqIdList));
        if (!deliveryList.isEmpty()) {
            List<Integer> deliveryStatusList = deliveryList.stream().map(SupplyDelivery::getStatusEnum).toList();
            return deliveryStatusList.stream().anyMatch(x -> x.equals(DispenseStatus.COMPLETED.getValue()));
        }
        return false;
    }

    /**
     * 更新请求状态：已完成
     *
     * @param supplyDeliveryIdList 供应发放id列表
     */
    @Override
    public void updateCompletedStatusBatch(List<Long> supplyDeliveryIdList) {
        baseMapper.update(
            new SupplyDelivery().setStatusEnum(DispenseStatus.COMPLETED.getValue())
                .setPractitionerId(SecurityUtils.getLoginUser().getPractitionerId())
                .setOccurrenceTime(DateUtils.getNowDate()).setReceiveTime(DateUtils.getNowDate()),
            new LambdaUpdateWrapper<SupplyDelivery>().in(SupplyDelivery::getId, supplyDeliveryIdList));
    }

    /**
     * 根据id，获取供应发放列表
     *
     * @param deliveryIdList id列表
     * @return 供应发放列表
     */
    @Override
    public List<SupplyDelivery> selectByIdList(List<Long> deliveryIdList) {
        return baseMapper.selectList(new LambdaQueryWrapper<SupplyDelivery>().in(SupplyDelivery::getId, deliveryIdList)
            .eq(SupplyDelivery::getDeleteFlag, DelFlag.YES.getCode()));
    }

    /**
     * 根据requestId，获取供应发放列表
     *
     * @param requestIdList requestId列表
     * @return 供应发放列表
     */
    @Override
    public List<SupplyDelivery> selectByRequestIdList(List<Long> requestIdList) {
        return baseMapper.selectList(new LambdaQueryWrapper<SupplyDelivery>()
            .in(SupplyDelivery::getRequestId, requestIdList).eq(SupplyDelivery::getDeleteFlag, DelFlag.NO.getCode()));
    }

    /**
     * 创建待发药的供应发放
     *
     * @param medicationId
     * @param lotNumber
     * @param patientId
     * @param minQuantity
     * @param minUnitCode
     * @param receiverId
     * @param supplyRequestId
     */
    @Override
    public void createSummarySupplyDelivery(Long medicationId, String lotNumber, Long patientId, BigDecimal minQuantity,
        String minUnitCode, Long receiverId, Long supplyRequestId) {
        baseMapper.insert(new SupplyDelivery().setItemId(medicationId)
            .setItemTable(CommonConstants.TableName.MED_MEDICATION_DEFINITION).setLotNumber(lotNumber)
            .setPatientId(patientId).setQuantity(minQuantity).setUnitCode(minUnitCode)
            .setTypeEnum(SupplyType.SUMMARY_DISPENSE.getValue()).setRequestId(supplyRequestId)
            .setStatusEnum(DispenseStatus.IN_PROGRESS.getValue()).setReceiverId(receiverId));
    }

    /**
     * 创建已发放的供应发放（耗材）
     *
     * @param deviceId
     * @param lotNumber
     * @param minQuantity
     * @param minUnitCode
     * @param supplyRequestId
     */
    @Override
    public void createDeviceSummarySupplyDelivery(Long deviceId, String lotNumber, BigDecimal minQuantity,
        String minUnitCode, Long supplyRequestId) {
        baseMapper.insert(new SupplyDelivery().setItemId(deviceId)
            .setItemTable(CommonConstants.TableName.ADM_DEVICE_DEFINITION).setLotNumber(lotNumber)
            .setQuantity(minQuantity).setUnitCode(minUnitCode).setTypeEnum(SupplyType.DEVICE_STOCKTAKING.getValue())
            .setRequestId(supplyRequestId).setStatusEnum(DispenseStatus.COMPLETED.getValue()));
    }

    /**
     * 根据供应申请id，删除供应发放
     *
     * @param requestIdList 供应申请id列表
     */
    @Override
    public void deleteSupplyDeliveryByReqId(List<Long> requestIdList) {
        baseMapper.delete(new LambdaQueryWrapper<SupplyDelivery>().in(SupplyDelivery::getRequestId, requestIdList));
    }
}
