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

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.mortals.framework.ap.SysConstains;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.BaseEntityLong;
import com.mortals.framework.model.Context;

import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.base.system.role.model.RoleUserQuery;
import org.apache.commons.beanutils.MethodUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
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.base.system.user.model.UserEntity;
import com.mortals.xhx.base.system.user.model.UserQuery;
import com.mortals.xhx.base.system.user.service.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 角色用户
 *
 * @author: zxfei
 * @date: 2022/5/7 15:15
 */
@RestController
@RequestMapping("role/user")
public class RoleUserController extends BaseCRUDJsonBodyMappingController<RoleUserService, RoleUserEntity, Long> {

    @Autowired
    private RoleService roleService;
    @Autowired
    private UserService userService;

    public RoleUserController() {
        super.setFormClass(RoleUserForm.class);
        super.setModuleDesc("角色用户");
    }


    @Override
    protected void init(Map<String, Object> model, Context context) {
        Map<String, Object> status = new HashMap<>(3);
        status.put("roleId", roleService.find(new RoleEntity(), null).stream()
                .collect(Collectors.toMap(e -> e.getId().toString(), RoleEntity::getName)));
        List<RoleUserEntity> roleUserList = (List<RoleUserEntity>) model.get(SysConstains.RESULT_KEY);
        if (roleUserList != null && roleUserList.size() > 0) {
            List<Long> userIdsList = roleUserList.stream().map(RoleUserEntity::getUserId).collect(Collectors.toList());
            List<UserEntity> userEntityList = userService.find(getQuery(UserQuery.class,
                    Sets.newHashSet("id", "realName", "loginName"), userIdsList.toArray(new Long[userIdsList.size()])), null);
            if (userEntityList != null) {
                status.put("userReNameMap",
                        userEntityList.stream().collect(Collectors.toMap(e -> e.getId().toString(), UserEntity::getRealName)));
                status.put("userId",
                        userEntityList.stream().collect(Collectors.toMap(e -> e.getId().toString(), UserEntity::getLoginName)));
            }
        }

        model.put(KEY_RESULT_DICT, status);
    }

    /**
     * 获取查询对象，限制查询返回的结果只包含ID和名称
     *
     * @param IdList
     * @return
     */
    private <E extends BaseEntityLong> E getQuery(Class<E> clz, Set<String> selectCols, Long... IdList) {
        try {
            E query = clz.newInstance();
            query.setColPickMode(1);
            if (IdList != null && IdList.length > 0) {
                MethodUtils.invokeMethod(query, "setIdList", Lists.newArrayList(IdList));
            }
            query.setTabColMap(selectCols.stream().collect(Collectors.toMap(s -> s, s -> s, (oldv, newv) -> newv)));
            return query;
        } catch (Exception e) {
            log.error("", e);
            throw new AppException(e);
        }
    }

    /**
     * 分配用户
     */
    @PostMapping(value = "distributionUser")
    public String distributionUser(@RequestBody RoleUserQuery query) {
        try {
            service.doDistributionUser(query);
            JSONObject ret = new JSONObject();
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
            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();
        }
    }

    /**
     * 分配角色
     */
    @PostMapping(value = "distributionRole")
    public String distributionRole(@RequestBody RoleUserQuery query) {
        try {
            service.doDistributionRole(query);
            JSONObject ret = new JSONObject();
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
            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();
        }
    }

}