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


import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mortals.xhx.base.system.role.model.RoleQuery;
import com.mortals.xhx.base.system.role.model.RoleUserEntity;
import com.mortals.xhx.base.system.role.model.RoleUserQuery;
import com.mortals.xhx.base.system.role.service.RoleService;
import com.mortals.xhx.base.system.role.service.RoleUserService;
import com.mortals.xhx.common.code.UserStatus;
import com.mortals.xhx.common.code.UserType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.web.BaseCRUDJsonMappingController;
import com.mortals.xhx.base.framework.annotation.Operlog;
import com.mortals.xhx.base.system.user.model.UserEntity;
import com.mortals.xhx.base.system.user.service.UserService;

/**
 * 用户信息
 *
 * @author: zxfei
 * @date: 2021/11/30 10:06
 */
@RestController
@RequestMapping("user")
public class UserController extends BaseCRUDJsonMappingController<UserService, UserForm, UserEntity, Long> {

    @Autowired
    private RoleService roleService;
    @Autowired
    private RoleUserService roleUserService;

    public UserController() {
        super.setFormClass(UserForm.class);
        super.setModuleDesc("用户信息");
    }

    @Override
    protected void init(HttpServletRequest request, HttpServletResponse response, UserForm form,
                        Map<String, Object> model, Context context) {
        this.addDict(model, "userType", UserType.getEnumMap());
        this.addDict(model, "status", UserStatus.getEnumMap());
        this.addDict(model, "roleIds", roleService.find(new RoleQuery()).stream().collect(Collectors.toMap(x -> x.getId().toString(), y -> y.getName())));
        super.init(request, response, form, model, context);
    }

    @Override
    protected void doListBefore(HttpServletRequest request, HttpServletResponse response, UserForm form, Map<String, Object> model, Context context) throws AppException {
        if (!StringUtils.isEmpty(form.getQuery().getRealName())) {
            form.getQuery().setRealName("%".concat(form.getQuery().getRealName()).concat("%"));
        }
        if (!StringUtils.isEmpty(form.getQuery().getLoginName())) {
            form.getQuery().setLoginName("%".concat(form.getQuery().getLoginName()).concat("%"));
        }
    }

    @Override
    protected void editBefore(HttpServletRequest request, HttpServletResponse response, UserForm form,
                              Map<String, Object> model, Context context) throws AppException {
        form.getEntity().setLoginPwd(null);
        form.getEntity().setLoginPwd1(null);
        form.getEntity().setLoginPwd2(null);
        super.editBefore(request, response, form, model, context);
    }

    @Override
    protected int editAfter(HttpServletRequest request, HttpServletResponse response, UserForm form,
                            Map<String, Object> model, UserEntity entity, Context context) throws AppException {
        entity.setLoginPwd(entity.getLoginPwd3());
        entity.setLoginPwd1(null);
        entity.setLoginPwd2(null);


        RoleUserQuery roleUserQuery = new RoleUserQuery();
        roleUserQuery.setUserId(entity.getId());
        String roleIds = roleUserService.find(roleUserQuery).stream().map(RoleUserEntity::getRoleId).map(String::valueOf).collect(Collectors.joining(","));
        entity.setRoleIds(roleIds);

        return super.editAfter(request, response, form, model, entity, context);
    }

    @Override
    protected int saveAfter(HttpServletRequest request, HttpServletResponse response, UserForm form, Map<String, Object> model, Context context) throws AppException {

        if (form.getEntity().getId() == getCurUser().getId()) {
            saveCurrUserForSession(request, response, this.service.get(form.getEntity().getId(), false));
        }
        return VALUE_RESULT_SUCCESS;
    }

    @Override
    protected void saveBefore(HttpServletRequest request, HttpServletResponse response, UserForm form,
                              Map<String, Object> model, Context context) throws AppException {
        if (!ObjectUtils.isEmpty(form.getEntity().getLoginName()) && service.existUser(form.getEntity().getLoginName(), form.getEntity().getId())) {
            throw new AppException("登录名已存在！");
        }
        super.saveBefore(request, response, form, model, context);
    }

    @RequestMapping(value = "change/password", method = RequestMethod.POST)
    @Operlog(msg = "密码修改成功!")
    public String changePassword(@RequestParam String oldPwd, @RequestParam String newPwd) {
        JSONObject ret = new JSONObject();
        try {
            service.updateUserPwd(super.getCurUser().getLoginName(), oldPwd, newPwd);
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
            ret.put(KEY_RESULT_MSG, "密码修改成功！");
        } catch (Exception e) {
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, super.convertException(e));
        }
        return ret.toJSONString();
    }


}