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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.core.common.utils.SecurityUtils;
import com.core.common.utils.bean.BeanUtils;
import com.openhis.common.utils.HisPageUtils;
import com.openhis.common.utils.HisQueryUtils;
import com.openhis.document.domain.DocStatistics;
import com.openhis.document.mapper.DocStatisticsMapper;
import com.openhis.document.service.IDocStatisticsService;
import com.openhis.web.document.appservice.IDocStatisticsAppService;
import com.openhis.web.document.dto.DocStatisticsDto;
import com.openhis.web.document.dto.DocStatisticsQueryParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 文档模板 业务实现类
 */
@Slf4j
@Service
public class DocStatisticsAppServiceImpl implements IDocStatisticsAppService {

    @Resource
    private IDocStatisticsService docStatisticsService;
    @Resource
    private DocStatisticsMapper docStatisticsMapper;


    @Override
    public R<?> createOrUpdte(List<DocStatisticsDto> docStatisticsList) {
        if (docStatisticsList.size() == 0) {
            return R.ok();
        }
        //根据recordId和statisticDefinitionId判断是否存在，存在则更新，不存在则新增
        LambdaQueryWrapper<DocStatistics> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DocStatistics::getRecordId, docStatisticsList.get(0).getRecordId());
//        queryWrapper.eq(DocStatistics::getStatisticDefinitionId, docStatisticsList.get(0).getStatisticDefinitionId());
        List<DocStatistics> docStatisticsOldList = docStatisticsService.list(queryWrapper);
        if (docStatisticsOldList.size() > 0) {
            //批量删除
            docStatisticsService.removeByIds(docStatisticsOldList.stream().map(DocStatistics::getId).toList());
        }
        List<DocStatistics> docStatisticsInsertList = new ArrayList<>();
        //批量新增
        for (DocStatisticsDto docStatisticsDto : docStatisticsList) {
            DocStatistics docStatistics = new DocStatistics();
            docStatistics.setRecordId(docStatisticsDto.getRecordId());
            docStatistics.setStatisticDefinitionId(docStatisticsDto.getStatisticDefinitionId());
            docStatistics.setEncounterId(docStatisticsDto.getEncounterId());
            docStatistics.setPatientId(docStatisticsDto.getPatientId());
            docStatistics.setStatisticDefinitionCode(docStatisticsDto.getStatisticDefinitionCode());
            docStatistics.setOrganizationId(SecurityUtils.getLoginUser().getOrgId());
            docStatistics.setValue(docStatisticsDto.getValue());
            docStatistics.setRecordTime(docStatisticsDto.getRecordTime());
            docStatistics.setSource(docStatisticsDto.getSource());
            docStatisticsInsertList.add(docStatistics);
        }
        boolean result = docStatisticsService.saveBatch(docStatisticsInsertList);
        if (result) {
            return R.ok();
        } else {
            return R.fail("新增或更新文档统计数据失败");
        }
    }

    @Override
    public R<?> delete(List<Long> ids) {
        return null;
    }

    @Override
    public R<?> queryByRecordId(Long recordId) {
        return null;
    }

    @Override
    public R<?> queryByEncounterId(Long encounterId) {
        LambdaQueryWrapper<DocStatistics> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(DocStatistics::getEncounterId, encounterId);
        List<DocStatistics> docStatisticsList = docStatisticsService.list(queryWrapper);
        List<DocStatisticsDto> docStatisticsDtoList = new ArrayList<>();
        for (DocStatistics docStatistics : docStatisticsList) {
            DocStatisticsDto docStatisticsDto = new DocStatisticsDto();
            docStatisticsDto.setId(docStatistics.getId());
            docStatisticsDto.setRecordId(docStatistics.getRecordId());
            docStatisticsDto.setStatisticDefinitionId(docStatistics.getStatisticDefinitionId());
            docStatisticsDto.setEncounterId(docStatistics.getEncounterId());
            docStatisticsDto.setPatientId(docStatistics.getPatientId());
            docStatisticsDto.setStatisticDefinitionCode(docStatistics.getStatisticDefinitionCode());
            docStatisticsDto.setOrganizationId(docStatistics.getOrganizationId());
            docStatisticsDto.setValue(docStatistics.getValue());
            docStatisticsDto.setRecordTime(docStatistics.getRecordTime());
            docStatisticsDto.setSource(docStatistics.getSource());
            docStatisticsDtoList.add(docStatisticsDto);
        }
        return R.ok(docStatisticsDtoList);
    }

    @Override
    public R<?> getStatisticsList(DocStatisticsQueryParam queryParam, Integer isPage, Integer pageNo, Integer pageSize, String searchKey, HttpServletRequest request) {
        // 1. 分页查询逻辑
        if (isPage != null && isPage == 1) {
            QueryWrapper<DocStatistics> queryWrapper = HisQueryUtils.buildQueryWrapper(
                    queryParam, null, null, request);
            // 按记录时间倒序（最新记录在前）
            queryWrapper.lambda().orderByDesc(DocStatistics::getRecordTime);

            Page<DocStatisticsDto> recordPage = HisPageUtils.selectPage(
                    docStatisticsMapper, queryWrapper, pageNo, pageSize, DocStatisticsDto.class);
            return R.ok(recordPage, "获取患者文书统计数据成功");
        }
        //2. 不分页查询逻辑
        else {
            LambdaQueryWrapper<DocStatistics> queryWrapper = new LambdaQueryWrapper<>();
            // 患者ID查询条件
            if (queryParam.getPatientId() != null) {
                queryWrapper.eq(DocStatistics::getPatientId, queryParam.getPatientId());
            }
            // 就诊ID查询条件（修复原逻辑：原代码字段匹配错误，用EncounterId匹配DefinitionBusNo）
            if (queryParam.getEncounterId() != null) {
                queryWrapper.eq(DocStatistics::getEncounterId, queryParam.getEncounterId());
            }
            // 科室ID查询条件（修复原逻辑：原代码字段匹配错误，用OrganizationId匹配EncounterId）
            if (queryParam.getOrganizationId() != null) {
                queryWrapper.eq(DocStatistics::getOrganizationId, queryParam.getOrganizationId());
            }
            if (queryParam.getStatisticsDefinitionCode() != null) {
                queryWrapper.eq(DocStatistics::getStatisticDefinitionCode, queryParam.getStatisticsDefinitionCode());
            }

            // 实体转DTO
            List<DocStatisticsDto> dtoList = new ArrayList<>();
            List<DocStatistics> statisticsList = docStatisticsService.list(queryWrapper);
            for (DocStatistics statistics : statisticsList) {
                DocStatisticsDto dto = new DocStatisticsDto();
                BeanUtils.copyProperties(statistics, dto);
                dtoList.add(dto);
            }
            return R.ok(dtoList, "获取患者文书统计数据成功");
        }
    }
}
