/*
 * Copyright ©2023 CJB-CNIT Team. All rights reserved
 */
package com.openhis.web.reportmanage.appservice.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.core.common.core.domain.entity.SysDictData;
import com.core.common.utils.MessageUtils;
import com.core.system.service.ISysDictTypeService;
import com.openhis.administration.domain.Organization;
import com.openhis.administration.domain.Practitioner;
import com.openhis.administration.service.IOrganizationService;
import com.openhis.common.constant.PromptMsgConstant;
import com.openhis.common.enums.*;
import com.openhis.common.utils.HisQueryUtils;
import com.openhis.web.reportmanage.dto.InboundReportPageDto;
import com.openhis.web.reportmanage.dto.InboundReportSearchParam;
import com.openhis.web.reportmanage.dto.MedDevUseReportDto;
import com.openhis.web.reportmanage.dto.MedUseReportInfoDto;
import com.openhis.web.reportmanage.utils.ExcelFillerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.core.common.core.domain.R;
import com.openhis.common.constant.CommonConstants;
import com.openhis.web.reportmanage.appservice.IMedicationDeviceReportAppService;
import com.openhis.web.reportmanage.mapper.MedicationDeviceReportMapper;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 药品耗材统计查询用 impl
 *
 * @author liuhr
 * @date 2025-07-15
 */
@Service
public class MedicationDeviceReportAppServiceImpl implements IMedicationDeviceReportAppService {

    @Autowired
    private MedicationDeviceReportMapper medicationDeviceReportMapper;
    @Resource
    private ISysDictTypeService sysDictTypeService;
    @Resource
    private IOrganizationService organizationService;

    /**
     * 药品耗材日结/周结/月结算（统计筛选时间区内）
     *
     * @param dispenseDateSTime 开始时间
     * @param dispenseDateETime 结束时间
     * @return 药品耗材日结/周结/月结算单
     */
    @Override
    public R<?> selectMedDevReport(String dispenseDateSTime, String dispenseDateETime) {

        return R.ok(medicationDeviceReportMapper.selectMedDevReport(CommonConstants.TableName.MED_MEDICATION_REQUEST,
            CommonConstants.TableName.WOR_DEVICE_REQUEST, CommonConstants.TableName.MED_MEDICATION_DEFINITION,
            CommonConstants.TableName.ADM_DEVICE_DEFINITION, RequestStatus.COMPLETED.getValue(),
            DispenseStatus.COMPLETED.getValue(), dispenseDateSTime, dispenseDateETime));
    }

    /**
     * 药品耗材日结/周结/月结算 明细清单
     *
     * @param orgId 科室
     * @param dispenseDateSTime 开始时间
     * @param dispenseDateETime 结束时间
     * @param pageNo 当前页码
     * @param pageSize 查询条数
     * @return 药品耗材日结/周结/月结算单
     */
    @Override
    public Page<MedUseReportInfoDto> selectMedDdevInfo(Long orgId, String name, String dispenseDateSTime,
        String dispenseDateETime, Integer pageNo, Integer pageSize) {

        Page<MedUseReportInfoDto> medUseReportInfoDto = medicationDeviceReportMapper.selectMedDdevInfo(
            new Page<>(pageNo, pageSize), CommonConstants.TableName.MED_MEDICATION_REQUEST,
            CommonConstants.TableName.WOR_DEVICE_REQUEST, CommonConstants.TableName.MED_MEDICATION_DEFINITION,
            CommonConstants.TableName.ADM_DEVICE_DEFINITION, RequestStatus.COMPLETED.getValue(),
            DispenseStatus.COMPLETED.getValue(), SupplyType.ISSUE_INVENTORY.getValue(),
            SupplyType.RETURN_ISSUE.getValue(), orgId, name, dispenseDateSTime, dispenseDateETime);

        return medUseReportInfoDto;
    }

