package com.yfd.platform.system.controller;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yfd.platform.annotation.Log;
import com.yfd.platform.config.ResponseResult;
import com.yfd.platform.datasource.DataSource;
import com.yfd.platform.system.domain.SysLog;
import com.yfd.platform.system.domain.SysUser;
import com.yfd.platform.system.service.ISysLogService;
import com.yfd.platform.system.service.IUserService;
import com.yfd.platform.utils.RequestHolder;
import com.yfd.platform.utils.StringUtils;
import com.yfd.platform.utils.sm4.SM4Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户信息 前端控制器
 * </p>
 *
 *
 * @since 2022-09-20
 */
@RestController
@RequestMapping("/system/user")
@Api(tags = "系统用户")
public class UserController {

    @Resource
    private IUserService userService;

    @Resource
    private ISysLogService sysLogService;

    @Value("${rsa.private_key}")
    private String privateKey;

    @Log(module = "系统用户", value = "新增系统用户", type = "0")
    @PostMapping("/addUser")
    @ApiOperation("新增系统用户")
    @ResponseBody
    @PreAuthorize("@el.check('add:user')")
    public ResponseResult addUser(@RequestBody SysUser user, String roleids) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUsername, user.getUsername());
        int count = userService.count(queryWrapper);
        if (count > 0) {
            return ResponseResult.error("当前用户已经存在");
        }
        String phone = user.getPhone();
        String email = user.getEmail();
        if (StrUtil.isNotBlank(email)) {
            if (!Validator.isEmail(email)) {
                return ResponseResult.error("邮箱输入不合法");
            }
        }
        if (StrUtil.isNotBlank(phone)) {
            if (!Validator.isMobile(phone)) {
                return ResponseResult.error("手机号输入不合法");
            }
            LambdaQueryWrapper<SysUser> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(SysUser::getPhone, user.getPhone());
            int count1 = userService.count(queryWrapper1);
            if (count1 > 0) {
                return ResponseResult.error("当前手机号已经绑定用户");
            }
        }
        Map reslut = userService.addUser(user, roleids);
        return ResponseResult.successData(reslut);
    }

    @Log(module = "系统用户", value = "修改用户信息", type = "0")
    @PostMapping("/updateUser")
    @ApiOperation("修改用户信息")
    @ResponseBody
    @PreAuthorize("@el.check('update:user')")
    public ResponseResult updateUser(@RequestBody SysUser user,
                                     String roleids) {
        if (StrUtil.isEmpty(user.getId())) {
            return ResponseResult.error("没有用户ID");
        }
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ne(SysUser::getId, user.getId()).eq(SysUser::getUsername, user.getUsername());
        int count = userService.count(queryWrapper);
        if (count > 0) {
            return ResponseResult.error("当前用户已经存在");
        }
        String phone = user.getPhone();
        String email = user.getEmail();
        if (StrUtil.isNotBlank(email)) {
            if (!Validator.isEmail(email)) {
                return ResponseResult.error("邮箱输入不合法");
            }
        }
        if (StrUtil.isNotBlank(phone)) {
            if (!Validator.isMobile(phone)) {
                return ResponseResult.error("手机号输入不合法");
            }
            LambdaQueryWrapper<SysUser> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(SysUser::getPhone, user.getPhone()).ne(SysUser::getId, user.getId());
            int count1 = userService.count(queryWrapper1);
            if (count1 > 0) {
                return ResponseResult.error("当前手机号已经绑定用户");
            }
        }
        //填写 当前用户名称
        user.setLastmodifier(userService.getUsername());
        //填写 当前日期
        user.setLastmodifydate(new Timestamp(System.currentTimeMillis()));
        Map reslut = userService.updateById(user, roleids);
        return ResponseResult.successData(reslut);
    }

    @Log(module = "系统用户", value = "解除用户锁定", type = "0")
    @PostMapping("/unlockUser")
    @ApiOperation("解除用户锁定")
    @ResponseBody
    public ResponseResult unlockUser(@RequestBody SysUser user) {
        if (StrUtil.isEmpty(user.getId())) {
            return ResponseResult.error("没有用户ID");
        }
        //填写 当前用户名称
        user.setLastmodifier(userService.getUsername());
        //填写 当前日期
        user.setLastmodifydate(new Timestamp(System.currentTimeMillis()));
        boolean ok = userService.updateById(user);
        if (!ok) {
            return ResponseResult.error();
        }
        return ResponseResult.success();
    }

    @GetMapping("/queryUserById")
    @ApiOperation("根据ID查询用户信息")
    @ResponseBody
    public ResponseResult queryUserById(String id) {
        SysUser sysUser = userService.getById(id);
        return ResponseResult.successData(sysUser);
    }

    @GetMapping("/queryUsers")
    @ApiOperation("查询用户信息")
    @ResponseBody
    @PreAuthorize("@el.check('select:user')")
    public ResponseResult queryUsers(String orgid,
                                     String username, String status, Page<SysUser> page) {

        Page<Map<String, Object>> mapPage = userService.queryUsers(orgid,
                username, status, page);
        return ResponseResult.successData(mapPage);
    }

    @GetMapping("/queryUserByID")
    @ApiOperation("查询用户保存的视频列表样式")
    @ResponseBody
    public ResponseResult queryUserByID(String id) {
        SysUser sysUser = userService.getById(id);
        return ResponseResult.successData(sysUser);
    }

    /***********************************
     * 用途说明：用户分配角色
     * 参数说明
     *idMap     用户id与角色id
     * 返回值说明: 判断是否添加成功
     ************************************/
    @Log(module = "系统用户", value = "用户分配角色及权限！", type = "0")
    @PostMapping("/setUserRoles")
    @ApiOperation("用户分配角色")
    @ResponseBody
    public ResponseResult setUserRoles(String roleid, String userids) {
        boolean ok = userService.setUserRoles(roleid, userids);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error();
        }
    }

    /***********************************
     * 用途说明：根据id删除用户
     * 参数说明
     *id         用户id
     * 返回值说明: 判断是否删除成功
     ************************************/
    @Log(module = "系统用户", value = "根据ID删除用户", type = "0")
    @PostMapping("/deleteById")
    @ApiOperation("根据ID删除用户")
    @ResponseBody
    @PreAuthorize("@el.check('delete:user')")
    public ResponseResult deleteById(String id) {
        userService.deleteById(id);
        return ResponseResult.success();
    }

    /***********************************
     * 用途说明：根据ID批量删除用户
     * 参数说明
     *ids        用户id集合
     * 返回值说明: 判断是否删除成功
     ************************************/
    @Log(module = "系统用户", value = "根据ID批量删除用户")
    @PostMapping("/deleteUserByIds")
    @ApiOperation("根据ID批量删除用户")
    @ResponseBody
    @PreAuthorize("@el.check('delete:user')")
    public ResponseResult deleteUserByIds(String id) {
        if (StrUtil.isBlank(id)) {
            return ResponseResult.error("参数为空");
        }
        boolean ok = userService.deleteUserByIds(id);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error();
        }
    }

    /***********************************
     * 用途说明：重置用户密码(管理员)
     * 参数说明
     *id        重置密码的 用户id
     * 返回值说明: 判断是否重置成功
     ************************************/
    @Log(module = "系统用户", value = "重置用户密码")
    @PostMapping("/resetPassword")
    @ApiOperation("重置用户密码")
    @ResponseBody
    @DataSource
    public ResponseResult resetPassword(String id) throws Exception {
        if (StrUtil.isBlank(id)) {
            ResponseResult.error("参数为空");
        }
        boolean ok = userService.resetPassword(id);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("重置用户密码失败！");
        }
    }

    /***********************************
     * 用途说明：二次用户密码认证
     * 用户账号   username
     *原密码      password
     * 返回值说明: 判断是否认证成功！
     ************************************/
    @PostMapping("/secondauthPassword")
    @ApiOperation("二次用户密码认证")
    @ResponseBody
    @DataSource
    public ResponseResult secondauthPassword(String username, String password) throws Exception {
        String decryptpassword = SM4Utils.decrypt(password, privateKey);
        boolean isok = userService.checkPassword(username, decryptpassword);
        if (isok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.successData("二次密码认证错误！");
        }
    }

    /***********************************
     * 用途说明：用户更新密码(用户自己)
     * 参数说明
     * 用户账号   username
     *原密码      oldpassword
     *新密码      newpassword
     * 返回值说明: 判断是否重成功
     ************************************/
    @PostMapping("/updatePassword")
    @ApiOperation("用户更新密码")
    @ResponseBody
    public ResponseResult updatePassword(@RequestBody String params) throws Exception {
        JSONObject jsonObject = JSONUtil.parseObj(params);
        String username = jsonObject.getStr("username");
        SysUser sysUser = userService.getUserInfo(username);
        if (ObjUtil.isNull(sysUser)) {
            return ResponseResult.error("您输入的用户名称不存在！");
        }
        String decryptoldpassword = SM4Utils.decrypt(jsonObject.getStr("oldpassword"), privateKey);
        String decryptnewpassword = SM4Utils.decrypt(jsonObject.getStr("newpassword"), privateKey);

        boolean isok = userService.checkPassword(username, decryptoldpassword);
        if (isok == false) {
            return ResponseResult.error("您输入的旧密码不正确，请重新输入！");
        } else {
            userService.updatePassword(username, decryptnewpassword);
        }
        HttpServletRequest request = RequestHolder.getHttpServletRequest();
        String requestip = StringUtils.getIp(request);
        String brower = StringUtils.getBrowser(request);
        SysLog sysLog = new SysLog();
        sysLog.setUsercode(username);
        sysLog.setUsername(sysUser.getNickname());
        sysLog.setRequestip(requestip);
        sysLog.setBrowser(brower);
        sysLog.setType("0");
        sysLog.setOpttype("修改(update)");
        sysLog.setModule("系统用户");
        String className = this.getClass().getName();
        String method =
                Thread.currentThread().getStackTrace()[1].getMethodName();
        sysLog.setMethod(className + "." + method + "()");
        sysLog.setDescription(sysUser.getNickname() + "用户更新密码！");
        sysLog.setLogtime(new Timestamp(System.currentTimeMillis()));
        sysLogService.save(sysLog);
        return ResponseResult.success(String.format("您的密码更新成功，密码有限期为%s天!", sysUser.getPwdvalidperiod()));
    }

    /***********************************
     * 用途说明：设置账号状态(管理员)
     * 参数说明
     *id        用户id
     * status   设置状态
     * 返回值说明: 判断是否设置成功
     ************************************/
    @Log(module = "系统用户", value = "设置账号状态，启用或者停止用户账号！", type = "0")
    @PostMapping("/setStatus")
    @ApiOperation("设置账号状态")
    @ResponseBody
    public ResponseResult setStatus(@RequestParam String id,
                                    @RequestParam String status) {
        boolean ok = userService.setStatus(id, status);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error();
        }
    }

    /***********************************
     * 用途说明：修改头像(管理员)
     * 参数说明
     * multipartFile   文件对象
     * status   设置状态
     * 返回值说明: 文件名
     ************************************/
    @ApiOperation("修改头像")
    @PostMapping(value = "/updateAvatar")
    public ResponseResult updateAvatar(String id, MultipartFile multipartFile) {
        if (multipartFile.isEmpty()) {
           return ResponseResult.error("文件是空的");
        }
//        String filename = multipartFile.getOriginalFilename();
//        String suffix = StrUtil.subAfter(filename, ".", true).toLowerCase();
//        if (!"png".equals(suffix) && !"jpg".equals(suffix) && !"gif".equals(suffix)) {
//            return ResponseResult.error("非法文件类型");
//        }
//        String contentType = multipartFile.getContentType();
//        if (!"image/jpeg".equals(contentType) && !"image/png".equals(contentType)&& !"image/gif".equals(contentType)) {
//            return ResponseResult.error("非法文件内容");
//        }
        boolean ok = userService.uploadAvatar(id, multipartFile);
        return ResponseResult.success();
    }
}
