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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.core.common.core.domain.R;
import com.openhis.check.domain.CheckPackage;
import com.openhis.check.domain.CheckPackageDetail;
import com.openhis.check.service.ICheckPackageDetailService;
import com.openhis.check.service.ICheckPackageService;
import com.openhis.web.check.appservice.ICheckPackageAppService;
import com.openhis.web.check.dto.CheckPackageDetailDto;
import com.openhis.web.check.dto.CheckPackageDto;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 检查套餐AppService实现
 * 
 * @author system
 * @date 2025-11-26
 */
@Slf4j
@Service
@AllArgsConstructor
public class CheckPackageAppServiceImpl implements ICheckPackageAppService {

    private final ICheckPackageService checkPackageService;
    private final ICheckPackageDetailService checkPackageDetailService;

    @Override
    public R<?> getCheckPackageList() {
        try {
            List<CheckPackage> list = checkPackageService.list();
            return R.ok(list);
        } catch (Exception e) {
            log.error("获取检查套餐列表失败", e);
            return R.fail("获取检查套餐列表失败");
        }
    }

    @Override
    public R<?> getCheckPackageById(Long id) {
        try {
            CheckPackage checkPackage = checkPackageService.getById(id);
            if (checkPackage == null) {
                return R.fail("套餐不存在");
            }

            // 获取套餐明细
            List<CheckPackageDetail> details = checkPackageDetailService.list(
                    new LambdaQueryWrapper<CheckPackageDetail>()
                            .eq(CheckPackageDetail::getPackageId, id)
                            .orderByAsc(CheckPackageDetail::getOrderNum)
            );

            // 转换为DTO
            CheckPackageDto dto = new CheckPackageDto();
            BeanUtils.copyProperties(checkPackage, dto);
            
            List<CheckPackageDetailDto> detailDtos = details.stream().map(detail -> {
                CheckPackageDetailDto detailDto = new CheckPackageDetailDto();
                BeanUtils.copyProperties(detail, detailDto);
                return detailDto;
            }).collect(Collectors.toList());
            
            dto.setItems(detailDtos);
            
            return R.ok(dto);
        } catch (Exception e) {
            log.error("获取检查套餐详情失败", e);
            return R.fail("获取检查套餐详情失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<?> addCheckPackage(CheckPackageDto checkPackageDto) {
        try {
            // 创建套餐主表数据
            CheckPackage checkPackage = new CheckPackage();
            BeanUtils.copyProperties(checkPackageDto, checkPackage);
            
            // 设置套餐维护日期为当前系统日期
            checkPackage.setMaintainDate(LocalDate.now());
            checkPackage.setCreateTime(LocalDateTime.now());
            checkPackage.setUpdateTime(LocalDateTime.now());
            
            // 保存套餐主表
            boolean saveResult = checkPackageService.save(checkPackage);
            if (!saveResult) {
                return R.fail("保存套餐失败");
            }

            // 保存套餐明细
            if (checkPackageDto.getItems() != null && !checkPackageDto.getItems().isEmpty()) {
                List<CheckPackageDetail> details = new ArrayList<>();
                int orderNum = 1;
                for (CheckPackageDetailDto detailDto : checkPackageDto.getItems()) {
                    CheckPackageDetail detail = new CheckPackageDetail();
                    BeanUtils.copyProperties(detailDto, detail);
                    detail.setPackageId(checkPackage.getId());
                    detail.setOrderNum(orderNum++);
                    detail.setCreateTime(LocalDateTime.now());
                    detail.setUpdateTime(LocalDateTime.now());
                    details.add(detail);
                }
                checkPackageDetailService.saveBatch(details);
            }

            return R.ok(checkPackage.getId(), "保存成功");
        } catch (Exception e) {
            log.error("新增检查套餐失败", e);
            return R.fail("新增检查套餐失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<?> updateCheckPackage(CheckPackageDto checkPackageDto) {
        try {
            // 检查套餐是否存在
            CheckPackage existPackage = checkPackageService.getById(checkPackageDto.getId());
            if (existPackage == null) {
                return R.fail("套餐不存在");
            }

            // 更新套餐主表数据
            CheckPackage checkPackage = new CheckPackage();
            BeanUtils.copyProperties(checkPackageDto, checkPackage);
            
            // 更新套餐维护日期为当前系统日期
            checkPackage.setMaintainDate(LocalDate.now());
            checkPackage.setUpdateTime(LocalDateTime.now());
            
            boolean updateResult = checkPackageService.updateById(checkPackage);
            if (!updateResult) {
                return R.fail("更新套餐失败");
            }

            // 删除原有明细
            checkPackageDetailService.remove(
                    new LambdaQueryWrapper<CheckPackageDetail>()
                            .eq(CheckPackageDetail::getPackageId, checkPackage.getId())
            );

            // 保存新的套餐明细
            if (checkPackageDto.getItems() != null && !checkPackageDto.getItems().isEmpty()) {
                List<CheckPackageDetail> details = new ArrayList<>();
                int orderNum = 1;
                for (CheckPackageDetailDto detailDto : checkPackageDto.getItems()) {
                    CheckPackageDetail detail = new CheckPackageDetail();
                    BeanUtils.copyProperties(detailDto, detail);
                    detail.setPackageId(checkPackage.getId());
                    detail.setOrderNum(orderNum++);
                    detail.setCreateTime(LocalDateTime.now());
                    detail.setUpdateTime(LocalDateTime.now());
                    details.add(detail);
                }
                checkPackageDetailService.saveBatch(details);
            }

            return R.ok("更新成功");
        } catch (Exception e) {
            log.error("更新检查套餐失败", e);
            return R.fail("更新检查套餐失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<?> deleteCheckPackage(Long id) {
        try {
            // 检查套餐是否存在
            CheckPackage existPackage = checkPackageService.getById(id);
            if (existPackage == null) {
                return R.fail("套餐不存在");
            }

            // 删除套餐明细
            checkPackageDetailService.remove(
                    new LambdaQueryWrapper<CheckPackageDetail>()
                            .eq(CheckPackageDetail::getPackageId, id)
            );

            // 删除套餐主表
            boolean deleteResult = checkPackageService.removeById(id);
            if (!deleteResult) {
                return R.fail("删除套餐失败");
            }

            return R.ok("删除成功");
        } catch (Exception e) {
            log.error("删除检查套餐失败", e);
            return R.fail("删除检查套餐失败: " + e.getMessage());
        }
    }
}

