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

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

import javax.annotation.Resource;

import com.openhis.web.departmentmanage.mapper.DepartmentIssuanceOrderMapper;
import com.openhis.web.pharmacyDispensarymanage.dto.PharmacyDispensaryDetailDto;
import com.openhis.web.pharmacyDispensarymanage.dto.PharmacyDispensaryInitDto;
import com.openhis.web.pharmacyDispensarymanage.mapper.PharmacyDispensaryDispensingOrderMapper;
import com.openhis.workflow.domain.SupplyDelivery;
import com.openhis.workflow.service.ISupplyDeliveryService;
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.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.departmentmanage.appservice.IDepartmentCommonService;
import com.openhis.web.departmentmanage.appservice.IDepartmentIssuanceOrderService;
import com.openhis.web.departmentmanage.dto.DepartmentDetailDto;
import com.openhis.web.departmentmanage.dto.DepartmentInitDto;
import com.openhis.web.departmentmanage.mapper.DepartmentCommonMapper;
import com.openhis.web.inventorymanage.dto.ProductStocktakingInitDto;
import com.openhis.workflow.domain.SupplyRequest;
import com.openhis.workflow.service.ISupplyRequestService;

/**
 * 科室材料发出单
 *
 * @author yuxj
 * @date 2025-07-22
 */
@Service
public class DepartmentIssuanceOrderServiceImpl implements IDepartmentIssuanceOrderService {

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

    @Autowired
    private IDepartmentCommonService departmentCommonService;

    @Autowired
    private DepartmentCommonMapper departmentCommonMapper;
    @Autowired
    private DepartmentIssuanceOrderMapper departmentIssuanceOrderMapper;
    /**
     * 初始化
     *
     * @return 初始化信息
     */
    @Override
    public R<?> init() {

        DepartmentInitDto issuanceOrderInitDto = departmentCommonService.init();

        // 单据分类
        List<DepartmentInitDto.IntegerOption> supplyCategoryOption = new ArrayList<>();
        supplyCategoryOption
            .add(new DepartmentInitDto.IntegerOption(SupplyCategory.OUTPATIENT_PATIENT_DISPENSING.getValue(),
                SupplyCategory.OUTPATIENT_PATIENT_DISPENSING.getInfo()));
        supplyCategoryOption
            .add(new DepartmentInitDto.IntegerOption(SupplyCategory.INPATIENT_PATIENT_DISPENSING.getValue(),
                SupplyCategory.INPATIENT_PATIENT_DISPENSING.getInfo()));
        supplyCategoryOption.add(
            new DepartmentInitDto.IntegerOption(SupplyCategory.INPATIENT_PATIENT_SUMMARY_DISPENSING.getValue(),
                SupplyCategory.INPATIENT_PATIENT_SUMMARY_DISPENSING.getInfo()));

        issuanceOrderInitDto.setSupplyCategoryOptions(supplyCategoryOption);

        return R.ok(issuanceOrderInitDto);
    }

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

        Page<DepartmentDetailDto> issuanceOrderDtoDetailPage =
            departmentCommonMapper.getDetailPage(new Page<>(pageNo, pageSize), busNo);

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

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

    /**
     * 添加/编辑发出单
     *
     * @param dispenseIdList 耗材发放id
     * @return 操作结果
     */

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

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

        List<SupplyRequest> supplyRequestList = new ArrayList<>();
        SupplyRequest supplyRequest;
        List<SupplyDelivery> supplyDeliveryList = new ArrayList<>();
        SupplyDelivery supplyDelivery;
        for (DepartmentDetailDto item : detailDto) {
            // 供应申请
            supplyRequest = new SupplyRequest().setBusNo(busNo).setTypeEnum(SupplyType.DISPENSING_ORDER.getValue())
                .setStatusEnum(SupplyStatus.AGREE.getValue()).setCategoryEnum(item.getCategoryEnum())
                .setItemTable(CommonConstants.TableName.ADM_DEVICE_DEFINITION).setItemId(item.getItemId())
                .setUnitCode(item.getUnitCode()).setItemQuantity(item.getItemQuantity())
                .setLotNumber(item.getLotNumber())
                .setSourceTypeEnum(LocationForm.CABINET.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.WOR_DEVICE_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;
    }
}
