package com.huimv.employment.service.auth;

import com.huimv.employment.common.exception.BizException;
import com.huimv.employment.common.exception.ErrorCode;
import com.huimv.employment.common.util.AesUtils;
import com.huimv.employment.dao.entity.FeEnterprise;
import com.huimv.employment.dao.entity.FeUser;
import com.huimv.employment.dao.entity.FeWorker;
import com.huimv.employment.dao.mapper.FeUserMapper;
import com.huimv.employment.service.auth.dto.MpUserInfoResponse;
import com.huimv.employment.service.config.SecurityProperties;
import com.huimv.employment.service.enterprise.EnterpriseService;
import com.huimv.employment.service.worker.WorkerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 小程序用户综合信息查询。
 */
@Service
public class ProfileService {

    private static final Logger log = LoggerFactory.getLogger(ProfileService.class);

    private static final String USER_TYPE_ENTERPRISE = "enterprise";
    private static final String USER_TYPE_WORKER = "worker";

    private final FeUserMapper feUserMapper;
    private final EnterpriseService enterpriseService;
    private final WorkerService workerService;
    private final SecurityProperties securityProperties;

    public ProfileService(FeUserMapper feUserMapper,
                          EnterpriseService enterpriseService,
                          WorkerService workerService,
                          SecurityProperties securityProperties) {
        this.feUserMapper = feUserMapper;
        this.enterpriseService = enterpriseService;
        this.workerService = workerService;
        this.securityProperties = securityProperties;
    }

    public MpUserInfoResponse getInfo(Long userId) {
        FeUser user = feUserMapper.selectById(userId);
        if (user == null) {
            throw new BizException(ErrorCode.UNAUTHORIZED);
        }

        String userType = user.getUserType();
        MpUserInfoResponse response = new MpUserInfoResponse();
        response.setUserType(userType);
        response.setMobileMask(user.getMobileMask());

        if (USER_TYPE_ENTERPRISE.equals(userType)) {
            enterpriseService.requireEnterpriseUser(userId);
            FeEnterprise enterprise = enterpriseService.findEnterpriseByUserId(userId);
            if (enterprise == null) {
                response.setRegistered(false);
            } else {
                response.setRegistered(true);
                response.setEnterprise(toEnterpriseInfo(enterprise));
            }
        } else if (USER_TYPE_WORKER.equals(userType)) {
            workerService.requireWorkerUser(userId);
            FeWorker worker = workerService.findWorkerByUserId(userId);
            if (worker == null) {
                response.setRegistered(false);
            } else {
                response.setRegistered(true);
                response.setWorker(toWorkerInfo(worker));
            }
        } else {
            throw new BizException(ErrorCode.BAD_REQUEST, "不支持的用户类型");
        }
        return response;
    }

    private MpUserInfoResponse.EnterpriseInfo toEnterpriseInfo(FeEnterprise enterprise) {
        MpUserInfoResponse.EnterpriseInfo info = new MpUserInfoResponse.EnterpriseInfo();
        info.setEnterpriseId(enterprise.getId());
        info.setEnterpriseCode(enterprise.getEnterpriseCode());
        info.setName(enterprise.getName());
        info.setCreditCode(enterprise.getCreditCode());
        info.setLegalPerson(enterprise.getLegalPerson());
        info.setLegalPersonIdCardMask(enterprise.getLegalPersonIdCardMask());
        info.setLegalPersonIdCard(decryptQuietly(enterprise.getLegalPersonIdCardEnc()));
        info.setRegisteredAddress(enterprise.getRegisteredAddress());
        info.setContactName(enterprise.getContactName());
        info.setContactMobileMask(enterprise.getContactMobileMask());
        info.setContactMobile(decryptQuietly(enterprise.getContactMobileEnc()));
        info.setAuthStatus(enterprise.getAuthStatus());
        return info;
    }

    /** 本人企业 getInfo 解密回显；密文缺失或解密失败时返回 null，不阻断整单查询。 */
    private String decryptQuietly(String cipherText) {
        if (!StringUtils.hasText(cipherText)) {
            return null;
        }
        try {
            return AesUtils.decrypt(cipherText, securityProperties.getMobileAesKey());
        } catch (Exception ex) {
            log.warn("敏感字段解密失败，跳过明文回显：{}", ex.getMessage());
            return null;
        }
    }

    private static MpUserInfoResponse.WorkerInfo toWorkerInfo(FeWorker worker) {
        MpUserInfoResponse.WorkerInfo info = new MpUserInfoResponse.WorkerInfo();
        info.setWorkerId(worker.getId());
        info.setWorkerNo(worker.getWorkerNo());
        info.setRealName(worker.getRealName());
        info.setMobileMask(worker.getMobileMask());
        info.setIdCardNoMask(worker.getIdCardNoMask());
        info.setBankAccountMask(worker.getBankAccountMask());
        info.setBankName(worker.getBankName());
        info.setBankBranch(worker.getBankBranch());
        info.setVerifyStatus(worker.getVerifyStatus());
        return info;
    }
}
