package com.template.services.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.template.common.constanst.Constanst;
import com.template.common.utils.*;
import com.template.mapper.SmartUserMapper;
import com.template.mapper.WechatScanLoginMapper;
import com.template.model.pojo.SmartUser;
import com.template.model.tongji.*;
import com.template.model.weixin.AccessToken;
import com.template.model.weixin.HttpParame;
import com.template.model.weixin.WechatUserUnionID;
import com.template.services.WechatScanLoginService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>Title: WechatScanLoginServiceImpl</p>
 * <p>Description: 业务接口实现 </p>
 * @author fengyong
 * @date 2018年9月7日
 */
@Service
public class WechatScanLoginServiceImpl implements WechatScanLoginService {

	@Autowired
	public SmartUserMapper smartUserMapper;

	@Autowired
	public WechatScanLoginMapper wechatScanLoginMapper;

	/**
	 * <p>Title: wechatLoginUrl</p>
	 * <p>Description: 网页授权回调地址处理</p>
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@Override
	public Map<String, String> wechatLoginUrl() {
		String content = Constanst.PWD_MD5+DateUtils.getYYYYMMdd();
		byte[] encrypt = AesUtil.encrypt(content, AesUtil.PASSWORD_SECRET_KEY, 16);
		String parseByte2HexStr = AesUtil.parseByte2HexStr(encrypt);
		Map<String,String> map = new HashMap<String,String>();
		String url = HttpParame.AUTHORIZATION_URL;
		url = url.replaceAll("APPID", PropertiesUtil.getValue(HttpParame.APPID));
		try {
			url = url.replaceAll("REDIRECT_URI", URLEncoder.encode(
					PropertiesUtil.getValue(HttpParame.REDIRECT_URI),"UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		url = url.replaceAll("SCOPE", "snsapi_login");
		url = url.replace("STATE", parseByte2HexStr);	//加密state进行验证 回调地址当天有效 防止恶意攻击
		map.put("url", url);
		return map;
	}

	@Override
	public Map<String, String> wechatBindUrl(String phone,String messageCode) {
		String content = Constanst.PWD_MD5+ DateUtils.getYYYYMMdd();
		byte[] encrypt = AesUtil.encrypt(content, AesUtil.PASSWORD_SECRET_KEY, 16);
		String parseByte2HexStr = AesUtil.parseByte2HexStr(encrypt);
		Map<String,String> map = new HashMap<String,String>();
		String url = HttpParame.BIND_URL;
		url = url.replaceAll("APPID", PropertiesUtil.getValue(HttpParame.APPID));
		try {
			url = url.replaceAll("REDIRECT_URI", URLEncoder.encode(
					PropertiesUtil.getValue(HttpParame.BIND_URI)+"?phone="+phone+"&messageCode="+messageCode,"UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		//url = url.replaceAll("SCOPE", "snsapi_login");
		url = url.replaceAll("SCOPE", "snsapi_login");
		url = url.replace("STATE", parseByte2HexStr);	//加密state进行验证 回调地址当天有效 防止恶意攻击
		map.put("url", url);
		return map;
	}
	
	/**
	 * <p>Title: getAccessToken</p>
	 * <p>Description: 用户授权后获取用户唯一标识 </p>
	 * @param code
	 * @return
	 */
	@Override
	public AccessToken getAccessToken(String code) {
		String accessTokenUrl = HttpParame.ACCESS_TOKEN_URL;
		accessTokenUrl = accessTokenUrl.replaceAll("APPID", PropertiesUtil.getValue(HttpParame.APPID));
		accessTokenUrl = accessTokenUrl.replaceAll("SECRET", PropertiesUtil.getValue(HttpParame.SECRET));
		accessTokenUrl = accessTokenUrl.replaceAll("CODE", code);
		String responseContent = HttpClientUtils.getInstance().sendHttpGet(accessTokenUrl);
		if (responseContent == null || responseContent == "") {
			return null;
		}
		JSONObject parseObject = JSONObject.parseObject(responseContent);
		AccessToken accessToken = JSONObject.toJavaObject(parseObject, AccessToken.class);
		return accessToken;
	}

	/**
	 * <p>Title: getUserUnionID</p>
	 * <p>Description: 获取用户统一标识。针对一个微信开放平台帐号下的应用，
	 * 同一用户的unionid在多个应用中是唯一的。
	 * 此方法不牵扯到多个应用时候可以不用。
	 * 
	 * 此处用到只是为了获取微信扫码用户的省份城市(此信息获取的只是微信用户所填的城市省份，
	 * 并不是用户的实时位置信息，如果用户未填写是获取不到的。)
	 * </p>
	 * @return
	 */
	@Override
	public WechatUserUnionID getUserUnionID() {
		String unionIDUrl = HttpParame.GET_UNIONID_URL;
		unionIDUrl = unionIDUrl.replace("ACCESS_TOKEN", PropertiesUtil.getValue(HttpParame.ACCESS_TOKEN));
		unionIDUrl = unionIDUrl.replace("OPENID", PropertiesUtil.getValue(HttpParame.OPENID));
		String responseContent = HttpClientUtils.getInstance().sendHttpGet(unionIDUrl);
		if (responseContent == null || responseContent == "") {
			return null;
		}
		JSONObject parseObject = JSONObject.parseObject(responseContent);
		WechatUserUnionID userUnionID = JSONObject.toJavaObject(parseObject, WechatUserUnionID.class);
		return userUnionID;
	}

	@Override
	public SmartUser selectByOpenid(String openid){
		QueryWrapper<SmartUser> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq( "open_id", openid);
		List<SmartUser> users = smartUserMapper.selectList(queryWrapper);
		if (users==null || users.size()<=0){
			return null;
		}
		return users.get(0);
	}

