package com.dxhy.admin.sys.controller;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSON;
import com.dxhy.admin.sys.config.SysConfig;
import com.dxhy.admin.sys.entity.SysUserEntity;
import com.dxhy.admin.sys.entity.SysUserOrgEntity;
import com.dxhy.admin.sys.model.User;
import com.dxhy.admin.sys.service.SysUserBusinessService;
import com.dxhy.admin.sys.service.SysUserOrgService;
import com.dxhy.admin.sys.service.SysUserRoleService;
import com.dxhy.admin.sys.service.SysUserService;
import com.dxhy.common.constant.UserConstant;
import com.dxhy.common.controller.AbstractController;
import com.dxhy.common.utils.*;
import com.dxhy.common.utils.group.AddGroup;
import com.dxhy.common.utils.group.UpdateGroup;
import com.dxhy.common.vo.UserInfo;

import cn.hutool.core.codec.Base64;
import lombok.extern.slf4j.Slf4j;

/**
 * 系统用户
 *
 * @author jiaohongyang
 */
@RestController
@RequestMapping("/sys/user")
@Slf4j
public class SysUserController extends AbstractController {

    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysUserRoleService sysUserRoleService;
    @Resource
    private SysUserOrgService sysUserOrgService;
    @Resource
    private SysUserBusinessService sysUserBusinessService;

    /**
     * 所有用户列表
     *
     * @param params
     *            查询条件
     * @return 用户信息
     */
    @RequestMapping("/list")

    public ResponseEntity<?> list(@RequestBody Map<String, Object> params) {
        UserInfo userInfo = getUserInfo();

        log.debug("传输数据：" + params + " userInfo信息" + JSON.toJSONString(userInfo));

        if (Long.parseLong(userInfo.getId()) != Constant.SUPER_ADMIN
            && !userInfo.getCompany().contains(SysConfig.ZXQY)) {
            params.put("company", userInfo.getCompany());
        }

        PageUtils page = sysUserService.queryPage(params);

        return ResponseEntity.ok(R.ok().put("page", page));
    }

    /**
     * 获取登录的用户信息
     */
    @RequestMapping("/info")
    @ResponseBody
    public ResponseEntity<?> info() {
        return ResponseEntity.ok(R.ok().put("user", sysUserService.queryUserName(getLoginName(), null)));
    }

    /**
     * 修改登录用户密码
     */
    @RequestMapping("/password")
    @ResponseBody
    public ResponseEntity<?> password(String password, String newPassword) {
        try {
            password = Rsaencrypt.decrypt(password, UserConstant.PRIVATE_KEY);
            newPassword = Rsaencrypt.decrypt(newPassword, UserConstant.PRIVATE_KEY);
            Assert.isBlank(newPassword, "新密码不为能空！");

            // 更新密码
            boolean flag = sysUserService.updatePassword(Long.parseLong(getUserId()), password, newPassword);
            if (!flag) {
                return ResponseEntity.ok(R.error("原密码不正确！"));
            }
            return ResponseEntity.ok(R.ok("修改密码成功！"));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.ok(R.error("修改密码失败！"));
        }

    }

    /**
     * 用户信息
     */
    @RequestMapping("/info/{userId}")
    @ResponseBody
    public ResponseEntity<?> info(@PathVariable("userId") Long userId) {
        SysUserEntity user = sysUserService.queryUserById(userId);

        // 获取用户所属的角色列表
        List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
        if (roleIdList != null && roleIdList.size() > 0) {
            user.setRoleIdList(roleIdList);
        }
        // 获取用户关联 权限
        List<SysUserOrgEntity> userOrgList = sysUserOrgService.queryOrgIdList(userId);
        if (userOrgList != null && userOrgList.size() > 0) {
            user.setUserOrgEntities(userOrgList);
        }

        // 获取用户关联 业务单元
        List<Long> businessIdList = sysUserBusinessService.queryBusinessIdList(userId);
        if (businessIdList != null && businessIdList.size() > 0) {
            user.setBusinessIdList(businessIdList);
        }
        return ResponseEntity.ok(R.ok().put("user", user));
    }

