package com.ruoyi.madridmark.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.madridmark.domain.CMadridmark;
import com.ruoyi.madridmark.mapper.CMadridmarkMapper;
import com.ruoyi.madridmark.service.ICMadridmarkService;
import com.ruoyi.madridmark.vo.CMadridmarkDTO;
import com.ruoyi.madridmark.vo.CMadridmarkVO;
import com.ruoyi.system.domain.BladeRegion;
import com.ruoyi.system.service.IBladeRegionService;

/**
 * 马德里商标Service业务层处理
 *
 * @author ruoyi
 * @date 2023-04-29
 */
@Service
public class CMadridmarkServiceImpl extends ServiceImpl<CMadridmarkMapper, CMadridmark> implements ICMadridmarkService {
	private static final Logger logger = LoggerFactory.getLogger(CMadridmarkServiceImpl.class);
	@Autowired
	private RuoYiConfig ruoYiConfig;
	@Autowired
	private IBladeRegionService bladeRegionService;
	@Autowired
	private CMadridmarkMapper cMadridmarkMapper;
	@Autowired
	private RedisCache redisCache;

	@Override
	public CMadridmarkDTO listReport(CMadridmark cMadridmark) {
		CMadridmarkDTO dto = new CMadridmarkDTO();
		dto.setList(new ArrayList<CMadridmarkVO>());
		Map<String, CMadridmarkVO> alreadyMap = new HashMap<String, CMadridmarkVO>();

		
		boolean retEmpty=false;
		if (StringUtils.isNotBlank(cMadridmark.getCityCode()) && !"53".equals(cMadridmark.getCityCode())) {
			String cityCode = cMadridmark.getCityCode().trim();
			if(SecurityUtils.isNeedFilterByCityCode()) {
				String cc=SecurityUtils.needFilterByCityCode();
				if(!cc.equals(cityCode) ) {
					retEmpty=true;
				}
			}
		}else {
			if(SecurityUtils.isNeedFilterByCityCode()) {
				String cityCode=SecurityUtils.needFilterByCityCode();
				cMadridmark.setCityCode(cityCode);
			}
		}
		
		List<Map> dataList =new ArrayList<Map>();
		if(!retEmpty) { 
			dataList = cMadridmarkMapper.listReport(cMadridmark);
		}

		Set<String> yearSet = new HashSet<String>();
		for (Map map : dataList) {
			yearSet.add(getStr(map, "reg_year"));
		}

	

		if (StringUtils.isNotBlank(cMadridmark.getBeginDate()) && StringUtils.isNotBlank(cMadridmark.getEndDate())
				&& Integer.parseInt(cMadridmark.getBeginDate()) <= Integer.parseInt(cMadridmark.getEndDate())) {
			int begin = Integer.parseInt(cMadridmark.getBeginDate().substring(0, 4));
			int end = Integer.parseInt(cMadridmark.getEndDate().substring(0, 4));
			for (int b = begin; b < end; b++) {
				yearSet.add((b+1) + "");
			}
		} else {
			int currYear = Integer.parseInt(new SimpleDateFormat("yyyy").format(new Date()));
			for (int i = 0; i < 6; i++) {
				yearSet.add((currYear - 5) + "");
			}
		}
		List<String> years = new ArrayList<String>();
		years.addAll(yearSet);
		Collections.sort(years, new Comparator<String>() {
			@Override
			public int compare(String o1, String o2) {
				return Integer.parseInt(o1) - Integer.parseInt(o2);
			}

		});

		dto.setYears(years);

		for (Map map : dataList) {

			String areaName = getStr(map, "modify_city");
			if (!alreadyMap.containsKey(areaName)) {
				CMadridmarkVO vo = new CMadridmarkVO();
				vo.setAreaName(areaName);
				alreadyMap.put(areaName, vo);
				vo.setTotals(new HashMap<String, Long>());
				for (String year : yearSet) {
					vo.getTotals().put(year, 0L);
				}
			}

			CMadridmarkVO vo = alreadyMap.get(areaName);
			String year = getStr(map, "reg_year");
			long oldCnt = 0L;
			if (vo.getTotals().containsKey(year)) {
				oldCnt = vo.getTotals().get(year);
			}
			long newCnt = getLong(map, "total_cnt");
			vo.getTotals().put(year, oldCnt + newCnt);

		}

		dto.getList().addAll(alreadyMap.values());

		return dto;
	}

