package com.openhis.web.pharmacyWarehousemanage.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.utils.AssignSeqUtil;
import com.core.common.utils.DateUtils;
import com.core.common.utils.MessageUtils;
import com.openhis.administration.domain.Practitioner;
import com.openhis.administration.domain.Supplier;
import com.openhis.common.constant.CommonConstants;
import com.openhis.common.constant.PromptMsgConstant;
import com.openhis.common.enums.*;
import com.openhis.common.utils.EnumUtils;
import com.openhis.common.utils.HisQueryUtils;
import com.openhis.web.common.dto.LocationDto;
import com.openhis.web.common.dto.UnitDto;
import com.openhis.web.inventorymanage.dto.*;
import com.openhis.web.pharmacyWarehousemanage.appservice.IPharmacyWarehouseCommonService;
import com.openhis.web.pharmacyWarehousemanage.appservice.IPharmacyWarehousePurchaseOrderService;
import com.openhis.web.pharmacyWarehousemanage.dto.*;
import com.openhis.web.pharmacyWarehousemanage.mapper.PharmacyWarehouseCommonMapper;
import com.openhis.web.pharmacyWarehousemanage.mapper.PharmacyWarehousePurchaseOrderMapper;
import com.openhis.workflow.domain.SupplyDelivery;
import com.openhis.workflow.domain.SupplyRequest;
import com.openhis.workflow.service.ISupplyDeliveryService;
import com.openhis.workflow.service.ISupplyRequestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 药库订货单
 *
 * @author yuxj
 * @date 2025-07-22
 */
@Service
public class PharmacyWarehousePurchaseOrderServiceImpl implements IPharmacyWarehousePurchaseOrderService {

    @Resource
    private AssignSeqUtil assignSeqUtil;
    @Resource
    private ISupplyRequestService supplyRequestService;

    @Autowired
    private IPharmacyWarehouseCommonService pharmacyWarehouseCommonService;

    @Autowired
    private   PharmacyWarehouseCommonMapper pharmacyWarehouseCommonMapper;
    /**
     * 初始化
     *
     * @return 初始化信息
     */
    @Override
    public R<?> init() {

        PharmacyWarehouseInitDto purchaseOrderInitDto = pharmacyWarehouseCommonService.init();

        // 单据分类
        List<PharmacyWarehouseInitDto.IntegerOption> supplyCategoryOption = new ArrayList<>();
        supplyCategoryOption.add(new PharmacyWarehouseInitDto.IntegerOption(SupplyCategory.NORMAL.getValue(),
            SupplyCategory.NORMAL.getInfo()));
        supplyCategoryOption.add(new PharmacyWarehouseInitDto.IntegerOption(SupplyCategory.PURCHASE_PLAN_GENERATION.getValue(),
            SupplyCategory.PURCHASE_PLAN_GENERATION.getInfo()));

        purchaseOrderInitDto.setSupplyCategoryOptions(supplyCategoryOption);

        return R.ok(purchaseOrderInitDto);
    }

    /**
     * 订货单单据详情
     *
     * @param busNo 单据号
     * @param pageNo 当前页码
     * @param pageSize 查询条数
     * @return 订货单单据详情
     */
    @Override
    public R<?> getDetailPage(String busNo, Integer pageNo, Integer pageSize) {

        Page<PharmacyWarehouseDetailDto> purchaseOrderDtoDetailPage =
            pharmacyWarehouseCommonMapper.getDetailPage(new Page<>(pageNo, pageSize), busNo);

        purchaseOrderDtoDetailPage.getRecords().forEach(e -> {
            // 单据分类
            e.setCategoryEnum_enumText(EnumUtils.getInfoByValue(SupplyCategory.class, e.getCategoryEnum()));
            // 单据状态
            e.setStatusEnum_enumText(EnumUtils.getInfoByValue(SupplyStatus.class, e.getStatusEnum()));
            // 单据类型
            e.setTypeEnum_enumText(EnumUtils.getInfoByValue(SupplyType.class, e.getTypeEnum()));
        });

        List<PharmacyWarehouseDetailDto.Option> unitList;
        for (PharmacyWarehouseDetailDto item : purchaseOrderDtoDetailPage.getRecords()) {
            unitList = new ArrayList<>();
            unitList.add(new PharmacyWarehouseDetailDto.Option(item.getMaxUnitCode(),item.getMaxUnitCode_dictText()));
            unitList.add(new PharmacyWarehouseDetailDto.Option(item.getMinUnitCode(),item.getMinUnitCode_dictText()
            ));

            item.setUnitList(unitList);
        }

        return R.ok(purchaseOrderDtoDetailPage);
    }

    /**
     * 获取单据号
     *
     * @return 初始化信息
     */
    @Override
    public R<?> getBusNo() {

        ProductStocktakingInitDto initDto = new ProductStocktakingInitDto();
        // 单据号
        initDto.setBusNo(assignSeqUtil.getSeqByDay(AssignSeqEnum.PHARMACY_WAREHOUSE_PURCHASE.getPrefix(), 4));

        return R.ok(initDto);
    }

    /**
     * 添加/编辑采购单
     *
     * @param purchaseOrderDtoList 采购信息
     * @return 操作结果
     */

    @Override
    public R<?> addOrEditPurchaseOrder(List<PharmacyWarehouseDetailDto> purchaseOrderDtoList) {
        // 请求数据取得
        List<SupplyRequest> requestList = supplyRequestService.getSupplyByBusNo(purchaseOrderDtoList.get(0).getBusNo());
        if (!requestList.isEmpty()) {
            // 请求id取得
            List<Long> requestIdList = requestList.stream().map(SupplyRequest::getId).collect(Collectors.toList());
            // 单据信息删除
            supplyRequestService.removeByIds(requestIdList);
        }

        List<SupplyRequest> supplyRequestList = new ArrayList<>();
        for (PharmacyWarehouseDetailDto item : purchaseOrderDtoList) {
            SupplyRequest supplyRequest =
                new SupplyRequest().setBusNo(item.getBusNo()).setTypeEnum(SupplyType.CABINET_PURCHASE.getValue())
                    .setStatusEnum(SupplyStatus.PENDING_REVIEW.getValue()).setCategoryEnum(item.getCategoryEnum())
                    .setItemTable(CommonConstants.TableName.MED_MEDICATION_DEFINITION).setItemId(item.getItemId())
                    .setUnitCode(item.getUnitCode()).setItemQuantity(item.getItemQuantity())
                    .setSpecificationInventory(item.getSpecificationInventory()).setPrice(item.getPrice())
                    .setTotalPrice(item.getTotalPrice()).setRetailPrice(item.getRetailPrice())
                    .setTotalRetailPrice(item.getTotalRetailPrice()).setPurposeTypeEnum(LocationForm.CABINET.getValue())
                    .setPurposeLocationId(item.getPurposeLocationId()).setSupplierId(item.getSupplierId())
                    .setApplicantId(item.getApplicantId()).setApplyTime(item.getApplyTime()).setReason(item.getReason())
                    .setRemake(item.getRemake());
            supplyRequestList.add(supplyRequest);
        }
        // 更新请求表
        boolean flg = supplyRequestService.saveOrUpdateBatch(supplyRequestList);
        if (!flg) {
            return R.fail(MessageUtils.createMessage(PromptMsgConstant.Common.M00011, null));
        }

        return R.ok(MessageUtils.createMessage(PromptMsgConstant.Common.M00004, null));
    }
}
