package com.ym.mec.collectfee.service.impl;

import com.alibaba.fastjson.JSON;
import com.thoughtworks.xstream.XStream;
import com.ym.mec.collectfee.common.dao.BaseDAO;
import com.ym.mec.collectfee.common.service.impl.BaseServiceImpl;
import com.ym.mec.collectfee.dao.OrderDao;
import com.ym.mec.collectfee.entity.*;
import com.ym.mec.collectfee.service.OrderService;
import com.ym.mec.collectfee.service.SchoolService;
import com.ym.mec.collectfee.utils.HttpUtil;
import com.ym.mec.collectfee.utils.XStreamUtil;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Random;

@Service
public class OrderServiceImpl extends BaseServiceImpl<Integer, Order> implements OrderService {
	
	@Autowired
	private OrderDao orderDao;
	@Autowired
	private SchoolService schoolService;

	//公共密钥
	private String publicKey = "e99a18c428cb38d5f260853678922e03";

	private String url = "http://101.200.2.249:9001/api/sys";

	@Override
	public BaseDAO<Integer, Order> getDAO() {
		return orderDao;
	}

	@Override
	public List<Order> getOrderByUserId(Integer userId) {
		return orderDao.getOrderByUserId(userId);
	}

	@Override
	public String pushOrder(String batchNum){
		try {
			RequestParamBean requestParamBean = new RequestParamBean();
			List<Order> orderList = orderDao.getOrderByBatch(batchNum);
			if(orderList == null || orderList.size() < 1){
				return null;
			}
			XStream xs = new XStream();
			xs.autodetectAnnotations(true);
			Writer writer = new StringWriter();
			Orders orders = new Orders(orderList);
			xs.toXML(orders,writer);
			String body = writer.toString();
			body = body.substring(body.indexOf("<body>")+6,body.indexOf("</body>"));

			body = Base64.getEncoder().encodeToString(body.getBytes());
			requestParamBean.setBody(body);
			requestParamBean.setHead(getOrdersHead(body,121512));

			xs.autodetectAnnotations(true);
			writer = new StringWriter();
			writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
			xs.toXML(requestParamBean,writer);
			return writer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private RequestHead getOrdersHead(String body,Integer cmd){
		RequestHead head = new RequestHead();
		head.setMsgId(getRandom(7));
		head.setCmd(cmd);
		head.setSign(getSign(head, body, publicKey));
		return head;
	}


	private String getSign(RequestHead head,String body,String userSign){
		//msgId+cmd+uid+ts+body+用户密钥/公共密钥
		StringBuffer sb = new StringBuffer(head.getMsgId());
		sb.append(head.getCmd()).append(head.getUid()).append(head.getTs()).append(body).append(userSign);
		return XStreamUtil.encryption(sb.toString()).toLowerCase();
	}

	@Override
	public int countOrder(String poName, String voicePort) {
		return orderDao.countOrder(poName,voicePort);
	}


	@Override
	public Order getOrderByOrderNo(String orderNo) {
		return orderDao.getOrderByOrderNo(orderNo);
	}

	@Override
	public Object getSchoolDetail(Integer schoolId,Integer clazzId) {
		try {
			RequestParamBean requestParamBean = new RequestParamBean();
			String body = "<schoolId>" + schoolId + "</schoolId><classId>" + clazzId + "</classId>";
			body = Base64.getEncoder().encodeToString(body.getBytes());
			requestParamBean.setBody(body);
			requestParamBean.setHead(getOrdersHead(body,124005));
			XStream xs = new XStream();
			xs.autodetectAnnotations(true);
			Writer writer = new StringWriter();
			writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
			xs.toXML(requestParamBean,writer);
			String parseBody = parseBody(HttpUtil.postXmlData(writer.toString(), url));
			ResponseCourseEntity xmlToObject = XStreamUtil.xmlToObject("body", ResponseCourseEntity.class, parseBody);
			return schoolService.upsetSchool(xmlToObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public String parseBody(String body){
		body = body.substring(body.indexOf("<body>")+6,body.indexOf("</body>"));
		return "<body><courses>" + new String(Base64.getDecoder().decode(body)) + "</courses></body>";
	}

	public static String getRandom(int length) {
		String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}
}