package com.huiju.estateagents.property.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.center.taUser.entity.TaUser;
import com.huiju.estateagents.center.taUser.mapper.TaUserMapper;
import com.huiju.estateagents.common.CommConstant;
import com.huiju.estateagents.common.wxpay.WXPay;
import com.huiju.estateagents.common.wxpay.WXPayConstants;
import com.huiju.estateagents.common.wxpay.WXPayUtil;
import com.huiju.estateagents.common.wxpay.WxConfig;
import com.huiju.estateagents.entity.TaPerson;
import com.huiju.estateagents.entity.TaWxPayConfig;
import com.huiju.estateagents.event.EventBus;
import com.huiju.estateagents.mapper.TaPersonMapper;
import com.huiju.estateagents.mapper.TaWxPayConfigMapper;
import com.huiju.estateagents.property.common.Constant;
import com.huiju.estateagents.property.common.UserElement;
import com.huiju.estateagents.property.dao.*;
import com.huiju.estateagents.property.exception.WisdomException;
import com.huiju.estateagents.property.model.*;
import com.huiju.estateagents.property.perproties.PayNotifyPerproties;
import com.huiju.estateagents.property.service.WxPayServiceI;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author FXF
 * @date 2018-10-25
 */
@Service("wxPayService")
@Transactional(rollbackFor = Exception.class)
public class WxPayServiceImpl implements WxPayServiceI {
	private Logger log = LoggerFactory.getLogger(WxPayServiceImpl.class);
	
	@Autowired
	private BillInvoiceMapper tpBillInvoiceMapper;
	
	@Autowired
	private BillStatementMapper tpBillStatementMapper;

	@Autowired
	private BillMapper tpBillMapper;

	@Autowired
	private TaPersonMapper taPersonMapper;

	@Autowired
	private TaSysRoleMapper taSysRoleMapper;

	@Autowired
	private MessageMapper tpMessageMapper;

	@Autowired
	private TpBillOrderMapper tpBillOrderMapper;

	@Autowired
	private TaUserVerifyMapper taUserVerifyMapper;

	@Autowired
	private TpBuildingOwnerInfoMapper tpBuildingOwnerInfoMapper;

	@Autowired
	private PayNotifyPerproties payNotifyPerproties;

//	@Autowired
//	private TaUserLicenseOrderMapper taUserLicenseOrderMapper;

	@Autowired
	private ApplicationContext applicationContext;

	@Autowired
	private TaWxPayConfigMapper taWxPayConfigMapper;

//	@Autowired
//	private IFuShiService iFuShiService;

//	@Autowired
//	private TaUserLicenseMapper taUserLicenseMapper;
//
//	@Autowired
//	private ITaUserLicenseService iTaUserLicenseService;

//	private IdGen idGen = IdGen.get();

