package com.openhis.web.inhospitalnursestation.appservice.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.core.common.core.domain.R;
import com.core.common.exception.ServiceException;
import com.core.common.utils.AssignSeqUtil;
import com.core.common.utils.DateUtils;
import com.core.common.utils.SecurityUtils;
import com.openhis.common.constant.CommonConstants;
import com.openhis.common.enums.AssignSeqEnum;
import com.openhis.common.enums.PublicationStatus;
import com.openhis.common.utils.HisQueryUtils;
import com.openhis.web.common.dto.UnitDto;
import com.openhis.web.inhospitalnursestation.appservice.IOrgDeviceStockTakeAppService;
import com.openhis.web.inhospitalnursestation.dto.OrgDeviceDto;
import com.openhis.web.inhospitalnursestation.dto.OrgDeviceSummaryFromDto;
import com.openhis.web.inhospitalnursestation.dto.OrgDeviceSummaryParam;
import com.openhis.web.inhospitalnursestation.mapper.OrgDeviceStockTakeAppMapper;
import com.openhis.web.pharmacymanage.mapper.ReturnMedicineMapper;
import com.openhis.workflow.domain.InventoryItem;
import com.openhis.workflow.mapper.InventoryItemMapper;
import com.openhis.workflow.service.IDeviceDispenseService;
import com.openhis.workflow.service.IInventoryItemService;
import com.openhis.workflow.service.ISupplyDeliveryService;
import com.openhis.workflow.service.ISupplyRequestService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 科室耗材盘点 应用实现类
 *
 * @author wuyan
 * @date 2025/11/05
 */
@Service
public class OrgDeviceStockTakeAppServiceImpl implements IOrgDeviceStockTakeAppService {

    @Resource
    private OrgDeviceStockTakeAppMapper orgDeviceStockTakeAppMapper;

    @Resource
    private IInventoryItemService inventoryItemService;

    @Resource
    private ISupplyRequestService supplyRequestService;

    @Resource
    private ISupplyDeliveryService supplyDeliveryService;

    @Resource
    private AssignSeqUtil assignSeqUtil;

    @Resource
    private IDeviceDispenseService deviceDispenseService;

    @Resource
    private InventoryItemMapper inventoryItemMapper;

