package cn.superdesk.uniorder.controller._wechat.accounting;

import cn.hutool.core.date.DateUtil;
import cn.superdesk.uniorder.common.constants.ResponseMsgConstants;
import cn.superdesk.uniorder.common.json.AnJsonUtils;
import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.common.enums.pay.UnifiedOrderPayTypeEnum;
import cn.superdesk.uniorder.controller.base.BaseController;
import cn.superdesk.uniorder.dao.entity.accounting.unified.customer.AccountingUnifiedCustomer;
import cn.superdesk.uniorder.dao.entity.base.UnifiedOrder;
import cn.superdesk.uniorder.dao.entity.organisation.SysEnterprise;
import cn.superdesk.uniorder.dao.entity.channel.UnifiedChannelSync;
import cn.superdesk.uniorder.dto.vo.accounting.unified.customer.DzMainWx;
import cn.superdesk.uniorder.dto.vo.accounting.unified.customer.statement.CustomerStatementOfAccountDetailVo;
import cn.superdesk.uniorder.dto.vo._function.select.SelectOptionUnifiedService;
import cn.superdesk.uniorder.dto.vo.unified.UnifiedEncouragePage;
import cn.superdesk.uniorder.dto.vo.wechat.*;
import cn.superdesk.uniorder.dubbo.consumer.accounting.customer.AccountingUnifiedCustomerDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.order.base.UnifiedOrderDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.channel.UnifiedChannelProfitSyncDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.channel.UnifiedChannelProfitXVirtDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.channel.UnifiedChannelSyncDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.marketing.UnifiedStatisticsVirtCommonDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.marketing.UnifiedStatisticsVirtDimMonthDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.sys.SysOderUserDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.organisation.SysEnterpriseDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.unified.*;
import cn.superdesk.uniorder.common.HttpClientUtils;
import cn.superdesk.uniorder.common.security.crypt.SuperdeskUniorderRsaUtils;
import cn.superdesk.uniorder.common.exception.utils.ExceptionUtils;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/***
 * 服务之窗 对账单
 * @author Administrator
 *
 */
@Slf4j
@RestController
@RequestMapping("/wechat")
public class WxBillController extends BaseController {

	@Autowired
	private UnifiedOrderDubboConsumerService   unifiedOrderDubboConsumerService;
	@Autowired
	private SysEnterpriseDubboConsumerService  sysEnterpriseDubboConsumerService;
	@Autowired
	private SysOderUserDubboConsumerService    sysOderUserDubboConsumerService;
	@Autowired
	private UnifiedServiceDubboConsumerService unifiedServiceDubboConsumerService;

	@Autowired
	private UnifiedEncourageDubboConsumerService          unifiedEncourageDubboConsumerService;
	@Autowired
	private UnifiedChannelProfitSyncDubboConsumerService  unifiedChannelProfitSyncDubboConsumerService;
	@Autowired
	private UnifiedChannelProfitXVirtDubboConsumerService unifiedChannelProfitXVirtDubboConsumerService;
	@Autowired
	private UnifiedChannelSyncDubboConsumerService        unifiedChannelSyncDubboConsumerService;

	@Autowired
	private WeixinNotifyInfoDubboConsumerService          weixinNotifyInfoDubboConsumerService;
	@Autowired
	private AccountingUnifiedCustomerDubboConsumerService   accountingUnifiedCustomerDubboConsumerService;

	@Autowired
	private UnifiedStatisticsVirtCommonDubboConsumerService   unifiedStatisticsVirtCommonDubboConsumerService;
	@Autowired
	private UnifiedStatisticsVirtDimMonthDubboConsumerService unifiedStatisticsVirtDimMonthDubboConsumerService;

//	@Autowired
//	UnifiedAreaDubboConsumerService unifiedAreaDubboConsumerService;
//	@Autowired
//	SysUserDubboConsumerService     sysUserDubboConsumerService;

	/**
	 * #[服务之窗-统一支付 接口 ---- 支付]
	 */
	@Value("${unified.dzman.wx.pay.apiurl}")
	private String SUPERDESK_UNIPAY_WXPAY_API_URL;
	/**
	 * #[服务之窗-统一支付 接口 ---- 订单支付状态 查询]
	 */
	@Value("${unified.dzman.wx.pay.orderquery}")
	private String SUPERDESK_UNIPAY_ORDER_QUERY_API_URL;
	/**
	 * #[统一订单-callback 当服务之窗 统一支付 返回结果]
	 */
	@Value("${unified.dzman.wx.pay.notifyurl}")
	private String UNIORDER_WXPAY_RESULT_NOTIFY_URL;
	/**
	 * #[微信前端-支付结果页面]
	 */
	@Value("${unified.dzman.wx.pay.backurl}")
	private String UNIORDER_WXPAY_FRONT_RESULT_PAGE_URL;

