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

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.common.utils.HisQueryUtils;
import com.openhis.web.common.appservice.ICommonService;
import com.openhis.web.common.dto.InventoryItemDto;
import com.openhis.web.common.dto.UnitDto;
import com.openhis.web.pharmacyWarehousemanage.appservice.IPharmacyWarehouseCommonService;
import com.openhis.web.pharmacyWarehousemanage.dto.PharmacyWarehouseMedicationInfoDto;
import com.openhis.web.pharmacyWarehousemanage.mapper.PharmacyWarehouseCommonMapper;
import com.openhis.web.pharmacyWarehousemanage.mapper.PharmacyWarehousePurchaseOrderMapper;
import com.openhis.workflow.domain.SupplyRequest;
import com.openhis.workflow.service.ISupplyRequestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.core.common.core.domain.R;
import com.core.common.utils.AssignSeqUtil;
import com.openhis.administration.domain.Location;
import com.openhis.administration.domain.Practitioner;
import com.openhis.administration.domain.Supplier;
import com.openhis.administration.service.ILocationService;
import com.openhis.administration.service.IPractitionerService;
import com.openhis.administration.service.ISupplierService;
import com.openhis.web.common.dto.LocationDto;
import com.openhis.web.pharmacyWarehousemanage.dto.PharmacyWarehouseInitDto;
import com.openhis.web.pharmacyWarehousemanage.dto.PharmacyWarehouseDto;
import com.openhis.web.pharmacyWarehousemanage.dto.PharmacyWarehouseSearchParam;

/**
 * 药库共通
 *
 * @author yuxj
 * @date 2025-07-22
 */
@Service
public class PharmacyWarehouseCommonServiceImpl implements IPharmacyWarehouseCommonService {

    @Resource
    private ISupplierService supplierService;

    @Resource
    private IPractitionerService practitionerService;

    @Resource
    private ISupplyRequestService supplyRequestService;

    @Resource
    private PharmacyWarehouseCommonMapper pharmacyWarehouseCommonMapper;
    @Resource
    private ICommonService commonServiceImpl;

    /**
     * 初始化
     *
     * @return 初始化信息
     */
    @Override
    public PharmacyWarehouseInitDto init() {
        PharmacyWarehouseInitDto orderInitDto = new PharmacyWarehouseInitDto();

        // 查询供应商列表
        List<Supplier> supplierList = supplierService.getList();
        // 查询经手人列表
        List<Practitioner> practitionerList = practitionerService.getList();
        // 经手人信息
        List<PharmacyWarehouseInitDto.LongOption> practitionerListOption = practitionerList.stream()
            .map(practitioner -> new PharmacyWarehouseInitDto.LongOption(practitioner.getId(), practitioner.getName()))
            .collect(Collectors.toList());
        // 供应商信息
        List<PharmacyWarehouseInitDto.SupplierOption> supplierListOption =
            supplierList.stream().map(supplier -> new PharmacyWarehouseInitDto.SupplierOption(supplier.getId(),
                supplier.getName(), supplier.getPhone())).collect(Collectors.toList());
        // 审批状态
        List<PharmacyWarehouseInitDto.IntegerOption> supplyStatusOption = Stream.of(SupplyStatus.values()).map(
            supplyStatus -> new PharmacyWarehouseInitDto.IntegerOption(supplyStatus.getValue(), supplyStatus.getInfo()))
            .collect(Collectors.toList());

        // 包装情况
        List<PharmacyWarehouseInitDto.IntegerOption> packagingConditionOption = Stream.of(PackagingCondition.values())
            .map(packagingCondition -> new PharmacyWarehouseInitDto.IntegerOption(packagingCondition.getValue(),
                packagingCondition.getInfo()))
            .collect(Collectors.toList());

        // 验收结果
        List<PharmacyWarehouseInitDto.IntegerOption> acceptanceResultOption = Stream.of(AcceptanceResult.values())
            .map(acceptanceResult -> new PharmacyWarehouseInitDto.IntegerOption(acceptanceResult.getValue(),
                acceptanceResult.getInfo()))
            .collect(Collectors.toList());

        // 仓库列表
        List<LocationDto> cabinetList = commonServiceImpl.getCabinetList();
        // 药房列表
        List<LocationDto> pharmacyList = commonServiceImpl.getPharmacyList();

        orderInitDto.setCabinetListOptions(cabinetList).setPharmacyListOptions(pharmacyList)
            .setSupplierOption(supplierListOption).setPractitionerOption(practitionerListOption)
            .setSupplyStatusOptions(supplyStatusOption).setPackagingConditionOptions(packagingConditionOption)
            .setAcceptanceResultoryOptions(acceptanceResultOption);

        return orderInitDto;
    }