	@Override
	public SmartUser selectByCardNo(String CardNo){
		QueryWrapper<SmartUser> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq( "card_no", CardNo);
		List<SmartUser> users = smartUserMapper.selectList(queryWrapper);
		if (users==null || users.size()<=0){
			return null;
		}
		return users.get(0);
	}

	@Override
	public int updateSmartUser(SmartUser sa) {
		int result = smartUserMapper.updateById(sa);
		return result;
	}

	// 用户类别统计
	@Override
	public List<Tj> getUserIdTj(){
		return wechatScanLoginMapper.getUserIdTj();
	}

	// 用户总数
	@Override
	public All getUserIdTjt(){
		return wechatScanLoginMapper.getUserIdTjt();
	}

	// 水表总计
	@Override
	public DAll getWaterTj(){
		return wechatScanLoginMapper.getWaterTj();
	}

	// 电表总计
	@Override
	public DAll getElcTj(){
		return wechatScanLoginMapper.getElcTj();
	}

	@Override
	public void insertMonthMeter(String month){
		List<EnergyTj> waterl = wechatScanLoginMapper.getWaterTjByMonAndBuild(month);
		List<EnergyTj> elcl = wechatScanLoginMapper.getElcTjByMonAndBuild(month);
		for (int i = 0; i < waterl.size(); i++) {
			EnergyTj e = wechatScanLoginMapper.getTjByMon(waterl.get(i).getName(),month,"0");
			if (e==null){
				waterl.get(i).setType(0);waterl.get(i).setDate(month);
				wechatScanLoginMapper.insertMonthMeter(waterl.get(i));
			} else {
				waterl.get(i).setId(e.getId());
				wechatScanLoginMapper.updateMonthMeter(waterl.get(i));
			}
		}
		for (int j = 0; j < elcl.size(); j++) {
			EnergyTj w = wechatScanLoginMapper.getTjByMon(elcl.get(j).getName(),month,"1");
			if (w==null){
				elcl.get(j).setType(1);elcl.get(j).setDate(month);
				wechatScanLoginMapper.insertMonthMeter(elcl.get(j));
			} else {
				elcl.get(j).setId(w.getId());
				wechatScanLoginMapper.updateMonthMeter(elcl.get(j));
			}
		}
	}

	@Override
	public void insertDayMeter(String day){
		List<EnergyTj> waterl = wechatScanLoginMapper.getWaterTjByDayAndBuild(day);
		List<EnergyTj> elcl = wechatScanLoginMapper.getElcTjByDayAndBuild(day);
		for (int i = 0; i < waterl.size(); i++) {
			EnergyTj w = wechatScanLoginMapper.getTjByDay(waterl.get(i).getName(),day,"0");
			if (w==null){
				waterl.get(i).setType(0);waterl.get(i).setDate(day);
				wechatScanLoginMapper.insertDayMeter(waterl.get(i));
			} else {
				waterl.get(i).setId(w.getId());
				wechatScanLoginMapper.updateDayMeter(waterl.get(i));
			}
		}
		for (int j = 0; j < elcl.size(); j++) {
			EnergyTj e = wechatScanLoginMapper.getTjByDay(elcl.get(j).getName(),day,"1");
			if (e==null){
				elcl.get(j).setType(1);elcl.get(j).setDate(day);
				wechatScanLoginMapper.insertDayMeter(elcl.get(j));
			} else {
				elcl.get(j).setId(e.getId());
				wechatScanLoginMapper.updateDayMeter(elcl.get(j));
			}
		}
	}

	// 每个月各水表数据
	@Override
	public List<MonthMeterDetail> getMonWater() throws ParseException {
		List<String> dates = TimeExchange2.getLastSevenMonth();
		List<MonthMeterDetail> lm = new ArrayList<>();
		for (int i = 0; i < dates.size(); i++) {
			MonthMeterDetail mm = new MonthMeterDetail();
			List<Tj> list = wechatScanLoginMapper.getMonWater(dates.get(i));
			mm.setDate(TimeExchange2.ToSimpleMonth(TimeExchange2.StringToDate(dates.get(i),"yyyy-MM"))+"月");
			mm.setLt(list);
			lm.add(mm);
		}
		return lm;
	}

	// 每个月各电表数据
	@Override
	public List<MonthMeterDetail> getMonElc() throws ParseException {
		List<String> dates = TimeExchange2.getLastSevenMonth();
		List<MonthMeterDetail> lm = new ArrayList<>();
		for (int i = 0; i < dates.size(); i++) {
			MonthMeterDetail mm = new MonthMeterDetail();
			List<Tj> list = wechatScanLoginMapper.getMonElc(dates.get(i));
			mm.setDate(TimeExchange2.ToSimpleMonth(TimeExchange2.StringToDate(dates.get(i),"yyyy-MM"))+"月");
			mm.setLt(list);
			lm.add(mm);
		}
		return lm;
	}

	// 区域能耗统计
	@Override
	public PageInfo<MeterMonthData> getMeterMonthPage(@Param("meterMonthData")MeterMonthData meterMonthData){
		List<MeterMonthData> list = wechatScanLoginMapper.getMeterMonthPage(meterMonthData);
		PageInfo<MeterMonthData> meterPageInfo = new PageInfo<>(list);
		return meterPageInfo;
	}

	// 实时抄表
	@Override
	public PageInfo<MeterMonthData> getMeterDayPage(@Param("meterMonthData")MeterMonthData meterMonthData){
		List<MeterMonthData> list = wechatScanLoginMapper.getMeterDayPage(meterMonthData);
		PageInfo<MeterMonthData> meterPageInfo = new PageInfo<>(list);
		return meterPageInfo;
	}
}
