package com.cyksj.web.controller.manage.corp.relation;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.util.GoogleGenerator;
import com.cyksj.common.util.Jsons;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.DoubleVerifyClickRecordMapper;
import com.cyksj.mapper.DoubleVerifyClickRefreshRecordMapper;
import com.cyksj.model.dto.DoubleVerifyDto;
import com.cyksj.model.entity.DoubleVerifyClickRecord;
import com.cyksj.model.entity.DoubleVerifyClickRefreshRecord;
import com.cyksj.model.manage.views.GroupsRelationView;
import com.cyksj.model.request.NfDeviceReq;
import com.cyksj.model.request.TicketLoginReq;
import com.cyksj.model.views.DoubleVerifyCodeView;
import com.cyksj.model.views.RenewalView;
import com.cyksj.redis.RedisService;
import com.cyksj.service.relation.GroupRelationFrontService;
import com.cyksj.service.relation.GroupsRelationNetflixService;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * admin/企业微信/车票功能
 * 项目名: yhlxj2
 * 文件名: CorpRelationController
 * 创建者: JavaZou
 * 创建时间:2025/1/16 18:13
 */
@RestController
@RequestMapping("/manage/corp/relation")
@RequiredArgsConstructor
public class CorpRelationController {
	private final GroupRelationFrontService groupRelationFrontService;

	private final GroupsRelationNetflixService groupsRelationNetflixService;

	private final DoubleVerifyClickRecordMapper doubleVerifyRecordMapper;

	private final DoubleVerifyClickRefreshRecordMapper refreshRecordMapper;

	private final BeanSearcher beanSearcher;

	private final RedisService redisService;


	/**
	 * 车票用户所有购买平台
	 */
	@GetMapping("/get/pay/goods")
	public Result<List<RenewalView>> getHasPayGoods(Long userId) {
		List<RenewalView> hasPayGoods = groupRelationFrontService.getHasPayGoods(userId);
		return GatewayResponse.SUCCESS.newBuilder().toResult(hasPayGoods);
	}

	/**
	 * 奈飞同户装置链接
	 */
	@GetMapping("/get/nf/household/device")
	public Result<String> getNfHouseholdDevice(@NotNull Long relationId, Long userId) throws Exception {
		String url = groupRelationFrontService.getNfHouseholdDevice(userId, relationId);
		return GatewayResponse.SUCCESS.newBuilder().toResult(url);
	}

	/**
	 * 读取车票账号登录验证码
	 */
	@PostMapping("/get/verifyCode")
	public Result<String> getAiVerifyCode(@RequestBody TicketLoginReq loginReq) throws Exception {
		return GatewayResponse.SUCCESS.newBuilder().toResult(groupRelationFrontService.getAiVerifyCode(loginReq));
	}

	/**
	 * 设置pin码
	 */
	@PutMapping("/set/pin/{relationId}")
	public Result<String> setPin(@PathVariable Long relationId, String code, Long userId) {
		JSONObject data = groupsRelationNetflixService.setNetflixPin(relationId, userId, code);
		return GatewayResponse.SUCCESS.newBuilder().toResult(data.toString());
	}

	/**
	 * 查询是否设置成功
	 */
	@GetMapping("/get/pin/status/{taskId}")
	public Result<Integer> getPinStatus(@PathVariable String taskId) throws Exception {
		return GatewayResponse.SUCCESS.newBuilder().toResult(groupsRelationNetflixService.getPinStatus(taskId));
	}

	/**
	 * 踢出奈飞设备
	 */
	@PostMapping("/kickOut/nf/{relationId}")
	public Result<String> nfKickOut(@PathVariable Long relationId, Long userId) {
		JSONObject data = groupsRelationNetflixService.nfKickOut(userId, relationId);
		return GatewayResponse.SUCCESS.newBuilder().toResult(data.toString());
	}

	/**
	 * 代点奈飞同户装置
	 */
	@PostMapping("/click/nf/household/device")
	public void clickNfHouseholdDevice(@RequestBody NfDeviceReq nfDeviceReq) {
		groupsRelationNetflixService.clickNfHouseholdDevice(nfDeviceReq);
	}

	/**
	 * 获取双重验证码记录
	 */
	@GetMapping("/get/doubleVerify/codeList")
	public Result<List<DoubleVerifyCodeView>> getDoubleVerifyCodeList(Long relationId, Long userId) {
		List<DoubleVerifyCodeView> views = doubleVerifyRecordMapper.getDoubleVerifyCodeList(userId, relationId);
		return GatewayResponse.SUCCESS.newBuilder().toResult(views);
	}

