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.XCRoleDTO;
import com.chinaweal.aiccs.door.dto.XCUserRoleDTO;
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.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
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.Optional;

/**
 * 用户角色消息处理(根据角色更新)
 * @author ymc
 * @date 2023年01月30日 17:29
 */
@Component
@Slf4j
public class UserRoleOtherXCMessageHandler implements XCMessageHandler {

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

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

    @Override
    public void handle(JSONObject paramObj) {

        String roleId = paramObj.getString("updateId"); // 角色id

        // 1.前置校验
        XCRoleDTO roleDTO;
        ForestResponse<DoorResult<XCRoleDTO>> forestResponse = xcDoorApi.queryRoleById(roleId);
        if (!forestResponse.isSuccess()) {
            return;
        }
        DoorResult<XCRoleDTO> doorResult = forestResponse.getResult();
        if (!doorResult.isQuerySuccess()) {
           return;
        }
        roleDTO = doorResult.getResult();
        if (GzcssTokenUtils.APPID_XC.equals(roleDTO.getSubSystemId())) {
            log.info("{}  非本系统角色，无需处理", roleDTO.getSubSystemId());
        }
        if (StringUtils.isBlank(roleDTO.getDescription())) {
            log.error("没有找到sys_menu主键。 roleName：" + roleDTO.getRoleName());
        }

        // 2.删除门户关联本地用户的权限，根据roleId
        userMenuService.remove(new QueryWrapper<TUsermenu>()
                .eq("sysMenuID", roleDTO.getDescription())
                .exists("SELECT 1 FROM T_USERPORTAL tup WHERE T_USERMENU.USERID = tup.LOCALUSERID"));


        // 3.重新插入
        ForestResponse<DoorResult<List<XCUserRoleDTO>>> resultForestResponse = xcDoorApi.userRolesByCondition(0, roleId, GzcssTokenUtils.APPID_XC);
        if (resultForestResponse.isSuccess()) {
            DoorResult<List<XCUserRoleDTO>> result = resultForestResponse.getResult();
            if (result.isQuerySuccess()) {
                List<XCUserRoleDTO> xcUserRoleDTOS = result.getResult();
                for (XCUserRoleDTO userRoleDTO : xcUserRoleDTOS) {
                    try {
                        itUserportalService.saveUserRole(userRoleDTO, null);
                    } catch (Exception e) {
                        log.error("接收信创门户用户角色信息出错, 参数: type-6, {}。原因：", JSON.toJSONString(userRoleDTO), e);
                    }
                }
            }
        }
    }
}