	private String getStr(Map map, String key) {
		if (map == null || key == null || !map.containsKey(key)) {
			return "";
		}
		return map.get(key).toString();
	}

	private int getInt(Map map, String key) {
		if (map == null || key == null || !map.containsKey(key)) {
			return 0;
		}
		return Integer.parseInt(map.get(key).toString());
	}

	private long getLong(Map map, String key) {
		if (map == null || key == null || !map.containsKey(key)) {
			return 0;
		}
		return Long.parseLong(map.get(key).toString());
	}
	
	
	public CMadridmark queryByPid(String pid) {
		CMadridmark qo=new CMadridmark();
		qo.setPid(pid);
		List<CMadridmark>list=queryList(qo);
		if(list!=null && !list.isEmpty() &&  list.get(0)!=null) {
			return list.get(0);
		}
		return null;
	}

	public void doSyncForIprd(String beginDate, String endDate) {

		String baseUrl = ruoYiConfig.getPressApiServer() + "tm/iprd_tmwo?project_code=530000&ak=368394769%4020230406&time_update=" + beginDate + "&size=1000";

		String code = "200";
		String scroll_id = null;

		logger.debug("同步马德里商标之前先清空数据...");
		cMadridmarkMapper.clearData();
		
		int i = 0;
		while ("200".equals(code)) {
			String url = baseUrl;
			if (StringUtils.isNotBlank(scroll_id)) {
				url = baseUrl + "&scroll_id=" + scroll_id;
			}
			i++;
			logger.debug("开始查询第" + i + "页马德里商标基本数据,url:" + url);
			long beginTime = System.currentTimeMillis();
			String res = HttpUtils.sendGet(url);
			logger.debug("第" + i + "页基本数据查询结果,用时:" + (System.currentTimeMillis() - beginTime) + ",res:" + res);
			MadridmarkMod mod = new Gson().fromJson(res, MadridmarkMod.class);
			scroll_id = mod.scroll_id;
			code = mod.code;
			if (mod.results == null || mod.results.isEmpty()) {
				break;
			}
			for (MadridmarkItem ti : mod.results) {
				
				CMadridmark old = queryByPid(ti._id);
				CMadridmark t = ti.toCMadridmark();
//
				if (StringUtils.isNotBlank(t.getProvince())) {
					BladeRegion bladeRegion = bladeRegionService.selectByProvinceName(t.getProvince());
					if (bladeRegion != null) {
						t.setProvinceCode(bladeRegion.getCode());
					}
				}
//
				if (StringUtils.isNotBlank(t.getCity()) && StringUtils.isNotBlank(t.getProvinceCode())) {
					BladeRegion bladeRegion = bladeRegionService.selectByCityName(t.getCity(), t.getProvinceCode());
					if (bladeRegion != null) {
						t.setCityCode(bladeRegion.getCode());
					}
				}
//
				if (StringUtils.isNotBlank(t.getArea()) && StringUtils.isNotBlank(t.getCityCode())) {
					BladeRegion bladeRegion = bladeRegionService.selectByAreaName(t.getArea(), t.getCityCode());
					if (bladeRegion != null) {
						t.setAreaCode(bladeRegion.getCode());
					}
				}
//
//				if (StringUtils.isNotBlank(t.getModifyAppProvince())) {
//					BladeRegion bladeRegion = bladeRegionService.selectByProvinceName(t.getModifyAppProvince());
//					if (bladeRegion != null) {
//						t.setModifyAppProvinceCode(bladeRegion.getCode());
//					}
//				}
//
//				if (StringUtils.isNotBlank(t.getModifyAppCity()) && StringUtils.isNotBlank(t.getModifyAppProvinceCode())) {
//					BladeRegion bladeRegion = bladeRegionService.selectByCityName(t.getModifyAppCity(),
//							t.getModifyAppProvinceCode());
//					if (bladeRegion != null) {
//						t.setModifyAppCityCode(bladeRegion.getCode());
//					}
//				}
//
//				if (StringUtils.isNotBlank(t.getModifyAppCounty()) && StringUtils.isNotBlank(t.getModifyAppCityCode())) {
//					BladeRegion bladeRegion = bladeRegionService.selectByAreaName(t.getModifyAppCounty(),
//							t.getModifyAppCityCode());
//					if (bladeRegion != null) {
//						t.setModifyAppCountyCode(bladeRegion.getCode());
//					}
//				}

				t.setRegYearSrc(t.getRegYear());
				t.setRegYear(getModifyYear(t.getRegDate(), t.getRegYear()));

				if(old!=null) {
					t.setId(old.getId());
					t.setUpdateTime(new Date());
					updateById(t);
				}else {
					save(t);
				}
			}
		}

	}