	/***
	 * 企业账单
	 * @return
	 */
	@PostMapping("/getvirtbill")
	@ResponseBody
	public R<WxBillVirt> getVirtBill(Long virtId, int syear, String serviceNo) {

		R<WxBillVirt> result = new R<>();

		try {

			WxBillVirt billVirt = new WxBillVirt();

			// 消费总额
			Map<String, Object> map = new HashMap<>();
			map.put("onlyyear", syear);
			map.put("virtId", virtId);
			map.put("groupserviceNo", serviceNo);

			BigDecimal amount = unifiedOrderDubboConsumerService.getAmount(map);

			if (amount == null) {
				amount = new BigDecimal(0);
			}

			billVirt.setAmount(amount);


			// 待付款总额
			Map<String, Object> upaymap = new HashMap<>();
			upaymap.put("onlyyear", syear);
			upaymap.put("virtId", virtId);
			upaymap.put("groupserviceNo", serviceNo);

			BigDecimal payamount = unifiedOrderDubboConsumerService.getPayAmount(upaymap);

			if (payamount == null) {
				payamount = new BigDecimal(0);
			}

			billVirt.setUpayamount(amount.subtract(payamount));
			billVirt.setVirtId(virtId);

			SysEnterprise se = sysEnterpriseDubboConsumerService.findByVirtId(virtId);

			billVirt.setVirtName(se.getEnterpriseName());

			List<WxBillVirtItem> items = new ArrayList<>();

			for (int i = 1; i <= 12; i++) {

				WxBillVirtItem item = new WxBillVirtItem();

				Map<String, Object> itemmap = new HashMap<>();

				itemmap.put("onlyyear", syear);
				itemmap.put("virtId", virtId);
				itemmap.put("groupserviceNo", serviceNo);
				itemmap.put("onlymonth", i);

				BigDecimal iamount = unifiedOrderDubboConsumerService.getAmount(itemmap);

				if (iamount == null) {
					iamount = new BigDecimal(0);
				}

				item.setAmount(iamount);
				item.setMonth(i);

				BigDecimal ipayamount = unifiedOrderDubboConsumerService.getPayAmount(itemmap);

				if (ipayamount == null) {
					ipayamount = new BigDecimal(0);
				}

				item.setUpayamount(iamount.subtract(ipayamount));
				item.setYear(syear);

				items.add(item);

			}

			billVirt.setItems(items);

			// WxBillVirt detail = unifiedOrderDubboConsumerService.getVirtBill(virtid,syear);
			result.setData(billVirt);

		} catch (Exception e) {

			result.setCode(String.valueOf(e.hashCode()));
			result.setSuccess(false);
			result.setMessage(e.getMessage());

			log.error(ExceptionUtils.getMessage(e));
			e.printStackTrace();
		}

		return result;
	}

	/***
	 * 获取业务类型
	 * @return
	 */
	@PostMapping("/getservicetype")
	@ResponseBody
	public R<List<SelectOptionUnifiedService>> getServiceType(Long virtId) {

		R<List<SelectOptionUnifiedService>> result = new R<>();

		try {

			Map<String, Object> params = new HashMap<>();
			params.put("virtId", virtId);
			List<SelectOptionUnifiedService> ls = unifiedServiceDubboConsumerService.getSelectByVirt(params);

			result.setData(ls);
			result.setSuccess(true);

		} catch (Exception e) {

			result.setCode(String.valueOf(e.hashCode()));
			result.setSuccess(false);
			result.setMessage(e.getMessage());

			log.error(ExceptionUtils.getMessage(e));
			e.printStackTrace();

			e.printStackTrace();
		}

		return result;
	}

	/***
	 * 企业订单
	 * @return
	 */
	@PostMapping("/getvirtorder")
	@ResponseBody
	public R<List<WxBillOrder>> getVirtOrder(Long virtId, int syear, int month, String serviceNo) {

		R<List<WxBillOrder>> result = new R<>();

		try {

			Map<String, Object> params = new HashMap<>();

			params.put("onlyyear", syear);
			params.put("virtId", virtId);
			params.put("groupserviceNo", serviceNo);
			params.put("onlymonth", month);

			List<WxBillOrder> detail = unifiedOrderDubboConsumerService.getVirtOrder(params);

			result.setData(detail);

		} catch (Exception e) {

			result.setCode(String.valueOf(e.hashCode()));
			result.setSuccess(false);
			result.setMessage(e.getMessage());

			log.error(ExceptionUtils.getMessage(e));
			e.printStackTrace();

		}

		return result;
	}

	/***
	 * TODO 微信端-渠道商账单首页
	 * @return
	 */
	@PostMapping("/getchanneldata")
	@ResponseBody
	public R<WxChannelDetail> getChannelData(Long channelId, String year, String month) {

		R<WxChannelDetail> result = new R<>();

		try {

			WxChannelDetail detail = new WxChannelDetail();

			UnifiedChannelSync channelSync = unifiedChannelSyncDubboConsumerService.findUnifiedChannelSyncByChannelId(channelId);
			if (channelSync == null) {
				result.setSuccess(false);
				result.setMessage("渠道商信息获取失败！");
				return result;
			}

			detail.setChannelName(channelSync.getChannelName());
			detail.setCode(channelSync.getCode());

			Map<String, Object> amountProfitQuery = new HashMap<>();

			amountProfitQuery.put("onlyyear", year);
			amountProfitQuery.put("onlymonth", month);
			amountProfitQuery.put("channelId", channelId);

			// 累计分润金额
			BigDecimal amountProfit = unifiedEncourageDubboConsumerService.getAmountProfit(amountProfitQuery);
			// 激励金额
			BigDecimal amountEncourage = unifiedEncourageDubboConsumerService.getAmountEncourage(amountProfitQuery);
			// 回款金额
			BigDecimal amountBack = unifiedEncourageDubboConsumerService.getAmountBack(amountProfitQuery);
			// 累计推广金额
			BigDecimal amount = unifiedEncourageDubboConsumerService.getOrderAmount(amountProfitQuery);


			if (amountProfit == null) {
				amountProfit = new BigDecimal(0);
			}
			if (amountEncourage == null) {
				amountEncourage = new BigDecimal(0);
			}
			if (amountBack == null) {
				amountBack = new BigDecimal(0);
			}
			if (amount == null) {
				amount = new BigDecimal(0);
			}

//			if(amountBack.doubleValue()!=0&&amount.doubleValue()!=0){
//				double comCash= amountProfit.doubleValue()*amountBack.doubleValue()/amount.doubleValue() + amountEncourage.doubleValue();
//				detail.setAmountCash(new BigDecimal(comCash));//可提现
//			}else{
//				detail.setAmountCash(new BigDecimal(0));//可提现
//			}


			// 这个计数方式 是错的吧
			Integer virtCount = unifiedEncourageDubboConsumerService.getVirtCountByChannelId(amountProfitQuery);

			detail.setVirtCount(virtCount);
			detail.setAmount(amount);

			//Map<String,Object> amountGetCashQuery = new HashMap<>();
			BigDecimal amountGetCash = unifiedEncourageDubboConsumerService.getAmountGetCash(amountProfitQuery);

			if (amountGetCash == null) {
				amountGetCash = new BigDecimal(0);
			}

			detail.setAmountGetCash(amountGetCash);
			detail.setAmountProfit(amountProfit.add(amountEncourage));//累计可分润
			detail.setChannelId(channelId);

			if (StringUtils.isNotEmpty(month)) {
				detail.setSearchMonth(Integer.parseInt(month));
			}

			detail.setSearchYear(Integer.parseInt(year));

			List<WxChannelItemList> channelItemList = unifiedEncourageDubboConsumerService.getChannelItemList(amountProfitQuery);


			List<Long> channelIdXVirts = unifiedChannelProfitXVirtDubboConsumerService.getVirtsByChannelId(channelId);

			log.info("返回的企业ids", AnJsonUtils.toJson(channelIdXVirts));

//			virtCount = channelIdXVirts.size();

			// TODO 不改原来的逻辑了
			// 在这再查一下渠道 X 企业 过滤一下吧
//			List<WxChannelItemList> filterChannelItemList = channelItemList.stream().filter(info -> channelIdXVirts.contains(info.getVirtId())).collect(Collectors.toList());

			List<WxChannelItemList> filterChannelItemList = channelItemList.stream().filter(info -> info.getVirtId() != null).collect(Collectors.toList());


			log.info("channelItemList.size:", channelItemList.size());
			log.info("filterChannelItemList.size:", filterChannelItemList.size());


			// 可提现
			double cashAmount = amountEncourage.doubleValue();

//			for (WxChannelItemList item : channelItemList)
			for (WxChannelItemList item : filterChannelItemList) {
				if (item.getAmount() != null
						&& item.getAmount().doubleValue() > 0
						&& item.getAmountBack() != null
						&& item.getAmountBack().doubleValue() > 0
						&& item.getAmountProfit() != null
						&& item.getAmountProfit().doubleValue() > 0) {

					item.setAmountCash(
							new BigDecimal(item.getAmountProfit().doubleValue() * item.getAmountBack().doubleValue() / item.getAmount().doubleValue())
					);

					cashAmount += item.getAmountCash().doubleValue();
				}
			}

			detail.setAmountCash(new BigDecimal(cashAmount));
//			detail.setChannelItemList(channelItemList);
			detail.setChannelItemList(filterChannelItemList);

			List<UnifiedEncouragePage> unifiedEncourageList = unifiedEncourageDubboConsumerService.getEncourageList(amountProfitQuery);

			detail.setUnifiedEncourageList(unifiedEncourageList);

			result.setData(detail);

		} catch (Exception e) {

			result.setCode(String.valueOf(e.hashCode()));
			result.setSuccess(false);
			result.setMessage(e.getMessage());

			log.error(ExceptionUtils.getMessage(e));
			e.printStackTrace();

			e.printStackTrace();
		}

		return result;
	}