    /**
     * 保存用户
     */
    @RequestMapping("/save")
    @ResponseBody
    public ResponseEntity<?> save(@RequestBody SysUserEntity user) {
        try {
            ValidatorUtils.validateEntity(user, AddGroup.class);
            try {
                String password = Rsaencrypt.decrypt(user.getPassword(), UserConstant.PRIVATE_KEY);
                user.setPassword(password);
            } catch (Exception e) {
                user.setPassword(user.getPassword());
            }
            // 根据登录名获取用户信息
            SysUserEntity sysUser = sysUserService.queryUserName(user.getLoginname(), null);
            if (sysUser != null) {
                return ResponseEntity.ok(R.error("保存失败，用户名重复！"));
            }
            sysUserService.saveUser(user);
            return ResponseEntity.ok(R.ok("保存成功"));
        } catch (Exception e) {
            e.printStackTrace();
            log.debug("保存失败日志---", e);
            return ResponseEntity.ok(R.error("保存失败！"));
        }

    }

    /**
     * 修改用户
     */
    @RequestMapping("/update")
    @ResponseBody
    public ResponseEntity<?> update(@RequestBody SysUserEntity user) {
        try {
            ValidatorUtils.validateEntity(user, UpdateGroup.class);
            String password = Rsaencrypt.decrypt(user.getPassword(), UserConstant.PRIVATE_KEY);
            user.setPassword(password);
            // 根据登录名获取用户信息
            SysUserEntity sysUser = sysUserService.queryUserName(user.getLoginname(), user.getUserId());
            if (sysUser != null) {
                return ResponseEntity.ok(R.error("保存失败，用户名重复！"));
            }
            sysUserService.update(user);
            return ResponseEntity.ok(R.ok("保存成功"));
        } catch (Exception e) {
            log.debug("保存失败日志---", e);
            return ResponseEntity.ok(R.error("保存失败！"));
        }

    }

    /**
     * 删除用户
     */

    @RequestMapping("/delete")
    @ResponseBody
    public ResponseEntity<?> delete(Long userIds) {
        try {

            getUserId();

            sysUserService.deleteUser(userIds);
            // 删除关联角色
            sysUserRoleService.delete(userIds);
            // 删除关联数据权限
            sysUserOrgService.delete(userIds);
            // 删除关联业务单元
            sysUserBusinessService.delete(userIds);

            return ResponseEntity.ok(R.ok("删除成功"));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.ok(R.error("删除失败，请稍后重试！"));
        }

    }

    @RequestMapping(value = "/userInfo", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<?> getUser() {
        User user = sysUserService.getUser(getLoginName());
        String userJson = JSON.toJSONString(user);
        log.info("user:{}", userJson);
        if (user == null) {
            return ResponseEntity.ok(R.error(40001, "登录失败，用户名或密码错误！"));
        } else {
            return ResponseEntity.ok(R.ok().put("data", Base64.encode(userJson)));
        }
    }

    /**
     * 刷新用户缓存
     *
     */
    @RequestMapping(value = "/refreshCache", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<?> refreshCache() {
        if (sysUserService.refreshCache(true, null)) {
            return ResponseEntity.ok(R.ok("刷新缓存成功！"));
        } else {
            return ResponseEntity.ok(R.error("刷新缓存失败，请稍后重试！"));
        }
    }

    /**
     * 刷新用户缓存
     *
     */
    @RequestMapping(value = "/getDict", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<?> getDict() {
        log.info("获取字典信息");
        return ResponseEntity.ok(R.ok().put("data", sysUserService.getDict()));
    }

    /**
     * 刷新用户缓存
     *
     */
    @RequestMapping(value = "/getMenu", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<?> getMenu() {
        String id = getUserInfo().id;
        log.info("获取菜单信息,用户ID：{} , 登录名：{}", id, getUserInfo().loginname);
        String menu = sysUserService.getMenu(Long.parseLong(id));
        log.info("返回菜单信息：{}", menu);
        return ResponseEntity.ok(R.ok().put("data", menu));
    }

}
