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

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

import com.core.common.core.domain.entity.SysDictData;
import com.core.common.utils.MessageUtils;
import com.core.common.utils.SecurityUtils;
import com.core.system.service.ISysDictTypeService;
import com.openhis.administration.domain.Practitioner;
import com.openhis.administration.domain.Supplier;
import com.openhis.administration.service.IPractitionerService;
import com.openhis.common.constant.CommonConstants;
import com.openhis.common.constant.PromptMsgConstant;
import com.openhis.common.enums.*;
import com.openhis.web.reportmanage.dto.OutboundReportPageDto;
import com.openhis.web.reportmanage.dto.OutboundReportSearchParam;
import com.openhis.web.reportmanage.utils.ExcelFillerUtil;
import org.springframework.beans.factory.annotation.Autowired;
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.openhis.common.utils.EnumUtils;
import com.openhis.common.utils.HisQueryUtils;
import com.openhis.web.reportmanage.appservice.IInventoryProductReportAppService;
import com.openhis.web.reportmanage.dto.InventoryProductReportPageDto;
import com.openhis.web.reportmanage.dto.InventoryProductReportSearchParam;
import com.openhis.web.reportmanage.mapper.InventoryProductReportMapper;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 库存商品明细报表 impl
 *
 * @author GYY
 * @date 2025-04-21
 */
@Service
public class InventoryProductReportAppServiceImpl implements IInventoryProductReportAppService {

    @Autowired
    private InventoryProductReportMapper inventoryProductReportMapper;

    @Resource
    private ISysDictTypeService sysDictTypeService;
    @Resource
    private IPractitionerService practitionerService;

    /**
     * 库存商品明细列表
     *
     * @param inventoryProductReportSearchParam 库存商品明细查询条件
     * @param pageNo 当前页码
     * @param pageSize 查询条数
     * @param searchKey 模糊查询关键字
     * @param request 请求数据
     * @return 库存商品明细
     */
    @Override
    public R<?> getPage(InventoryProductReportSearchParam inventoryProductReportSearchParam, Integer pageNo,
        Integer pageSize, String searchKey, HttpServletRequest request) {

        // 数据初始化，不使用eq条件拼接
        // 库存范围
        Integer inventoryScope = inventoryProductReportSearchParam.getInventoryScope();
        inventoryProductReportSearchParam.setInventoryScope(null);

        // 设置模糊查询的字段名
        HashSet<String> searchFields = new HashSet<>();
        searchFields.add(CommonConstants.FieldName.BusNo);

        // 构建查询条件
        QueryWrapper<InventoryProductReportSearchParam> queryWrapper =
            HisQueryUtils.buildQueryWrapper(inventoryProductReportSearchParam, searchKey, searchFields, request);

        // 查询库存商品明细分页列表
        Page<InventoryProductReportPageDto> productReportPage = inventoryProductReportMapper.selectProductReportPage(
            new Page<>(pageNo, pageSize), queryWrapper, ConditionCode.LOT_NUMBER_COST.getValue().toString(),
            inventoryScope);

        productReportPage.getRecords().forEach(e -> {
            // 药品类型
            e.setItemTableText(EnumUtils.getInfoByValue(CategoryType.class, e.getItemTable()));
            // 仓库类型
            e.setPurposeTypeEnum_enumText(EnumUtils.getInfoByValue(LocationForm.class, e.getPurposeTypeEnum()));
        });
        return R.ok(productReportPage);
    }

    /**
     * 导出
     *
     * @param inventoryProductReportSearchParam 库存商品明细查询条件
     * @param pageNo 当前页码
     * @param pageSize 查询条数
     * @param searchKey 模糊查询关键字
     * @param request 请求数据
     * @return 单据详情
     */
    @Override
    public R<?> makeExcelFile(InventoryProductReportSearchParam inventoryProductReportSearchParam, Integer pageNo,
        Integer pageSize, String searchKey, HttpServletRequest request, HttpServletResponse response) {
        pageNo = 1;
        pageSize = 10000;
        // 数据初始化，不使用eq条件拼接
        // 库存范围
        Integer inventoryScope = inventoryProductReportSearchParam.getInventoryScope();
        inventoryProductReportSearchParam.setInventoryScope(null);

        // 设置模糊查询的字段名
        HashSet<String> searchFields = new HashSet<>();
        searchFields.add(CommonConstants.FieldName.BusNo);

        // 构建查询条件
        QueryWrapper<InventoryProductReportSearchParam> queryWrapper =
            HisQueryUtils.buildQueryWrapper(inventoryProductReportSearchParam, searchKey, searchFields, request);

        // 查询库存商品明细分页列表
        Page<InventoryProductReportPageDto> productReportPage = inventoryProductReportMapper.selectProductReportPage(
            new Page<>(pageNo, pageSize), queryWrapper, ConditionCode.LOT_NUMBER_COST.getValue().toString(),
            inventoryScope);

        productReportPage.getRecords().forEach(e -> {
            // 药品类型
            e.setItemTableText(EnumUtils.getInfoByValue(CategoryType.class, e.getItemTable()));
            // 仓库类型
            e.setPurposeTypeEnum_enumText(EnumUtils.getInfoByValue(LocationForm.class, e.getPurposeTypeEnum()));
        });

        List<InventoryProductReportPageDto> receiptDetailList = productReportPage.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 // 冲突时保留旧值（第一个）
            ));
        // 遍历赋值
        receiptDetailList.forEach(detail -> {
            detail.setUnitCode_dictText(unitCodeToNameMap.get(detail.getUnitCode()));
            detail.setMinPackageUnit_dictText(unitCodeToNameMap.get(detail.getMinPackageUnit()));
        });

        try {
            // 准备表头（key对应DTO的字段名）
            Map<String, String> headers = new LinkedHashMap<>();
            headers.put("busNo", "药品编码");
            headers.put("name", "药品名称");
            headers.put("lotNumber", "生产批号");
            headers.put("manufacturerText", "厂家/产地");
            headers.put("itemTableText", "药品类型");
            headers.put("itemQuantity", "库存数量");
            headers.put("unitCode_dictText", "计量单位");
            headers.put("minPackageQuantity", "小包装库存数");
            headers.put("minPackageUnit_dictText", "小包装单位");
            headers.put("price", "进价");
            headers.put("salePrice", "售价");
            headers.put("partPrice", "拆零进价");
            headers.put("partSalePrice", "拆零售价");
            headers.put("totalPrice", "进价金额");
            headers.put("totalSalePrice", "售价金额");
            headers.put("purposeTypeEnum_enumText", "仓库类型");
            headers.put("locationName", "仓库名称");
            headers.put("locationStoreName", "货位名称");
            headers.put("expirationDate", "有效期至");
            // 计算合计
            BigDecimal totalPrice =
                receiptDetailList.stream().filter(Objects::nonNull).map(InventoryProductReportPageDto::getTotalPrice)
                    .filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal totalSalePrice = receiptDetailList.stream().filter(Objects::nonNull)
                .map(InventoryProductReportPageDto::getTotalSalePrice).filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

            // 表头上的字段
            Map<String, Object> totalValues = new LinkedHashMap<>();
            totalValues.put("进价金额合计", totalPrice);
            totalValues.put("售价金额合计", totalSalePrice);

            // 文件名，只传文字部分
            String excelName = SupplyType.INVENTORY_PRODUCT.getInfo();
            // 导出到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));
    }
}