	/***
	 * 微信端 --- 支付对帐单页面 --- 查看对帐单支付详情-调取 服务之窗 统一支付
	 * @return
	 */
	@PostMapping("/dzmaindetail")
	@ResponseBody
	public R<CustomerStatementOfAccountDetailVo> getDzmainDetail(String urlContent) {

		R<CustomerStatementOfAccountDetailVo> result = new R<>();

		try {
			Map<String, String> param = new HashMap<>();

			String decodestr = SuperdeskUniorderRsaUtils.decode(urlContent);

			log.info("微信端 --- 支付对帐单页面 --- 查看对帐单支付详情 --- id :" + decodestr);

			CustomerStatementOfAccountDetailVo viewDzMain = accountingUnifiedCustomerDubboConsumerService.getCustomerStatementOfAccountDetailDimOrder2Goods(Long.parseLong(decodestr));

			result.setData(viewDzMain);
			result.setSuccess(true);

		} catch (Exception e) {

			result.setCode(String.valueOf(e.hashCode()));
			result.setSuccess(false);
			result.setMessage(e.getMessage());

			log.error(ExceptionUtils.getMessage(e));
			e.printStackTrace();
		}

		return result;
	}

	/***
	 * 微信支付-调取服务之窗统一支付
	 * @return
	 */
	@PostMapping("/wechatpay")
	@ResponseBody
	public R<String> wechatPay(String urlContent) {

		R<String> result = new R<>();

		try {


			String decodestr = SuperdeskUniorderRsaUtils.decode(urlContent);

			CustomerStatementOfAccountDetailVo viewDzMain = accountingUnifiedCustomerDubboConsumerService.getCustomerStatementOfAccountDetailDimOrder2Goods(Long.parseLong(decodestr));


			// 服务之窗 统一支付 查询
			Map<String, String> requestUniPayOrderQuery = new HashMap<>();
			requestUniPayOrderQuery.put("orderNo", viewDzMain.getAccountingOrderSn());

			String responseUniPayOrderQuery = HttpClientUtils.doPost(SUPERDESK_UNIPAY_ORDER_QUERY_API_URL, requestUniPayOrderQuery);


//			参考文档 : https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_2
//			交易状态	trade_state
//			SUCCESS-支付成功
//			REFUND-转入退款
//			NOTPAY-未支付
//			CLOSED-已关闭
//			REVOKED-已撤销(付款码支付)
//			USERPAYING-用户支付中(付款码支付)
//			PAYERROR-支付失败(其他原因,如银行返回失败)
//			支付状态机请见下单API页面


//			SUCCESS-支付成功
//			REFUND-转入退款
//			NOTPAY-未支付
//			CLOSED-已关闭
//			REVOKED-已撤销
//			USERPAYING-用户支付中
//			PAYERROR-支付失败
//			{
//				"code": 500,
//					"msg": "订单不存在"
//			}
//
//			{
//				"code": 200,
//					"msg": "未支付",
//					"data": "NOTPAY"
//			}
//
//			{
//				"code": 200,
//					"msg": "支付成功",
//					"data": "SUCCESS"
//			}

			/**
			 * 查询订单状态后 是否中断 微信支付
			 */
			boolean isSuspend = false;

			// 1. 得有返回
			if (StringUtils.isNoneBlank()) {

				JSONObject jsonObject = JSONObject.parseObject(responseUniPayOrderQuery);

				if (jsonObject.getInteger("code").equals(200)) {


					switch (jsonObject.getString("data")) {

						case "SUCCESS": // 支付成功

							isSuspend = true;
							result.setSuccess(false);
							result.setMessage("调取-服务之窗-统一支付-查询订单状态-" + jsonObject.getString("msg") + "-orderNo : " + viewDzMain.getAccountingOrderSn());

							// TODO 修正这个对帐单的支付?

							break;
						case "REFUND": // 转入退款

							isSuspend = true;
							result.setSuccess(false);
							result.setMessage("调取-服务之窗-统一支付-查询订单状态-" + jsonObject.getString("msg") + "-orderNo : " + viewDzMain.getAccountingOrderSn());

							break;
						case "NOTPAY": //未支付


							break;
						case "CLOSED": //已关闭

							isSuspend = true;
							result.setSuccess(false);
							result.setMessage("调取-服务之窗-统一支付-查询订单状态-" + jsonObject.getString("msg") + "-orderNo : " + viewDzMain.getAccountingOrderSn());

							break;
						case "REVOKED": //已撤销

							isSuspend = true;
							result.setSuccess(false);
							result.setMessage("调取-服务之窗-统一支付-查询订单状态-" + jsonObject.getString("msg") + "-orderNo : " + viewDzMain.getAccountingOrderSn());

							break;
						case "USERPAYING": //用户支付中

							isSuspend = true;
							result.setSuccess(false);
							result.setMessage("调取-服务之窗-统一支付-查询订单状态-" + jsonObject.getString("msg") + "-orderNo : " + viewDzMain.getAccountingOrderSn());

							break;
						case "PAYERROR": //支付失败


							break;
						default:
							break;
					}

				} else {


					result.setSuccess(false);
					result.setData(jsonObject.getString("data"));
					result.setMessage(jsonObject.getString("msg"));
				}
			} else {
				result.setSuccess(false);
				result.setMessage("调取-服务之窗-统一支付-查询订单状态-失败-接口未返回信息-orderNo : " + viewDzMain.getAccountingOrderSn());
			}

			if (isSuspend) {
				log.info("中断!不发起微信支付\n" + AnJsonUtils.toPrettyJson(result));
				return result;
			}


			// 服务之窗 统一支付 支付 init&call start
			Map<String, String> requestUniPayWxPay = new HashMap<>();
			requestUniPayWxPay.put("orgId", viewDzMain.getProjectId().toString());
			requestUniPayWxPay.put("orderNo", viewDzMain.getAccountingOrderSn());
			requestUniPayWxPay.put("orderFee", (viewDzMain.getAccountingAmount().doubleValue() * 100) + "");
			// param.put("openid",openid);
			requestUniPayWxPay.put("orderDesc", "统一订单系统微信支付");
			requestUniPayWxPay.put("notifyUrl", UNIORDER_WXPAY_RESULT_NOTIFY_URL);
			requestUniPayWxPay.put("orderSource", "TYDD");
			requestUniPayWxPay.put("orderModule", "TYZF");
			// 支付完成 跳转页面
			requestUniPayWxPay.put("resultPageUrl", UNIORDER_WXPAY_FRONT_RESULT_PAGE_URL);

			String responseUniPayWxPay = HttpClientUtils.doPost(SUPERDESK_UNIPAY_WXPAY_API_URL, requestUniPayWxPay);

			if (StringUtils.isNotEmpty(responseUniPayWxPay)) {

				JSONObject jsonObject = JSONObject.parseObject(responseUniPayWxPay);

				if (jsonObject.getInteger("code").equals(200)) {
					result.setSuccess(true);
					result.setData(jsonObject.getString("data"));
				} else {
					result.setSuccess(false);
					result.setData(jsonObject.getString("data"));
					result.setMessage(jsonObject.getString("msg"));
				}

			} else {
				result.setSuccess(false);
				result.setMessage("调取-服务之窗-统一支付-WXPAY-失败");
			}

		} catch (Exception e) {

			result.setCode(String.valueOf(e.hashCode()));
			result.setSuccess(false);
			result.setMessage(e.getMessage());

			log.error(ExceptionUtils.getMessage(e));
			e.printStackTrace();
		}

		return result;
	}