    /**
     * 导出
     *
     * @param orgId 科室
     * @param dispenseDateSTime 开始时间
     * @param dispenseDateETime 结束时间
     * @param pageNo 当前页码
     * @param pageSize 查询条数
     * @param response excel导出用
     *
     * @return 单据详情
     */
    @Override
    public R<?> makeExcelFile(Long orgId, String name, String dispenseDateSTime, String dispenseDateETime,
        Integer pageNo, Integer pageSize, HttpServletResponse response) {
        pageNo = 1;
        pageSize = 10000;
        // 获取科室的耗材和药品总金额数据
        List<MedDevUseReportDto> medDevReport =
            medicationDeviceReportMapper.selectMedDevReport(CommonConstants.TableName.MED_MEDICATION_REQUEST,
                CommonConstants.TableName.WOR_DEVICE_REQUEST, CommonConstants.TableName.MED_MEDICATION_DEFINITION,
                CommonConstants.TableName.ADM_DEVICE_DEFINITION, RequestStatus.COMPLETED.getValue(),
                DispenseStatus.COMPLETED.getValue(), dispenseDateSTime, dispenseDateETime);
        MedDevUseReportDto medDevReportDto = medDevReport.stream().filter(dto -> orgId.equals(dto.getOrgId()))
            .findFirst().orElseThrow(() -> new IllegalArgumentException("未找到指定科室的数据"));

        // 查询数据
        Page<MedUseReportInfoDto> medUseReportInfoDto = medicationDeviceReportMapper.selectMedDdevInfo(
            new Page<>(pageNo, pageSize), CommonConstants.TableName.MED_MEDICATION_REQUEST,
            CommonConstants.TableName.WOR_DEVICE_REQUEST, CommonConstants.TableName.MED_MEDICATION_DEFINITION,
            CommonConstants.TableName.ADM_DEVICE_DEFINITION, RequestStatus.COMPLETED.getValue(),
            DispenseStatus.COMPLETED.getValue(), SupplyType.ISSUE_INVENTORY.getValue(),
            SupplyType.RETURN_ISSUE.getValue(), orgId, name, dispenseDateSTime, dispenseDateETime);

        List<MedUseReportInfoDto> receiptDetailList = medUseReportInfoDto.getRecords();

        if (receiptDetailList.isEmpty()) {
            System.out.printf("导出Excel失败,无数据。");
            return R.fail("导出Excel失败,无数据。");
        }
        // 获取药品分类
        List<SysDictData> unitCodeList = sysDictTypeService.selectDictDataByType("unit_code");
        // 创建单位代码到单位名称的映射
        Map<String, String> unitCodeToNameMap = unitCodeList.stream().collect(
            Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel, (oldValue, newValue) -> oldValue // 冲突时保留旧值（第一个）
            ));
        // 做成科室List
        List<Organization> organizationList = organizationService.getList(OrganizationType.DEPARTMENT.getValue(), null);
        // 创建id到名字的映射
        Map<Long, String> rganizationToNameMap = organizationList.stream()
            .collect(Collectors.toMap(Organization::getId, Organization::getName, (oldValue, newValue) -> oldValue // 冲突时保留旧值（第一个）
            ));
        // 遍历赋值
        receiptDetailList.forEach(detail -> {
            detail.setUnitCode_dictText(unitCodeToNameMap.get(detail.getUnitCode()));
            detail.setOrgId_dictText(rganizationToNameMap.get(detail.getOrgId()));
        });

        try {
            // 准备表头（key对应DTO的字段名）
            Map<String, String> headers = new LinkedHashMap<>();
            headers.put("name", "项目名");
            headers.put("totalVolume", "规格");
            headers.put("lotNumber", "产品型号");
            headers.put("manufacturerText", "生产厂家");
            headers.put("totalQuantity", "数量");
            headers.put("unitCode_dictText", "单位");
            headers.put("unitPrice", "单价");
            headers.put("totalMoney", "项目总价");
            headers.put("orgId_dictText", "所属科室");
            headers.put("dispenseTime", "发放时间");

            // 表头上的字段
            Map<String, Object> totalValues = new LinkedHashMap<>();
            totalValues.put("科室名", medDevReportDto.getOrgName());
            totalValues.put("耗材和药品总金额", medDevReportDto.getTotalMoney());

            // 文件名，只传文字部分
            String excelName = "药房月结";
            // 导出到Excel
            ExcelFillerUtil.makeExcelFile(response, receiptDetailList, headers, excelName, totalValues);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.printf("导出Excel失败：" + e.getMessage());
            return R.fail("导出Excel失败：" + e.getMessage());
        }

        return R.ok(null, MessageUtils.createMessage(PromptMsgConstant.Common.M00004, null));

    }

}