package com.cyksj.web.controller.kf;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.corp.kf.CorpKfAccountMapper;
import com.cyksj.model.entity.CorpKfAccount;
import com.cyksj.redis.RedisService;
import com.cyksj.service.corp.WxCorpOps;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 项目名: yhlxj2
 * 文件名: CorpKfController
 * 创建者: JavaZou
 * 创建时间:2025/1/10 11:18
 */
@RestController
@RequestMapping("/applets/corp/kf")
@RequiredArgsConstructor
public class CorpKfAppletController {
	private final CorpKfAccountMapper corpKfAccountMapper;

	private final WxCorpOps wxCorpOps;

	private final RedisService redisService;

	/**
	 * 获取微信客服
	 */
	@GetMapping("/get")
	public Result<String> getCorpKf(Integer scene) throws Exception {
		CorpKfAccount corpKfAccount = corpKfAccountMapper.selectOne(Wrappers.lambdaQuery(CorpKfAccount.class).eq(CorpKfAccount::getScene, scene).last("limit 1"));
		//默认官网
		if (corpKfAccount == null) {
			corpKfAccount = corpKfAccountMapper.selectOne(Wrappers.lambdaQuery(CorpKfAccount.class).eq(CorpKfAccount::getScene, 1).last("limit 1"));
			if (corpKfAccount == null) {
				return GatewayResponse.SUCCESS.newBuilder().toResult();
			}
		}
		String openKfId = corpKfAccount.getOpenKfId();
		String key = RedisService.key.CORP_KF_ACCOUNT_URL.getName() + openKfId;
		String url = redisService.getStr(key);
		if (StrUtil.isEmpty(url)) {
			url = wxCorpOps.getCorpKfUrl(openKfId, null);
			redisService.setNx(key, url, RedisService.key.CORP_KF_ACCOUNT_URL.getTimeout());
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult(url);
	}
}