	private String getModifyYear(String date, String year) {
		if (StringUtils.isBlank(date) || date.length() != 8) {
			return year;
		}
		int yearInt = Integer.parseInt(date.substring(0, 4));
		int dateInt = Integer.parseInt(date.substring(4, 8));
		if (dateInt >= 1216) {
			yearInt++;
		}
		return yearInt + "";

	}

	public static class MadridmarkMod {
		public String code;
		public Long total;
		public String scroll_id;
		public List<MadridmarkItem> results;
	}

	public static class MadridmarkItem {
//		 "_id": "9786d7d93f389412fedacdc4402bf63d",
		public String _id;
//	      "app": "KUNMING CITY DAN SHAN FLAVORING AND FOOD CO., LTD.",
		public String app;
//	      "country": "CN",
		public String country;
//	      "time_create": "20230417",
		public String time_create;
//	      "address": "INDUSTRIAL NEW VILLAGE, DABANQIAO TOWN, GUANDU DISTRICT INDUSTRIAL PARK, KUNMING YUNNAN",
		public String address;
//	      "reg_no": "1468977",
		public String reg_no;
//	      "reg_date": "20190327",
		public String reg_date;
//	      "property_end_date": "20290327",
		public String property_end_date;
//	      "time_update": "20230417",
		public String time_update;
//	      "province": "云南省",
		public String province;
//	      "nc": "30",
		public String nc;
//	      "name": "",
		public String name;
//	      "is_del": "0",
		public String is_del;
//	      "reg_year": "2019"
		public String reg_year;

		public CMadridmark toCMadridmark() {
			CMadridmark m = new CMadridmark();
//			 "_id": "9786d7d93f389412fedacdc4402bf63d",
			m.setPid(_id);
//		      "app": "KUNMING CITY DAN SHAN FLAVORING AND FOOD CO., LTD.",
			m.setApp(app);
//		      "country": "CN",
			m.setCountry(country);
//		      "time_create": "20230417",
			m.setTimeCreate(time_create);
//		      "address": "INDUSTRIAL NEW VILLAGE, DABANQIAO TOWN, GUANDU DISTRICT INDUSTRIAL PARK, KUNMING YUNNAN",
			m.setAddress(address);
//		      "reg_no": "1468977",
			m.setRegNo(reg_no);
//		      "reg_date": "20190327",
			m.setRegDate(reg_date);
//		      "property_end_date": "20290327",
			m.setPropertyEndDate(property_end_date);
//		      "time_update": "20230417",
			m.setTimeUpdate(time_update);
//		      "province": "云南省",
			m.setProvince(province);
//		      "nc": "30",
			m.setNc(nc);
//		      "name": "",
			m.setName(name);
//		      "is_del": "0",
			m.setIsDel(is_del);
//		      "reg_year": "2019"
			m.setRegYear(reg_year);

			return m;
		}

	}

