package com.ym.mec.student.controller;

import com.ym.mec.biz.dal.dao.*;
import com.ym.mec.biz.dal.dto.*;
import com.ym.mec.biz.dal.entity.*;
import com.ym.mec.biz.service.*;
import com.ym.mec.util.date.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.snaker.engine.entity.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.huifu.adapay.model.payment.PayChannelEnum;
import com.huifu.adapay.model.payment.Payment;
import com.ym.mec.biz.dal.enums.DealStatusEnum;
import com.ym.mec.biz.dal.enums.GroupType;
import com.ym.mec.common.controller.BaseController;
import com.ym.mec.common.entity.HttpResponseResult;
import com.ym.mec.thirdparty.adapay.NotifyEvent;
import com.ym.mec.thirdparty.adapay.Pay;
import com.ym.mec.thirdparty.yqpay.Msg;
import com.ym.mec.thirdparty.yqpay.RsqMsg;
import com.ym.mec.thirdparty.yqpay.YqPayFeignService;
import com.ym.mec.thirdparty.yqpay.YqPayUtil;
import com.ym.mec.util.http.HttpUtil;

import javax.servlet.http.HttpServletResponse;

@RequestMapping("studentOrder")
@Api(tags = "订单回调")
@RestController
@EnableScheduling
public class StudentOrderController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(StudentOrderController.class);
    @Autowired
    private StudentPaymentOrderService studentPaymentOrderService;
    @Autowired
    private StudentRegistrationService studentRegistrationService;
    @Autowired
    private VipGroupService vipGroupService;
    @Autowired
    private MusicGroupService musicGroupService;
    @Autowired
    private StudentPaymentOrderDetailService studentPaymentOrderDetailService;
    @Autowired
    private YqPayFeignService yqPayFeignService;
    @Autowired
    private StudentPaymentOrderDao studentPaymentOrderDao;
    @Autowired
    private SysConfigDao sysConfigDao;
    @Autowired
    private SporadicChargeInfoService sporadicChargeInfoService;
    @Autowired
    private OrganizationDao organizationDao;
    @Autowired
    private TeacherCourseStatisticsDao teacherCourseStatisticsDao;
    @Autowired
    private CourseScheduleEvaluateDao courseScheduleEvaluateDao;

    @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);
            studentPaymentOrderService.updateOrder(notifyMap);
            msg.setCode("000000");
            msg.setMsg("success");
        }
        return msg;
    }


    @ApiOperation(value = "查询订单状态")
    @PostMapping("/checkOrderStatus")
    public Object checkOrderStatus(String orderNo) {
        if (StringUtils.isBlank(orderNo)) {
            return failed("请指定订单");
        }
        StudentPaymentOrder orderByOrderNo = studentPaymentOrderService.findOrderByOrderNo(orderNo);
        if (Objects.isNull(orderByOrderNo)) {
            return failed("未找到指定订单");
        }
        HashMap<String, Object> orderDetail = new HashMap<>();
        orderDetail.put("order", orderByOrderNo);
        orderDetail.put("groupType", orderByOrderNo.getGroupType());
        if (orderByOrderNo.getGroupType().equals(GroupType.MUSIC)) {
            MusicGroup musicGroup = musicGroupService.get(orderByOrderNo.getMusicGroupId());
            List<Goods> goodsList = studentPaymentOrderDetailService.findApplyOrderGoods(orderByOrderNo.getId());
            orderDetail.put("goods", goodsList);
            orderDetail.put("course", musicGroup.getCourseForm());
            orderDetail.put("ownershipType", musicGroup.getOwnershipType());
        } else if (orderByOrderNo.getGroupType().equals(GroupType.VIP)) {
            VipBuyResultDto vipBuyResultInfo = vipGroupService.findVipBuyResultInfo(Integer.valueOf(orderByOrderNo.getMusicGroupId()));
            orderDetail.put("detail", vipBuyResultInfo);
        } else if (orderByOrderNo.getGroupType().equals(GroupType.SPORADIC)) {
            SporadicChargeInfo info = sporadicChargeInfoService.get(Integer.valueOf(orderByOrderNo.getMusicGroupId()));
            orderDetail.put("detail", info);
        }

        return succeed(orderDetail);
    }

    @ApiOperation(value = "台牌支付")
    @PostMapping("/executePayment")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "amount", value = "支付金额", required = true, dataType = "BigDecimal"),
            @ApiImplicitParam(name = "orderNo", value = "订单号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "payChannel", value = "支付方式（alipay-支付宝app支付）", required = true, dataType = "String"),
    })
    public Object executePayment(BigDecimal amount, String orderNo, String payChannel, String notifyUrl, String returnUrl, String orderSubject, String orderBody, String sign, String code) throws Exception {
        String appId = "wxcf8e8b33a9477845";
        String appSecret = "1286452b9c68b13325dece7cdf892645";
        String wxMpOAuth2AccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
        payChannel = PayChannelEnum.ALIPAY_QR.getCode();
//        if (!new Pay().verifySign(amount, orderNo, notifyUrl, orderSubject, orderBody,sign)) {
//            return failed("签名验证失败");
//        }

        String openid = "";
        if (payChannel == "wx_pub") {
            if (code == null || code.isEmpty()) {
                return failed("微信支付请先授权");
            }
            wxMpOAuth2AccessTokenUrl = String.format(wxMpOAuth2AccessTokenUrl, appId, appSecret, code);
            Map<String, String> weChatRes = JSON.parseObject(HttpUtil.get(wxMpOAuth2AccessTokenUrl, new HashMap<>()), Map.class);
            if (!weChatRes.containsKey("openid")) {
                return failed("授权失败,请重新授权");
            }
            openid = weChatRes.get("openid");
        }

        StudentPaymentOrder order = studentPaymentOrderService.findOrderByOrderNo(orderNo);
        if (order == null) {
            return failed("订单不存在");
        }

        Payment payment = new Pay().executePayment(amount, orderNo, payChannel, orderSubject, orderBody, code);
        order.setTransNo(payment.getId());
        studentPaymentOrderService.update(order);

        return succeed(payment);
    }

    @PostMapping("/adaNotify")
    public void adaNotify(@ModelAttribute NotifyEvent notifyEvent) throws Exception {
        logger.info(notifyEvent.toString());
        if (notifyEvent.getType().equals("payment.success") && notifyEvent.getType().equals("payment.failed")) {
            return;
        }

        Map<String, String> notifyMap = JSON.parseObject(notifyEvent.getData(), Map.class);

        //支付中订单存在，更新状态
        if (notifyMap.size() > 0) {
            String tradeState = notifyEvent.getType().equals("payment.success") ? "1" : "0";
            notifyMap.put("tradeState", tradeState);
            notifyMap.put("totalMoney", notifyMap.get("pay_amt"));
            notifyMap.put("merOrderNo", notifyMap.get("order_no"));
            notifyMap.put("merOrderNo", notifyMap.get("order_no"));
            notifyMap.put("remarks", notifyMap.get("description"));
            studentPaymentOrderService.updateOrder(notifyMap);
        }
    }

    @GetMapping("/authorize")
    public String authorize(@RequestParam("returnUrl") String returnUrl) {
        String appId = "wxcf8e8b33a9477845";
        String url = URLEncoder.encode("http://wxwechat.utools.club/studentOrder/userInfo");

        String redirectURL = String.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_base&state=1&connect_redirect=1#wechat_redirect",
                appId, url);

        return "redirect:" + redirectURL;
    }

    @GetMapping("/userInfo")
    public Object userInfo(@RequestParam("code") String code,
                           @RequestParam("state") String returnUrl) throws Exception {
        String appId = "wxcf8e8b33a9477845";
        String appSecret = "1286452b9c68b13325dece7cdf892645";

        String wxMpOAuth2AccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";

        wxMpOAuth2AccessTokenUrl = String.format(wxMpOAuth2AccessTokenUrl, appId, appSecret, code);

        Map<String, String> map = JSON.parseObject(HttpUtil.get(wxMpOAuth2AccessTokenUrl, new HashMap<>()), Map.class);

        if (!map.containsKey("openid")) {
            return failed("授权失败，请重新授权");
        }

        return map.get("openid");

    }

    //    @Scheduled(cron = "0/30 * * * * ?")
    @GetMapping("/setSuccessStatus")
    public void setSuccessStatus() throws Exception {
        List<StudentPaymentOrder> payingOrders = studentPaymentOrderService.findOrdersByStatus(DealStatusEnum.ING, "YQPAY");

        String[] statusArr = {"0", "1", "7"};
        for (StudentPaymentOrder 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 {
                    studentPaymentOrderService.updateOrder(rpMap); //更新订单
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
            }
        }

    }

    @GetMapping("/getOrderStatus")
    private HttpResponseResult getOrderStatus(String orderNo) throws Exception {

        if (orderNo == null || orderNo.isEmpty()) {
            return failed("订单号必须填");
        }

        String notifyUrl = ""; //回调地址
        Map<String, Object> resultMap = new LinkedHashMap<>();
        resultMap.put("merOrderNoList", orderNo);
        Map<String, Object> requestMap = YqPayUtil.getRequestMap(notifyUrl, resultMap);

        RsqMsg rsqMsg = new RsqMsg(requestMap);

        Msg queryRs = yqPayFeignService.orderQuery(rsqMsg);

        if (queryRs.getCode().equals("88")) {
            String responseParameters = queryRs.getResponseParameters();
            List<Map<String, Object>> responseList = JSON.parseObject(responseParameters, List.class);
            return succeed(responseList);
        }
        return succeed("订单不存在");
    }


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

    @GetMapping("/getLuckStatis")
    public HttpResponseResult getLuckStatis() {
        List<Organization> organs = organizationDao.findAllOrgans();
        List<OrderStatisDto> orders = studentPaymentOrderDao.getLuckStatis();


        for (Organization organ : organs) {
            boolean flag = false;
            for (OrderStatisDto order : orders) {
                if (organ.getName().equals(order.getOrganName())) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                OrderStatisDto orderStatisDto = new OrderStatisDto();
                orderStatisDto.setOrganName(organ.getName());
                orderStatisDto.setMoney(BigDecimal.ZERO);
                orderStatisDto.setNums(0);
                orders.add(orderStatisDto);
            }
        }

        BigDecimal totalMoney = BigDecimal.ZERO;
        Integer totalNum = 0;
        Iterator<OrderStatisDto> iterator = orders.iterator();
        while (iterator.hasNext()) {
            OrderStatisDto order = iterator.next();
            if (order.getOrganName().equals("总部国际") || order.getOrganName().equals("阳光总部国际") || order.getOrganName().equals("武汉小学")) {
                iterator.remove();
                continue;
            }
            totalMoney = totalMoney.add(order.getMoney());
            totalNum += order.getNums();
        }
        orders = orders.stream().sorted(Comparator.comparing(OrderStatisDto::getNums).reversed()).collect(Collectors.toList());

        LuckStatisDto luckStatisDto = new LuckStatisDto();
        luckStatisDto.setOrderStatisDtoList(orders);
        luckStatisDto.setTotalNum(totalNum);
        luckStatisDto.setTotalMoney(totalMoney);
        return succeed(luckStatisDto);
    }

    @GetMapping("/getPracticeGroupStatis")
    public HttpResponseResult getPracticeGroupStatis() {
        List<Organization> organs = organizationDao.findAllOrgans();
        List<PracticeGroupsDto> hasReportNums = courseScheduleEvaluateDao.getHasReportNums();
        List<PracticeGroupsDto> organMoneys = courseScheduleEvaluateDao.getOrganMoney();
        List<PracticeGroupsDto> organPracticeGroups = courseScheduleEvaluateDao.getOrganPracticeGroups();
        List<PracticeGroupsDto> practiceGroupsFrees = courseScheduleEvaluateDao.getPracticeGroupsFree();
        List<PracticeGroupsDto> practiceGroupsBuys = courseScheduleEvaluateDao.getPracticeGroupsBuy();

        List<PracticeGroupsDto> practiceGroups = new ArrayList<>();
        for (Organization organ : organs) {
            PracticeGroupsDto practiceGroupsDto = new PracticeGroupsDto();
            practiceGroupsDto.setOrganName(organ.getName());
            practiceGroupsDto.setOrganId(organ.getId());
            //体验人数
            for (PracticeGroupsDto practiceGroupsFree : practiceGroupsFrees) {
                if (organ.getId().equals(practiceGroupsFree.getOrganId())) {
                    practiceGroupsDto.setTotalNums(practiceGroupsFree.getTotalNums());
                    break;
                }
            }
            //购买人数
            for (PracticeGroupsDto practiceGroupsBuy : practiceGroupsBuys) {
                if (organ.getId().equals(practiceGroupsBuy.getOrganId())) {
                    practiceGroupsDto.setBuyNums(practiceGroupsBuy.getBuyNums());
                    break;
                }
            }
            //已完成人数
            for (PracticeGroupsDto organPracticeGroup : organPracticeGroups) {
                if (organ.getId().equals(organPracticeGroup.getOrganId()) && organPracticeGroup.getBuyNums() >= organPracticeGroup.getTotalNums()) {
                    practiceGroupsDto.setOverNums(practiceGroupsDto.getOverNums() + 1);
                }
            }

            //已提交报告人数
            for (PracticeGroupsDto hasReportNum : hasReportNums) {
                if (organ.getId().equals(hasReportNum.getOrganId())) {
                    practiceGroupsDto.setReportNums(hasReportNum.getReportNums());
                    break;
                }
            }
            //成交金额
            for (PracticeGroupsDto organMoney : organMoneys) {
                if (organ.getId().equals(organMoney.getOrganId())) {
                    practiceGroupsDto.setTotalMoney(organMoney.getTotalMoney());
                    break;
                }
            }

            if(practiceGroupsDto.getTotalNums() >0 ){
                double scale = new BigDecimal(practiceGroupsDto.getBuyNums()).multiply(new BigDecimal(100)).divide(new BigDecimal(practiceGroupsDto.getTotalNums()),2, BigDecimal.ROUND_HALF_UP).doubleValue();
                practiceGroupsDto.setBuyScale(scale);
            }

            practiceGroups.add(practiceGroupsDto);
        }

        BigDecimal totalMoney = BigDecimal.ZERO;
        Integer totalNum = 0;
        Integer buyNum = 0;
        Integer overNum = 0;
        Integer reportNum = 0;

        Iterator<PracticeGroupsDto> iterator = practiceGroups.iterator();
        while (iterator.hasNext()) {
            PracticeGroupsDto next = iterator.next();
            if (next.getOrganName().equals("总部国际") || next.getOrganName().equals("阳光总部国际") || next.getOrganName().equals("武汉小学")) {
                iterator.remove();
                continue;
            }
            totalMoney = totalMoney.add(next.getTotalMoney());
            totalNum += next.getTotalNums();
            overNum += next.getOverNums();
            buyNum += next.getBuyNums();
            reportNum += next.getReportNums();
        }
        practiceGroups = practiceGroups.stream().sorted(Comparator.comparingDouble(PracticeGroupsDto::getBuyScale).reversed()).collect(Collectors.toList());

        practiceGroupStatisDto practiceGroupStatisDto = new practiceGroupStatisDto();
        practiceGroupStatisDto.setPracticeGroupsDtoList(practiceGroups);
        practiceGroupStatisDto.setTotalMoney(totalMoney);
        practiceGroupStatisDto.setTotalNum(totalNum);
        practiceGroupStatisDto.setBuyNum(buyNum);
        practiceGroupStatisDto.setOverNum(overNum);
        practiceGroupStatisDto.setReportNum(reportNum);

        if(totalNum >0 ){
            BigDecimal scale = new BigDecimal(buyNum).multiply(new BigDecimal(100)).divide(new BigDecimal(totalNum), 2, BigDecimal.ROUND_HALF_UP);
            practiceGroupStatisDto.setBuyScale(scale);
        }

        return succeed(practiceGroupStatisDto);
    }
}