	/***
	 * 服务之窗 ---- 统一支付 ---- 回调函数
	 * @param request
	 */
	@RequestMapping("/wxpayNotify")
	@ResponseBody
	public Map<String, Object> wxpayNotify(HttpServletRequest request) throws Exception {

		log.info("服务之窗支付完成回调。");

		Map<String, Object> resMap = new HashMap<>();

		//orderNo=DZ2020041300015&state=SUCCESS&type=PAY&attach=

		try {
			String orderNo = request.getParameter("orderNo");
			String state   = request.getParameter("state");
			String type    = request.getParameter("type");

			log.info("支付单号:" + orderNo + ",支付结果:" + state);

			if (state.equals("SUCCESS")) {

				// 对帐单
				AccountingUnifiedCustomer accountingUnifiedCustomer = accountingUnifiedCustomerDubboConsumerService.findByAccountingOrderSn(orderNo);

				// 微信支付 状态
				// TODO 写死
				accountingUnifiedCustomer.setPayType(UnifiedOrderPayTypeEnum.微信支付.getKey());
				accountingUnifiedCustomer.setPayStatus(1);
				accountingUnifiedCustomer.setUpdateTime(DateUtil.date());

				accountingUnifiedCustomerDubboConsumerService.updateObj(getToken(), accountingUnifiedCustomer);

				Map<String, Object> queryMap = new HashMap<>();
				queryMap.put("dzId", accountingUnifiedCustomer.getId());
				// 对帐单 下的 订单
				List<UnifiedOrder> orders = unifiedOrderDubboConsumerService.findAll(queryMap, getToken());

				for (UnifiedOrder unifiedOrder : orders) {

					// TODO 写死 1 是已支付
					unifiedOrder.setPayState(1);
					// TODO 写死
					unifiedOrder.setPayType(21);
					unifiedOrder.setUpdateTime(DateUtil.date());

					unifiedOrderDubboConsumerService.updateObj(unifiedOrder);
				}

				resMap.put("data", "成功");
				resMap.put("code", 200);
			}


		} catch (Exception e) {


			e.printStackTrace();

			log.info("微信支付失败:" + e.getMessage());
		}
		return resMap;

	}

//	/***
//	 * 微信支付回调函数
//	 * @param request
//	 * @param response
//	 */
//	@RequestMapping("/wxpayNotify")
//	@ResponseBody
//	public void wxpayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
//		log.info("微信支付完成回调。");
//		log.info("微信支付回调request:" + request.getInputStream());
//		try {
//			request.setCharacterEncoding("UTF-8");
//			response.setCharacterEncoding("UTF-8");
//			// 处理接收消息
//			ServletInputStream in = request.getInputStream();
//			// 将流转换为字符串
//			StringBuilder xmlMsg = new StringBuilder();
//			byte[]        b      = new byte[4096];
//			for (int n; (n = in.read(b)) != -1; ) {
//				xmlMsg.append(new String(b, 0, n, "UTF-8"));
//			}
//			log.info("微信支付回调XML:" + xmlMsg.toString());
//			Map<String, String> tMap = WXUtils.xmlToMap(xmlMsg.toString());
//			if (tMap.get("return_code").equals("SUCCESS")) {
//				log.info("微信支付完成回调:支付成功。");
//				WeixinNotifyInfo weixinNotifyInfo = new WeixinNotifyInfo();
//				weixinNotifyInfo.setBankType(tMap.get("bank_type"));
//				weixinNotifyInfo.setCashFee(Integer.parseInt(tMap.get("cash_fee")));
//				weixinNotifyInfo.setDelFlag(0);
//				if (tMap.containsKey("err_code")) {
//					weixinNotifyInfo.setErrCode(tMap.get("err_code"));
//				}
//				if (tMap.containsKey("err_code_des")) {
//					weixinNotifyInfo.setErrCodeDes(tMap.get("err_code_des"));
//				}
//				if (tMap.containsKey("is_subscribe")) {
//					weixinNotifyInfo.setIsSubscribe(tMap.get("is_subscribe"));
//				}
//				weixinNotifyInfo.setNonceStr(tMap.get("nonce_str"));
//				weixinNotifyInfo.setOpenid(tMap.get("openid"));
//				weixinNotifyInfo.setOutTradeNo(tMap.get("out_trade_no"));
//				weixinNotifyInfo.setResultCode(tMap.get("result_code"));
//				weixinNotifyInfo.setReturnCode(tMap.get("return_code"));
//				weixinNotifyInfo.setReturnMsg(tMap.get("return_msg"));
//				if (tMap.containsKey("settlement_total_fee")) {
//					weixinNotifyInfo.setSettlementTotalFee(Integer.parseInt(tMap.get("settlement_total_fee")));
//				}
//				weixinNotifyInfo.setSign(tMap.get("sign"));
//				if (tMap.containsKey("sign_type")) {
//					weixinNotifyInfo.setSignType(tMap.get("sign_type"));
//				}
//				weixinNotifyInfo.setTimeEnd(tMap.get("time_end"));
//				weixinNotifyInfo.setTotalFee(Integer.parseInt(tMap.get("total_fee")));
//				weixinNotifyInfo.setTradeType(tMap.get("trade_type"));
//				weixinNotifyInfo.setTransactionId(tMap.get("transaction_id"));
//				weixinNotifyInfoDubboConsumerService.addObj(weixinNotifyInfo);
//				Map<String, String> dataMap = new HashMap<String, String>();
//				dataMap.put("return_code", "SUCCESS");
//				response.getWriter().write(WXUtils.mapToXml(dataMap));
//			} else {
//				log.info("微信支付完成回调:支付失败。");
//			}
//		} catch (Exception e) {
//
//			e.printStackTrace();
//			log.info("微信支付失败:" + e.getMessage());
//		}
//
//	}

