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


import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.common.IBaseEnum;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.framework.web.BaseCRUDJsonMappingController;
import com.mortals.xhx.base.framework.annotation.Operlog;
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.base.system.user.model.UserEntity;
import com.mortals.xhx.base.system.user.service.UserService;
import com.mortals.xhx.common.code.UserStatus;
import com.mortals.xhx.common.code.UserType;
import com.mortals.xhx.module.dept.model.DeptQuery;
import com.mortals.xhx.module.dept.service.DeptService;
import com.mortals.xhx.module.staff.service.StaffService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

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

/**
 * 用户信息
 *
 * @author: zxfei
 * @date: 2022/5/7 15:42
 */
@RestController
@RequestMapping("user")
public class UserController extends BaseCRUDJsonBodyMappingController<UserService, UserEntity, Long> {

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

    @Autowired
    private StaffService staffService;

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

    @Override
    protected void init(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())));
        this.addDict(model, "deptId", deptService.find(new DeptQuery()).stream().collect(Collectors.toMap(x -> x.getId().toString(), y -> y.getDeptName(), (o, n) -> n)));

        this.addDict(model, "customerId",  staffService.getCacheList().stream().collect(Collectors.toMap(x -> x.getId().toString(), y -> y.getName(), (o, n) -> n)));

    }

    @Override
    protected void doListBefore(UserEntity query, Map<String, Object> model, Context context) throws AppException {
        if (!StringUtils.isEmpty(query.getRealName())) {
            query.setRealName("%".concat(query.getRealName()).concat("%"));
        }
        if (!StringUtils.isEmpty(query.getLoginName())) {
            query.setLoginName("%".concat(query.getLoginName()).concat("%"));
        }
    }


    @Override
    protected int editAfter(Long id, Map<String, Object> model, UserEntity entity, Context context) throws AppException {
        RoleUserQuery roleUserQuery = new RoleUserQuery();
        roleUserQuery.setUserId(entity.getId());
        List<Long> roleIds = roleUserService.find(roleUserQuery).stream().map(RoleUserEntity::getRoleId).collect(Collectors.toList());
        entity.setRoleIds(roleIds);
        return super.editAfter(id, model, entity, context);
    }

    @Override
    protected int saveAfter(UserEntity entity, Map<String, Object> model, Context context) throws AppException {
        if (entity.getId() == getCurUser().getId()) {
            // TODO: 2022/8/15 更新redis session信息
            //saveCurrUserForSession(request, response, userService.get(form.getEntity().getId(), false));
        }
        return super.saveAfter(entity, model, context);
    }


//    @Override
//    protected void saveBefore(UserEntity entity, Map<String, Object> model, Context context) throws AppException {
//        if (!ObjectUtils.isEmpty(entity.getLoginName()) && service.existUser(entity.getLoginName(), entity.getId())) {
//            throw new AppException("登录名已存在！");
//        }
//        super.saveBefore(entity, 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();
    }


    @RequestMapping(value = "repassword", method = RequestMethod.POST)
    public String rePassword(@RequestBody UserEntity userEntity) {
        JSONObject ret = new JSONObject();
        try {
             //查询用户是否存在
            boolean existUser = service.existUser(userEntity.getLoginName(), userEntity.getId());
            if(!existUser) throw  new AppException("用户不存在！");

            //修改密码
            //service.doHandlerUser(userEntity);

            service.update(userEntity,getContext());
            //更新密码


            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();
    }


    public static void main(String[] args) {

        String token = "eyJhbGciOiJIUzI1NiJ9.eyJsb2dpbl91c2VyX2tleSI6IjIzNGE5NDA5ZDVhOTQ3MWNhMzdkYjZkYmMwY2JjZTc5In0.MWyQW40HYDxyUz7PJRf_nRsFPWx3Hr811Ime984nixs";
        String secret = "026db82420614469897fcc2dc1b4ce38";
        Claims claims = Jwts.parser()
                .setSigningKey(Base64.getEncoder().encodeToString(secret.getBytes()))
                .parseClaimsJws(token)
                .getBody();

        String uuid = (String) claims.get("login_user_key");

        System.out.println(uuid);


    }

}