    /**
     * 查询科室耗材汇总
     *
     * @param orgDeviceSummaryParam 查询条件
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param pageNo 当前页码
     * @param pageSize 查询条数
     * @param searchKey 模糊查询关键字
     * @param request 请求
     * @return 科室耗材汇总单
     */
    @Override
    public R<?> getOrgDeviceSummaryFromPage(OrgDeviceSummaryParam orgDeviceSummaryParam, String startTime,
        String endTime, Integer pageNo, Integer pageSize, String searchKey, HttpServletRequest request) {
        pageSize = Integer.MAX_VALUE;

        QueryWrapper<OrgDeviceDto> queryWrapper = HisQueryUtils.buildQueryWrapper(orgDeviceSummaryParam, searchKey,
            new HashSet<>(List.of(CommonConstants.FieldName.ItemName)), request);
        if (!(startTime == null || endTime == null)) {
            queryWrapper.between(CommonConstants.FieldName.ApplyTime, LocalDate.parse(startTime),
                LocalDate.parse(endTime));
        }

        Page<OrgDeviceDto> orgDeviceDtoPage =
            orgDeviceStockTakeAppMapper.selectOrgDeviceInfo(new Page<>(pageNo, pageSize), queryWrapper);

        List<OrgDeviceDto> orgDeviceList =
            new ArrayList<>(orgDeviceDtoPage.getRecords()).stream().filter(x -> x.getDispenseId() != null).toList();

        // 根据项目id + 批次号 + 库房号分组
        Map<String, List<OrgDeviceDto>> orgDeviceGroupBy =
            orgDeviceList.stream().collect(Collectors.groupingBy(item -> item.getItemId() + CommonConstants.Common.DASH
                + item.getLotNumber() + CommonConstants.Common.DASH + item.getSourceLocationId()));

        ArrayList<OrgDeviceSummaryFromDto> orgDeviceSummaryFromDtoList = new ArrayList<>();

        orgDeviceGroupBy.forEach((k, v) -> {
            OrgDeviceSummaryFromDto orgDeviceSummaryFromDto = new OrgDeviceSummaryFromDto();

            String itemId = k.split(CommonConstants.Common.DASH)[0];
            String lotNumber = k.split(CommonConstants.Common.DASH)[1];
            String sourceLocationId = k.split(CommonConstants.Common.DASH)[2];

            OrgDeviceDto orgDeviceDtoFirst = v.get(0);
            // 拆零比例
            BigDecimal partPercent = orgDeviceDtoFirst.getPartPercent();
            // 最小单位
            String minUnitCode = orgDeviceDtoFirst.getMinUnitCode();
            // 常规单位
            String unitCode = orgDeviceDtoFirst.getMaxUnitCode();
            if (minUnitCode == null || unitCode == null || partPercent == null) {
                throw new ServiceException("耗材信息有误,请联系管理员");
            }

            List<Long> dispenseIdList = new ArrayList<>();

            // 最小单位数量
            BigDecimal minQuantity = BigDecimal.ZERO;
            for (OrgDeviceDto orgDeviceDto : v) {
                BigDecimal quantity = orgDeviceDto.getQuantity();
                if (unitCode.equals(orgDeviceDto.getUnitCode())) {
                    // 转换为小单位进行累加
                    quantity = orgDeviceDto.getQuantity().multiply(partPercent);
                }
                minQuantity = minQuantity.add(quantity);
                dispenseIdList.add(orgDeviceDto.getDispenseId());
            }

            List<UnitDto> unitList = new ArrayList<>();
            UnitDto unitDto = new UnitDto();
            // 单位列表
            unitDto.setUnitCode(orgDeviceDtoFirst.getUnitCode()).setMinUnitCode(minUnitCode);
            unitList.add(unitDto);

            orgDeviceSummaryFromDto.setItemId(Long.valueOf(itemId)) // 器材id
                .setName(orgDeviceDtoFirst.getItemName()) // 器材名称
                .setTotalVolume(orgDeviceDtoFirst.getTotalVolume()) // 规格
                .setManufacturer(orgDeviceDtoFirst.getManufacturer()) // 厂家
                .setLotNumber(lotNumber) // 批号
                .setUnitPrice(orgDeviceDtoFirst.getUnitPrice()) // 单价
                .setDispenseQuantity(minQuantity) // 发放数量
                .setUnitCode(orgDeviceDtoFirst.getUnitCode()) // 单位
                .setMinUnitCode(minUnitCode) // 最小单位
                .setPartPercent(partPercent) // 拆零比
                .setUnitCode_dictText(orgDeviceDtoFirst.getUnitCode_dictText()) // 单位文字
                .setSourceLocationId(Long.valueOf(sourceLocationId)) // 发放地点
                .setDispenseIdList(dispenseIdList) // 发放id列表
                .setUnitList(unitList); // 单位列表

            orgDeviceSummaryFromDtoList.add(orgDeviceSummaryFromDto);
        });

        List<Long> itemIdList = orgDeviceSummaryFromDtoList.stream().map(OrgDeviceSummaryFromDto::getItemId).toList();
        List<InventoryItem> inventoryItemList = inventoryItemService.selectInventoryByItemIdList(itemIdList, 1);
        for (InventoryItem inventoryItem : inventoryItemList)
            for (OrgDeviceSummaryFromDto orgDeviceSummaryFromDto : orgDeviceSummaryFromDtoList)
                if (orgDeviceSummaryFromDto.getItemId().equals(inventoryItem.getItemId())
                    && orgDeviceSummaryFromDto.getLotNumber().equals(inventoryItem.getLotNumber())
                    && orgDeviceSummaryFromDto.getSourceLocationId().equals(inventoryItem.getLocationId())) {
                    // 库存数量
                    orgDeviceSummaryFromDto.setQuantity(inventoryItem.getQuantity());
                    // 库存id
                    orgDeviceSummaryFromDto.setInventoryItemId(inventoryItem.getId());
                }

        return R.ok(orgDeviceSummaryFromDtoList);
    }

