package cn.timer.api.utils.aliyun;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;

import cn.timer.api.bean.qyzx.QyzxEmpLogin;
import cn.timer.api.bean.qyzx.businessService.QyzxRemainingQuantity;
import cn.timer.api.bean.qyzx.businessService.QyzxScene;
import cn.timer.api.bean.qyzx.businessService.QyzxUseRecord;
import cn.timer.api.config.enums.PinType;
import cn.timer.api.dto.qyzx.EntRegisterDto;

/**
 * aliyun阿里云短信服务
 * 
 * @author dsc
 *
 */
@Transactional
@Component
public class AliyunSMS {

	@Value("${config-8timer.Aliyun.PROJECT_NAME}")
	public String PROJECT_NAME;

	@Value("${config-8timer.Aliyun.REGION_ID}")
	public String REGION_ID;

	@Value("${config-8timer.Aliyun.ACCESSKEY_ID}")
	public String ACCESSKEY_ID;

	@Value("${config-8timer.Aliyun.SECRET}")
	public String SECRET;

	final static String CODE_NAME = "TemplateCode";// 短信模板代码参数名
	final static String TEMPLATE_PARAM = "TemplateParam";// 自定义参数
	final static String DOMAIN = "dysmsapi.aliyuncs.com";
	final static String VERSION = "2017-05-25";
	final static String ACTION_SEND = "SendSms"; // 发短信
	final static String ACTION_QUERY = "QuerySendDetails"; // 短信查询
	final static String PAGE_SIZE = "1";
	final static String CURRENT_PAGE = "1";

