package com.platform.modules.app.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;

import com.platform.common.utils.Constant;
import com.platform.common.utils.RedisUtils;
import com.platform.modules.app.entity.LocationEntity;
import com.platform.modules.sys.vo.SysUserInfoVo;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.shiro.crypto.hash.Sha256Hash;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.platform.common.annotation.SysLog;
import com.platform.common.utils.R;
import com.platform.common.validator.ValidatorUtils;
import com.platform.modules.app.annotation.Login;
import com.platform.modules.app.form.AppUserInfoForm;
import com.platform.modules.sys.entity.SysUserEntity;
import com.platform.modules.sys.form.PasswordForm;
import com.platform.modules.sys.service.SysUserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

/**
 * APP用户接口
 *
 * @author weiyan
 * @date 2019-02-22
 */
@RestController
@RequestMapping("/app/user")
@Api(value = "APP用户接口", tags = "APP用户接口")
public class AppUserController extends AppAbstractController {

	@Autowired
	private SysUserService sysUserService;

	@Autowired
	RedisUtils redisUtils;
	
	@Value("${materia.basePath}")
	private String DOMAIN;

	@Login
	@GetMapping("/info")
	@ApiOperation("获取用户信息")
	@ApiImplicitParams({@ApiImplicitParam(name = "userId", value = "用户ID", paramType = "query", dataType = "Integer")})
	@ApiResponses({
			@ApiResponse(code = HttpStatus.SC_OK, message = "success", response = SysUserEntity.class, responseContainer = "List")})
	public R info(Long userId) {
		if (userId == null) {
			return R.error("用户Id不能为空");
		}
		if (!getUserId().equals(userId)) {
			return R.error("不能访问他人信息");
		}
		SysUserEntity userEntity = sysUserService.selectById(userId);
		if (null == userEntity){
			return R.error("获取用户信息失败");
		}

		SysUserInfoVo infoVo = new SysUserInfoVo(userEntity);
		// 拼接头像地址
		String userImg = infoVo.getUserImg();
		if (StringUtils.isNotBlank(userImg)){
			userImg = DOMAIN + userImg;
			infoVo.setUserImg(userImg);
		}

		return R.ok().put("info", infoVo);
	}

	@Login
    @SysLog("系统app修改用户信息")
	@PostMapping("/update/info")
	@ApiOperation("系统app修改用户信息：仅修改姓名、手机号、邮箱")
	public R updateUserInfo(@RequestBody AppUserInfoForm userInfoForm) {
		ValidatorUtils.validateEntity(userInfoForm);
		return sysUserService.updateUserInfo(userInfoForm, getUserId());
	}

	@Login
	@SysLog("系统app修改密码")
	@PostMapping("/update/password")
	@ApiOperation("系统app修改用户密码")
	public R updateUserPassword(@RequestBody PasswordForm form) {

		if (StringUtils.isBlank(form.getPassword())) {
			return R.error("新密码不为能空");
		}

		// sha256加密
		String password = new Sha256Hash(form.getPassword(), getUser().getSalt()).toHex();
		// sha256加密
		String newPassword = new Sha256Hash(form.getNewPassword(), getUser().getSalt()).toHex();

		// 更新密码
		boolean flag = sysUserService.updatePassword(getUserId(), password, newPassword);
		if (!flag) {
			return R.error("原密码不正确");
		}

		return R.ok();
	}

	@Login
	@SysLog("系统app修改头像")
	@PostMapping("/update/img")
	@ApiOperation("系统app修改用户头像")
	public R updateUserImg(@RequestBody MultipartFile multipartFile) {

		SysUserEntity userEntity = sysUserService.selectById(getUserId());
		if (userEntity == null) {
			return R.error("错误的用户信息");
		}
        BufferedImage image = null;
        try {
            image = ImageIO.read(multipartFile.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("图片格式不正确");
        }
        if (image == null) {
            // 如果image=null 表示上传的不是图片格式
            return R.error("图片格式不正确");
        }
        String userImg = sysUserService.updateUserImg(userEntity, multipartFile);
        if(StringUtils.isNotBlank(userImg)){
        	userImg = DOMAIN + userImg;
        }
		return R.ok().put("userImg" , userImg);
	}

	@Login
	@PostMapping("/location/report")
	@ApiOperation(value = "坐标上报", notes = "经度、纬度")
	public R locationReport(String lng, String lat){

		if (StringUtils.isBlank(lng) || StringUtils.isBlank(lat))
			return R.error("经度或纬度不能为空");

		// 获取当前登陆用户
		SysUserEntity userEntity = getUser();
		if (null == userEntity)
			return R.error("获取用户信息失败");

		// 获取当前时间
		Long timeStamp = System.currentTimeMillis();

		// 将坐标信息存入Redis
		LocationEntity locationEntity = new LocationEntity(Double.parseDouble(lng), Double.parseDouble(lat), timeStamp);
		redisUtils.hset(Constant.REDIS_LOCATION_REPORT, userEntity.getUserId().toString(), locationEntity);
		return R.ok();
	}

}
