/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.security.multishop.controller;


import com.yami.shop.bean.model.ShopDetail;
import com.yami.shop.common.annotation.SysLog;
import com.yami.shop.dao.ShopDetailMapper;
import com.yami.shop.security.comment.model.UpdatePasswordDto;
import com.yami.shop.security.multishop.util.SecurityUtils;
import com.yami.shop.service.ShopDetailService;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
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 springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;

/**
 * 登录相关
 * @author lgh
 */
@Controller
@AllArgsConstructor
@ApiIgnore
@RequestMapping("/multishop")
public class MultishopLoginController {

	private final ShopDetailService shopDetailService;

	private final PasswordEncoder passwordEncoder;

	/**
	 * ping
	 */
	@GetMapping(value = "/ping")
	public ResponseEntity<Void> ping() {
		return ResponseEntity.ok().build();
	}

	/**
	 * 退出
	 */
	@PostMapping(value = "/logout")
	public ResponseEntity<String> logout() {
		SecurityContextHolder.clearContext();
		return ResponseEntity.ok().build();
	}


	/**
	 * 修改登录用户密码
	 */
	@SysLog("修改密码")
	@PostMapping("/password")
	@ApiOperation(value="修改密码", notes="修改当前登陆用户的密码")
	public ResponseEntity<String> password(@RequestBody @Valid UpdatePasswordDto param){
		String username = SecurityUtils.getShopUser().getRealUsername();

		ShopDetail shopDetail = shopDetailService.getShopByMobile(username);
		if (!passwordEncoder.matches(param.getPassword(), shopDetail.getPassword())) {
			return ResponseEntity.badRequest().body("原密码不正确");
		}
		//新密码
		String newPassword = passwordEncoder.encode(param.getNewPassword());
//		更新密码
		shopDetailService.updatePasswordByUserName(username, newPassword);
		return ResponseEntity.ok().build();
	}

}