	/**
	 * 微信支付统一下单
	 *
	 * @return
	 * @param orderNo
	 * @param
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Map<String, String> wxUnifiedOrder(String orderNo, String type, String personId, String clientIp) throws Exception {
		//构建微信配置
		WxConfig config = getWxConfig(1);
		WXPay wxpay = new WXPay(config);

		TaPerson person = taPersonMapper.selectById(personId);

		Map<String, Object> orderPriceAndNotifyUrl = getOrderPriceAndNotifyUrl(type, orderNo, "wx");

		String typeName = Constant.PAY_TYPE_BILL.equals(type) ? "物业缴费" : Constant.PAY_TYPE_CAR.equals(type) ? "车缴费" : "缴费";

		//下单
		Map<String, String> data = new HashMap<String, String>();
		data.put("body", typeName);
		//商品号唯一
		data.put("out_trade_no", orderNo);
		data.put("device_info", "");
		data.put("fee_type", "CNY");
		//金额 后台计算
		data.put("total_fee",String.valueOf(orderPriceAndNotifyUrl.get("payPrice")));
		//终端IP
		data.put("spbill_create_ip", clientIp);
		//回调地址
		data.put("notify_url", String.valueOf(orderPriceAndNotifyUrl.get("notifyUrl")));
		// 此处指定为APP支付
		data.put("trade_type", "JSAPI");
		//openid
		data.put("openid", person.getMiniOpenid());
		Map<String, String> resp = wxpay.unifiedOrder(data);
		log.info("下单成功：{}", resp);
		if (resp.get("result_code").equalsIgnoreCase(WXPayConstants.FAIL)){
			throw new Exception(resp.get("err_code_des"));
		}
		//插入下单记录表

		//第二次重新生成签名
		Map<String, String> secondSignData = new HashMap<String, String>();
		long timestamp = Instant.now().getEpochSecond();
		secondSignData.put("appId", config.getAppID());
		secondSignData.put("nonceStr", resp.get("nonce_str"));
		secondSignData.put("timeStamp", String.valueOf(timestamp));
		secondSignData.put("package", "prepay_id="+resp.get("prepay_id"));
		secondSignData.put("signType", WXPayConstants.SignType.MD5.toString());
		secondSignData.put("sign", WXPayUtil.generateSignature(secondSignData, config.getKey(), WXPayConstants.SignType.MD5));

		log.info("订单: {}，订单类型: {}, 状态变更为正在支付", orderNo, type);

		// 更改订单状态 为正在支付
		updateOrderStatus(orderNo, type, "2");
		return secondSignData;
	}

	/**
	 * 根据订单类型获取 金额 和 回调地址
	 * @param type
	 * @param orderNo
	 * @param notifyType wx 微信, ali 支付宝
	 * @return
	 * @throws Exception
	 */
	@Override
	public Map<String,Object> getOrderPriceAndNotifyUrl(String type, String orderNo, String notifyType) throws Exception {
		Map<String,Object> orderMap = Maps.newHashMap();

		// 物业缴费
		if (Constant.PAY_TYPE_BILL.equals(type)) {
			//获取支付金额
			List<TpBillOrder> billOrderList = tpBillOrderMapper.selectByOrderBumber(orderNo);
			if (CollectionUtils.isEmpty(billOrderList)){
				throw new Exception("订单不存在");
			}
			// 检测订单是否 已关闭
			billOrderList.forEach(e-> {
				if ("3".equals(e.getOrderStatus())) {
					throw new WisdomException("无法支付已关闭的订单!");
				}
			});
			// 计算金额
			Long payPrice = billOrderList.stream().mapToLong(e -> tpBillInvoiceMapper.selectById(e.getTpBillInvoiceId()).getPayPrice()).sum();
			orderMap.put("orderNo", orderNo);
			orderMap.put("payPrice", String.valueOf(payPrice));
			orderMap.put("notifyUrl", "wx".equals(notifyType) ? payNotifyPerproties.getWxBillNotify() : payNotifyPerproties.getAliBillNotify());

		} else if (Constant.PAY_TYPE_CAR.equals(type)) { // 车缴费
//			List<TaUserLicenseOrder> userLicenseOrders = taUserLicenseOrderMapper.selectByOrderNumber(orderNo);
//			if (CollectionUtils.isEmpty(userLicenseOrders)) {
//				throw new Exception("订单不存在");
//			}
//			// 检测订单是否 已关闭
//			userLicenseOrders.forEach(e-> {
//				if ("3".equals(e.getOrderStatus())) {
//					throw new WisdomException("无法支付已关闭的订单!");
//				}
//			});
//
//			// 总额
//			Long payPrice = userLicenseOrders.stream().map(e -> Long.parseLong(e.getExtensionPrice())).count();
//			orderMap.put("orderNo", orderNo);
//			orderMap.put("payPrice", String.valueOf(payPrice));
//			orderMap.put("notifyUrl", "wx".equals(notifyType) ? payNotifyPerproties.getWxCarNotify() : payNotifyPerproties.getAliCarNotify());
		}

		return orderMap;
	}




