package com.openhis.web.reportmanage.appservice.impl;

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

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.administration.service.ISupplierService;
import com.openhis.common.constant.PromptMsgConstant;
import com.openhis.common.enums.*;
import com.openhis.web.reportmanage.utils.ExcelFillerUtil;
import com.openhis.web.reportmanage.dto.*;
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.utils.HisQueryUtils;
import com.openhis.web.reportmanage.appservice.IOutboundReportAppService;
import com.openhis.web.reportmanage.mapper.OutboundReportMapper;

/**
 * 出库明细 应用实现类
 *
 * @author yuanzs
 * @date 2025/4/21
 */
@Service
public class OutboundReportAppServiceImpl implements IOutboundReportAppService {

    @Autowired
    OutboundReportMapper outboundReportMapper;

    @Resource
    private ISupplierService supplierService;

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

    /**
     * 出库明细页面初始化
     *
     * @return 初始化信息
     */
    @Override
    public R<?> init() {

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

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

        initDto.setSupplierListOptions(supplierListOptions);

        return R.ok(initDto);
    }

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

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

        // 查询出库明细分页列表
        Page<OutboundReportPageDto> medDetailsPage = outboundReportMapper.selectOutboundReportPage(
            new Page<>(pageNo, pageSize), queryWrapper, CommonConstants.TableName.MED_MEDICATION_DEFINITION,
            CommonConstants.TableName.ADM_DEVICE_DEFINITION, SupplyType.ISSUE_INVENTORY.getValue(),
            SupplyStatus.AGREE.getValue(), DispenseStatus.COMPLETED.getValue());

        return R.ok(medDetailsPage);
    }

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

        // 查询出库明细分页列表
        Page<OutboundReportPageDto> medDetailsPage = outboundReportMapper.selectOutboundReportPage(
            new Page<>(pageNo, pageSize), queryWrapper, CommonConstants.TableName.MED_MEDICATION_DEFINITION,
            CommonConstants.TableName.ADM_DEVICE_DEFINITION, SupplyType.ISSUE_INVENTORY.getValue(),
            SupplyStatus.AGREE.getValue(), DispenseStatus.COMPLETED.getValue());

        List<OutboundReportPageDto> receiptDetailList = medDetailsPage.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 // 冲突时保留旧值（第一个）
            ));
        // 查询供应商列表
        List<Supplier> supplierList = supplierService.getList();
        // 创建id到名字的映射
        Map<Long, String> supplierToNameMap = supplierList.stream()
            .collect(Collectors.toMap(Supplier::getId, Supplier::getName, (oldValue, newValue) -> oldValue // 冲突时保留旧值（第一个）
            ));
        // 遍历赋值
        receiptDetailList.forEach(detail -> {
            detail.setUnitCode_dictText(unitCodeToNameMap.get(detail.getUnitCode()));
            detail.setApproverId_dictText(practitionerToNameMap.get(detail.getApproverId()));
            detail.setSupplierId_dictText(supplierToNameMap.get(detail.getSupplierId()));
        });

        try {
            // 准备表头（key对应DTO的字段名）
            Map<String, String> headers = new LinkedHashMap<>();
            headers.put("supplyBusno", "单据号");
            headers.put("name", "药品名称");
            headers.put("busNo", "编码");
            headers.put("lotNumber", "生产批号");
            headers.put("sourceLocationName", "存放库房");
            headers.put("sourceLocationStoreName", "货位");
            headers.put("unitCode_dictText", "计量单位");
            headers.put("itemQuantity", "出库数量");
            headers.put("purchasePrice", "采购单价");
            headers.put("price", "领用单价");
            headers.put("totalPrice", "金额");
            headers.put("purposeLocationName", "领用科室");
            headers.put("supplierId_dictText", "供应商");
            headers.put("approverId_dictText", "审核人");
            headers.put("approvalTime", "审核日期");
            headers.put("remake", "备注");

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

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

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

}
