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.SM4Utils;
import com.chinaweal.aiccs.org.entity.ImsUser;
import com.chinaweal.aiccs.org.entity.dto.ImsUserDTO;
import com.chinaweal.aiccs.org.mapper.ImsUserMapper;
import com.chinaweal.aiccs.org.service.IImsUserService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * IMS用户同步服务实现
 *
 * @author aiccs
 * @since 2026-03-23
 */
@Service
public class ImsUserServiceImpl extends ServiceImpl<ImsUserMapper, ImsUser> implements IImsUserService {

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

    @Value("${oauth2.sm4.key}")
    private String sm4Key;

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

        String type = dto.getType();
        try {
            switch (type) {
                case "add":
                    return addOrUpdateUser(dto);
                case "delete":
                    return removeUser(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 addOrUpdateUser(ImsUserDTO dto) {
        if (StringUtils.isBlank(dto.getUsercode())) {
            logger.error("IMS用户同步失败: 用户编号为空");
            return false;
        }

        logger.info("IMS用户同步[新增/修改]: usercode={}, username={}", dto.getUsercode(), dto.getUsername());

        // 根据用户编号查询是否已存在
        ImsUser existUser = this.getById(dto.getUsercode());

        if (existUser != null) {
            // 存在则更新
            logger.info("IMS用户同步: 发现已有用户, 执行更新, usercode={}", existUser.getUsercode());
            updateImsUserFromDto(existUser, dto);
            this.updateById(existUser);
        } else {
            // 不存在则新增
            logger.info("IMS用户同步: 未发现已有用户, 执行新增");
            ImsUser newUser = new ImsUser();
            newUser.setUsercode(dto.getUsercode());
            newUser.setUsername(dto.getUsername());
            newUser.setMobile(dto.getMobile());
            newUser.setGender(dto.getGender());
            newUser.setEmail(dto.getEmail());
            newUser.setIdCard(SM4Utils.encrypt(dto.getIdCard(), sm4Key));
            newUser.setLandline(dto.getLandline());
            newUser.setJobna(dto.getJobna());
            newUser.setLecn(dto.getLecn());
            newUser.setCerdate(dto.getCerdate());
            newUser.setIsRoam(dto.getIsRoam());
            newUser.setStatus(dto.getStatus());
            newUser.setUserorg(dto.getUserorg());
            newUser.setUserorgcode(dto.getUserorgcode());
            newUser.setDeleted("0");
            this.save(newUser);
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeUser(ImsUserDTO dto) {
        if (StringUtils.isBlank(dto.getUsercode())) {
            logger.error("IMS用户删除失败: 用户编号为空");
            return false;
        }

        logger.info("IMS用户同步[删除]: usercode={}", dto.getUsercode());

        ImsUser existUser = this.getById(dto.getUsercode());
        if (existUser == null) {
            logger.warn("IMS用户删除: 用户不存在, usercode={}", dto.getUsercode());
            return true; // 不存在也返回成功
        }

        // 逻辑删除
        existUser.setDeleted("1");
        this.updateById(existUser);
        return true;
    }

    /**
     * 根据DTO更新ImsUser对象
     */
    private void updateImsUserFromDto(ImsUser user, ImsUserDTO dto) {
        user.setUsername(dto.getUsername());
        user.setMobile(dto.getMobile());
        user.setGender(dto.getGender());
        user.setEmail(dto.getEmail());
        user.setIdCard(SM4Utils.encrypt(dto.getIdCard(), sm4Key));
        user.setLandline(dto.getLandline());
        user.setJobna(dto.getJobna());
        user.setLecn(dto.getLecn());
        user.setCerdate(dto.getCerdate());
        user.setIsRoam(dto.getIsRoam());
        user.setStatus(dto.getStatus());
        user.setUserorg(dto.getUserorg());
        user.setDeleted(CommonConstants.FALSE_0);
    }
}
