package com.bcxin.ars.rest;

import com.bcxin.ars.dto.AjaxResult;
import com.bcxin.ars.dto.sb.OrderSearchDto;
import com.bcxin.ars.model.*;
import com.bcxin.ars.service.*;
import com.bcxin.ars.service.util.ArsUtil;
import com.bcxin.ars.util.*;
import com.bcxin.ars.util.message.messageUtils;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 
 * <b>订单相关</b>
 * 
 * @author LinQingLin
 * @date 2017年4月14日 下午6:39:23
 * @注意事项 </b>
 * <b>
 */
@Controller
@RequestMapping("order")
public class OrderController {

	private Logger logger = LoggerFactory.getLogger(OrderController.class);
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private OrderTransactionService transactionService;

	
	@Autowired
	private ConfigService configService;

	@Autowired
	private OrderPersonService orderPersonService;
	
	@Autowired
	private SecurityPersonService personService;
	
	@Autowired
	private ArsUtil arsUtil;

	@Value("${chinapay_b2b_url}")
	private String b2bUrl;
	
	@Value("${chinapay_b2c_url}")
	private String b2cUrl;

	@Value("${third_url}")
	private String thirdUrl;

	@Value("${channel}")
	private String channel;
	
	@Value("${callBackUrl}")
	private String callBackUrl;
	
	@Value("${callFrontUrl}")
	private String callFrontUrl;
	
	/**
	 * 
	 * <b>创建订单 </b> 
	 * 
	 * @param order
	 * @param personIds
	 * @return
	 * @author LinQingLin 
	 * @date 2017年4月14日 下午6:39:49
	 * @注意事项 </b>
	 * <b>
	 */
	@RequestMapping("save")
	public @ResponseBody AjaxResult createOrder(Order order,Long[] personIds) throws Exception{
		AjaxResult result = new AjaxResult();
		try {
			User user = arsUtil.getCurrentUser();

			if (user != null) {
				orderService.createOrder(order, personIds);
				result.setSuccessful(true);
				result.setData(order);
				
				/*new Thread(()->{
					//推送信息给分销平台保存 --start
					sendOrderInfoToFENXIAO(order);
					//推送信息给分销平台保存 ---end
		        }).start();*/
				
			} else {
				result.setSuccessful(false);
				result.setMsg("当前用户信息错误");
			}
		} catch (Exception e) {
			throw e;
		}
		return result;
	}
	
	/**
	 * 
	 * <b>Function </b> 跳转银联支付界面
	 * 
	 * @param orderId
	 * @return
	 * @author LinQingLin 
	 * @date 2017年4月14日 下午6:40:09
	 * @注意事项 </b>
	 * <b>
	 */
	@RequestMapping("b2bPay/{orderId}")
	public ModelAndView b2bPayByOrderId(@PathVariable Long orderId) throws Exception {
		ModelAndView view = new ModelAndView("redirect:"+thirdUrl);
		Order order = orderService.findById(orderId);

		String web_host = configService.findByKey("web_host").getValue();
		Config order_pay_test = configService.findByKey("order_pay_test");
		// 本地调试请打开此配置，切勿修改开发数据库中配置的地址，将扰乱其它环境！
//		rest_host= "http://justme070.xicp.net/ars-rest/";
		
		String transSign = MD5Util.string2MD5(channel+DateUtil.getCurrentDate());
		view.addObject("orderNo", order.getRandomOrderNo());
		if(order_pay_test != null && order_pay_test.getValue().equals("1")){
			view.addObject("payAmt", "0.01");
		}else{
			view.addObject("payAmt", order.getAmount());
		}
		view.addObject("transSign", transSign);
		view.addObject("channel", channel);
		view.addObject("callbackUrl", web_host + "/" + callBackUrl);
		view.addObject("callfrontUrl", web_host + "/" + callFrontUrl);
		view.addObject("product", order.getGoodsname());
		return view;
	}
	