	/**
	 * 支付成功的回调
	 *
	 * @return
	 * @param resultMap
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public String wxBillNotify(Map<String, String> resultMap) throws Exception {
		String outTradeNo = resultMap.get("out_trade_no");
		List<TpBillOrder> billOrderList = tpBillOrderMapper.selectByOrderBumber(outTradeNo);
		if (CollectionUtils.isEmpty(billOrderList)){
			return "不存在的订单";
		}

		// 缴费人在准备支付状态下更新, 这里是微信的回调所有没有 token

		for ( TpBillOrder billOrder : billOrderList){
			BillInvoice tpBillInvoice = tpBillInvoiceMapper.selectById(billOrder.getTpBillInvoiceId());

			// 更新为正在支付状态
			// 更改收费单的 缴费时间, 修改人, 修改时间
			tpBillInvoice.setBillStatus("1");
			tpBillInvoice.setPayDate(new Date());
			tpBillInvoice.setUpdateDate(new Date());
			// 缴费方式  0：微信支付  1：线下缴费 2.支付宝支付
			tpBillInvoice.setPayType(resultMap.get("pay_type"));
			tpBillInvoice.setOutTradeNo(outTradeNo);
			tpBillInvoiceMapper.updateById(tpBillInvoice);
			// 同时加积分
			applicationContext.publishEvent(new EventBus(billOrder, EventBus.EventType.payment,1));

			//插入流水账单表
			BillStatement tpBillStatement = new BillStatement();
			tpBillStatement.setBillInvoiceId(tpBillInvoice.getId());
			tpBillStatement.setOrgId(billOrder.getOrgId());
			tpBillStatement.setTaUserId(tpBillInvoice.getTaUserId());
			tpBillStatement.setPayPrice(tpBillInvoice.getPayPrice());
			tpBillStatement.setPayName(tpBillInvoice.getPayName());
			tpBillStatement.setPayRemark(tpBillInvoice.getBillInvoiceExplain());
			tpBillStatement.setPayType(resultMap.get("pay_type"));
			tpBillStatement.setCreateTime(new Date());
			tpBillStatementMapper.insert(tpBillStatement);

			// 更新 收费单流水id
			tpBillInvoice.setBillStatementId(tpBillStatement.getId());
			tpBillInvoiceMapper.updateById(tpBillInvoice);

			// 更新收费组的 未交费用户数 和 已缴费用户数
			Bill tpBill = tpBillMapper.selectById(tpBillInvoice.getBillId());
			tpBill.setPayedNum(tpBill.getPayedNum() + 1);
			tpBill.setUnpayedNum(tpBill.getUnpayedNum() - 1);
			// 如果为零, 表示这个收费组收费完成
			if (tpBill.getUnpayedNum() <= 0) {
				tpBill.setBillStatus("1");
				tpBill.setUnpayedNum(0);
			}
			tpBillMapper.updateById(tpBill);

			// 把相对应的APP端, 代办消息设置为无效
//			Map<String, Object> map = Maps.newHashMap();
//			map.put("communityId", tpBillInvoice.getCommunityId());
//			map.put("billInvoiceId", tpBillInvoice.getId());
//			map.put("userId", tpBillInvoice.getTaUserId());
//			TpMessage tpMessage = tpMessageMapper.selectBillinvoiceMessage(map);
//			tpMessage.setStatus("0");
//			tpMessageMapper.updateByPrimaryKeySelective(tpMessage);
		}

		log.info("订单: {}，订单类型: {}, 状态变更为支付成功", outTradeNo, Constant.PAY_TYPE_BILL);

		// 更改订单状态 为支付成功
		updateOrderStatus(outTradeNo, Constant.PAY_TYPE_BILL, "1");

		    // 只取第一条根据订单号去匹配列表
		    TpBillOrder tpBillOrder = billOrderList.get(0);
			BillInvoice tpBillInvoice = tpBillInvoiceMapper.selectById(tpBillOrder.getTpBillInvoiceId());
//			List<TpUser> tpUserList= tpUserMapper.selectCommunityId(tpBillOrder.getCommunityId());
//
//			// 推物业端，推这个小区下的所有管理员
//			TaUser taUser= taUserMapper.selectByPrimaryKey(tpBillOrder.getCreateUser());
//			for (TpUser tpUser:tpUserList) {
//				Map<String, Object> mapProp = new HashMap<>();
//				mapProp.put("communityId", tpBillOrder.getCommunityId());
//				mapProp.put("tpUserId", tpUser.getId());
//				mapProp.put("createUserId", tpBillOrder.getCreateUser());
//				mapProp.put("billInvoiceId", tpBillOrder.getId());
//				mapProp.put("name", taUser.getUserName());
//				applicationContext.publishEvent(new MessageEvent(mapProp, Constant.PAY_TYPE_SUCCEED, mapProp));
//		}
		return "success";
	}
	
	/**
	 * 订单查询
	 *
	 * @return
	 */
	@Override
	public Map<String, String> wxOrderQuery(String outTradeNo) throws Exception {
		WxConfig config = getWxConfig(1);
		WXPay wxpay = new WXPay(config);
		
		Map<String, String> data = new HashMap<String, String>();
		data.put("out_trade_no", outTradeNo);
		return wxpay.orderQuery(data);
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public String wxStartPay(List<Integer> idArray, String type, Integer extensionMonth, String personId) throws Exception {
		if (StringUtils.isBlank(type)) {
			throw new WisdomException("type 不能为空！");
		}

		// 缴费的用户
		TaPerson taPerson = taPersonMapper.selectById(personId);

		Random random = new Random();
		String orderNo = String.valueOf(System.currentTimeMillis()) + random.nextInt();

		// 创建订单
		createOrder(idArray, type, taPerson, personId, orderNo, extensionMonth, null);

		return orderNo;
	}

	/**
	 * 创建订单
	 * @param idArray
	 * @param type
	 * @param orderNo
	 * @param extensionMonth 延期月份，也就是延期几个月！
	 *                       	只有在 车缴费的时候才有效
	 * @param paymentType 缴费方式 1是支付宝 2是微信支付
	 * @throws Exception
	 */
	private void createOrder(List<Integer> idArray, String type, TaPerson taPerson, String personId, String orderNo, Integer extensionMonth, String paymentType) throws Exception {
		// 物业缴费
		if (Constant.PAY_TYPE_BILL.equals(type)) {
			//获取支付金额
			for (Integer billInvoiceId : idArray) {
				BillInvoice tpBillInvoice = tpBillInvoiceMapper.selectById(billInvoiceId);
				if (null == tpBillInvoice){
					throw new Exception("订单不存在");
				}else if (!tpBillInvoice.getBillStatus().equals("0")){
					throw new Exception("正在支付的订单");
				}

				TpBillOrder tpBillOrder = new TpBillOrder();
				tpBillOrder.setOrgId(tpBillInvoice.getOrgId());
				tpBillOrder.setTpBillId(tpBillInvoice.getBillId());
				tpBillOrder.setTpBillInvoiceId(tpBillInvoice.getId());
				tpBillOrder.setCreateDate(LocalDateTime.now());
				tpBillOrder.setCreateUser(personId);
				tpBillOrder.setUpdateDate(LocalDateTime.now());
				tpBillOrder.setUpdateUser(personId);
				tpBillOrder.setOrderBumber(orderNo);
				tpBillOrder.setPayPhone(taPerson.getPhone());
				tpBillOrder.setOrderStatus("0");

				tpBillOrderMapper.insert(tpBillOrder);

			}
			// 修改缴费人, 修改为正在缴费
			updateBillInvoiceBillStatus(idArray, taPerson.getName(), "3");

			// 车缴费
		} else if (Constant.PAY_TYPE_CAR.equals(type)) {
//			if (null == extensionMonth || extensionMonth <= 0) {
//				throw new Exception("延期月份不能为空，并且要大于0!");
//			}
//
//			for (Integer clicenseId : idArray) {
//				// 根据车牌id，查询车牌
//				TaUserLicense taUserLicense = taUserLicenseMapper.selectByPrimaryKey(clicenseId);
//				// 获取车牌最新信息
//				ResponseBean responseLicense = iTaUserLicenseService.getLicense(userElement, taUserLicense.getLicensePlate());
//				Object licenseData = responseLicense.getData();
//				if (null != licenseData && licenseData instanceof TaUserLicense) {
//					taUserLicense = (TaUserLicense) licenseData;
//				}
//
//				// 校验车状态
//				if (taUserLicense.getLicenseType().intValue() != 1) {
//					throw new WisdomException("异常状态，不能缴月租费!");
//				}
//
//				// 校验是否，超出缴费有效期时间
//				LocalDateTime expireDateLocalDateTime = LocalDateTime.ofInstant(taUserLicense.getExpireDate().toInstant(), ZoneId.systemDefault());
//				expireDateLocalDateTime.plusDays(taUserLicense.getRenewTime());
//				if (taUserLicense.getRenewTime().intValue() > 0 && System.currentTimeMillis() > expireDateLocalDateTime.toEpochSecond(ZoneOffset.of("+8"))) {
//					throw new WisdomException("已超出续费时间，请找物业处理!");
//				}
//
//				TaUserLicenseOrder taUserLicenseOrder = new TaUserLicenseOrder();
//				taUserLicenseOrder.setCommunityId(userElement.getCommunityId());
//				taUserLicenseOrder.setTaUserId(userElement.getId());
//				taUserLicenseOrder.setOrderNumber(orderNo);
//				taUserLicenseOrder.setOrderStatus("0");
//				taUserLicenseOrder.setCreateDate(new Date());
//				taUserLicenseOrder.setCreateUser(userElement.getId());
//				taUserLicenseOrder.setExtensionMonth(extensionMonth);
//
//				// 费用
//				String extensionPrice = BigDecimal.valueOf(Double.valueOf(taUserLicense.getUnitPrice()) / 100).multiply(BigDecimal.valueOf(extensionMonth)).toString();
//				String price = String.valueOf(Double.valueOf(extensionPrice) * 100);
//				taUserLicenseOrder.setExtensionPrice(price.substring(0, price.lastIndexOf(".")));
//
//				taUserLicenseOrder.setPaymentTel(taUser.getLoginName());
//				taUserLicenseOrder.setPaymentName(taUser.getUserName());
//				taUserLicenseOrder.setPaymentType(paymentType);
//
//				// 到期时间 (具体的到期时候，在支付回调里面以车辆管理系统为准)
//				LocalDateTime localDateTime = LocalDateTime.ofInstant(taUserLicense.getExpireDate().toInstant(), ZoneId.systemDefault());
//				localDateTime.plusMonths(extensionMonth);
//				taUserLicenseOrder.setExpireDate(Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()));
//				taUserLicenseOrder.setUnitPrice(taUserLicense.getUnitPrice());
//				taUserLicenseOrder.setParkingLot(taUserLicense.getParkingLot());
//				taUserLicenseOrder.setLicensePlate(taUserLicense.getLicensePlate());
//
//				// 插入数据
//				taUserLicenseOrderMapper.insertSelective(taUserLicenseOrder);

//			}

		}
	}



	/**
	 * 取消支付
	 *
	 * @param outTradeNo
	 * @param
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void wxCancelPay(String outTradeNo, String type, String personId) throws Exception {

		/**
		 * 如果是车缴费订单，就只直接更新 订单状态为关闭
		 */
		// 如果是车缴费
//		if (Constant.PAY_TYPE_CAR.equals(type)) {
//			// 更改订单状态 为订单已关闭
//			updateOrderStatus(outTradeNo, type, "3");
//			return;
//		}

		// --------------------------- 物业缴费 --------------------------------

		//获取支付金额
		List<TpBillOrder> billOrderList = tpBillOrderMapper.selectByOrderBumber(outTradeNo);
		if (CollectionUtils.isEmpty(billOrderList)){
			throw new Exception("订单不存在");
		}

		List<BillInvoice> billInvoiceList = Lists.newArrayList();
		for (TpBillOrder tpBillOrder : billOrderList) {
			BillInvoice billInvoice = tpBillInvoiceMapper.selectById(tpBillOrder.getTpBillInvoiceId());
			if (!billInvoice.getBillStatus().equals("3")){
				throw new Exception("不是正在支付的订单");
			}
			billInvoiceList.add(billInvoice);
		}

		// 缴费单id集合
		List<Integer> billInvoiceIdList = billInvoiceList.stream().map(e -> e.getId()).collect(Collectors.toList());

		//更新为 未支付状态
		updateBillInvoiceBillStatus(billInvoiceIdList, "","0");
		log.info("订单: {}， 订单类型: {}, 状态变更为取消支付", outTradeNo, type);

		// 更改订单状态 为订单已关闭
		updateOrderStatus(outTradeNo, type, "3");

	}

