package com.reptileclient.jlifeapp.service.impl;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.reptileclient.jlifeapp.constant.HemaConstant;
import com.reptileclient.jlifeapp.constant.JlifeConstant;
import com.reptileclient.jlifeapp.dao.hm.HmTokenMapper;
import com.reptileclient.jlifeapp.dao.jz.JzShopMapper;
import com.reptileclient.jlifeapp.dao.jz.SysCityMapper;
import com.reptileclient.jlifeapp.entity.hm.HmToken;
import com.reptileclient.jlifeapp.entity.jz.JzShop;
import com.reptileclient.jlifeapp.entity.jz.SysCity;
import com.reptileclient.jlifeapp.service.JzShopService;
import com.reptileclient.jlifeapp.util.HttpUtil;
import com.reptileclient.jlifeapp.util.JsonUtil;

@Service
public class JzShopServiceImpl implements JzShopService {

	private static final Logger logger = LoggerFactory.getLogger(JzShopServiceImpl.class);
	@Autowired
	HmTokenMapper hmtk;

	@Autowired
	JzShopMapper jzShopMapper;

	@Autowired
	SysCityMapper sysCityMapper;

	public static RestTemplate restTemplate = new RestTemplate();

	@SuppressWarnings("unchecked")
	@Override
	public void getHmShop() {
		HmToken hm = hmtk.selectAll();
		List<SysCity> cityList = sysCityMapper.selectAll();
		List<JzShop> tempShopList=new ArrayList<JzShop>();

		String resultData = HttpUtil.requestGet(hm.getToken(), "{}", JlifeConstant.HM_STATION);
		logger.info("盒马门店数据："+resultData);

		List<Map<String, String>> dataList = JsonUtil.getEntity(resultData, List.class);
		for (Map<String, String> m : dataList) {
			String shopNo = m.get("shopCode");
			String shopName = m.get("shopName");
			//System.out.println(shop_no);
			//System.out.println(shop_name);

			//如果包含了 其中之一 就保存 北京上海深圳...
			//未处理 关闭，废弃 2种数据
			Integer cityId=findCityName(cityList, shopName);
			if (cityId>0){						
				JzShop jzShop=new JzShop();
				jzShop.setShopNo(shopNo);
				jzShop.setShopName(shopName);
				jzShop.setShopChannel(4);//4 盒马
				jzShop.setShopCity(cityId);

				tempShopList.add(jzShop);
			} 
		}

		logger.info("插入门店数"+tempShopList.size());
		jzShopMapper.beatchInsert(tempShopList);
		
		logger.info("update关闭和废弃的门店");
		jzShopMapper.updateCloseShop();

	}


	public Integer findCityName(List<SysCity> city,String shopName) {
		for(SysCity c:city) {
			if(shopName.contains(c.getCityName())) {
				return Integer.parseInt(c.getId().toString());
			}
		}
		
		return 0;
	}


}
