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

package com.yami.shop.api.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Maps;
import com.yami.shop.bean.app.param.SendSmsParam;
import com.yami.shop.bean.dto.ShopDetailDto;
import com.yami.shop.bean.enums.SmsType;
import com.yami.shop.bean.model.ShopAuditing;
import com.yami.shop.bean.model.ShopDetail;
import com.yami.shop.bean.param.ShopDetailParam;
import com.yami.shop.common.exception.GlobalException;
import com.yami.shop.common.util.R;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.security.comment.model.UpdatePasswordDto;
import com.yami.shop.security.comment.model.UsernameAndPasswordDto;
import com.yami.shop.service.ShopAuditingService;
import com.yami.shop.service.ShopDetailService;
import com.yami.shop.service.SmsLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Objects;


/**
 *
 * @author lgh on 2018/08/29.
 */
@RestController
@RequestMapping("/p/shop")
@Api(tags = "店铺相关接口")
@AllArgsConstructor
public class MyShopDetailController {

    private final ShopDetailService shopDetailService;

	private final PasswordEncoder passwordEncoder;

	private final ShopAuditingService shopAuditingService;

	private final MapperFacade mapperFacade;

	private SmsLogService smsLogService;

	@PostMapping("/apply")
	@ApiOperation(value = "申请店铺")
	public ResponseEntity<Void> apply(@Valid @RequestBody ShopDetailParam shopDetailParam) {
		String userId = SecurityUtils.getUser().getUserId();
		shopDetailService.applyShop(userId,shopDetailParam);
		return ResponseEntity.ok().build();
	}

	@PostMapping("/saveUsernameAndPassword")
	@ApiOperation(value = "保存店铺账号密码")
	public ResponseEntity<Void> saveUsernameAndPassword(@Valid @RequestBody UsernameAndPasswordDto usernameAndPasswordDto) {
		String userId = SecurityUtils.getUser().getUserId();

		ShopDetail shopDetail = shopDetailService.getShopDetailByUserId(userId);

        if (shopDetail == null) {
            throw new GlobalException("请先进行开店申请");
        }

        if (StrUtil.isNotBlank(shopDetail.getMobile())) {
            throw new GlobalException("店铺账号已设置不能修改");
        }


        ShopDetail dbUsernameUser = shopDetailService.getShopByMobile(usernameAndPasswordDto.getUsername());
        if (dbUsernameUser != null) {
            throw new GlobalException("该账号已经开通过店铺，无法重复开通");
        }

        if (!smsLogService.checkValidCode(usernameAndPasswordDto.getUsername(), usernameAndPasswordDto.getCode(), SmsType.VALID)){
            throw new GlobalException("验证码有误或已过期");
        }

        String password = passwordEncoder.encode(usernameAndPasswordDto.getPassword());
		shopDetail.setPassword(password);
		shopDetail.setMobile(usernameAndPasswordDto.getUsername());
		shopDetail.setPassword(password);
		shopDetailService.updateById(shopDetail);
		shopDetailService.removeShopDetailCacheByShopId(shopDetail.getShopId());
		return ResponseEntity.ok().build();
	}



	@PostMapping("/updatePassword")
	@ApiOperation(value = "更新店铺密码")
	public ResponseEntity<Void> updatePassword(@Valid @RequestBody UpdatePasswordDto updatePasswordDto) {
		String userId = SecurityUtils.getUser().getUserId();

		ShopDetail shopDetail = shopDetailService.getShopDetailByUserId(userId);
		if (shopDetail == null) {
			throw new GlobalException("请先进行开店申请");
		}

		if (!passwordEncoder.matches(updatePasswordDto.getPassword(), shopDetail.getPassword())) {
			throw new GlobalException("原密码不正确");
		}
		//新密码
		String newPassword = passwordEncoder.encode(updatePasswordDto.getNewPassword());
//		更新密码
		shopDetailService.updatePasswordByUserName(shopDetail.getMobile(), newPassword);
		return ResponseEntity.ok().build();
	}


	@GetMapping()
	@ApiOperation(value = "获取拥有的店铺信息")
	public ResponseEntity<ShopDetailDto> auditingDetail() {
		ShopDetail shopDetail = shopDetailService.getShopDetailByUserId(SecurityUtils.getUser().getUserId());
		ShopDetailDto shopDetailDto = mapperFacade.map(shopDetail, ShopDetailDto.class);
		return ResponseEntity.ok(shopDetailDto);
	}

	@GetMapping("/shopAudit" )
	@ApiOperation(value = "获取店铺的审核信息")
	public ResponseEntity<ShopAuditing> getShopAuditing() {
		ShopAuditing shopAuditing = shopAuditingService.getOne(new LambdaQueryWrapper<ShopAuditing>().eq(ShopAuditing::getUserId, SecurityUtils.getUser().getUserId()));
		return ResponseEntity.ok(shopAuditing);
	}

	/**
	 * 发送验证码接口
	 */
	@PostMapping("/sendCode")
	@ApiOperation(value = "发送验证码")
	public ResponseEntity<Void> sendLoginCode(@Valid @RequestBody SendSmsParam sendSmsParam) {
		String userId = SecurityUtils.getUser().getUserId();
		if (Objects.isNull(sendSmsParam.getMobile())){
			throw new GlobalException("手机号不能为空");
		}
		smsLogService.sendSms(SmsType.VALID, userId ,sendSmsParam.getMobile(), Maps.newHashMap());
		return ResponseEntity.ok().build();
	}

	/**
	 * 获取店铺信息
	 */
	@GetMapping("/info/{shopId}")
	@ApiOperation(value = "获取店铺信息")
	public R<ShopDetail> info(@PathVariable("shopId") Long shopId) {
		ShopDetail shopDetailByShopId = shopDetailService.getShopDetailByShopId(shopId);
		return R.SUCCESS(shopDetailByShopId);
	}
}