	@Override
	public String wxCarNotify(Map<String, String> resultMap) {
//
//		String outTradeNo = resultMap.get("out_trade_no");
//		String pay_type = resultMap.get("pay_type");
//		String payTypeName = pay_type.equals("0") ? "微信支付" : pay_type.equals("2") ? "支付宝" : "未知";
//
//		List<TaUserLicenseOrder> userLicenseOrderList = taUserLicenseOrderMapper.selectByOrderNumber(outTradeNo);
//		if (CollectionUtils.isEmpty(userLicenseOrderList)){
//			return "不存在的订单";
//		}
//
//		log.info("订单：{},订单类型: {} 开始推送到 车辆管理系统 ", outTradeNo, Constant.PAY_TYPE_CAR);
//
//		TaUserLicenseOrder taUserLicenseOrder = userLicenseOrderList.get(0);
//		TaUser taUser = taUserMapper.selectByPrimaryKey(taUserLicenseOrder.getTaUserId());
//
//		ApiThirdPartyMonthCardPay apiThirdPartyMonthCardPay = new ApiThirdPartyMonthCardPay();
//		apiThirdPartyMonthCardPay.setPhone(taUser.getLoginName());
//		apiThirdPartyMonthCardPay.setRenewDayType("2");
//		apiThirdPartyMonthCardPay.setRenewDay(String.valueOf(taUserLicenseOrder.getExtensionMonth()));
//		apiThirdPartyMonthCardPay.setPayStyle(payTypeName);
//		apiThirdPartyMonthCardPay.setCarNo(taUserLicenseOrder.getLicensePlate());
//		apiThirdPartyMonthCardPay.setCardNo(null);
//		apiThirdPartyMonthCardPay.setRechargeAmt(String.valueOf(Double.valueOf(taUserLicenseOrder.getExtensionPrice()) / 100));
//		apiThirdPartyMonthCardPay.setDealNo(outTradeNo);
//
//		// 推送到车辆管理系统
//		iFuShiServer.apiThirdPartyMonthCardPay(JSONObject.toJSONString(apiThirdPartyMonthCardPay));
//
//		// 推送到车辆管理系统
////		iFuShiService.apiThirdPartyMonthCardPay(taUser.getLoginName(), "2",
////				String.valueOf(taUserLicenseOrder.getExtensionMonth()),
////				payTypeName, taUserLicenseOrder.getLicensePlate(),
////				null, String.valueOf(Double.valueOf(taUserLicenseOrder.getExtensionPrice()) / 100));
//
//
////		userLicenseOrderList.forEach(e-> {
////			UserElement userElement = new UserElement();
////			userElement.setCommunityId(e.getCommunityId());
////			userElement.setId(e.getTaUserId());
////			ResponseBean responseLicense = iTaUserLicenseService.getLicense(userElement, e.getLicensePlate());
////			Object licenseData = responseLicense.getData();
////			TaUserLicense taUserLicense = null;
////			if (null != licenseData && licenseData instanceof TaUserLicense) {
////				taUserLicense = (TaUserLicense) licenseData;
////				e.setExpireDate(taUserLicense.getExpireDate());
////			}
////			e.setPaymentType(pay_type);
////			e.setUpdateUser(e.getCreateUser());
////			e.setUpdateDate(new Date());
////			taUserLicenseOrderMapper.updateByPrimaryKeySelective(e);
////
////		});
//
//
//		log.info("订单: {}，订单类型: {}, 状态变更为支付成功", outTradeNo, Constant.PAY_TYPE_CAR);
//
//		// 更改订单状态 为支付成功
//		updateOrderStatus(outTradeNo, Constant.PAY_TYPE_CAR, "1");
//
//		// 推物业端，推这个小区下的所有管理员
//
//		List<TpUser> tpUserList = tpUserMapper.selectCommunityId(taUserLicenseOrder.getCommunityId());
//		for (TpUser tpUser : tpUserList) {
//			Map<String, Object> mapProp = new HashMap<>();
//			mapProp.put("communityId", taUserLicenseOrder.getCommunityId());
//			mapProp.put("tpUserId", tpUser.getId());
//			mapProp.put("createUserId", taUserLicenseOrder.getTaUserId());
//			mapProp.put("licenseOrderId", taUserLicenseOrder.getId());
//			mapProp.put("name", taUserLicenseOrder.getPaymentName());
//			mapProp.put("number", taUserLicenseOrder.getLicensePlate());
//			applicationContext.publishEvent(new MessageEvent(mapProp, Constant.PAY_MONTH_Bill_SUCCEED, mapProp));
//		}

		return "success";
	}

