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

import java.util.ArrayList;
import java.util.List;

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

/**
 * 药房发药单
 *
 * @author yuxj
 * @date 2025-07-22
 */
@Service
public class PharmacyDispensaryDispensingOrderServiceImpl implements IPharmacyDispensaryDispensingOrderService {

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

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

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

        PharmacyDispensaryInitDto purchaseOrderInitDto = pharmacyDispensaryCommonService.init();

        // 单据分类
        List<PharmacyDispensaryInitDto.IntegerOption> supplyCategoryOption = new ArrayList<>();
        // supplyCategoryOption
        // .add(new PharmacyDispensaryInitDto.IntegerOption(SupplyCategory.OUTPATIENT_PATIENT_DISPENSING.getValue(),
        // SupplyCategory.OUTPATIENT_PATIENT_DISPENSING.getInfo()));
        // supplyCategoryOption
        // .add(new PharmacyDispensaryInitDto.IntegerOption(SupplyCategory.INPATIENT_PATIENT_DISPENSING.getValue(),
        // SupplyCategory.INPATIENT_PATIENT_DISPENSING.getInfo()));
        // supplyCategoryOption.add(
        // new PharmacyDispensaryInitDto.IntegerOption(SupplyCategory.INPATIENT_PATIENT_SUMMARY_DISPENSING.getValue(),
        // SupplyCategory.INPATIENT_PATIENT_SUMMARY_DISPENSING.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> dispensingOrderDtoDetailPage =
            pharmacyDispensaryCommonMapper.getDetailPage(new Page<>(pageNo, pageSize), busNo);

        dispensingOrderDtoDetailPage.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()));

        });

        return R.ok(dispensingOrderDtoDetailPage);
    }

    /**
     * 获取单据号
     *
     * @return 单据号
     */
    public String getBusNo() {
        return assignSeqUtil.getSeqByDay(AssignSeqEnum.DISPENSING_ORDER.getPrefix(), 4);
    }

    /**
     * 添加/编辑发药单
     *
     * @param dispenseIdList 药品发放id
     * @return 操作结果
     */

    @Override
    public boolean addOrEditDispensingOrder(List<Long> dispenseIdList) {

        // 获取单据号
        String busNo = this.getBusNo();
        // 获取更表所需信息
        List<PharmacyDispensaryDetailDto> detailDto =
            pharmacyDispensaryDispensingOrderMapper.getInfo(dispenseIdList, DispenseStatus.COMPLETED.getValue());

        List<SupplyRequest> supplyRequestList = new ArrayList<>();
        SupplyRequest supplyRequest;
        List<SupplyDelivery> supplyDeliveryList = new ArrayList<>();
        SupplyDelivery supplyDelivery;
        for (PharmacyDispensaryDetailDto item : detailDto) {
            // 供应申请
            supplyRequest = new SupplyRequest().setBusNo(busNo).setTypeEnum(SupplyType.DISPENSING_ORDER.getValue())
                .setStatusEnum(SupplyStatus.AGREE.getValue()).setCategoryEnum(item.getCategoryEnum())
                .setItemTable(CommonConstants.TableName.MED_MEDICATION_DEFINITION).setItemId(item.getItemId())
                .setUnitCode(item.getUnitCode()).setItemQuantity(item.getItemQuantity())
                .setLotNumber(item.getLotNumber()).setSourceTypeEnum(LocationForm.PHARMACY.getValue())
                .setSourceLocationId(item.getSourceLocationId()).setPurposeTypeEnum(LocationForm.DEPARTMENT.getValue())
                .setPurposeLocationId(item.getPurposeLocationId()).setApplicantId(item.getApplicantId())
                .setApplyTime(item.getApplyTime()).setApproverId(item.getApproverId())
                .setApprovalTime(item.getApprovalTime());
            supplyRequestList.add(supplyRequest);
            // 供应发放
            supplyDelivery = new SupplyDelivery().setRequestId(supplyRequest.getId())
                .setStatusEnum(DispenseStatus.COMPLETED.getValue()).setTypeEnum(supplyRequest.getTypeEnum())
                .setItemTable(supplyRequest.getItemTable()).setItemId(supplyRequest.getItemId())
                .setBasedOnTable(CommonConstants.TableName.MED_MEDICATION_DISPENSE).setBasedOnIds(item.getDispenseIds())
                .setUnitCode(supplyRequest.getUnitCode()).setQuantity(supplyRequest.getItemQuantity())
                .setLotNumber(supplyRequest.getLotNumber()).setPractitionerId(supplyRequest.getApplicantId())
                .setOccurrenceTime(supplyRequest.getApprovalTime()).setReceiverId(supplyRequest.getPurposeLocationId())
                .setReceiveTime(supplyRequest.getApprovalTime());

            supplyDeliveryList.add(supplyDelivery);
        }

        // 更新供应请求表
        boolean requestFlg = supplyRequestService.saveBatch(supplyRequestList);
        if (!requestFlg) {
            return false;
        }
        // 更新供应发放表
        boolean deliveryFlg = supplyDeliveryService.saveBatch(supplyDeliveryList);
        if (!deliveryFlg) {
            return false;
        }

        return true;
    }

}
