package com.zt.plat.module.qms.business.reportdoc.listener;

import com.alibaba.fastjson.JSONObject;
import com.zt.plat.framework.common.enums.UserTypeEnum;
import com.zt.plat.framework.security.core.LoginUser;
import com.zt.plat.framework.web.core.util.WebFrameworkUtils;
import com.zt.plat.module.qms.business.reportdoc.service.ReportDocumentAssistService;
import com.zt.plat.module.qms.business.reportdoc.service.ReportDocumentMainService;
import com.zt.plat.module.qms.common.dic.controller.vo.DictionaryBusinessRespVO;
import com.zt.plat.module.qms.common.dic.dal.dataobject.DictionaryBusinessDO;
import com.zt.plat.module.qms.common.dic.service.DictionaryBusinessService;
import com.zt.plat.module.system.api.permission.RoleApi;
import com.zt.plat.module.system.mq.iwork.IWorkBizCallbackMessage;
import com.zt.plat.module.system.mq.iwork.IWorkBizCallbackResultMessage;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
@RequiredArgsConstructor
@RocketMQMessageListener(
        topic = IWorkBizCallbackMessage.TOPIC,
        consumerGroup = IWorkBizCallbackMessage.TOPIC + "_CONSUMER_local",
        selectorExpression = ReportDocListenerConstant.IWORK_BIZ_CALL_BACK_KEY  // 与 bizCallbackKey 一致
)
public class IWorkBizCallbackListener implements RocketMQListener<IWorkBizCallbackMessage> {
    private final RocketMQTemplate rocketMQTemplate;

    @Resource private ReportDocumentAssistService reportDocumentAssistService;
    @Resource private ReportDocumentMainService reportDocumentMainService;
    @Resource private DictionaryBusinessService dictionaryBusinessService;
    @Override
    public void onMessage(IWorkBizCallbackMessage message) {
        log.info("收到 iWork 回调: requestId={}", message.getRequestId());
        log.info("收到 iWork 回调: message={}", JSONObject.toJSONString(message));

        IWorkBizCallbackResultMessage result;
        try {
            LoginUser loginUser = initLoginUser();
            setLoginUser(loginUser);
            // 处理业务逻辑
            processCallback(message);

            result = IWorkBizCallbackResultMessage.builder()
                    .requestId(message.getRequestId())
                    .bizCallbackKey(message.getBizCallbackKey())
                    .success(true)
                    .attempt(message.getAttempt())
                    .maxAttempts(message.getMaxAttempts())
                    .payload(message.getPayload())
                    .build();
        } catch (Exception e) {
            log.error("处理回调失败", e);
            result = IWorkBizCallbackResultMessage.builder()
                    .requestId(message.getRequestId())
                    .bizCallbackKey(message.getBizCallbackKey())
                    .success(false)
                    .errorMessage(e.getMessage())
                    .attempt(message.getAttempt())
                    .maxAttempts(message.getMaxAttempts())
                    .payload(message.getPayload())
                    .build();
        }

        // 发送处理结果
        rocketMQTemplate.syncSend(IWorkBizCallbackResultMessage.TOPIC, result);
    }

    private LoginUser initLoginUser(){

        DictionaryBusinessRespVO dicDO = dictionaryBusinessService.getDataByDataKey("report_doc_iwork_conf").getData();
        if(dicDO == null || ObjectUtils.isEmpty(dicDO.getCustomConfig())){
            String msg = "业务参数字典缺少用印iwork配置，配置key：report_doc_iwork_conf";
            log.error(msg);
            throw new RuntimeException(msg);
        }
        String report_doc_iwork_conf = dicDO.getCustomConfig();
        JSONObject jsonObject = JSONObject.parseObject(report_doc_iwork_conf);

        LoginUser loginUser = new LoginUser();
        loginUser.setId(jsonObject.getLong("qms_user_id"));
        loginUser.setVisitDeptId(jsonObject.getLong("qms_dept_id"));
        loginUser.setVisitCompanyId(jsonObject.getLong("qms_company_id"));
        loginUser.setId(jsonObject.getLong("qms_user_id"));
        loginUser.setUserType(UserTypeEnum.ADMIN.getValue());
        loginUser.setTenantId(jsonObject.getLong("qms_tenant_id"));
        loginUser.setExpiresTime(LocalDateTime.now().plusHours(1));

        //设置用户信息
        Map<String, String> info = new HashMap<>();
        info.put(LoginUser.INFO_KEY_NICKNAME, jsonObject.getString("qms_user_name"));
        info.put(LoginUser.INFO_KEY_TENANT_ID, jsonObject.getString("qms_tenant_id"));
        loginUser.setInfo( info);
        return loginUser;
    }


    private void setLoginUser(LoginUser loginUser){
        //设置到Spring Security上下文
        Authentication authentication = new UsernamePasswordAuthenticationToken(loginUser, null, Collections.emptyList());
        SecurityContextHolder.getContext().setAuthentication(authentication);

        //设置到web请求上下文，供DefaultDBFieldHandler使用
        HttpServletRequest request = WebFrameworkUtils.getRequest();
        if(request != null){
            WebFrameworkUtils.setLoginUserId(request, loginUser.getId());
            WebFrameworkUtils.setLoginUserType(request, loginUser.getUserType());
        }
    }



    /**
     * 处理报告用印iwork回调逻辑
     * 1. 解析 payload 获取回调数据
     * 2. 保存签章文件等
     * 3. 更新业务状态
     * */
    private void processCallback(IWorkBizCallbackMessage message) {
        reportDocumentMainService.execCallBackByIwork( message);
    }
}
