/*
 * 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.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.administration.domain.Supplier;
import com.openhis.administration.service.ISupplierService;
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.PurchaseReturnReportAppService;
import com.openhis.web.reportmanage.mapper.PurchaseReturnReportMapper;

/**
 * 采购退货明细报表 impl
 *
 * @author ym
 * @date 2025-05-23
 */
@Service
public class PurchaseReturnReportAppServiceImpl implements PurchaseReturnReportAppService {

    @Autowired
    private PurchaseReturnReportMapper purchaseReturnReportMapper;

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

    /**
     * 采购退货明细页面初始化
     *
     * @return 初始化信息
     */
    @Override
    public R<?> init() {

        PurchaseReturnReportInitDto initDto = new PurchaseReturnReportInitDto();
        // 查询供应商列表
        List<Supplier> supplierList = supplierService.getList();

        // 供应商信息
        List<PurchaseReturnReportInitDto.supplierListOption> supplierListOptions = supplierList.stream()
            .map(supplier -> new PurchaseReturnReportInitDto.supplierListOption(supplier.getId(), supplier.getName()))
            .collect(Collectors.toList());

        initDto.setSupplierListOptions(supplierListOptions);

        return R.ok(initDto);
    }

    /**
     * 采购退货明细列表
     *
     * @param purchaseReturnReportSearchParam 采购退货明细查询条件
     * @param pageNo 当前页码
     * @param pageSize 查询条数
     * @param searchKey 模糊查询关键字
     * @param request 请求数据
     * @return 采购退货明细
     */
    @Override
    public R<?> getPage(PurchaseReturnReportSearchParam purchaseReturnReportSearchParam, Integer pageNo,
        Integer pageSize, String searchKey, HttpServletRequest request) {

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

        // 查询采购退货明细分页列表
        Page<PurchaseReturnReportPageDto> purchaseReturnReportPageDto =
            purchaseReturnReportMapper.selectPurchaseReturnReportPage(new Page<>(pageNo, pageSize), queryWrapper,
                CommonConstants.TableName.MED_MEDICATION_DEFINITION, CommonConstants.TableName.ADM_DEVICE_DEFINITION,
                SupplyType.PRODUCT_RETURN.getValue(), SupplyStatus.AGREE.getValue(),
                DispenseStatus.COMPLETED.getValue());

        return R.ok(purchaseReturnReportPageDto);
    }

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

        // 查询采购退货明细分页列表
        Page<PurchaseReturnReportPageDto> purchaseReturnReportPageDto =
            purchaseReturnReportMapper.selectPurchaseReturnReportPage(new Page<>(pageNo, pageSize), queryWrapper,
                CommonConstants.TableName.MED_MEDICATION_DEFINITION, CommonConstants.TableName.ADM_DEVICE_DEFINITION,
                SupplyType.PRODUCT_RETURN.getValue(), SupplyStatus.AGREE.getValue(),
                DispenseStatus.COMPLETED.getValue());

        List<PurchaseReturnReportPageDto> receiptDetailList = purchaseReturnReportPageDto.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("name", "药品名称");
            headers.put("busNo", "编码");
            headers.put("originalBusNo", "采购单据号");
            headers.put("lotNumber", "生产批号");
            headers.put("locationName", "存放仓库");
            headers.put("locationStoreName", "货位");
            headers.put("unitCode_dictText", "计量单位");
            headers.put("quantity", "退货数量");
            headers.put("price", "采购单价");
            headers.put("returnPrice", "退货单价");
            headers.put("totalPrice", "退货金额");
            headers.put("supplier", "供应商");
            headers.put("approverId_dictText", "审核人");
            headers.put("createTime", "制单日期");
            headers.put("approvalTime", "审核日期");

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

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

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