	/**
	 * 更新支付状态
	 * @param billInvoiceIdList
	 * @param status
	 */
	private void updateBillInvoiceBillStatus(List<Integer> billInvoiceIdList, String status) {
		billInvoiceIdList.forEach(e -> {
			BillInvoice tpBillInvoiceUpdate = new BillInvoice();
			tpBillInvoiceUpdate.setBillStatus(status);
			tpBillInvoiceUpdate.setId(e);
			tpBillInvoiceMapper.updateById(tpBillInvoiceUpdate);
		});

	}

	/**
	 * 更新支付状态
	 * @param billInvoiceIdList
	 * @param userName 缴费人
	 * @param status
	 */
	private void updateBillInvoiceBillStatus(List<Integer> billInvoiceIdList, String userName, String status) {
		billInvoiceIdList.forEach(e -> {
			BillInvoice tpBillInvoiceUpdate = new BillInvoice();
			tpBillInvoiceUpdate.setBillStatus(status);
			tpBillInvoiceUpdate.setId(e);
			tpBillInvoiceUpdate.setPayName(userName);
			tpBillInvoiceMapper.updateById(tpBillInvoiceUpdate);
		});
	}

	/**
	 * 更改订单状态
	 * @param orderNumber
	 * @param type
	 * @param status
	 */
	private void updateOrderStatus(String orderNumber, String type, String status){
		// 物业缴费
		if (Constant.PAY_TYPE_BILL.equals(type)) {
			List<TpBillOrder> billOrders = tpBillOrderMapper.selectByOrderBumber(orderNumber);
			billOrders.forEach(e-> {
				e.setOrderStatus(status);
				tpBillOrderMapper.updateById(e);
			});

			// 车缴费
		} else if (Constant.PAY_TYPE_CAR.equals(type)) {
//			List<TaUserLicenseOrder> taUserLicenseOrders = taUserLicenseOrderMapper.selectByOrderNumber(orderNumber);
//			taUserLicenseOrders.forEach(e-> {
//				e.setOrderStatus(status);
//				taUserLicenseOrderMapper.updateByPrimaryKeySelective(e);
//			});
		}
	}