	/**
	 * 
	 * @param phone
	 * @param templateCode 1."身份验证验证码" 2."登录确认验证码" 3."登录异常验证码" 4."用户注册验证码"
	 *                     5."修改密码验证码" 6."信息变更验证码"
	 */
	@SuppressWarnings("deprecation")
	public List<Object> authCode(EntRegisterDto entRegisterDto,
			@RequestParam(required = false, defaultValue = "1") Integer templateCode, Integer code) {

		String phone = entRegisterDto.getPhone();

		QyzxRemainingQuantity quantity = null;
		Integer remainder = null;
		String orderNo = null;
		Integer orgCode = null;
//		if (templateCode != 4) {
//			orgCode = QyzxEmpLogin.builder().build()
//					.selectOne(new LambdaQueryWrapper<QyzxEmpLogin>().eq(QyzxEmpLogin::getPhone, phone)).getOrgId();
//			quantity = QyzxRemainingQuantity.builder().build()
//					.selectOne(new LambdaQueryWrapper<QyzxRemainingQuantity>()
//							.eq(QyzxRemainingQuantity::getOrgCode, orgCode).eq(QyzxRemainingQuantity::getPmid, 1)
//							.gt(QyzxRemainingQuantity::getRemainder, 0));
//			remainder = quantity.getRemainder();
//			Date date = quantity.getExpireDate();
//			orderNo = quantity.getOrderNo();
//
//			if (remainder == null || remainder <= 0) {
//				System.err.println("企业 " + orgCode + " :套餐余额不足,请充钱");
//				return null;
//			}
//			if (date != null && date.getTime() <= new Date().getTime()) {
//				System.err.println("企业 " + orgCode + " :短信套餐已过期");
//				return null;
//			}
//		}

//		QyzxUseRecord qyzxUseRecord = new QyzxUseRecord();

		DefaultProfile profile = DefaultProfile.getProfile(REGION_ID, ACCESSKEY_ID, SECRET);
		IAcsClient client = new DefaultAcsClient(profile);

		CommonRequest request = new CommonRequest();
		request.setMethod(MethodType.POST);
		request.setDomain(DOMAIN);
		request.setVersion(VERSION);
		request.setAction(ACTION_SEND);
		request.putQueryParameter("RegionId", REGION_ID);
		request.putQueryParameter("PhoneNumbers", phone);
		request.putQueryParameter("SignName", PROJECT_NAME);
		switch (templateCode) {
		case 1:
			request.putQueryParameter(CODE_NAME, PinType.AUTHENTICATION.getCode());
//			qyzxUseRecord.setScene(QyzxScene.MSG_AUTHENTICATION.getMessage());
			break;
		case 2:
			request.putQueryParameter(CODE_NAME, PinType.LOGIN_CONFIRMATION.getCode());
//			qyzxUseRecord.setScene(QyzxScene.MSG_LOGIN_CONFIRM.getMessage());
			break;
		case 3:
			request.putQueryParameter(CODE_NAME, PinType.LOGIN_ABNORMAL.getCode());
//			qyzxUseRecord.setScene(QyzxScene.MSG_LOGIN_CONFIRM.getMessage());
			break;
		case 4:
			request.putQueryParameter(CODE_NAME, PinType.REGISTER.getCode());
//			qyzxUseRecord.setScene(QyzxScene.MSG_REGISTER.getMessage());
			break;
		case 5:
			request.putQueryParameter(CODE_NAME, PinType.CHANGE_PASSWORD.getCode());
//			qyzxUseRecord.setScene(QyzxScene.MSG_CHANGE_PWD.getMessage());
			break;
		case 6:
			request.putQueryParameter(CODE_NAME, PinType.CHANGE_INFORMATION.getCode());
//			qyzxUseRecord.setScene(QyzxScene.MSG_CHANGE_IMP.getMessage());
			break;
		default:
			request.putQueryParameter(CODE_NAME, PinType.AUTHENTICATION.getCode());
//			qyzxUseRecord.setScene(QyzxScene.MSG_AUTHENTICATION.getMessage());
		}
		// 【8小时人事管家】验证码934169,您正在尝试修改登录密码,请妥善保管账户信息。
		request.putQueryParameter(TEMPLATE_PARAM, "{\"code\":\"" + code + "\"}");
		CommonResponse response = null;
		String a = null;
		try {
			response = client.getCommonResponse(request);
			a = response.getData();
//			System.err.println("response:"+a); // 短信服务响应内容
		} catch (ServerException e) {
			e.printStackTrace();
		} catch (ClientException e) {
			e.printStackTrace();
		}
		Integer id = null;
		if (a != null && a.contains("OK")) {
//			if (templateCode != 4) {
//				qyzxUseRecord.setOriginalTotalNum(remainder); // 原数量
//				qyzxUseRecord.setNowTotalNum(--remainder);
//				qyzxUseRecord.setUserPhone(phone);
//				qyzxUseRecord.setOrderNo(orderNo);
//				qyzxUseRecord.setUseNum(1);
//				qyzxUseRecord.setPmid(quantity.getPmid());
//				qyzxUseRecord.setCreateUser("System");
//				qyzxUseRecord.setOrgCode(orgCode);
//				qyzxUseRecord.insert();
//
//				id = qyzxUseRecord.getId();
//
//				quantity.setRemainder(remainder);
//				quantity.update(new LambdaUpdateWrapper<QyzxRemainingQuantity>()
//						.eq(QyzxRemainingQuantity::getOrgCode, orgCode).eq(QyzxRemainingQuantity::getOrderNo, orderNo));
//			}

			List<Object> list = new ArrayList<Object>();

			list.add(id);
			list.add(JSONObject.parseObject(response.getData()));
			return list;// 代表请求成功
		}

		return null;
	}

	/**
	 * 短信内容查询(短信发送日期,支持查询最近30天的记录)
	 */
	@SuppressWarnings("deprecation")
	public String QuerySendDetails(String phone, String date, String bizId) {
		DefaultProfile profile = DefaultProfile.getProfile(REGION_ID, ACCESSKEY_ID, SECRET);
		IAcsClient client = new DefaultAcsClient(profile);

		CommonRequest request = new CommonRequest();
		request.setMethod(MethodType.POST);
		request.setDomain(DOMAIN);
		request.setVersion(VERSION);
		request.setAction(ACTION_QUERY);
		request.putQueryParameter("RegionId", REGION_ID);
		request.putQueryParameter("PhoneNumber", phone);
		request.putQueryParameter("SendDate", date);
		request.putQueryParameter("PageSize", PAGE_SIZE);
		request.putQueryParameter("CurrentPage", CURRENT_PAGE);
		request.putQueryParameter("BizId", bizId);
		String a = null;
		try {
			CommonResponse response = client.getCommonResponse(request);

			a = response.getData();

		} catch (Exception e) {
			e.printStackTrace();
		}
		if (a != null && a.contains("OK")) {
			return a;// 代表请求成功
		}
		return "获取失败";
	}

