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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.core.common.core.domain.R;
import com.openhis.document.domain.DocDefinitionOrganization;
import com.openhis.document.service.IDocDefinitionOrganizationService;
import com.openhis.web.document.appservice.IDocDefinitionOrganizationAppService;
import com.openhis.web.document.dto.DocDefinitionOrganizationDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class DocDefinitionOrganizationAppServiceImpl implements IDocDefinitionOrganizationAppService {

    @Resource
    private IDocDefinitionOrganizationService docDefinitionOrganizationService;

    /**
     * 新增文书分配科室列表
     * 注：新增前未删除原有分配，若需"覆盖新增"请使用updateOrganization方法
     */
    @Override
    public R<?> add(DocDefinitionOrganizationDto definitionOrganizationDto) {
        // 1. 参数校验（明确错误原因，避免模糊提示）
        if (definitionOrganizationDto == null) {
            return R.fail("文书科室分配失败：请求参数不能为空");
        }
        if (definitionOrganizationDto.getOrganizationIds() == null || definitionOrganizationDto.getOrganizationIds().isEmpty()) {
            return R.fail("文书科室分配失败：科室ID列表不能为空");
        }
        if (definitionOrganizationDto.getDefinitionId() == null || definitionOrganizationDto.getDefinitionId() == 0) {
            return R.fail("文书科室分配失败：文书定义ID不能为空（或不能为0）");
        }
        if (definitionOrganizationDto.getBusNo() == null || definitionOrganizationDto.getBusNo().trim().isEmpty()) {
            return R.fail("文书科室分配失败：业务编号不能为空（或不能为空白字符）");
        }

        // 2. DTO转实体（批量封装科室分配关系）
        List<DocDefinitionOrganization> organizationList = new ArrayList<>();
        for (Long orgId : definitionOrganizationDto.getOrganizationIds()) {
            DocDefinitionOrganization docOrg = new DocDefinitionOrganization();
            docOrg.setDefinitionId(definitionOrganizationDto.getDefinitionId());
            docOrg.setBusNo(definitionOrganizationDto.getBusNo().trim()); // 去除业务编号前后空白
            docOrg.setOrganizationId(orgId);
            organizationList.add(docOrg);
        }

        // 3. 批量新增
        boolean saveSuccess = docDefinitionOrganizationService.saveBatch(organizationList);
        if (saveSuccess) {
            return R.ok("文书科室分配成功");
        } else {
            log.error("文书科室分配新增失败：文书定义ID={}, 业务编号={}",
                    definitionOrganizationDto.getDefinitionId(), definitionOrganizationDto.getBusNo());
            return R.fail("文书科室分配失败：数据库新增操作异常");
        }
    }

    /**
     * 根据文书定义ID和业务编号，删除对应的科室分配关系
     */
    @Override
    public R<?> delete(Long definitionId, String busNo) {
        // 1. 参数校验
        if (definitionId == null || definitionId == 0) {
            return R.fail("文书科室分配删除失败：文书定义ID不能为空（或不能为0）");
        }
        if (busNo == null || busNo.trim().isEmpty()) {
            return R.fail("文书科室分配删除失败：业务编号不能为空（或不能为空白字符）");
        }

        // 2. 构建查询条件（精准匹配文书+业务编号）
        LambdaQueryWrapper<DocDefinitionOrganization> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DocDefinitionOrganization::getDefinitionId, definitionId)
                .eq(DocDefinitionOrganization::getBusNo, busNo.trim()); // 去除业务编号前后空白

        // 3. 执行删除
        boolean deleteSuccess = docDefinitionOrganizationService.remove(queryWrapper);
        if (deleteSuccess) {
            return R.ok("文书科室分配删除成功");
        } else {
            log.warn("文书科室分配删除失败：未找到匹配的分配关系（文书定义ID={}, 业务编号={}）",
                    definitionId, busNo);
            return R.fail("文书科室分配删除失败：未找到对应的科室分配记录");
        }
    }

    /**
     * 根据文书定义ID和业务编号，查询已分配的科室ID列表
     */
    @Override
    public R<?> getOrganizationIdlist(Long definitionId, String busNo) {
        // 1. 参数校验
        if (definitionId == null || definitionId == 0) {
            return R.fail("文书科室分配查询失败：文书定义ID不能为空（或不能为0）");
        }
        if (busNo == null || busNo.trim().isEmpty()) {
            return R.fail("文书科室分配查询失败：业务编号不能为空（或不能为空白字符）");
        }

        // 2. 构建查询条件
        LambdaQueryWrapper<DocDefinitionOrganization> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DocDefinitionOrganization::getDefinitionId, definitionId)
                .eq(DocDefinitionOrganization::getBusNo, busNo.trim());

        // 3. 查询并提取科室ID（避免返回冗余字段）
        List<DocDefinitionOrganization> orgList = docDefinitionOrganizationService.list(queryWrapper);
        List<Long> orgIdList = new ArrayList<>();
        for (DocDefinitionOrganization docOrg : orgList) {
            orgIdList.add(docOrg.getOrganizationId());
        }

        log.info("文书科室分配查询成功：文书定义ID={}, 业务编号={}, 分配科室数量={}",
                definitionId, busNo, orgIdList.size());
        return R.ok(orgIdList, "文书科室分配查询成功");
    }

    /**
     * 更新文书科室分配（先删除原有分配，再新增新分配，实现"全量覆盖"）
     */
    @Override
    public R<?> updateOrganization(DocDefinitionOrganizationDto definitionOrganizationDto) {
        // 1. 参数校验（与add方法保持一致的校验逻辑）
        if (definitionOrganizationDto == null) {
            return R.fail("文书科室分配更新失败：请求参数不能为空");
        }
        if (definitionOrganizationDto.getDefinitionId() == null || definitionOrganizationDto.getDefinitionId() == 0) {
            return R.fail("文书科室分配更新失败：文书定义ID不能为空（或不能为0）");
        }
        if (definitionOrganizationDto.getBusNo() == null || definitionOrganizationDto.getBusNo().trim().isEmpty()) {
            return R.fail("文书科室分配更新失败：业务编号不能为空（或不能为空白字符）");
        }

        // 2. 先删除原有分配关系
        LambdaQueryWrapper<DocDefinitionOrganization> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DocDefinitionOrganization::getDefinitionId, definitionOrganizationDto.getDefinitionId())
                .eq(DocDefinitionOrganization::getBusNo, definitionOrganizationDto.getBusNo().trim());
        Long count = docDefinitionOrganizationService.count(wrapper);
        if (count > 0) {
            boolean deleteSuccess = docDefinitionOrganizationService.remove(wrapper);
            if (!deleteSuccess) {
                log.error("文书科室分配更新失败：删除原有分配记录异常（文书定义ID={}, 业务编号={}",
                        definitionOrganizationDto.getDefinitionId(), definitionOrganizationDto.getBusNo());
                return R.fail("文书科室分配更新失败：删除原有分配记录异常");
            }
        }
        if (definitionOrganizationDto.getOrganizationIds() == null || definitionOrganizationDto.getOrganizationIds().isEmpty()) {
            return R.ok("文书科室分配更新成功");
        } else {
            // 3. 再新增新的分配关系
            List<DocDefinitionOrganization> newOrgList = new ArrayList<>();
            for (Long orgId : definitionOrganizationDto.getOrganizationIds()) {
                DocDefinitionOrganization docOrg = new DocDefinitionOrganization();
                docOrg.setDefinitionId(definitionOrganizationDto.getDefinitionId());
                docOrg.setBusNo(definitionOrganizationDto.getBusNo().trim());
                docOrg.setOrganizationId(orgId);
                newOrgList.add(docOrg);
            }
            boolean saveSuccess = docDefinitionOrganizationService.saveBatch(newOrgList);
            if (saveSuccess) {
                return R.ok("文书科室分配更新成功");
            } else {
                log.error("文书科室分配更新失败：新增新分配记录异常（文书定义ID={}, 业务编号={}",
                        definitionOrganizationDto.getDefinitionId(), definitionOrganizationDto.getBusNo());
                return R.fail("文书科室分配更新失败：新增新分配记录异常");
            }
        }
    }
}