    /**
     * 获取药品
     *
     * @param purchaseOrderSearchParam 查询条件
     * @return 药品信息
     */
    @Override
    public R<?> getMedicationInfo(PharmacyWarehouseSearchParam purchaseOrderSearchParam, Integer pageNo,
        Integer pageSize, String searchKey, HttpServletRequest request) {

        Long locationId = purchaseOrderSearchParam.getLocationId();
        purchaseOrderSearchParam.setLocationId(null);
        Long supplierId = null;
        // 为药库订货时，需要传参数supplierId
        if (purchaseOrderSearchParam.getTypeEnum() != null
            && purchaseOrderSearchParam.getTypeEnum().equals(SupplyType.CABINET_PURCHASE.getValue())) {
            supplierId = purchaseOrderSearchParam.getSupplierId();
            purchaseOrderSearchParam.setSupplierId(null);
            purchaseOrderSearchParam.setTypeEnum(null);
        }
        // 构建查询条件
        QueryWrapper<PharmacyWarehouseSearchParam> queryWrapper =
            HisQueryUtils.buildQueryWrapper(purchaseOrderSearchParam, searchKey,
                new HashSet<>(Arrays.asList(CommonConstants.FieldName.Name, CommonConstants.FieldName.PyStr)), request);
        // 设置排序
        queryWrapper.orderByDesc(CommonConstants.FieldName.Name);

        Page<PharmacyWarehouseMedicationInfoDto> medicationInfoDto = pharmacyWarehouseCommonMapper
            .getMedicationInfo(new Page<>(pageNo, pageSize), queryWrapper, locationId, supplierId);

        for (PharmacyWarehouseMedicationInfoDto item : medicationInfoDto.getRecords()) {
            List<PharmacyWarehouseMedicationInfoDto.Option> unitList = new ArrayList<>();
            unitList
                .add(new PharmacyWarehouseMedicationInfoDto.Option(item.getUnitCode(), item.getUnitCode_dictText()));
            unitList.add(
                new PharmacyWarehouseMedicationInfoDto.Option(item.getMinUnitCode(), item.getMinUnitCode_dictText()));

            item.setUnitList(unitList);
        }

        return R.ok(medicationInfoDto);
    }

    /**
     * 单据列表
     *
     * @param purchaseOrderSearchParam 查询条件
     * @param pageNo 当前页码
     * @param pageSize 查询条数
     * @param searchKey 模糊查询关键字
     * @param request 请求数据
     * @param locationFlg 仓库flg
     * @param supplyType 单据类型
     * @return 订货单据分页列表
     */
    @Override
    public R<?> getPage(PharmacyWarehouseSearchParam purchaseOrderSearchParam, Integer pageNo, Integer pageSize,
        String searchKey, HttpServletRequest request, String locationFlg, Integer supplyType) {
        // 判断哪个画面使用
        if (supplyType != null) {
            purchaseOrderSearchParam.setTypeEnum(supplyType);
        }
        // if (locationForm != null) {
        // purchaseOrderSearchParam.setLocationTypeEnum(locationForm);
        // }
        String originalBusNoFlg = purchaseOrderSearchParam.getOriginalBusNoFlg();
        purchaseOrderSearchParam.setOriginalBusNoFlg(null);
        // 构建查询条件
        QueryWrapper<PharmacyWarehouseSearchParam> queryWrapper =
            HisQueryUtils.buildQueryWrapper(purchaseOrderSearchParam, searchKey,
                new HashSet<>(
                    Arrays.asList(CommonConstants.FieldName.SupplyBusNo, CommonConstants.FieldName.ApplicantName)),
                request);
        // 设置排序
        queryWrapper.orderByDesc(CommonConstants.FieldName.SupplyBusNo);
        // 查询订货单分页列表
        Page<PharmacyWarehouseDto> purchaseOrderDtoPage = pharmacyWarehouseCommonMapper
            .getPage(new Page<>(pageNo, pageSize), queryWrapper, originalBusNoFlg, locationFlg);

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

        return R.ok(purchaseOrderDtoPage);
    }

    /**
     * 删除单据
     *
     * @param busNo 单据号
     * @return 操作结果
     */
    @Override
    public R<?> deleteOrder(String busNo) {
        // 根据原始单据号查询信息
        List<SupplyRequest> supplyRequest = supplyRequestService.getSupplyByOriginalBusNo(busNo);
        if (!supplyRequest.isEmpty()) {
            // 将原始单据号信息的原始单据号删除
            boolean flg = supplyRequestService.updateByBusNo(supplyRequest.get(0).getBusNo());
            if (!flg) {
                R.fail(MessageUtils.createMessage(PromptMsgConstant.Common.M00007, null));
            }
        }

        // 删除单据
        boolean result = supplyRequestService.removeByBusNo(busNo);
        return result ? R.ok(null, MessageUtils.createMessage(PromptMsgConstant.Common.M00004, null))
            : R.fail(MessageUtils.createMessage(PromptMsgConstant.Common.M00007, null));
    }

    // /**
    // * 提交审批
    // *
    // * @param busNo 单据号
    // * @return 操作结果
    // */
    // @Override
    // public R<?> submitApproval(String busNo) {
    // // 单据提交审核
    // boolean result = supplyRequestService.submitApproval(busNo);
    // return result ? R.ok(null, MessageUtils.createMessage(PromptMsgConstant.Common.M00004, null))
    // : R.fail(MessageUtils.createMessage(PromptMsgConstant.Common.M00007, null));
    // }

    // /**
    // * 同意审批
    // *
    // * @param busNo 单据号
    // * @return 操作结果
    // */
    // @Override
    // public R<?> agreeApproval(String busNo) {
    // // 单据同意审核
    // List<SupplyRequest> result = supplyRequestService.agreeRequest(busNo, DateUtils.getNowDate());
    // return result == null ? R.ok(null, MessageUtils.createMessage(PromptMsgConstant.Common.M00004, null))
    // : R.fail(MessageUtils.createMessage(PromptMsgConstant.Common.M00007, null));
    // }

    // /**
    // * 撤回审批
    // *
    // * @param busNo 单据号
    // * @return 操作结果
    // */
    // @Override
    // public R<?> withdrawApproval(String busNo) {
    // // 撤回审核
    // boolean result = supplyRequestService.withdrawApproval(busNo);
    // return result ? R.ok(null, MessageUtils.createMessage(PromptMsgConstant.Common.M00004, null))
    // : R.fail(MessageUtils.createMessage(PromptMsgConstant.Common.M00007, null));
    // }

}