	/**
	 * 获取每个小程序独立的微信账户
	 * @param orgId
	 * @return
	 */
	private WxConfig getWxConfig(Integer orgId) throws Exception {
		//根据orgId获取支付配置
		QueryWrapper<TaWxPayConfig> taWxPayConfigQueryWrapper = new QueryWrapper<>();
		taWxPayConfigQueryWrapper.eq("org_id",orgId);
		TaWxPayConfig taWxPayConfig = taWxPayConfigMapper.selectOne(taWxPayConfigQueryWrapper);
		if (null == taWxPayConfig){
			throw new Exception("请先完善支付信息");
		}
		log.info("正在配置orgId为{}的微信支付参数，商户号为{}",orgId,taWxPayConfig.getMchId());
		//把库里的值赋值给微信
		URL urlConet = new URL(taWxPayConfig.getApiPath());
		HttpURLConnection con = (HttpURLConnection)urlConet.openConnection();
		con.setRequestMethod("GET");
		con.setConnectTimeout(4 * 1000);
		InputStream inStream = con .getInputStream();
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[2048];
		int len = 0;
		while( (len=inStream.read(buffer)) != -1 ){
			outStream.write(buffer, 0, len);
		}
		inStream.close();

		WxConfig config = new WxConfig();
		config.setAppid(taWxPayConfig.getAppid());
		config.setMachId(taWxPayConfig.getMchId());
		config.setCertData(outStream.toByteArray());
		config.setKey(taWxPayConfig.getMchKey());
		return config;
	}
}