	/**
	 * 
	 * <b>Function </b> 支付完成回调处理
	 * 
	 * @param request
	 * @param res
	 * @author LinQingLin 
	 * @date 2017年4月14日 下午6:40:29
	 * @注意事项 </b>
	 * <b>
	 */
	@RequestMapping("callBack")
	public void callBack(HttpServletRequest request, HttpServletResponse res) throws Exception {
		try {
			Map<String, String> respParam = getAllRequestParam(request);
			// 打印请求报文
			logger.debug(respParam.toString());
			
	        String orderNo = respParam.get("orderNo"); 
			String payStatus = respParam.get("payStatus");
			String transSign = respParam.get("transSign");
			
//			Order order = orderService.findByOrderNo(orderNo);
			Order order = orderService.findByRandomOrderNo(orderNo);
			OrderTransaction transaction = transactionService.findByOrderNo(order.getOrdernumber());
			String validateSign = MD5Util.string2MD5(channel + DateUtil.getCurrentDate());
			if ( !transSign.equals(validateSign)) {
				logger.debug("验证签名结果[失败]."); 
			} else {
				logger.debug("验证签名结果[成功].");
				if ( "1".equals(payStatus) ) {
					transaction.setPaystate("2");
					order.setPaystate("2");
					order.setOrderstate("4");
					//增加权限
//					Config coninsConfig = configService.findByKey(Constants.TRAIN);
					List<OrderPerson> orderPersons = orderPersonService.findListByOrderId(order.getId());
					for (OrderPerson orderPerson : orderPersons) {
						SecurityPerson person = personService.findById(orderPerson.getPersonid());
//						String url = coninsConfig.getValue() + ThirdPartyURL.ADDAUTH+"?identitynumber="+orderPerson.getIdentitynumber()
//						+"&groupid="+orderPerson.getGroupid()+"&name="+orderPerson.getName()
//						+"&mobile="+orderPerson.getPhone()+"&orderID="+order.getOrdernumber()
//						+"&startdate="+order.getEffectivestarttime()+"&enddate="+order.getEffectiveendtime()
//						+"&companyid="+person.getRelation().getCompany().getId()+"&companyname="+order.getCompanyname();
//						messageUtils.getJsonByInternet(url);
//						orderPerson.setSigntime(new Date());
//						orderPersonService.updateTrainInfo(orderPerson);
//						
//						//TODO
						if(order.getTraintype().equals("2")){//继续再教育 更新投保状态。
							if(StringUtil.isNotEmpty(person.getPersonType()) && person.getPersonType().equals("3")) {
								//押运人员
								person.setInsuranceAmount(person.getRelation().getCompany().getInsuranceEscortAmount());
							}else {
								person.setInsuranceAmount(person.getRelation().getCompany().getInsuranceAmount());
							}
							//person.setInsured(true);
							person.setUpdateTime(new Date());
							personService.updateBX(person);
						}
					}
					new Thread(()->{
						//推送信息给分销平台保存 --start
						orderService.sendOrderInfoToFENXIAO(order);
						//推送信息给分销平台保存 ---end
			        }).start();
				} else if ( "0".equals(payStatus) ){
					transaction.setPaystate("3");
					order.setPaystate("3");
					order.setOrderstate("2");
				}
				transactionService.update(transaction);
				orderService.update(order);
			}
		} catch (Exception e) {
			throw e;
		}
	}
	
	/**
	 * 
	 * <b>Function </b> 支付完成返回界面
	 * 
	 * @param request
	 * @param res
	 * @return
	 * @author LinQingLin 
	 * @date 2017年4月14日 下午6:40:47
	 * @注意事项 </b>
	 * <b>
	 */
	@RequestMapping("callFront")
	public ModelAndView callFront(HttpServletRequest request, HttpServletResponse res){
		String web_host = configService.findByKey("web_host").getValue();
		// 本地调试请打开此配置，切勿修改开发数据库中配置的地址，将扰乱其它环境！
//		web_host= "http://justme070.xicp.net/ars-web/";
		return new ModelAndView("redirect:"+web_host);
	}
	
