/*
 * 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.service.IPractitionerService;
import com.openhis.common.constant.PromptMsgConstant;
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.EnumUtils;
import com.openhis.common.utils.HisQueryUtils;
import com.openhis.web.reportmanage.appservice.ITransferReportAppService;
import com.openhis.web.reportmanage.dto.TransferReportPageDto;
import com.openhis.web.reportmanage.dto.TransferReportSearchParam;
import com.openhis.web.reportmanage.mapper.TransferReportMapper;

/**
 * 商品调拨明细报表 impl
 *
 * @author GYY
 * @date 2025-04-15
 */
@Service
public class TransferReportAppServiceImpl implements ITransferReportAppService {

    @Autowired
    private TransferReportMapper transferReportMapper;

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

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

        // 构建查询条件
        QueryWrapper<TransferReportSearchParam> queryWrapper = HisQueryUtils.buildQueryWrapper(
            transferReportSearchParam, searchKey, new HashSet<>(Arrays.asList("name", "supply_bus_no")), request);

        // 查询商品调拨明细分页列表
        Page<TransferReportPageDto> transferReportPage =
            transferReportMapper.selectTransferReportPage(new Page<>(pageNo, pageSize), queryWrapper,
                CommonConstants.TableName.MED_MEDICATION_DEFINITION, CommonConstants.TableName.ADM_DEVICE_DEFINITION,
                SupplyType.PRODUCT_TRANSFER.getValue(), SupplyType.PRODUCT_BATCH_TRANSFER.getValue(),
                SupplyStatus.AGREE.getValue(), DispenseStatus.COMPLETED.getValue());

        transferReportPage.getRecords().forEach(e -> {
            // 单据状态
            e.setStatusEnum_enumText(EnumUtils.getInfoByValue(SupplyStatus.class, e.getStatusEnum()));
        });
        return R.ok(transferReportPage);
    }

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

        // 查询商品调拨明细分页列表
        Page<TransferReportPageDto> transferReportPage =
            transferReportMapper.selectTransferReportPage(new Page<>(pageNo, pageSize), queryWrapper,
                CommonConstants.TableName.MED_MEDICATION_DEFINITION, CommonConstants.TableName.ADM_DEVICE_DEFINITION,
                SupplyType.PRODUCT_TRANSFER.getValue(), SupplyType.PRODUCT_BATCH_TRANSFER.getValue(),
                SupplyStatus.AGREE.getValue(), DispenseStatus.COMPLETED.getValue());

        transferReportPage.getRecords().forEach(e -> {
            // 单据状态
            e.setStatusEnum_enumText(EnumUtils.getInfoByValue(SupplyStatus.class, e.getStatusEnum()));
        });

        List<TransferReportPageDto> receiptDetailList = transferReportPage.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.setApplicantId_dictText(practitionerToNameMap.get(detail.getApplicantId()));
            detail.setApproverId_dictText(practitionerToNameMap.get(detail.getApproverId()));
        });

        try {
            // 准备表头（key对应DTO的字段名）
            Map<String, String> headers = new LinkedHashMap<>();
            headers.put("supplyBusNo", "单据号");
            headers.put("name", "药品");
            headers.put("statusEnum_enumText", "是否调拨"); // TODO 画面的已调拨是前台又转换的吗
            headers.put("lotNumber", "生产批号");
            headers.put("sourceLocationName", "源仓库");
            headers.put("sourceLocationStoreName", "源货位");
            headers.put("purposeLocationName", "目的仓库");
            headers.put("purposeLocationStoreName", "目的货位");
            headers.put("itemQuantity", "调拨数量");
            headers.put("unitCode_dictText", "计量单位");
            headers.put("price", "单价");
            headers.put("totalPrice", "合计金额");
            headers.put("applicantId_dictText", "制单人");
            headers.put("approverId_dictText", "审核人");
            headers.put("createTime", "制单日期");
            headers.put("applyTime", "申请日期");
            headers.put("approvalTime", "调拨日期");

            BigDecimal totalPrice =
                receiptDetailList.stream().filter(Objects::nonNull).map(TransferReportPageDto::getTotalPrice)
                    .filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);

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

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

    }
}
