package com.chinaweal.aiccs.door.subscribe;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.door.dto.XCUserRoleDTO;
import com.chinaweal.aiccs.door.entity.TUserportal;
import com.chinaweal.aiccs.door.service.ITUserportalService;
import com.chinaweal.aiccs.org.entity.TUsermenu;
import com.chinaweal.aiccs.org.service.TUsermenuService;
import com.chinaweal.aiccs.outside.api.XCDoorApi;
import com.chinaweal.aiccs.outside.util.DoorResult;
import com.chinaweal.aiccs.outside.util.GzcssTokenUtils;
import com.dtflys.forest.http.ForestResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 用户角色消息处理(根据用户更新)
 *
 *
 * 需求：删除用户权限再重新拉取最新权限。 by 刘付 2023.1.31
 * @author ymc
 * @date 2023年01月29日 14:32
 */
@Component
@Slf4j
public class UserRoleXCMessageHandler implements XCMessageHandler {

    @Resource
    private XCDoorApi xcDoorApi;
    @Resource
    private ITUserportalService itUserportalService;
    @Resource
    private TUsermenuService userMenuService;

    @Override
    public boolean support(String opType) {
        return "6".equals(opType);
    }

    @Override
    public void handle(JSONObject paramObj) {

        String userId = paramObj.getString("updateId"); // 用户id

        TUserportal tUserportal = itUserportalService.getById(userId);
        if (Objects.isNull(tUserportal) || StringUtils.isBlank(tUserportal.getLocaluserid())) {
            log.info("用户角色消息处理: 用户为空或没有关联本地用户，无需处理");
        }

        // 删除用户权限 根据用户ID
        userMenuService.remove(new QueryWrapper<TUsermenu>().eq("userID", tUserportal.getLocaluserid()));

        ForestResponse<DoorResult<List<XCUserRoleDTO>>> forestResponse = xcDoorApi.userRolesByUserId(userId, GzcssTokenUtils.APPID_XC);
        if (forestResponse.isSuccess()) {
            DoorResult<List<XCUserRoleDTO>> doorResult = forestResponse.getResult();

            if (doorResult.isQuerySuccess()) {
                List<XCUserRoleDTO> xcUserRoleDTOS = doorResult.getResult();

                for (XCUserRoleDTO userRoleDTO : xcUserRoleDTOS) {
                    try {
                        itUserportalService.saveUserRole(userRoleDTO, tUserportal);
                    } catch (Exception e) {
                        log.error("接收信创门户用户角色信息出错, 参数: type-6, {}。原因：", JSON.toJSONString(userRoleDTO), e);
                    }

                }
            }

        }

    }
}
