package com.inspect.system.controller;

import com.inspect.base.core.domain.Response;
import com.inspect.base.core.utils.StringUtils;
import com.inspect.base.core.web.controller.BaseController;
import com.inspect.base.core.web.domain.AjaxResult;
import com.inspect.common.log.annotation.Log;
import com.inspect.common.log.enums.BizType;
import com.inspect.base.redis.service.RedisService;
import com.inspect.common.security.service.TokenService;
import com.inspect.common.security.utils.SecurityUtils;
import com.inspect.system.base.RemoteFileService;
import com.inspect.system.base.domain.SysFile;
import com.inspect.system.base.domain.SysUser;
import com.inspect.system.base.model.LoginUser;
import com.inspect.system.service.ISysUserService;

import java.io.IOException;
import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping({"/user/profile"})
public class SysProfileController extends BaseController {
    private final ISysUserService userService;
    private final TokenService tokenService;
    private final RemoteFileService remoteFileService;
    @Resource
    private RedisService redisService;

    public SysProfileController(ISysUserService userService, TokenService tokenService, RemoteFileService remoteFileService) {
        this.userService = userService;
        this.tokenService = tokenService;
        this.remoteFileService = remoteFileService;
    }

    @GetMapping
    public AjaxResult profile() {
        String username = SecurityUtils.getUsername();
        SysUser user = this.userService.selectUserByUserName(username);
        AjaxResult ajax = AjaxResult.success(user);
        ajax.put("roleGroup", this.userService.selectUserRoleGroup(username));
        ajax.put("postGroup", this.userService.selectUserPostGroup(username));
        return ajax;
    }

    @Log(
            title = "个人信息",
            businessType = BizType.UPDATE
    )
    @PostMapping({"/edit"})
    public AjaxResult updateProfile(@RequestBody SysUser user) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
        user.setUserName(sysUser.getUserName());
        if (StringUtils.isNotEmpty(user.getPhonenumber()) && "1".equals(this.userService.checkPhoneUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && "1".equals(this.userService.checkEmailUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        } else {
            user.setUserId(sysUser.getUserId());
            user.setPassword((String) null);
            if (this.userService.updateUserProfile(user) > 0) {
                loginUser.getSysUser().setNickName(user.getNickName());
                loginUser.getSysUser().setPhonenumber(user.getPhonenumber());
                loginUser.getSysUser().setEmail(user.getEmail());
                loginUser.getSysUser().setSex(user.getSex());
                this.tokenService.setLoginUser(loginUser);
                return AjaxResult.success();
            } else {
                return AjaxResult.error("修改个人信息异常，请联系管理员");
            }
        }
    }

    @Log(
            title = "个人信息",
            businessType = BizType.UPDATE
    )
    @PostMapping({"/updatePwd"})
    public AjaxResult updatePwd(String oldPassword, String newPassword) {
        String username = SecurityUtils.getUsername();
        SysUser user = this.userService.selectUserByUserName(username);
        String password = user.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password)) {
            return AjaxResult.error("修改密码失败，旧密码错误");
        } else if (SecurityUtils.matchesPassword(newPassword, password)) {
            return AjaxResult.error("新密码不能与旧密码相同");
        } else if (this.userService.resetUserPwd(username, SecurityUtils.encryptPassword(newPassword)) > 0) {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            String userKey = this.tokenService.getTokenKey(loginUser.getToken());
            this.redisService.deleteObject(userKey);
            return AjaxResult.success();
        } else {
            return AjaxResult.error("修改密码异常，请联系管理员");
        }
    }

    @Log(
            title = "用户头像",
            businessType = BizType.UPDATE
    )
    @PostMapping({"/avatar"})
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            Response<SysFile> fileResult = this.remoteFileService.upload(file);
            if (StringUtils.isNull(fileResult) || StringUtils.isNull(fileResult.getData())) {
                return AjaxResult.error("文件服务异常，请联系管理员");
            }

            String url = fileResult.getData().getUrl();
            if (this.userService.updateUserAvatar(loginUser.getUsername(), url)) {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", url);
                loginUser.getSysUser().setAvatar(url);
                this.tokenService.setLoginUser(loginUser);
                return ajax;
            }
        }

        return AjaxResult.error("上传图片异常，请联系管理员");
    }
}