    /**
     * 科室耗材汇总
     *
     * @return 科室耗材汇总单
     */
    @Override
    public R<?> orgDeviceSummary(OrgDeviceSummaryParam orgDeviceSummaryParam) {
        // 申请时间
        Date now = DateUtils.getNowDate();
        // 申请人
        Long practitionerId = SecurityUtils.getLoginUser().getPractitionerId();
        // 汇总单据号
        String busNo = assignSeqUtil.getSeqByDay(AssignSeqEnum.DEVICE_SUMMARY_NO.getPrefix(), 4);

        // 数量
        BigDecimal stockTakeQuantity = orgDeviceSummaryParam.getStockTakeQuantity();
        // 使用单位
        String useUnitCode = orgDeviceSummaryParam.getUseUnitCode();
        // 最小单位
        String minUnitCode = orgDeviceSummaryParam.getMinUnitCode();
        // 拆零比
        BigDecimal partPercent = orgDeviceSummaryParam.getPartPercent();
        // 发放id列表
        List<Long> dispenseIdList = orgDeviceSummaryParam.getDispenseIdList();

        if (orgDeviceSummaryParam.getInventoryItemId() == null) {
            return R.ok("未匹配到库存");
        }
        List<InventoryItem> inventoryItemList = new ArrayList<>();
        // 获取库存信息
        InventoryItem inventoryItem = inventoryItemMapper.selectById(orgDeviceSummaryParam.getInventoryItemId());
        if (inventoryItem != null) {
            if (PublicationStatus.ACTIVE.getValue().equals(inventoryItem.getInventoryStatusEnum())) {
                // 库存数量判定
                if (useUnitCode.equals(inventoryItem.getUnitCode())) {
                    // 当前库存数量(拆零单位)=当前库存数量(拆零单位)-请求数量
                    BigDecimal quantity = inventoryItem.getQuantity().subtract(stockTakeQuantity);
                    // 库存数量判定
                    if (quantity.compareTo(BigDecimal.ZERO) < 0) {
                        // 库存数量不足
                        return R.fail("当前库存数量不足");
                    } else {
                        inventoryItem.setQuantity(quantity);
                    }
                } else {
                    // 当前库存数量(拆零单位)=当前库存数量(拆零单位)-拆零数量（拆零比×请求数量）
                    BigDecimal quantity = inventoryItem.getQuantity().subtract(partPercent.multiply(stockTakeQuantity));
                    // 库存数量判定
                    if (quantity.compareTo(BigDecimal.ZERO) < 0) {
                        // 库存数量不足
                        return R.fail("当前库存数量不足");
                    } else {
                        inventoryItem.setQuantity(quantity);
                    }
                }
                inventoryItemList.add(inventoryItem);
            }
            // 库存更新
            inventoryItemService.updateBatchById(inventoryItemList);
            // 添加汇总单
            Long supplyRequestId = supplyRequestService.createDeviceSummarySupplyRequest(
                orgDeviceSummaryParam.getItemId(), orgDeviceSummaryParam.getSourceLocationId(),
                orgDeviceSummaryParam.getLotNumber(), stockTakeQuantity, minUnitCode, practitionerId, now, busNo);
            supplyDeliveryService.createDeviceSummarySupplyDelivery(orgDeviceSummaryParam.getItemId(),
                orgDeviceSummaryParam.getLotNumber(), stockTakeQuantity, minUnitCode, supplyRequestId);

            // 耗材发放状态更新
            deviceDispenseService.updateDispenseStatusSummarized(dispenseIdList, busNo);
            return R.ok("盘点成功");
        }
        return R.fail("未找到对应库存数据");
    }

}
