package com.chinaweal.aiccs.org.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chinaweal.aiccs.common.constant.CommonConstants;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.org.entity.ImsOrg;
import com.chinaweal.aiccs.org.entity.dto.ImsOrgDTO;
import com.chinaweal.aiccs.org.mapper.ImsOrgMapper;
import com.chinaweal.aiccs.org.service.IImsOrgService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * IMS机构同步服务实现
 *
 * @author aiccs
 * @since 2026-03-23
 */
@Service
public class ImsOrgServiceImpl extends ServiceImpl<ImsOrgMapper, ImsOrg> implements IImsOrgService {

    private static final Logger logger = LoggerFactory.getLogger(ImsOrgServiceImpl.class);

    @Override
    public boolean syncOrg(ImsOrgDTO dto) {
        if (dto == null || dto.getType() == null) {
            logger.error("IMS机构同步失败: 参数为空或类型未指定");
            return false;
        }

        String type = dto.getType();
        try {
            switch (type) {
                case "add":
                    return addOrUpdateOrg(dto);
                case "delete":
                    return removeOrg(dto);
                case "test":
                    logger.info("IMS机构连接测试成功");
                    return true;
                default:
                    logger.warn("IMS机构同步失败: 未知的操作类型 {}", type);
                    return false;
            }
        } catch (Exception e) {
            logger.error("IMS机构同步异常: {}", e.getMessage(), e);
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addOrUpdateOrg(ImsOrgDTO dto) {
        if (dto.getCode() == null || dto.getCode().isEmpty()) {
            logger.error("IMS机构同步失败: 机构编码为空");
            return false;
        }

        logger.info("IMS机构同步[新增/修改]: code={}, name={}", dto.getCode(), dto.getName());

        // 根据机构编码查询是否已存在
        ImsOrg existOrg = this.getById(dto.getCode());
        LocalDateTime now = LocalDateTime.now();

        if (existOrg != null) {
            // 存在则更新
            logger.info("IMS机构同步: 发现已有机构, 执行更新, code={}", existOrg.getCode());
            existOrg.setName(dto.getName());
            existOrg.setAreacode(dto.getAreacode());
            existOrg.setPr(dto.getPr());
            existOrg.setParent(dto.getParent());
            existOrg.setOrgstate(dto.getOrgstate());
            existOrg.setIsDepart(dto.getIsDepart());
            existOrg.setId(dto.getId());
            existOrg.setParentcode(dto.getParentcode());
            existOrg.setRb(dto.getRb());
            existOrg.setCa(dto.getCa());
            existOrg.setDeleted(CommonConstants.FALSE_0);
            existOrg.setUpdateTime(now);
            return this.updateById(existOrg);
        } else {
            // 不存在则新增
            logger.info("IMS机构同步: 未发现已有机构, 执行新增");
            ImsOrg newOrg = new ImsOrg();
            newOrg.setCode(dto.getCode());
            newOrg.setName(dto.getName());
            newOrg.setAreacode(dto.getAreacode());
            newOrg.setPr(dto.getPr());
            newOrg.setParent(dto.getParent());
            newOrg.setOrgstate(dto.getOrgstate());
            newOrg.setIsDepart(dto.getIsDepart());
            newOrg.setId(dto.getId());
            newOrg.setParentcode(dto.getParentcode());
            newOrg.setRb(dto.getRb());
            newOrg.setCa(dto.getCa());
            newOrg.setCreateTime(now);
            newOrg.setUpdateTime(now);
            return this.save(newOrg);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeOrg(ImsOrgDTO dto) {
        if (StringUtils.isBlank(dto.getCode())) {
            logger.error("IMS机构删除失败: 机构编码为空");
            return false;
        }

        logger.info("IMS机构同步[删除]: orgCode={}", dto.getCode());

        // 根据机构编码查询机构
        ImsOrg existOrg = this.getById(dto.getCode());
        if (existOrg == null) {
            logger.warn("IMS机构删除: 机构不存在, orgCode={}", dto.getCode());
            return true; // 不存在也返回成功
        }

        // 逻辑删除
        existOrg.setDeleted("1");
        existOrg.setUpdateTime(LocalDateTime.now());
        return this.updateById(existOrg);
    }
}