	/**
	 * 查询马德里商标列表
	 *
	 * @param cMadridmark 马德里商标
	 * @return 马德里商标集合
	 * @date 2023-04-29
	 */
	@Override
	public List<CMadridmark> queryList(CMadridmark cMadridmark) {
		QueryWrapper<CMadridmark> queryWrapper = Wrappers.query();
		if (StringUtils.isNotEmpty(cMadridmark.getPid())) {
			queryWrapper.eq("pid", cMadridmark.getPid());
		}
		if (StringUtils.isNotEmpty(cMadridmark.getRegNo())) {
			queryWrapper.eq("reg_no", cMadridmark.getRegNo());
		}
		if (StringUtils.isNotEmpty(cMadridmark.getRegDate())) {
			queryWrapper.eq("reg_date", cMadridmark.getRegDate());
		}
		if (StringUtils.isNotEmpty(cMadridmark.getRegYear())) {
			queryWrapper.eq("reg_year", cMadridmark.getRegYear());
		}
		if (StringUtils.isNotEmpty(cMadridmark.getNc())) {
			queryWrapper.eq("nc", cMadridmark.getNc());
		}
		if (StringUtils.isNotNull(cMadridmark.getApp())) {
			queryWrapper.eq("app", cMadridmark.getApp());
		}
		if (StringUtils.isNotEmpty(cMadridmark.getAddress())) {
			queryWrapper.eq("address", cMadridmark.getAddress());
		}
		if (StringUtils.isNotEmpty(cMadridmark.getName())) {
			queryWrapper.like("name", cMadridmark.getName());
		}
		if (StringUtils.isNotEmpty(cMadridmark.getCountry())) {
			queryWrapper.eq("country", cMadridmark.getCountry());
		}
		if (StringUtils.isNotEmpty(cMadridmark.getProvince())) {
			queryWrapper.eq("province", cMadridmark.getProvince());
		}
		if (StringUtils.isNotEmpty(cMadridmark.getCity())) {
			queryWrapper.eq("city", cMadridmark.getCity());
		}
		if (StringUtils.isNotEmpty(cMadridmark.getArea())) {
			queryWrapper.eq("area", cMadridmark.getArea());
		}
		if (StringUtils.isNotEmpty(cMadridmark.getProvinceCode())) {
			queryWrapper.eq("province_code", cMadridmark.getProvinceCode());
		}
		if (StringUtils.isNotEmpty(cMadridmark.getCityCode())) {
			queryWrapper.eq("city_code", cMadridmark.getCityCode());
		}
		if (StringUtils.isNotEmpty(cMadridmark.getAreaCode())) {
			queryWrapper.eq("area_code", cMadridmark.getAreaCode());
		}
		if (StringUtils.isNotEmpty(cMadridmark.getPropertyEndDate())) {
			queryWrapper.eq("property_end_date", cMadridmark.getPropertyEndDate());
		}
		if (StringUtils.isNotEmpty(cMadridmark.getIsDel())) {
			queryWrapper.eq("is_del", cMadridmark.getIsDel());
		}
		if (StringUtils.isNotEmpty(cMadridmark.getTimeCreate())) {
			queryWrapper.eq("time_create", cMadridmark.getTimeCreate());
		}
		if (StringUtils.isNotEmpty(cMadridmark.getTimeUpdate())) {
			queryWrapper.eq("time_update", cMadridmark.getTimeUpdate());
		}
		if (StringUtils.isNotNull(cMadridmark.getStatus())) {
			queryWrapper.eq("status", cMadridmark.getStatus());
		}
		if (StringUtils.isNotNull(cMadridmark.getSysFileId())) {
			queryWrapper.eq("sys_file_id", cMadridmark.getSysFileId());
		}
		queryWrapper.orderByDesc("id");
		return this.list(queryWrapper);
	}

}