	/**
	 * 获取AI类 ChatGPT产品谷歌验证码
	 */
	@GetMapping("/get/authCode")
	public Result<String> getAuthCode(Long relationId, Long userId) {
		if (relationId == null) throw BusinessRuntimeException.getInstance("车票不存在");
		GroupsRelationView groupsRelationView = beanSearcher.searchFirst(GroupsRelationView.class, MapUtils.builder()
				.field(GroupsRelationView::getId, relationId)
				.field(GroupsRelationView::getUserId, userId).build());
		if (groupsRelationView == null) throw BusinessRuntimeException.getInstance("车票不存在");
		if (StrUtil.isEmpty(groupsRelationView.getApiSecret()))
			throw BusinessRuntimeException.getInstance("未开启验证");
		DateTime now = DateTime.now();
		//获取双重验证码
		Boolean isHasVerifyCode = StrUtil.isNotBlank(groupsRelationView.getVerifyCode()) ? true : false;
		//一分钟内 只能一人获取
		boolean b = redisService.setNx(RedisService.key.DOUBLE_VERIFY_CODE_VIEW_MINUTES_KEY.getName() + groupsRelationView.getTripsAccount(), relationId, RedisService.key.DOUBLE_VERIFY_CODE_VIEW_MINUTES_KEY.getTimeout());
		if (!b) {
			throw BusinessRuntimeException.getInstance("一分钟内已有人获取该账号验证码,请稍后获取..");
		}
		int second = now.second();
		if (second < 30 && 30 - second < 3) {
			ThreadUtil.sleep(30 - second + 1, TimeUnit.SECONDS);
		} else if (second > 30 && 60 - second < 3) {
			ThreadUtil.sleep(60 - second + 1, TimeUnit.SECONDS);
		}
		StringBuilder sb = new StringBuilder();
		JSONObject re = new JSONObject();
		try {
			long code = GoogleGenerator.getCode(groupsRelationView.getApiSecret(), now.getTime());
			sb.append(code);
			while (sb.length() < 6) {
				sb.insert(0, 0);
			}
			re.putOpt("code", sb.toString());
			int nowSecond = DateTime.now().second();
			int time = 0;
			if (nowSecond < 30) {
				time = 30 - nowSecond;
			} else {
				time = 60 - nowSecond;
			}
			re.putOpt("time", time);

			DoubleVerifyClickRecord doubleVerifyClickRecord = new DoubleVerifyClickRecord();
			doubleVerifyClickRecord.setRelationId(relationId);
			//设置为0
			doubleVerifyClickRecord.setUserId(0l);

			doubleVerifyClickRecord.setAccountId(groupsRelationView.getAccountId());
			doubleVerifyClickRecord.setAccount(groupsRelationView.getTripsAccount());
			doubleVerifyClickRecord.setSkuId(groupsRelationView.getSkuId());
			doubleVerifyClickRecord.setCode(sb.toString());
			doubleVerifyClickRecord.setRemainTime(time);
			doubleVerifyRecordMapper.insert(doubleVerifyClickRecord);

			DoubleVerifyDto doubleVerifyDto = new DoubleVerifyDto();
			doubleVerifyDto.setClickId(doubleVerifyClickRecord.getId());
			doubleVerifyDto.setApiSecret(groupsRelationView.getApiSecret());
			redisService.set(String.format("%s-%s", userId, sb.toString()), 0, 60 * 10l);
			redisService.set(String.format("%s/%s", userId, sb.toString()), Jsons.toJson(doubleVerifyDto), 60 * 10l);
		} catch (Exception e) {
			throw BusinessRuntimeException.getInstance("获取双重验证码错误,请联系开发");
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult(re.toString());
	}

	/**
	 * 刷新验证码
	 */
	@GetMapping("/refresh/code")
	public Result<String> refreshCode(String code, Long userId) {
		String objKey = String.format("%s/%s", userId, code);
		Object objValue =  redisService.get(objKey);
		String apiSecret = null;
		Long clickId = 0l;
		try {
			DoubleVerifyDto dto = Jsons.parseObject(objValue.toString(), DoubleVerifyDto.class);
			apiSecret = dto.getApiSecret();
			clickId = dto.getClickId();
		} catch (Exception e) {
			apiSecret = objValue.toString();
		}
		if (apiSecret == null) {
			throw BusinessRuntimeException.getInstance("密钥不存在");
		}
		StringBuilder sb = new StringBuilder();
		try {
			long c = GoogleGenerator.getCode(apiSecret, DateTime.now().getTime());
			sb.append(c);
			while (sb.length() < 6) {
				sb.insert(0, 0);
			}

		} catch (Exception e) {
			throw BusinessRuntimeException.getInstance("刷新双重验证码错误,请联系开发");
		}
		if (clickId != 0) {
			int nowSecond = DateTime.now().second();
			int time = 0;
			if (nowSecond < 30) {
				time = 30 - nowSecond;
			} else {
				time = 60 - nowSecond;
			}
			//刷新双重验证码记录
			DoubleVerifyClickRefreshRecord refreshRecord = new DoubleVerifyClickRefreshRecord();
			refreshRecord.setClickId(clickId);
			refreshRecord.setUserId(0l);
			refreshRecord.setCode(sb.toString());
			refreshRecord.setRemainTime(time);
			refreshRecordMapper.insert(refreshRecord);
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult(sb.toString());
	}
}
