package com.ym.mec.teacher.controller;

import io.swagger.annotations.Api;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.ym.mec.biz.dal.dao.SysConfigDao;
import com.ym.mec.biz.dal.dao.TenantPaymentOrderDao;
import com.ym.mec.biz.dal.entity.TenantPaymentOrder;
import com.ym.mec.biz.dal.enums.DealStatusEnum;
import com.ym.mec.biz.service.TenantPaymentOrderService;
import com.ym.mec.common.controller.BaseController;
import com.ym.mec.thirdparty.yqpay.Msg;
import com.ym.mec.thirdparty.yqpay.YqPayFeignService;

@RequestMapping("teacherOrder")
@Api(tags = "订单回调")
@RestController
public class TeacherOrderController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(TeacherOrderController.class);
	@Autowired
	private YqPayFeignService yqPayFeignService;
	@Autowired
	private TenantPaymentOrderDao tenantPaymentOrderDao;
	@Autowired
	private SysConfigDao sysConfigDao;
	@Autowired
	private TenantPaymentOrderService tenantPaymentOrderService;

	@PostMapping("/notify")
	public Msg notify(@ModelAttribute Msg msg) throws Exception {
		logger.info(msg.toString());
		Map<String, Object> rqMap = new LinkedHashMap<String, Object>();
		rqMap.put("code", msg.getCode());
		rqMap.put("msg", msg.getMsg());
		rqMap.put("responseType", msg.getResponseType());
		rqMap.put("responseParameters", msg.getResponseParameters());
		rqMap.put("sign", msg.getSign());
		// boolean rs = YqPayUtil.verify(rqMap);
		msg.setMsg("fail");
		Map<String, String> notifyMap = new HashMap<>();
		// if (rs) {
		notifyMap = JSON.parseObject(msg.getResponseParameters(), Map.class);
		// }
		// 支付中订单存在，更新状态
		if (msg.getResponseType().equals("1") && notifyMap.size() > 0) {
			String tradeState = msg.getCode().equals("88") ? "1" : "0";
			String channelType = notifyMap.get("channelType").equals("1") ? "WXPay" : (notifyMap.get("channelType").equals("2") ? "Alipay" : "quickPay");
			notifyMap.put("tradeState", tradeState);
			notifyMap.put("totalMoney", notifyMap.get("payAmount"));
			notifyMap.put("merOrderNo", notifyMap.get("merMerOrderNo"));
			notifyMap.put("channelType", channelType);

			DealStatusEnum status = tradeState.equals("1") ? DealStatusEnum.SUCCESS : DealStatusEnum.FAILED;
			TenantPaymentOrder order = tenantPaymentOrderDao.findOrderByOrderNo(notifyMap.get("merMerOrderNo"));
			if (order == null || !order.getStatus().equals(DealStatusEnum.ING)) {
				return msg;
			}

			if (status.equals(DealStatusEnum.SUCCESS)) {
				order.setPayTime(new Date());
			} else {
				order.setMemo(notifyMap.get("remarks"));
			}
			order.setStatus(status);
			order.setTransNo(notifyMap.get("orderNo"));
			order.setPaymentBusinessChannel(channelType);
			order.setActualAmount(new BigDecimal(notifyMap.get("payAmount")));
			tenantPaymentOrderService.paymentForCallback(order);
			msg.setCode("000000");
			msg.setMsg("success");
		}
		return msg;
	}

	@GetMapping("/setSuccessStatus")
	public void setSuccessStatus() throws Exception {
		List<TenantPaymentOrder> payingOrders = tenantPaymentOrderDao.findOrdersByStatus(DealStatusEnum.ING, "YQPAY");

		String[] statusArr = { "0", "1", "7" };
		for (TenantPaymentOrder payingOrder : payingOrders) {
			Map<String, String> rpMap = new HashMap<>();
			rpMap.put("tradeState", "1");
			rpMap.put("remarks", "模拟支付成功");
			rpMap.put("merOrderNo", payingOrder.getOrderNo());
			rpMap.put("orderNo", payingOrder.getOrderNo());
			rpMap.put("channelType", "1");

			String channelType = rpMap.get("channelType").equals("1") ? "WXPay" : (rpMap.get("channelType").equals("2") ? "Alipay" : "quickPay");
			rpMap.put("channelType", channelType);
			if (Arrays.asList(statusArr).contains(rpMap.get("tradeState"))) {
				try {
					tenantPaymentOrderService.paymentForCallback(payingOrder); // 更新订单
				} catch (Exception e) {
					e.printStackTrace();
					continue;
				}
			}
		}

	}

	@RequestMapping("paymentResult")
	public void paymentResult(HttpServletResponse response, String orderNo) {
		try {
			String baseApiUrl = sysConfigDao.findConfigValue("teacher_base_url");
			response.sendRedirect(baseApiUrl + "/#/paymentresult?orderNo=" + orderNo);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

    @GetMapping("/queryByOrderNo")
    public Object query(String orderNo){
        TenantPaymentOrder order = tenantPaymentOrderService.queryByOrderNo(orderNo);
        if(order == null){
        	return failed("订单不存在");
        }
        return succeed(order);
    }

}
