package com.cyksj.web.controller.market;

import cn.hutool.core.util.StrUtil;
import com.cyksj.common.annotation.NoSubmit;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.UserMapper;
import com.cyksj.model.entity.TaskFollowPlatVerify;
import com.cyksj.model.entity.User;
import com.cyksj.model.request.LoginReq;
import com.cyksj.model.request.TaskFollowReq;
import com.cyksj.model.request.UserBindInfoReq;
import com.cyksj.model.views.TaskFrontView;
import com.cyksj.service.market.MarketFrontService;
import com.cyksj.service.market.task.BindTaskService;
import com.cyksj.service.user.BadIntentionOpService;
import com.cyksj.service.user.UserBindRelationService;
import com.cyksj.service.user.UserService;
import com.cyksj.web.util.StpUserUtil;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.util.MapUtils;
import com.ejlchina.searcher.util.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
 *项目名: netflix
 *文件名: TaskFrontController
 *创建者: JavaZou
 *创建时间:2022/12/28 13:51
 */
@Slf4j
@RestController
@RequestMapping("/applets/market/task")
@RequiredArgsConstructor
public class TaskFrontController {

	private final BeanSearcher beanSearcher;

	private final MarketFrontService marketFrontService;

	private final UserMapper userMapper;

	private final BindTaskService bindTaskService;

	private final UserService userService;

	private final UserBindRelationService userBindRelationService;

	private final BadIntentionOpService badIntentionOpService;

	private final HttpServletRequest request;

	/**
	 * 任务列表
	 */
	@GetMapping("/get")
	public Result<SearchResult<TaskFrontView>> getTask(HttpServletRequest request) {
		Long userId = StpUserUtil.getLoginIdAsLong();
		SearchResult<TaskFrontView> search = beanSearcher.search(TaskFrontView.class, MapUtils.flatBuilder(request.getParameterMap())
				.orderBy(TaskFrontView::getSorted).desc()
				.orderBy(TaskFrontView::getId).desc()
				.build());
		search.getDataList().forEach(data -> {
			marketFrontService.updateTaskStatus(data, userId);
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 领取任务积分
	 */
	@PostMapping("/post/points/{taskId}")
	@NoSubmit
	public Result<String> getTaskPoints(@PathVariable Long taskId) {
		Long userId = StpUserUtil.getLoginIdAsLong();
		marketFrontService.receivedTaskPoints(userId, taskId);
		return GatewayResponse.SUCCESS.newBuilder().toResult("领取成功");
	}

	/**
	 * 绑定手机号
	 */
	@PostMapping("/bind/phone")
	@NoSubmit
	@Deprecated
	public Result<String> bindPhone(@RequestBody LoginReq phoneReq) {
		Long userId = StpUserUtil.getLoginIdAsLong();
		log.info("绑定手机号 userId:{}, params:{}", userId, phoneReq);
		if(StringUtils.isNotBlank(phoneReq.getPhone())){
			badIntentionOpService.isBadOpLoginPhone(request, phoneReq.getPhone());
		}
		User user = userMapper.selectById(userId);
		if (StrUtil.isEmpty(phoneReq.getCode())) {
			throw BusinessRuntimeException.getInstance("请输入验证码");
		}
		bindTaskService.bindPhone(user, phoneReq.getPhone(), phoneReq.getCode());
		return GatewayResponse.SUCCESS.newBuilder().toResult("绑定手机号成功");
	}

	/**
	 * 绑定邮箱
	 */
	@PostMapping("/bind/email")
	@Deprecated
	public Result<String> bindEmail(@RequestBody LoginReq phoneReq) {
		Long userId = StpUserUtil.getLoginIdAsLong();
		User user = userMapper.selectById(userId);
		bindTaskService.bindEmail(user, phoneReq.getEmail(), phoneReq.getCode());
		return GatewayResponse.SUCCESS.newBuilder().toResult("绑定邮箱成功");
	}

	/**
	 * 修改手机号
	 */
	@PutMapping("/put/bind/phone")
	@Deprecated
	public Result<String> updateBindPhone(@RequestBody LoginReq phoneReq) {
		Long userId = StpUserUtil.getLoginIdAsLong();
		User user = userMapper.selectById(userId);
		bindTaskService.updateBindPhone(user, phoneReq.getPhone(), phoneReq.getCode());
		return GatewayResponse.SUCCESS.newBuilder().toResult("更换手机号成功");
	}

	/**
	 * 绑定手机号、邮箱、微信
	 */
	@PostMapping("/bind/account")
	@NoSubmit
	public Result<String> bindOtherAccount(@RequestBody @Validated UserBindInfoReq request) throws Exception {
		Long userId = StpUserUtil.getLoginIdAsLong();
		request.setUserId(userId);
		return bindTaskService.bindOtherAccount(request);
	}

	/**
	 * 修改绑定信息
	 */
	@PutMapping("/put/bind/account")
	@NoSubmit
	public Result<String> updateBindAccount(@RequestBody @Validated UserBindInfoReq request) {
		Long userId = StpUserUtil.getLoginIdAsLong();
		request.setUserId(userId);
		bindTaskService.updateBindAccount(request);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 更换登录账号
	 */
	@PutMapping("/change/bind/account")
	public Result<String> changeBindAccount(@RequestBody @Validated UserBindInfoReq request) {
		long userId = StpUserUtil.getLoginIdAsLong();
		request.setUserId(userId);
		bindTaskService.changeBindAccount(request);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 绑定微信信息回调
	 */
	@GetMapping("/bind/wx/baseRedirect")
	public void bindWxAccountRedirect(String code, String state, HttpServletResponse response) throws Exception {
		String redirectUrl = userService.bindWxAccountRedirect(code, state);
		response.sendRedirect(redirectUrl);
	}

	/**
	 * 去完成关注任务
	 */
	@PostMapping("/post/follow")
	@NoSubmit
	public Result<String> toCompleteFollowTask(@RequestBody @Validated TaskFollowReq taskFollowReq) {
		Long userId = StpUserUtil.getLoginIdAsLong();
		taskFollowReq.setUserId(userId);
		marketFrontService.toCompleteFollowTask(taskFollowReq);
		return GatewayResponse.SUCCESS.newBuilder().toResult("提交成功");
	}

	/**
	 * 关注任务提交详情
	 */
	@GetMapping("/get/follow/detail")
	public Result<TaskFollowPlatVerify> getFollowDetail(HttpServletRequest request) {
		Long userId = StpUserUtil.getLoginIdAsLong();
		TaskFollowPlatVerify taskFollowPlatVerify = beanSearcher.searchFirst(TaskFollowPlatVerify.class, MapUtils.flatBuilder(request.getParameterMap())
				.field(TaskFollowPlatVerify::getUserId, userId).build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(taskFollowPlatVerify);
	}

	/**
	 * 关注任务审核失败,重新提交
	 */
	@PutMapping("/put/follow")
	public Result<String> updateFailFollowTask(@RequestBody @Validated TaskFollowReq taskFollowReq) {
		Long userId = StpUserUtil.getLoginIdAsLong();
		taskFollowReq.setUserId(userId);
		marketFrontService.updateFailFollowTask(taskFollowReq);
		return GatewayResponse.SUCCESS.newBuilder().toResult("提交成功");
	}
}