	@RequestMapping("findAllByUserId")
	public @ResponseBody AjaxResult findAllByUserid(){
		AjaxResult result = new AjaxResult();
		try {
			User currentUser = arsUtil.getCurrentUser();
			List<Order> orders = orderService.findByUserid(currentUser.getId());
			result.setSuccessful(true);
			result.setData(orders);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	@RequestMapping("findAllByTrainorgid")
	public @ResponseBody AjaxResult findAllByTrainorgid(OrderSearchDto dto) throws Exception{
		AjaxResult result = new AjaxResult();
		try {
			User user = arsUtil.getCurrentUser();
			OrderSearchDto data = orderService.findByTrainorgid(dto);
			result.setSuccessful(true);
			result.setData(data);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	@RequestMapping("testinterface")
	public @ResponseBody AjaxResult test() throws Exception{
		AjaxResult result = new AjaxResult();

		List<OrderPerson> list =orderPersonService.findAll();
	    Config coninsConfig = configService.findByKey(Constants.TRAIN);
		for(int i =0;i<list.size();i++){
			String id = list.get(i).getIdentitynumber();
			String url = coninsConfig.getValue() + ThirdPartyURL.test+"?identitynumber="+list.get(i).getIdentitynumber()+"&groupid="+list.get(i).getGroupid();
			String resultStr = messageUtils.getJsonByInternet(url);
			JsonParser parser=new JsonParser();  //创建JSON解析器

			JsonObject object=(JsonObject) parser.parse(resultStr);  //创建JsonObject对象
			OrderPerson orderPerson = new OrderPerson();
			orderPerson.setIdentitynumber(list.get(i).getIdentitynumber());
			orderPerson.setGroupid(list.get(i).getGroupid());
			object.get("learnprogress").getAsString();
			orderPerson.setStudyprogress(object.get("learnprogress").getAsInt());
			orderPerson.setStudylong(object.get("learningtime").getAsInt());
			orderPerson.setVideonum(object.get("videonum").getAsInt());
			if(null!=object.get("endtime").getAsString()&&!"".equals(object.get("endtime").getAsString())){
				orderPerson.setEndtime(new SimpleDateFormat().parse(object.get("endtime").getAsString()));
			}
			orderPersonService.updateTrainInfo(orderPerson);
		}
		//保存分销商

		return null;
	}

	
	@RequestMapping("findDetail")
	public @ResponseBody AjaxResult findDetail(Long orderId) throws Exception{
		AjaxResult result = new AjaxResult();
		try {
			Order order = orderService.findById(orderId);
			result.setSuccessful(true);
			result.setData(order);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	@RequestMapping("getOrderPerson")
	public @ResponseBody AjaxResult getOrderPerson(Long orderId) throws Exception{
		AjaxResult result = new AjaxResult();
		try {
			List<OrderPerson> persons = orderPersonService.findListByOrderId(orderId);
			if(persons != null && persons.size() > 0){
				result.setSuccessful(true);
				result.setData(persons);
			}else{
				result.setSuccessful(false);
			}
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	

	@RequestMapping("orderCancel")
	public @ResponseBody AjaxResult orderCancel(Long orderId) throws Exception{
		AjaxResult result = new AjaxResult();
		try {
			orderService.orderCancel(orderId);
			result.setSuccessful(true);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	@RequestMapping("checkExistOrderByPersonIds")
	public @ResponseBody AjaxResult checkExistOrderByPersonIds(@RequestParam Long[] personIds,String traintype) throws Exception{
		AjaxResult result = new AjaxResult();
		try {
			result = orderService.checkExistOrderByPersonIds(personIds,traintype);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 初始化全部保安人员的继续再教育课程
	 * <b>Function </b> 
	 * 
	 * @return
	 * @throws Exception
	 * @author LinQingLin 
	 * @date 2017年11月10日 下午3:04:23
	 * @注意事项 </b>
	 * <b>
	 */
	@RequestMapping("personTrainInit")
	public @ResponseBody AjaxResult personTrainInit() throws Exception{
		AjaxResult result = new AjaxResult();
		try {
			orderService.personTrainInit();
			result.setSuccessful(true);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	
	/**
	 * 获取请求参数中所有的信息
	 * @param request
	 * @return
	 */
	private Map<String, String> getAllRequestParam(HttpServletRequest request) {
		Map<String, String> res = new HashMap<String, String>();
		Enumeration<?> temp = request.getParameterNames();
		if (null != temp) {
			while (temp.hasMoreElements()) {
				String en = (String) temp.nextElement();
				String value = request.getParameter(en);
				res.put(en, value);
				//在报文上送时，如果字段的值为空，则不上送<下面的处理为在获取所有参数数据时，判断若值为空，则删除这个字段>
				//System.out.println("ServletUtil类247行  temp数据的键=="+en+"     值==="+value);
				if (null == res.get(en) || "".equals(res.get(en))) {
					res.remove(en);
				}
			}
		}
		return res;
	}
}
