package com.cyksj.web.controller.user;

import cn.hutool.core.util.StrUtil;
import com.cyksj.common.util.Jsons;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.model.views.PhoneAreaCodeView;
import com.cyksj.redis.RedisService;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/*
 *项目名: netflix
 *文件名: PhoneAreaCodeController
 *创建者: JavaZou
 *创建时间:2023/6/21 14:09
 */
@RestController
@RequestMapping("/applets/phone")
@Slf4j
@RequiredArgsConstructor
public class PhoneAreaCodeController {
	private final BeanSearcher beanSearcher;

	private final RedisService redisService;

	/**
	 * 获取国家或地区手机号代码
	 */
	@GetMapping("/get/areaCode")
	public Result<List<PhoneAreaCodeView>> getPhoneAreaCode(String name) throws Exception {
		String key = RedisService.key.PHONE_AREA_CODE.getName();
		Object value = redisService.get(key);
		List<PhoneAreaCodeView> phoneAreaCodeViews = null;
		if (value == null) {
			phoneAreaCodeViews = beanSearcher.searchAll(PhoneAreaCodeView.class, MapUtils.builder().build());
			redisService.setNx(key, Jsons.toJson(phoneAreaCodeViews), RedisService.key.PHONE_AREA_CODE.getTimeout());
		}
		if (phoneAreaCodeViews == null) {
			phoneAreaCodeViews = Jsons.parseList(value.toString(), PhoneAreaCodeView.class);
		}
		if (StrUtil.isNotBlank(name)) {
			phoneAreaCodeViews = phoneAreaCodeViews.stream().filter(view -> view.getNameCn().contains(name)).collect(Collectors.toList());
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult(phoneAreaCodeViews);
	}
}
