package com.cyksj.web.controller.manage.mirrorshop.manage;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.UserCertRecordMapper;
import com.cyksj.mapper.mirrorshop.UserMirrorShopApplyRecordMapper;
import com.cyksj.mapper.mirrorshop.UserMirrorShopMapper;
import com.cyksj.model.entity.UserCertRecord;
import com.cyksj.model.entity.UserMirrorShop;
import com.cyksj.model.entity.UserMirrorShopApplyRecord;
import com.cyksj.model.request.UserMirrorShopApplyMoneyReq;
import com.cyksj.model.views.UserMirrorShopApplyInfoView;
import com.cyksj.service.mirrorshop.CmsUserMirrorShopService;
import com.cyksj.web.util.StpUserMirrorShopManageUser;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * admin/镜像店铺后台/店铺设置
 * 项目名: yhlxj2
 * 文件名: CmsUserMirrorShopController
 * 创建者: JavaZou
 * 创建时间:2024/11/7 16:10
 */
@RestController
@RequestMapping("/mirrorShop/manage")
@RequiredArgsConstructor
public class CmsUserMirrorShopController {
	private final BeanSearcher beanSearcher;

	private final HttpServletRequest request;

	private final UserMirrorShopMapper userMirrorShopMapper;

	private final UserMirrorShopApplyRecordMapper userMirrorShopApplyRecordMapper;

	private final CmsUserMirrorShopService cmsUserMirrorShopService;

	private final UserCertRecordMapper userCertRecordMapper;

	/**
	 * 店铺 信息详情
	 */
	@GetMapping("/get/shop/detail/data")
	public Result<UserMirrorShop> getShopDetail() {
		long yhShopUserId = StpUserMirrorShopManageUser.getLoginIdAsLong();
		UserMirrorShop detailView = beanSearcher.searchFirst(UserMirrorShop.class, MapUtils.flatBuilder(request.getParameterMap())
				.field(UserMirrorShop::getUserId, yhShopUserId)
				.build());
		UserMirrorShopApplyInfoView userMirrorShopApplyInfoView = beanSearcher.searchFirst(UserMirrorShopApplyInfoView.class, MapUtils.flatBuilder(request.getParameterMap())
				.field(UserMirrorShopApplyInfoView::getUserId, yhShopUserId).orderBy(UserMirrorShopApplyInfoView::getId).desc().build());
		detailView.setApplyInfoView(userMirrorShopApplyInfoView);

		UserMirrorShopApplyRecord userMirrorShopApplyRecord = userMirrorShopApplyRecordMapper.selectOne(Wrappers.lambdaQuery(UserMirrorShopApplyRecord.class)
				.eq(UserMirrorShopApplyRecord::getUserId, yhShopUserId)
				.ne(UserMirrorShopApplyRecord::getVerifyStatus, UserMirrorShopApplyRecord.Status.fail)
				.orderByDesc(UserMirrorShopApplyRecord::getId)
				.last("limit 1"));
		if (userMirrorShopApplyRecord != null) {
			detailView.setModifyTime(userMirrorShopApplyRecord.getCreatedTime());
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult(detailView);
	}

	/**
	 * 设置联系方式
	 */
	@PutMapping("/set/shop/contact")
	public Result<String> setShopContact(@RequestBody UserMirrorShop yhShop) {
		long userId = StpUserMirrorShopManageUser.getLoginIdAsLong();
		String contact = yhShop.getContact();
		UserMirrorShop userMirrorShop = userMirrorShopMapper.selectOne(Wrappers.lambdaQuery(UserMirrorShop.class)
				.eq(UserMirrorShop::getUserId, userId).last("limit 1"));
		if (userMirrorShop == null) {
			throw BusinessRuntimeException.getInstance("店铺不存在");
		}
		userMirrorShop.setContact(contact);
		userMirrorShop.setQrCode(yhShop.getQrCode());
		userMirrorShopMapper.updateById(userMirrorShop);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}


	/**
	 * 申请修改
	 */
	@PutMapping("/update/shop")
	@Transactional(rollbackFor = Throwable.class)
	public Result<String> updateShop(@RequestBody UserMirrorShopApplyRecord record) {
		long userId = StpUserMirrorShopManageUser.getLoginIdAsLong();
		UserMirrorShop userMirrorShop = userMirrorShopMapper.selectOne(Wrappers.lambdaQuery(UserMirrorShop.class)
				.eq(UserMirrorShop::getUserId, userId).last("limit 1"));
		String name = record.getName();
		if (userMirrorShop == null) {
			throw BusinessRuntimeException.getInstance("店铺不存在");
		}
		if (StrUtil.isEmpty(name)) {
			throw BusinessRuntimeException.getInstance("请输入申请修改的店铺名");
		}
		//是否存在正在修改的提交记录
		UserMirrorShopApplyRecord userMirrorShopApplyRecord = userMirrorShopApplyRecordMapper.selectOne(Wrappers.lambdaQuery(UserMirrorShopApplyRecord.class)
				.eq(UserMirrorShopApplyRecord::getUserId, userId)
				.eq(UserMirrorShopApplyRecord::getVerifyStatus, UserMirrorShopApplyRecord.Status.verify).last("limit 1"));

		if (userMirrorShopApplyRecord != null) {
			throw BusinessRuntimeException.getInstance("您提交的修改申请正在审核中..");
		}
		//三个月可修改一次
		Integer count = userMirrorShopApplyRecordMapper.selectCount(Wrappers.lambdaQuery(UserMirrorShopApplyRecord.class)
				.eq(UserMirrorShopApplyRecord::getUserId, userId)
				.isNull(UserMirrorShopApplyRecord::getCustomId)
				.eq(UserMirrorShopApplyRecord::getVerifyStatus, UserMirrorShopApplyRecord.Status.success)
				.ge(UserMirrorShopApplyRecord::getCreatedTime, DateUtil.offsetMonth(DateTime.now(), -3)));
		if (count > 0) {
			throw BusinessRuntimeException.getInstance("近三个月只可修改一次");
		}
		userMirrorShopApplyRecord = new UserMirrorShopApplyRecord();
		userMirrorShopApplyRecord.setVerifyStatus(UserMirrorShopApplyRecord.Status.verify);
		userMirrorShopApplyRecord.setName(name);
		userMirrorShopApplyRecord.setLogo(record.getLogo());
		userMirrorShopApplyRecord.setUserId(userId);
		userMirrorShopApplyRecordMapper.insert(userMirrorShopApplyRecord);

		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 申请 提现
	 */
	@PostMapping("/apply/money")
	public Result<String> yhShopApplyMoney(@RequestBody UserMirrorShopApplyMoneyReq applyMoneyReq) throws Exception {
		long userId = StpUserMirrorShopManageUser.getLoginIdAsLong();
		applyMoneyReq.setUserId(userId);
		return cmsUserMirrorShopService.applyMoney(applyMoneyReq);
	}


	/**
	 * 身份认证信息
	 */
	@GetMapping("/get/cert/info")
	public Result<UserCertRecord> getCertInfo() {
		long userId = StpUserMirrorShopManageUser.getLoginIdAsLong();
		UserCertRecord record = userCertRecordMapper.selectOne(Wrappers.lambdaQuery(UserCertRecord.class)
				.eq(UserCertRecord::getUserId, userId)
				.last("limit 1"));
		return GatewayResponse.SUCCESS.newBuilder().toResult(record);
	}
}