	/**
	 * 微信端 > 企业账单 > 我的对账单
	 *
	 * @param
	 * @return
	 */
	@PostMapping("/getvirtindex")
	@ResponseBody
	public R<List<CustomerStatementOfAccountDetailVo>> getVirtIndex() {

		R<List<CustomerStatementOfAccountDetailVo>> result = new R<>();

		try {

			String virtIdStr    = getString("virtId");
			String syearStr     = getString("syear");
			String smonthStr    = getString("smonth");
			String serviceNoStr = getString("orderType");


			// 临时补个错误码
			if (StringUtils.isBlank(virtIdStr)) {

				result.setSuccess(false);
				result.setCode(500);
				result.setMessage("非法访问! 企业信息不全! ");
				return result;
			}

			SysEnterprise sysEnterprise = sysEnterpriseDubboConsumerService.findById(Long.valueOf(virtIdStr));
			if (sysEnterprise == null) {
				result.setSuccess(false);
				result.setCode(500);
				result.setMessage("非法访问! 企业信息不存在! ");
				return result;
			}

			Map<String, Object> params = new HashMap<>();
			params.put("dateType", Byte.valueOf("1"));
			params.put("virtId", virtIdStr);
			params.put("syear", syearStr);
			params.put("smonth", smonthStr);
			params.put("serviceNo", serviceNoStr);
			params.put("dzStatusWx", "y");
			List<CustomerStatementOfAccountDetailVo> viewDzMainList = accountingUnifiedCustomerDubboConsumerService.getWxDzMainView(params);
			result.setData(viewDzMainList);


			/**
			 * 消费金额
			 */
			double amount = 0;
			/**
			 * 待付款总额
			 */
			double waitpayamount = 0;
			for (CustomerStatementOfAccountDetailVo item : viewDzMainList) {

				amount += item.getAccountingAmount().doubleValue();
				if (item.getPayStatus() != 1) {
					waitpayamount += item.getAccountingAmount().doubleValue();
				}

//				Map<String,Object> dzOrderMap = new HashMap<>();
//				dzOrderMap.put("dzId",item.getId());
//				List<DzOrder> dzOrders= dzMainDubboConsumerService.getDzOrderAll(dzOrderMap);
//				if(dzOrders!=null&&dzOrders.size()>0){
//					UnifiedOrder uo = unifiedOrderDubboConsumerService.findBySn(dzOrders.get(0).getOrdersn());
//					item.setOrderType(uo.getOrderType());
//				}
			}

			Map<String, Object> headData = new HashMap<>();
			// 前端 eg 2020-05消费总额
			headData.put("amount", amount);
			// 前端 eg 2020-05待付款总额
			headData.put("waitpayamount", waitpayamount);
			headData.put("virtName", sysEnterprise.getEnterpriseName());
			result.setHeadData(headData);

		} catch (Exception e) {

			result.setSuccess(false);
			result.setMessage(ResponseMsgConstants.ERROR_UNKNOW);
			log.error(ExceptionUtils.getMessage(e));
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 企业 对账单- 查看详单
	 *
	 * @param
	 * @return
	 */
	@PostMapping("/getvirtorderdetail")
	@ResponseBody
	public R<List<UnifiedOrder>> getVirtOrderDetail() {

		R<List<UnifiedOrder>> result = new R<>();

		try {

			Map<String, Object> params = new HashMap<>();

			params.put("dzId", getLong("dzId"));

			List<UnifiedOrder> ls = accountingUnifiedCustomerDubboConsumerService.getUnifiedOrderByDzId(params);

			result.setData(ls);

		} catch (Exception e) {

			result.setSuccess(false);
			result.setMessage(ResponseMsgConstants.ERROR_UNKNOW);

			log.error(ExceptionUtils.getMessage(e));
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 企业账单- 确认接口
	 *
	 * @param
	 * @return
	 */
	@PostMapping("/updatevirtdzorder")
	@ResponseBody
	public R<?> updateVirtDzOrder() {

		R<?> result = new R<>();

		try {

			Long    id     = getLong("dzId");
			Integer status = getInteger("status");

			AccountingUnifiedCustomer dzMain = new AccountingUnifiedCustomer();

			dzMain.setId(id);
			dzMain.setAccountingStatus(status);

			accountingUnifiedCustomerDubboConsumerService.updateObj(getToken(), dzMain);

		} catch (Exception e) {

			result.setSuccess(false);
			result.setMessage(ResponseMsgConstants.ERROR_UNKNOW);

			log.error(ExceptionUtils.getMessage(e));
			e.printStackTrace();
		}

		return result;
	}

	/**
	 * 企业对账单- 去支付详情
	 *
	 * @param
	 * @return
	 */
	@PostMapping("/getvirtdzmain")
	@ResponseBody
	public R<DzMainWx> getVirtDzMain() {

		R<DzMainWx> result = new R<>();

		try {

			Long id = getLong("dzId");

			AccountingUnifiedCustomer dzMain = accountingUnifiedCustomerDubboConsumerService.findById(id);

			DzMainWx wx = new DzMainWx();

			wx.setDzSn(dzMain.getAccountingOrderSn());
			wx.setEnterpriseId(dzMain.getEnterpriseId());
			SysEnterprise enterprise = sysEnterpriseDubboConsumerService.findByVirtId(dzMain.getEnterpriseId());
			wx.setEnterpriseName(enterprise.getEnterpriseName());
			wx.setId(dzMain.getId());
			wx.setPhone(dzMain.getPurchasePhone());
			wx.setRealname(dzMain.getPurchaseUserName());
			//List<SysOderUser>   user   = sysOderUserDubboConsumerService.findByUserId(dzMain.getRealnameId().longValue());

			Map<String, Object> params = new HashMap<>();

			params.put("id", id);

			List<CustomerStatementOfAccountDetailVo> viewDzMains = accountingUnifiedCustomerDubboConsumerService.getWxDzMainView(params);

			wx.setOrdermoney(viewDzMains.get(0).getAccountingAmount());
			wx.setOrderquantity(viewDzMains.get(0).getQuantityOrder());

//			if (user != null && user.size() > 0) {
//				wx.setPhone(user.get(0).getMobile());
//				wx.setRealname(user.get(0).getRealname());
//			}

			wx.setRealnameId(dzMain.getPurchaseUserId());

			result.setSuccess(true);
			result.setData(wx);

			Map<String, Object> headMap = new HashMap<>();

			headMap.put("encrypt_id", SuperdeskUniorderRsaUtils.encode(dzMain.getId().toString()));

			result.setHeadData(headMap);

		} catch (Exception e) {

			result.setSuccess(false);
			result.setMessage(ResponseMsgConstants.ERROR_UNKNOW);

			log.error(ExceptionUtils.getMessage(e));
			e.printStackTrace();
		}
		return result;
	}


	/**
	 * 服务之窗-返回订单数量
	 *
	 * @param
	 * @return
	 */
	@PostMapping("/getordercount")
	@ResponseBody
	public R<Integer> getOrderCount() {

		R<Integer> result = new R<>();

		try {

			String[] orgId = getString("orgId").split(",");//多个逗号分隔

			Long                saleId       = getLong("saleId");
			SimpleDateFormat    sdf          = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String              beginTimeStr = getString("beginTime");
			String              endTimeStr   = getString("endTime");
			Map<String, Object> queryMap     = new HashMap<>();

			queryMap.put("orgId", orgId);
			queryMap.put("saleId", saleId);
			//queryMap.put("payState",1);

			try {

				sdf.parse(beginTimeStr);
				sdf.parse(endTimeStr);

				queryMap.put("beginTime", beginTimeStr);
				queryMap.put("endTime", endTimeStr);

			} catch (Exception ee) {

				result.setSuccess(false);
				result.setMessage("时间格式错误！" + ee.getMessage());

				log.error(ee.getMessage());

				return result;
			}

			Integer count = unifiedOrderDubboConsumerService.getOrderCount(queryMap);

			result.setData(count);

		} catch (Exception e) {

			result.setSuccess(false);
			result.setMessage(e.getMessage());

			log.error(ExceptionUtils.getMessage(e));
			e.printStackTrace();
		}

		return result;
	}


//	/**
//	 * 执行企业统计
//	 *
//	 * @param
//	 * @return
//	 */
//	@PostMapping("/virttest")
//	@ResponseBody
//	public R<Integer> virttest() {
//
//		R<Integer> result = new R<>();
//
//		try {
//			//UnifiedStatisticsVirtDubboConsumerService jobDubboService = (UnifiedStatisticsVirtDubboConsumerService) SpringUtil.getBean("unifiedStatisticsVirtDubboConsumerService");
//			Date                dtnow    = DateUtil.date();
//			SimpleDateFormat    sdf      = new SimpleDateFormat("yyyy-MM");
//			Map<String, Object> queryMap = new HashMap<>();
//
//			String dtstr = sdf.format(dtnow);
//
//			//SysConfig vconfig = jobDubboService.getConfigData("VIRTTJ");
//			int year  = Integer.parseInt(dtstr.substring(0, 4));//vconfig.getValueInt();//
//			int month = Integer.parseInt(dtstr.substring(5));// Integer.parseInt(vconfig.getValueStr1())+1;//
//
//			if (month == 13) {
//				month = 1;
//				year = year + 1;
//			}
//
//			queryMap.put("year", year);
//			queryMap.put("month", month);
//
//			List<UnifiedStatisticsVirt> ls = unifiedStatisticsVirtDimMonthDubboConsumerService.queryVirtOrderStatisticalDimMonth(queryMap);
//
//			if (ls != null && ls.size() > 0) {
//				for (UnifiedStatisticsVirt item : ls) {
//					unifiedStatisticsVirtCommonDubboConsumerService.storeVirtOrderStatisticalDimMonth(item, year, month);
//				}
//			}
//
//			// 退货统计 TODO 待验证
//			List<UnifiedStatisticsVirt> return_ls = unifiedStatisticsVirtDimMonthDubboConsumerService.queryVirtRefundOrderStatistical(queryMap);
//
//			if (return_ls != null && return_ls.size() > 0) {
//
//				for (UnifiedStatisticsVirt item : return_ls) {
//
//					Map<String, Object> queryStatistics = new HashMap<>();
//
//					queryStatistics.put("virtId", item.getVirtId());
//					queryStatistics.put("sYear", year);
//					queryStatistics.put("sMonth", month);
//					queryStatistics.put("serviceNo", item.getServiceNo());
//
//					List<UnifiedStatisticsVirt> statisticsVirts = unifiedStatisticsVirtCommonDubboConsumerService.findAll(queryStatistics);
//
//					if (statisticsVirts != null && statisticsVirts.size() > 0) {
//
//						// update
//						UnifiedStatisticsVirt update = statisticsVirts.get(0);
//
//
//						/****************************************** mark by linjinyu at 20201125 重构 start ******************************************/
//						update.setOrderRefundAmount(item.getOrderRefundAmount());
//						update.setOrderRefundCostAmount(item.getOrderRefundCostAmount());
//
//						update.setGoodsRefundAmount(item.getGoodsRefundAmount());
//						update.setGoodsRefundCostAmount(item.getGoodsRefundCostAmount());
//
//						/****************************************** mark by linjinyu at 20201125 重构   end ******************************************/
//
//						unifiedStatisticsVirtCommonDubboConsumerService.updateStatisticsVirt(update);
//
//					} else {
//
//						//insert
//						UnifiedStatisticsVirt add = new UnifiedStatisticsVirt();
//
//						add.setVirtId(item.getVirtId());
//						add.setServiceNo(item.getServiceNo());
//
//						add.setQuantity(0);
//
//						add.setSMonth(month);
//						add.setSYear(year);
//
//						/****************************************** mark by linjinyu at 20201125 重构 start ******************************************/
//
//						add.setOrderAmount(new BigDecimal("0"));
//						add.setOrderCostAmount(new BigDecimal("0"));
//						add.setOrderRefundAmount(item.getOrderRefundAmount());
//						add.setOrderRefundCostAmount(item.getOrderRefundCostAmount());
//						add.setOrderTransportAmount(new BigDecimal("0"));
//
//						add.setGoodsAmount(new BigDecimal("0"));
//						add.setGoodsCostAmount(new BigDecimal("0"));
//						add.setGoodsRefundAmount(item.getGoodsRefundAmount());
//						add.setGoodsRefundCostAmount(item.getGoodsRefundCostAmount());
//						add.setGoodsTransportAmount(new BigDecimal("0"));
//
//						/****************************************** mark by linjinyu at 20201125 重构   end ******************************************/
//
//						add.setPayableAmount(new BigDecimal(0));
//
//						add.setCreateTime(DateUtil.date());
//
//
//						unifiedStatisticsVirtCommonDubboConsumerService.insertStatisticsVirt(add);
//					}
//				}
//			}
//
//			result.setData(1);
//
//		} catch (Exception e) {
//
//			result.setSuccess(false);
//			result.setMessage(e.getMessage());
//
//			log.error(ExceptionUtils.getMessage(e));
//			e.printStackTrace();
//		}
//		return result;
//	}


//	/**
//	 * 区域企业数据导入
//	 * @param excelFile
//	 * @return
//	 * @throws Exception
//	 */
//	@PostMapping("/areavirtimport")
//	public ResponseResult<?> importBankExcel(@RequestParam("excelFile") MultipartFile excelFile) throws Exception {
//		ResponseResult<?> result = new ResponseResult<>();
//
//		String fileName = excelFile.getOriginalFilename();
//		if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
//			throw new MyException(ExceptionMsg.SYS_ERROR.getCode(), "上传文件格式不正确");
//		}
//		boolean isExcel2003 = true;
//		if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
//			isExcel2003 = false;
//		}
//		InputStream is = excelFile.getInputStream();
//		Workbook wb = null;
//		if (isExcel2003) {
//			wb = new HSSFWorkbook(is);
//		} else {
//			wb = new XSSFWorkbook(is);
//		}
//		Sheet sheet = wb.getSheetAt(0);
//		if (sheet == null) {
//			throw new MyException(ExceptionMsg.SYS_ERROR.getCode(), "Excel文件无内容");
//		}
//		int rowCounts = sheet.getLastRowNum();
//
//		//List<Map<String, Object>> list = new ArrayList<>();
//		//通过mobile分类
//		for (int i = 1; i <= rowCounts; i++) {
//			Map<String, Object> excelMap = new HashMap<>();
//			if(sheet.getRow(i)==null||sheet.getRow(i).getCell(0)==null){
//				continue;
//			}
//			//企业ID
//			sheet.getRow(i).getCell(1).setCellType(CellType.STRING);
//			String virtId = sheet.getRow(i).getCell(1).getStringCellValue();
//			//1级区域
//			sheet.getRow(i).getCell(4).setCellType(CellType.STRING);
//			String areaName1 = sheet.getRow(i).getCell(4).getStringCellValue();
//
//			//2级区域
//			sheet.getRow(i).getCell(5).setCellType(CellType.STRING);
//			String areaName2 = sheet.getRow(i).getCell(5).getStringCellValue();
//
//			//3级区域
//			sheet.getRow(i).getCell(6).setCellType(CellType.STRING);
//			String areaName3 = sheet.getRow(i).getCell(6).getStringCellValue();
//
//			//客户经理
//			sheet.getRow(i).getCell(7).setCellType(CellType.STRING);
//			String cname = sheet.getRow(i).getCell(7).getStringCellValue();
//
//			//采购专家
//			sheet.getRow(i).getCell(8).setCellType(CellType.STRING);
//			String pname = sheet.getRow(i).getCell(8).getStringCellValue();
//
//			//获取区域信息 1-2-3
//			Map<String,Object> areaQuery = new HashMap<>();
//			areaQuery.put("areaNameFull",areaName1);
//			areaQuery.put("lev",1);
//			List<UnifiedAreaCity> areaCitys = unifiedAreaDubboConsumerService.findAll(areaQuery);
//			UnifiedAreaCity areaCity1 = null;
//			if(areaCitys!=null&&areaCitys.size()>0){
//				areaCity1 = areaCitys.get(0);
//			}else{
//				UnifiedAreaCity areaCityAdd = new UnifiedAreaCity();
//				areaCityAdd.setCreateTime(DateUtil.date());
//				areaCityAdd.setCreateUserId(1L);
//				areaCityAdd.setAreaName(areaName1);
//
//				//areaCityAdd.setCustomerUsers();
//				areaCityAdd.setLev(1);
//				//areaCityAdd.setPurchaseUsers();
//				areaCityAdd.setUpdateTime(DateUtil.date());
//				areaCityAdd.setUpdateUserId(1L);
//				areaCity1 = unifiedAreaDubboConsumerService.addObj(areaCityAdd);
//			}
//			areaQuery.clear();
//			areaQuery.put("areaNameFull",areaName2);
//			areaQuery.put("lev",2);
//			areaQuery.put("parentId",areaCity1.getId());
//			areaCitys = unifiedAreaDubboConsumerService.findAll(areaQuery);
//			UnifiedAreaCity areaCity2 = null;
//			if(areaCitys!=null&&areaCitys.size()>0){
//				areaCity2 = areaCitys.get(0);
//			}else{
//				UnifiedAreaCity areaCityAdd = new UnifiedAreaCity();
//				areaCityAdd.setCreateTime(DateUtil.date());
//				areaCityAdd.setCreateUserId(1L);
//				areaCityAdd.setAreaName(areaName2);
//
//				//areaCityAdd.setCustomerUsers();
//				areaCityAdd.setLev(2);
//				//areaCityAdd.setPurchaseUsers();
//				areaCityAdd.setUpdateTime(DateUtil.date());
//				areaCityAdd.setUpdateUserId(1L);
//				areaCityAdd.setParentId(areaCity1.getId());
//				areaCity2 = unifiedAreaDubboConsumerService.addObj(areaCityAdd);
//			}
//			areaQuery.clear();
//			areaQuery.put("areaNameFull",areaName3);
//			areaQuery.put("lev",3);
//			areaQuery.put("parentId",areaCity2.getId());
//			areaCitys = unifiedAreaDubboConsumerService.findAll(areaQuery);
//			UnifiedAreaCity areaCity3 = null;
//			if(areaCitys!=null&&areaCitys.size()>0){
//				areaCity3 = areaCitys.get(0);
//			}else{
//				UnifiedAreaCity areaCityAdd = new UnifiedAreaCity();
//				areaCityAdd.setCreateTime(DateUtil.date());
//				areaCityAdd.setCreateUserId(1L);
//				areaCityAdd.setAreaName(areaName3);
//
//				Map<String,Object> userQuery = new HashMap<>();
//				userQuery.put("fullname",cname);
//				List<SysUserSelect> userSelects = sysUserDubboConsumerService.findAll(userQuery);
//				if(userSelects!=null&&userSelects.size()>0){
//					areaCityAdd.setCustomerUsers(userSelects.get(0).getId().toString());
//				}
//				userQuery.clear();
//				userQuery.put("fullname",pname);
//				userSelects = sysUserDubboConsumerService.findAll(userQuery);
//				if(userSelects!=null&&userSelects.size()>0){
//					areaCityAdd.setPurchaseUsers(userSelects.get(0).getId().toString());
//				}
//
//				areaCityAdd.setLev(3);
//				areaCityAdd.setUpdateTime(DateUtil.date());
//				areaCityAdd.setUpdateUserId(1L);
//				areaCityAdd.setParentId(areaCity2.getId());
//				areaCity3 = unifiedAreaDubboConsumerService.addObj(areaCityAdd);
//			}
//
//			UnifiedAreaCityWithVirt areaCityVirt = unifiedAreaDubboConsumerService.getAreaDetailByVirtId(Long.parseLong(virtId));
//			if(areaCityVirt==null){
//				UnifiedAreaCityVirt addareaCityVirt = new UnifiedAreaCityVirt();
//				addareaCityVirt.setAreaCityId(areaCity3.getId());
//				addareaCityVirt.setVirtId(Long.parseLong(virtId));
//				unifiedAreaDubboConsumerService.addAreaVirt(addareaCityVirt);
//			}
//			//list.add(excelMap);
//		}
//		//invoiceBankDubboService.importBankExcel(getToken(), list);
//
//		return result;
//	}


}
