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

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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.common.constant.CommonConstants;
import com.openhis.common.constant.PromptMsgConstant;
import com.openhis.common.enums.*;
import com.openhis.common.utils.EnumUtils;
import com.openhis.web.inventorymanage.dto.ProductStocktakingInitDto;
import com.openhis.web.pharmacyDispensarymanage.appservice.IPharmacyDispensaryCommonService;
import com.openhis.web.pharmacyDispensarymanage.appservice.IPharmacyDispensaryProfitLossOrderService;
import com.openhis.web.pharmacyDispensarymanage.dto.PharmacyDispensaryDetailDto;
import com.openhis.web.pharmacyDispensarymanage.dto.PharmacyDispensaryInitDto;
import com.openhis.web.pharmacyDispensarymanage.mapper.PharmacyDispensaryCommonMapper;
import com.openhis.workflow.domain.SupplyRequest;
import com.openhis.workflow.service.ISupplyRequestService;

/**
 * 药房损益单
 *
 * @author yuxj
 * @date 2025-07-22
 */
@Service
public class PharmacyDispensaryProfitLossOrderServiceImpl implements IPharmacyDispensaryProfitLossOrderService {

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

    @Autowired
    private IPharmacyDispensaryCommonService pharmacyDispensaryCommonService;
    @Autowired
    private PharmacyDispensaryCommonMapper pharmacyDispensaryCommonMapper;

    /**
     * 初始化
     *
     * @return 初始化信息
     */
    @Override
    public R<?> init() {

        PharmacyDispensaryInitDto purchaseOrderInitDto = pharmacyDispensaryCommonService.init();

        // 单据分类
        List<PharmacyDispensaryInitDto.IntegerOption> supplyCategoryOption = new ArrayList<>();
        // supplyCategoryOption.add(new
        // PharmacyDispensaryInitDto.IntegerOption(SupplyCategory.GENERAL_PROFIT_AND_LOSS.getValue(),
        // SupplyCategory.GENERAL_PROFIT_AND_LOSS.getInfo()));
        // supplyCategoryOption.add(new
        // PharmacyDispensaryInitDto.IntegerOption(SupplyCategory.STOCKTAKING_PROFIT_AND_LOSS.getValue(),
        // SupplyCategory.STOCKTAKING_PROFIT_AND_LOSS.getInfo()));
        // supplyCategoryOption.add(new
        // PharmacyDispensaryInitDto.IntegerOption(SupplyCategory.STANDBY_RESCUE_MEDICINES.getValue(),
        // SupplyCategory.STANDBY_RESCUE_MEDICINES.getInfo()));
        // supplyCategoryOption.add(new
        // PharmacyDispensaryInitDto.IntegerOption(SupplyCategory.DAMAGED_EXPIRED_MEDICINES.getValue(),
        // SupplyCategory.DAMAGED_EXPIRED_MEDICINES.getInfo()));
        // supplyCategoryOption.add(new
        // PharmacyDispensaryInitDto.IntegerOption(SupplyCategory.DONATED_MEDICINES.getValue(),
        // SupplyCategory.DONATED_MEDICINES.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<PharmacyDispensaryDetailDto> profitLossOrderDtoDetailPage =
            pharmacyDispensaryCommonMapper.getDetailPage(new Page<>(pageNo, pageSize), busNo);

        profitLossOrderDtoDetailPage.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<PharmacyDispensaryDetailDto.Option> unitList;
        for (PharmacyDispensaryDetailDto item : profitLossOrderDtoDetailPage.getRecords()) {
            unitList = new ArrayList<>();
            unitList.add(new PharmacyDispensaryDetailDto.Option(item.getMaxUnitCode(), item.getMaxUnitCode_dictText()));
            unitList.add(new PharmacyDispensaryDetailDto.Option(item.getMinUnitCode(), item.getMinUnitCode_dictText()));

            item.setUnitList(unitList);
        }
        return R.ok(profitLossOrderDtoDetailPage);
    }

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

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

        return R.ok(initDto);
    }

    /**
     * 添加/编辑损益单
     *
     * @param profitLossOrderDtoList 损益信息
     * @return 操作结果
     */

    @Override
    public R<?> addOrEditProfitLossOrder(List<PharmacyDispensaryDetailDto> profitLossOrderDtoList) {
        // 请求数据取得
        List<SupplyRequest> requestList =
            supplyRequestService.getSupplyByBusNo(profitLossOrderDtoList.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<>();
        Date applyTime = DateUtils.getNowDate();
        for (PharmacyDispensaryDetailDto item : profitLossOrderDtoList) {
            SupplyRequest supplyRequest = new SupplyRequest().setBusNo(item.getBusNo())
                .setTypeEnum(SupplyType.PURCHASE_PRPFITLOSS.getValue())
                .setStatusEnum(SupplyStatus.PENDING_REVIEW.getValue()).setCategoryEnum(item.getCategoryEnum())
                .setItemTable(CommonConstants.TableName.MED_MEDICATION_DEFINITION).setItemId(item.getItemId())
                .setUnitCode(item.getUnitCode()).setItemQuantity(item.getItemQuantity()).setPrice(item.getPrice())
                .setTotalPrice(item.getTotalPrice()).setRetailPrice(item.getRetailPrice())
                .setTotalRetailPrice(item.getTotalRetailPrice()).setBatchInventory(item.getBatchInventory())
                .setSpecificationInventory(item.getSpecificationInventory()).setStartTime(item.getStartTime())
                .setEndTime(item.getEndTime()).setLotNumber(item.getLotNumber()).setTraceNo(item.getTraceNo())
                .setTraceNoUnitCode(item.getTraceNoUnitCode()).setReason(item.getReason())
                .setPurposeTypeEnum(LocationForm.PHARMACY.getValue()).setPurposeLocationId(item.getPurposeLocationId())
                .setApplicantId(item.getApplicantId()).setApplyTime(applyTime).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));
    }

}
