package com.keao.edu.user.controller;

import com.alibaba.fastjson.JSON;
import com.keao.edu.auth.api.client.SysUserFeignService;
import com.keao.edu.auth.api.entity.SysUser;
import com.keao.edu.common.controller.BaseController;
import com.keao.edu.common.entity.HttpResponseResult;
import com.keao.edu.thirdparty.adapay.ConfigInit;
import com.keao.edu.thirdparty.adapay.Payment;
import com.keao.edu.user.entity.ExamRegistrationPayment;
import com.keao.edu.user.entity.ExamSong;
import com.keao.edu.user.service.ExamRegistrationPaymentService;
import com.keao.edu.user.service.ExamRegistrationService;
import com.keao.edu.util.date.DateUtil;
import com.keao.edu.util.http.HttpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;


@RestController
@Api(tags = "报名订单服务")
@RequestMapping(value = "examOrder")
public class ExamOrderController extends BaseController {

    @Autowired
    private ExamRegistrationPaymentService examRegistrationPaymentService;
    @Autowired
    private SysUserFeignService sysUserFeignService;

    @ApiOperation("获取用户项目未支付的订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examinationBasicId", value = "项目id", required = true, dataType = "Integer")})
    @GetMapping(value = "/getExamIngOrder")
    public HttpResponseResult<ExamRegistrationPayment> getExamIngOrder(Integer examinationBasicId) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        return succeed(examRegistrationPaymentService.getExamIngOrder(examinationBasicId, sysUser.getId()));
    }

    @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 = "支付方式", required = true, dataType = "String"),
            @ApiImplicitParam(name = "returnUrl", value = "返回页面", required = true, dataType = "String"),
            @ApiImplicitParam(name = "orderSubject", value = "订单标题", required = true, dataType = "String"),
            @ApiImplicitParam(name = "orderBody", value = "订单内容", required = true, dataType = "String"),
            @ApiImplicitParam(name = "sign", value = "sign", required = true, dataType = "String"),
            @ApiImplicitParam(name = "code", value = "code", required = true, dataType = "String")
    })
    public Object executePayment(BigDecimal amount, String orderNo, String payChannel, String returnUrl, String orderSubject, String orderBody, String sign, String code, String platform) throws Exception {
        String openId = "";
        if (payChannel.equals("wx_pub")) {
            if (code == null || code.isEmpty()) {
                return failed("微信支付请先授权");
            }
            String wxMpOAuth2AccessTokenUrl = String.format(ConfigInit.wxMpOAuth2AccessTokenUrl, ConfigInit.wxAppId, ConfigInit.wxAppSecret, code);
            Map<String, String> weChatRes = JSON.parseObject(HttpUtil.get(wxMpOAuth2AccessTokenUrl, new HashMap<>()), Map.class);
            if (!weChatRes.containsKey("openid")) {
                return failed("授权失败,请重新授权");
            }
            openId = weChatRes.get("openid");
        }

        ExamRegistrationPayment examRegistrationPayment = examRegistrationPaymentService.getByOrderNo(orderNo);

        if (examRegistrationPayment == null) {
            return failed("订单不存在,请勿非法请求");
        }
        String merNos = examRegistrationPayment.getMerNo();
        Date createTime = examRegistrationPayment.getCreateTime();
        Calendar beforeTime = Calendar.getInstance();
        beforeTime.add(Calendar.MINUTE, -28);// 28 分钟之前的时间
        Date beforeDate = beforeTime.getTime();
        if (createTime.before(beforeDate)) {
            return failed("订单已超时,请重新下单");
        }
        amount = examRegistrationPayment.getTransAmount();

        Date expireDate = DateUtil.addMinutes(createTime, 30);
        String timeExpire = new SimpleDateFormat("yyyyMMddHHmmss").format(expireDate);

        Map<String, Object> paymentParams = new HashMap<>();
        paymentParams.put("app_id", ConfigInit.appId);
        paymentParams.put("order_no", orderNo);
        paymentParams.put("pay_channel", payChannel);
        paymentParams.put("pay_amt", amount);
        paymentParams.put("goods_title", orderSubject);
        paymentParams.put("goods_desc", orderBody);
        paymentParams.put("time_expire", timeExpire);

        if (!merNos.equals(ConfigInit.merNo)) {
            List<Map<String, Object>> divMembers = new ArrayList<>();
            Map<String, Object> divMember = new HashMap<>();
            divMember.put("member_id", merNos);//分佣账户
            divMember.put("amount", amount);//分佣金额
            divMember.put("fee_flag", "Y"); //承担手续费
            divMembers.add(divMember);
            paymentParams.put("div_members", JSON.toJSONString(divMembers));
        }

        Map<String, Object> expendParams = new HashMap<>(5);
        expendParams.put("open_id", openId);
        expendParams.put("is_raw", "1");
        expendParams.put("callback_url", returnUrl);
        expendParams.put("limit_pay", "1");
        paymentParams.put("expend", expendParams);

        Map<String, Object> payment = Payment.executePayment(paymentParams);

        examRegistrationPayment.setTransNo((String) payment.get("id"));
        examRegistrationPaymentService.update(examRegistrationPayment);
        return succeed(payment);
    }


}
