package org.springblade.activity.controller;


import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springblade.activity.dto.ForeignUnsubscribeKcDTO;
import org.springblade.activity.dto.vo.ForeignUnsubscribeKcVO;
import org.springblade.activity.dto.vo.HisFlowOrderKcVO;
import org.springblade.activity.entity.ForeignWhiteList;
import org.springblade.activity.service.IForeignApiService;
import org.springblade.activity.service.IForeignWhiteListService;
import org.springblade.activity.service.IHisFlowOrderService;
import org.springblade.activity.util.EnDecHelper2;
import org.springblade.core.tool.api.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <p>
 * 活动管理表 前端控制器
 * </p>
 *
 * @author zbc
 * @since 2021-04-21
 */
@RestController
@RequestMapping("foreign")
@Api(value = "对外开放api", tags = "对外开放api接口")
@Slf4j
public class ForeignApiController {


	@Autowired
	private IForeignApiService foreignApiService;

	@Autowired
	private IHisFlowOrderService hisFlowOrderService;

	@Autowired
	private IForeignWhiteListService foreignWhiteListService;


	@PostMapping("/getCpid")
	@ApiOperation(value = "获取cpid")
	public R getCpid(@RequestBody ForeignUnsubscribeKcDTO date,HttpServletRequest request) {
		//白名单校验
		String ip = getIp(request);
		log.info("ip = {}",ip);
		List<ForeignWhiteList> list = foreignWhiteListService.list(new LambdaQueryWrapper<ForeignWhiteList>()
			.eq(ForeignWhiteList::getIpAddress, ip)
		);
		if(list == null || list.size() == 0){
			return R.fail("请添加白名单");
		}

		if(StringUtils.isBlank(date.getPhone())){
			return R.fail("手机号不能为空");
		}

		String phone = EnDecHelper2.decode(date.getPhone());
		String regex = "^(1[3-9]\\d{9}$)";
		if (phone.length() == 11) {
			Pattern p = Pattern.compile(regex);
			Matcher m = p.matcher(phone);
			if (!m.matches()) {
				return R.fail("解密失败");
			}
		}else {
			return R.fail("非法手机号");
		}

		List<String> cpList = new ArrayList<String>() {
			{
				this.add("kuaishou");
				this.add("bilibl");
				this.add("tencent");
				this.add("mangtv16");
				this.add("aiqy");
				this.add("youtu");
				this.add("mangtv");
			}
		};
		String random = cpList.get(RandomUtil.randomInt(0, cpList.size()));
		//oracle 数据获取
		SimpleDateFormat simple = new SimpleDateFormat("yyyyMM");
		String format = simple.format(new Date());
		String tableName = "HIS_FLOW_ORDER_"+format;
		List<HisFlowOrderKcVO> orderList = hisFlowOrderService.getCpidByPhone(phone,tableName);
		List<String> collect = orderList.stream().map(HisFlowOrderKcVO::getCpid).collect(Collectors.toList());
		ForeignUnsubscribeKcVO res = foreignApiService.getDetailByPhone(phone);
		log.info("collect = {}",collect);
		log.info("res = {}",res);
		if (collect == null || collect.size() == 0) {
			if (res != null) {
				if (StringUtils.isNotBlank(res.getCpid1())) {
					return R.data(res.getCpid1());
				} else if (StringUtils.isNotBlank(res.getCpid2())) {
					return R.data(res.getCpid2());
				} else if (StringUtils.isNotBlank(res.getCpid3())) {
					return R.data(res.getCpid3());
				}
			}
			//随机返回
			return R.data(random);
		}else {
			boolean iscp1 = false;
			boolean iscp2 = false;
			boolean iscp3 = false;
			if(res != null){
				for (String s : collect) {
					if(StringUtils.isNotBlank(res.getCpid1())&&s.equals(res.getCpid1())){
						iscp1 = true;
					}
					if(StringUtils.isNotBlank(res.getCpid2())&&s.equals(res.getCpid2())){
						iscp2 = true;
					}
					if(StringUtils.isNotBlank(res.getCpid3())&&s.equals(res.getCpid3())){
						iscp3 = true;
					}
					if(!iscp1){
						return R.data(res.getCpid1());
					}
					if(iscp1 && !iscp2){
						return R.data(res.getCpid2());
					}
					if(iscp1 && iscp2 && !iscp3){
						return R.data(res.getCpid3());
					}
					if(iscp1&&iscp2&&iscp3){
						return R.data(res.getCpid1());
					}
					if(!iscp1&&!iscp2&&!iscp3){
						//随机返回
						return R.data(random);
					}
				}
			}
			//随机返回
			return R.data(random);
		}
	}


	private String getIp(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
			int index = ip.indexOf(",");
			if (index != -1) {
				return ip.substring(0, index);
			} else {
				return ip;
			}
		}
		ip = request.getHeader("X-Real-IP");
		if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
			return ip;
		}
		ip = request.getHeader("WL-Proxy-Client-IP");
		if (StringUtils.isNotEmpty(ip) && !"unknown".equalsIgnoreCase(ip)) {
			return ip;
		}
		return request.getRemoteAddr();
	}


}

