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

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

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.PromptMsgConstant;
import com.openhis.web.reportmanage.dto.*;
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.constant.CommonConstants;
import com.openhis.common.enums.DispenseStatus;
import com.openhis.common.enums.SupplyStatus;
import com.openhis.common.enums.SupplyType;
import com.openhis.common.utils.HisQueryUtils;
import com.openhis.web.reportmanage.appservice.IStocktakingReportAppService;
import com.openhis.web.reportmanage.mapper.StocktakingReportMapper;

/**
 * 库存盘点明细报表 impl
 *
 * @author GYY
 * @date 2025-04-16
 */
@Service
public class StocktakingReportAppServiceImpl implements IStocktakingReportAppService {

    @Autowired
    private StocktakingReportMapper stocktakingReportMapper;
    @Resource
    private ISysDictTypeService sysDictTypeService;
    @Resource
    private IPractitionerService practitionerService;

    /**
     * 库存盘点明细列表
     *
     * @param stocktakingReportSearchParam 库存盘点明细查询条件
     * @param pageNo 当前页码
     * @param pageSize 查询条数
     * @param searchKey 模糊查询关键字
     * @param request 请求数据
     * @return 库存盘点明细
     */
    @Override
    public R<?> getPage(StocktakingReportSearchParam stocktakingReportSearchParam, Integer pageNo, Integer pageSize,
        String searchKey, HttpServletRequest request) {
        stocktakingReportSearchParam.setTime(null);
        // 构建查询条件
        QueryWrapper<StocktakingReportSearchParam> queryWrapper = HisQueryUtils.buildQueryWrapper(
            stocktakingReportSearchParam, searchKey, new HashSet<>(Arrays.asList("name", "bus_no")), request);

        // 查询库存盘点明细分页列表
        Page<StocktakingReportPageDto> stocktakingReportPage =
            stocktakingReportMapper.selectStocktakingReportPage(new Page<>(pageNo, pageSize), queryWrapper,
                CommonConstants.TableName.MED_MEDICATION_DEFINITION, CommonConstants.TableName.ADM_DEVICE_DEFINITION,
                SupplyType.PRODUCT_STOCKTAKING.getValue(), SupplyType.PRODUCT_BATCH_STOCKTAKING.getValue(),
                SupplyStatus.AGREE.getValue(), DispenseStatus.COMPLETED.getValue());

        return R.ok(stocktakingReportPage);
    }

    /**
     * 库存盘点明细列表
     *
     * @param stocktakingReportSearchParam 库存盘点明细查询条件
     * @param pageNo 当前页码
     * @param pageSize 查询条数
     * @param searchKey 模糊查询关键字
     * @param request 请求数据
     * @return 库存盘点明细
     */
    @Override
    public R<?> getAutoPage(StocktakingReportSearchParam stocktakingReportSearchParam, Integer pageNo, Integer pageSize,
        String searchKey, HttpServletRequest request) {
        String time = stocktakingReportSearchParam.getTime();
        stocktakingReportSearchParam.setTime(null);

        // 查询库存盘点明细分页列表
        Page<StocktakingReportPageDto> stocktakingReportPage =
            stocktakingReportMapper.selectAutoStocktakingReportPage(new Page<>(pageNo, pageSize), time,
                CommonConstants.TableName.MED_MEDICATION_DEFINITION, CommonConstants.TableName.ADM_DEVICE_DEFINITION,
                SupplyType.AUTO_STOCKTAKING.getValue(), SupplyStatus.AGREE.getValue());

        return R.ok(stocktakingReportPage);
    }

    /**
     * 导出
     *
     * @param stocktakingReportSearchParam 库存盘点明细查询条件
     * @param pageNo 当前页码
     * @param pageSize 查询条数
     * @param searchKey 模糊查询关键字
     * @param request 请求数据
     * @return 单据详情
     */
    @Override
    public R<?> makeExcelFile(StocktakingReportSearchParam stocktakingReportSearchParam, Integer pageNo,
        Integer pageSize, String searchKey, HttpServletRequest request, HttpServletResponse response) {
        pageNo = 1;
        pageSize = 10000;
        // 构建查询条件
        QueryWrapper<StocktakingReportSearchParam> queryWrapper = HisQueryUtils.buildQueryWrapper(
            stocktakingReportSearchParam, searchKey, new HashSet<>(Arrays.asList("name", "bus_no")), request);

        // 查询库存盘点明细分页列表
        Page<StocktakingReportPageDto> stocktakingReportPage =
            stocktakingReportMapper.selectStocktakingReportPage(new Page<>(pageNo, pageSize), queryWrapper,
                CommonConstants.TableName.MED_MEDICATION_DEFINITION, CommonConstants.TableName.ADM_DEVICE_DEFINITION,
                SupplyType.PRODUCT_STOCKTAKING.getValue(), SupplyType.PRODUCT_BATCH_STOCKTAKING.getValue(),
                SupplyStatus.AGREE.getValue(), DispenseStatus.COMPLETED.getValue());

        List<StocktakingReportPageDto> receiptDetailList = stocktakingReportPage.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<Practitioner> practitionerList = practitionerService.getList();
        // 创建id到名字的映射
        Map<Long, String> practitionerToNameMap = practitionerList.stream()
            .collect(Collectors.toMap(Practitioner::getId, Practitioner::getName, (oldValue, newValue) -> oldValue // 冲突时保留旧值（第一个）
            ));
        // 遍历赋值
        receiptDetailList.forEach(detail -> {
            detail.setUnitCode_dictText(unitCodeToNameMap.get(detail.getUnitCode()));
            detail.setApproverId_dictText(practitionerToNameMap.get(detail.getApproverId()));
        });

        try {
            // 准备表头（key对应DTO的字段名）
            Map<String, String> headers = new LinkedHashMap<>();
            headers.put("supplyBusno", "单据号");
            headers.put("busNo", "编码");
            headers.put("name", "项目名称");
            headers.put("totalVolume", "规格");
            headers.put("manufacturerText", "厂家/产地");
            headers.put("lotNumber", "生产批号");
            headers.put("locationName", "仓库");
            headers.put("locationStoreName", "货位");
            headers.put("unitCode_dictText", "单位");
            headers.put("itemQuantity", "盈亏数量");
            headers.put("price", "采购单价");
            headers.put("totalPrice", "报损金额");
            headers.put("supplier", "供应商");
            headers.put("approverId_dictText", "审核人");
            headers.put("occurrenceTime", "制单日期");
            headers.put("approvalTime", "审批日期");

            BigDecimal totalPrice =
                receiptDetailList.stream().filter(Objects::nonNull).map(StocktakingReportPageDto::getTotalPrice)
                    .filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            // 表头上的字段
            Map<String, Object> totalValues = new LinkedHashMap<>();
            totalValues.put("合计金额", totalPrice);

            // 文件名，只传文字部分
            String excelName = SupplyType.PRODUCT_STOCKTAKING.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));
    }
}
