package com.qs.mp.web.controller.system;

import cn.jsms.api.ValidSMSResult;
import com.qs.mp.common.annotation.Log;
import com.qs.mp.common.constant.UserConstants;
import com.qs.mp.common.core.domain.AjaxResult;
import com.qs.mp.common.enums.BusinessType;
import com.qs.mp.common.enums.ErrorCodeEnum;
import com.qs.mp.common.exception.user.CaptchaExpireException;
import com.qs.mp.common.jsms.JSMSUtils;
import com.qs.mp.common.qcloud.QcloudFileUtils;
import com.qs.mp.common.utils.LogUtil;
import com.qs.mp.common.utils.StringUtils;
import com.qs.mp.common.utils.UUIDUtils;
import com.qs.mp.core.domain.LoginUser;
import com.qs.mp.framework.security.handle.HostHolder;
import com.qs.mp.framework.web.service.TokenService;
import com.qs.mp.system.domain.SysUser;
import com.qs.mp.system.service.ISysUserService;
import com.qs.mp.utils.SecurityUtils;
import com.qs.mp.web.controller.BaseController;
import com.qs.mp.web.controller.common.FileUploadController;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.Thumbnails.Builder;
import net.coobird.thumbnailator.geometry.Positions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
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;

/**
 * 个人信息 业务处理
 *
 * @author ygp
 */
@RestController
@RequestMapping("/system/user/profile")
public class SysProfileController extends BaseController
{

	private static final Logger log = LoggerFactory.getLogger(FileUploadController.class);

    @Autowired
    private ISysUserService userService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    protected HostHolder hostHolder;

    /**
     * 文件上传路径
     */
    @Value("${mp.profile}")
    public String filePath;

    /**
     * 公开
     */
    @Value("${cloud.public-bucket-name}")
    private String publicBucketName;


    /**
     * 个人信息
     */
    @GetMapping
    public AjaxResult profile()
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        AjaxResult ajax = AjaxResult.success(user);
        ajax.put("roleGroup", userService.selectUserRoleGroup(loginUser.getUsername()));
        ajax.put("postGroup", userService.selectUserPostGroup(loginUser.getUsername()));
        return ajax;
    }

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

    /**
     * 重置密码
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    public AjaxResult updatePwd(String oldPassword, String newPassword)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();


        if (!SecurityUtils.matchesPassword(oldPassword, password))
        {
            return AjaxResult.error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password))
        {
            return AjaxResult.error("新密码不能与旧密码相同");
        }
        if (userService.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword)) > 0)
        {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(SecurityUtils.encryptPassword(newPassword));
            tokenService.setLoginUser(loginUser);
            return AjaxResult.success();
        }
        return AjaxResult.error("修改密码异常，请联系管理员");
    }

    /**
     * 重置密码
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(String messageId, String authCode, String newPassword)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();

        //校验短信验证码
        ValidSMSResult res = JSMSUtils.sendValidSMSCode(
        		messageId, authCode);

        if(res == null || !res.getIsValid()){
            throw new CaptchaExpireException();
        }

        if (userService.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword)) > 0)
        {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(SecurityUtils.encryptPassword(newPassword));
            tokenService.setLoginUser(loginUser);
            return AjaxResult.success();
        }
        return AjaxResult.error("修改密码异常，请联系管理员");
    }

    /**
     * 头像上传
     */
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws IOException
    {
        if (!file.isEmpty())
        {
            // LoginUser loginUser = SecurityUtils.getLoginUser();
//            String avatar = FileUploadUtils.upload(YgpConfig.getAvatarPath(), file);
//            if (userService.updateUserAvatar(loginUser.getUsername(), avatar))
//            {
//                AjaxResult ajax = AjaxResult.success();
//                ajax.put("imgUrl", avatar);
//                // 更新缓存用户头像
//                loginUser.getUser().setAvatar(avatar);
//                tokenService.setLoginUser(loginUser);
//                return ajax;
//            }
        	return uploadAvatar(file);
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }


    private AjaxResult uploadAvatar(MultipartFile file) {
        try {
            if (null == file) {
                return AjaxResult.error("上传文件参数为空.");
            }
            //logger.info("upload...");
            LoginUser loginUser = hostHolder.getUser();
            String userId = loginUser.getUserId()+"";
            if (StringUtils.isBlank(userId)){
                return error(ErrorCodeEnum.ERROR_CODE_1002);
            }
            String bucketName = publicBucketName;
            // 上传文件路径
            LogUtil.info(logger, "ContentType：" + file.getContentType());
            String mimeType = file.getContentType();
            if (StringUtils.isBlank(mimeType)) {
                mimeType = "image/jpg";
            }
            LogUtil.info(logger,
                "userId:" + userId + " mimeType:" + mimeType + " fileName:" + file.getOriginalFilename());
            String name = commpressPicAndUpLoadOSS(userId, file, mimeType, 480, 480, bucketName);
            if (StringUtils.isBlank(name)) {
                LogUtil.error(logger, "头像上传失败.");
                return AjaxResult.error("头像上传失败.");
            }

            if (userService.updateUserAvatar(loginUser.getUsername(), name))
            {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", name);
                // 更新缓存用户头像
                loginUser.getUser().setAvatar(name);
                tokenService.setLoginUser(loginUser);
                return ajax;
            }
            return AjaxResult.error("头像上传失败.");
        } catch (Exception e) {
            LogUtil.error(log, e, "头像上传失败.");
            return AjaxResult.error("头像上传失败.");
        }
    }

    private String commpressPicAndUpLoadOSS(String userId,MultipartFile file,String mimeType,int width,int height,String bucketName) {
        String fileName = file.getOriginalFilename();
        int idx = fileName.lastIndexOf('.');
        String suffix = "";
        if (idx > 0) {
            suffix = fileName.substring(idx);
        }
        String name = userId+"/"+ UUIDUtils.newId() + suffix;
        try {
            QcloudFileUtils.putStream(file.getInputStream(), name, bucketName, mimeType );
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            Builder<BufferedImage> builder = Thumbnails.of(bufferedImage);
            int pWidth = bufferedImage.getWidth();
            int pHeight = bufferedImage.getHeight();
            if(pWidth > pHeight && pWidth > width) {
                builder.height(height);
            }else if(pHeight > pWidth && pHeight > height){
                builder.width(480);
            } else {
                builder.size(pWidth, pHeight);
            }
            String outFileDir = filePath+"/thumb/"+userId;
            File tempFile = new File(outFileDir);
            if(!tempFile.exists()) {
                tempFile.mkdirs();
            }
            String thumbName = name +"_s";
            String outFilePath = filePath+"/thumb/"+thumbName+"."+mimeType.substring(mimeType.lastIndexOf("/")+1);
            builder.toFile(outFilePath);
            //裁剪尺寸
            Thumbnails.of(outFilePath).scale(1f).sourceRegion(Positions.CENTER, 480,480).toFile(outFilePath);
            File outFile = new File(outFilePath);
            QcloudFileUtils.putFile(outFile, thumbName, bucketName, mimeType);
            if(outFile.exists()) {
                LogUtil.info(log, "delete file..."+outFilePath);
                outFile.delete();
            }
        }  catch (Exception e) {
            LogUtil.error(log, e, "");
            return null;
        }
        return name;
    }
}