	/**
	 * 提醒功能
	 * 
	 * @param name   用户名字
	 * @param htname 要提醒的东西的名字
	 * @param time   提醒的时间
	 * @param phone
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public String remind(String name, String htname, String time, String phone) {

		Integer orgCode = QyzxEmpLogin.builder().build()
				.selectOne(new LambdaQueryWrapper<QyzxEmpLogin>().eq(QyzxEmpLogin::getPhone, phone)).getOrgId();
		QyzxRemainingQuantity quantity = QyzxRemainingQuantity.builder().build()
				.selectOne(new LambdaQueryWrapper<QyzxRemainingQuantity>()
						.eq(QyzxRemainingQuantity::getOrgCode, orgCode).eq(QyzxRemainingQuantity::getPmid, 1)
						.orderByAsc(QyzxRemainingQuantity::getExpireDate));

		Integer remainder = quantity.getRemainder();
		Date date = quantity.getExpireDate();
		String orderNo = quantity.getOrderNo();

		if (quantity == null || remainder == null || remainder <= 0) {
			Logoutput("企业 " + orgCode + " :套餐余额不足,请充钱");
			return "请先充值购买短信套餐!";
		}
		if (date != null && date.getTime() <= new Date().getTime()) {
			Logoutput("企业 " + orgCode + " :短信套餐已过期");
			return "套餐已过期";
		}

		DefaultProfile profile = DefaultProfile.getProfile(REGION_ID, ACCESSKEY_ID, SECRET);
		IAcsClient client = new DefaultAcsClient(profile);

		CommonRequest request = new CommonRequest();
		request.setMethod(MethodType.POST);
		request.setDomain(DOMAIN);
		request.setVersion(VERSION);
		request.setAction(ACTION_SEND);
		request.putQueryParameter("RegionId", REGION_ID);
		request.putQueryParameter("PhoneNumbers", phone);
		request.putQueryParameter("SignName", PROJECT_NAME);
		request.putQueryParameter(CODE_NAME, PinType.REMIND.getCode());
		request.putQueryParameter(TEMPLATE_PARAM,
				"{\"name\":\"" + name + "\", \"htname\":\"" + htname + "\",\"time\":\"" + time + "\"}");

		String a = null;
		try {
			CommonResponse response = client.getCommonResponse(request);

			a = response.getData();

		} catch (ServerException e) {
			e.printStackTrace();
		} catch (ClientException e) {
			e.printStackTrace();
		}

		if (a != null && a.contains("OK")) {
			QyzxUseRecord qyzxUseRecord = new QyzxUseRecord();
			qyzxUseRecord.setOriginalTotalNum(remainder); // 原数量
			qyzxUseRecord.setNowTotalNum(--remainder);
			qyzxUseRecord.setUserPhone(phone);
			qyzxUseRecord.setOrderNo(orderNo);
			qyzxUseRecord.setScene(QyzxScene.MSG_REMIND.getMessage());
			qyzxUseRecord.setUseNum(1);
			qyzxUseRecord.setPmid(quantity.getPmid());
			qyzxUseRecord.setOrgCode(orgCode);
			qyzxUseRecord.insert();

			quantity.setRemainder(remainder);
			quantity.update(new LambdaUpdateWrapper<QyzxRemainingQuantity>()
					.eq(QyzxRemainingQuantity::getOrgCode, orgCode).eq(QyzxRemainingQuantity::getOrderNo, orderNo));

			return a;// 代表请求成功
		}
		return "发送失败";
	}

	@Value("${config-8timer.environmental-science}")
	public String environmental_science;
	
	public void Logoutput(String science) {
		
		if(!("pro").equals(environmental_science)) {
			
			System.out.println(science);
		}else {
			System.out.println("");
		}
		
	}
}