package com.mortals.xhx.base.system.role.web;


import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.common.IBaseEnum;
import com.mortals.framework.common.code.UserType;
import com.mortals.framework.model.Context;

import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.framework.web.BasePhpCRUDJsonMappingController;
import com.mortals.xhx.base.system.role.model.RoleQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.mortals.framework.web.BaseCRUDJsonMappingController;
import com.mortals.xhx.base.system.role.model.RoleEntity;
import com.mortals.xhx.base.system.role.model.RoleUserEntity;
import com.mortals.xhx.base.system.role.service.RoleService;
import com.mortals.xhx.base.system.role.service.RoleUserService;
import com.mortals.xhx.common.code.RoleType;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色信息
 *
 * @author: zxfei
 * @date: 2022/5/7 15:15
 */
@RestController
@RequestMapping("role")
public class RoleController extends BaseCRUDJsonBodyMappingController<RoleService,RoleEntity,Long> {

	@Autowired
	private RoleUserService roleUserService;
	
	public RoleController(){
		super.setFormClass(RoleForm.class);
		super.setModuleDesc("角色信息");
	}

	@Override
	protected void init(Map<String, Object> model, Context context) {
		Map<String, Object> status = new HashMap<>();
		status.put("userType", IBaseEnum.getEnumMap(UserType.class));
		status.put("roleType", RoleType.getEnumMap());
		model.put(KEY_RESULT_DICT, status);

	}

	/**
	 * 根据用户id获取角色名称
	 * @param userId
	 * @return
	 */
	@PostMapping("roleNameByUserId")
    public String getRoleNameByUserId(@RequestParam(value = "userId") Long userId) {
		try{
			JSONObject ret = new JSONObject();
			RoleUserEntity roleUserEntity = new RoleUserEntity();
			roleUserEntity.setUserId(userId);
			List<RoleUserEntity> find = roleUserService.find(roleUserEntity, new Context());
			List<RoleEntity> model = new ArrayList<>(); 
			if(find.size() > 0){
				for (RoleUserEntity roleUser : find) {
					RoleEntity entity = service.get(roleUser.getRoleId(), new Context());
					model.add(entity);
				}
			}
			ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
	        ret.put(KEY_RESULT_DATA, model);
	        return ret.toJSONString();
        } catch (Exception e) {
             log.error("查询用户角色错误", e);
             JSONObject ret = new JSONObject();
             ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
             ret.put(KEY_RESULT_MSG, super.convertException(e));
             return ret.toJSONString();
         }
	}
	
}