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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

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

import com.openhis.administration.domain.Organization;
import com.openhis.administration.service.IOrganizationService;
import com.openhis.common.enums.*;
import org.springframework.stereotype.Service;

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.MessageUtils;
import com.openhis.administration.domain.Practitioner;
import com.openhis.administration.domain.Supplier;
import com.openhis.administration.service.IPractitionerService;
import com.openhis.administration.service.ISupplierService;
import com.openhis.common.constant.CommonConstants;
import com.openhis.common.constant.PromptMsgConstant;
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.LocationDto;
import com.openhis.web.materialmanage.appservice.IMaterialCommonService;
import com.openhis.web.materialmanage.dto.MaterialDto;
import com.openhis.web.materialmanage.dto.MaterialInitDto;
import com.openhis.web.materialmanage.dto.MaterialDeviceInfoDto;
import com.openhis.web.materialmanage.dto.MaterialSearchParam;
import com.openhis.web.materialmanage.mapper.MaterialCommonMapper;
import com.openhis.workflow.domain.SupplyRequest;
import com.openhis.workflow.service.ISupplyRequestService;

/**
 * 物资共通
 *
 * @author yuxj
 * @date 2025-07-22
 */
@Service
public class MaterialCommonServiceImpl implements IMaterialCommonService {

    @Resource
    private ISupplierService supplierService;

    @Resource
    private IPractitionerService practitionerService;

    @Resource
    private ISupplyRequestService supplyRequestService;

    @Resource
    private MaterialCommonMapper materialCommonMapper;
    @Resource
    private ICommonService commonServiceImpl;
    @Resource
    private IOrganizationService organizationService;

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

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

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

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

        // 仓库列表
        List<LocationDto> warehouseList = commonServiceImpl.getWarehouseList();
        // 科室列表
        List<Organization> departmentList = organizationService.getList(OrganizationType.DEPARTMENT.getValue(), null);

        orderInitDto.setWarehouseListOptions(warehouseList).setDepartmentListOptions(departmentList)
            .setSupplierOption(supplierListOption).setPractitionerOption(practitionerListOption)
            .setSupplyStatusOptions(supplyStatusOption).setPackagingConditionOptions(packagingConditionOption)
            .setAcceptanceResultoryOptions(acceptanceResultOption);

        return orderInitDto;
    }

    /**
     * 获取器材
     *
     * @param purchaseOrderSearchParam 查询条件
     * @return 器材信息
     */
    @Override
    public R<?> getDeviceInfo(MaterialSearchParam 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.MATERIAL_PURCHASE.getValue())) {
            supplierId = purchaseOrderSearchParam.getSupplierId();
            purchaseOrderSearchParam.setSupplierId(null);
        }
        // 构建查询条件
        QueryWrapper<MaterialSearchParam> queryWrapper =
            HisQueryUtils.buildQueryWrapper(purchaseOrderSearchParam, searchKey,
                new HashSet<>(Arrays.asList(CommonConstants.FieldName.Name, CommonConstants.FieldName.PyStr)), request);
        // 设置排序
        queryWrapper.orderByDesc(CommonConstants.FieldName.Name);

        Page<MaterialDeviceInfoDto> deviceInfoDto =
            materialCommonMapper.getDeviceInfo(new Page<>(pageNo, pageSize), queryWrapper, locationId, supplierId);

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

            item.setUnitList(unitList);
        }

        return R.ok(deviceInfoDto);
    }

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