package com.keao.edu.user.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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.common.page.PageInfo;
import com.keao.edu.thirdparty.adapay.ConfigInit;
import com.keao.edu.thirdparty.adapay.Payment;
import com.keao.edu.thirdparty.yqpay.Msg;
import com.keao.edu.user.dto.ExamPaymentInfo;
import com.keao.edu.user.dto.ExamRegistrationPaymentDto;
import com.keao.edu.user.entity.Employee;
import com.keao.edu.user.entity.ExamRegistrationPayment;
import com.keao.edu.user.enums.TransStatusEnum;
import com.keao.edu.user.page.ExamRegistrationPaymentQueryInfo;
import com.keao.edu.user.service.EmployeeService;
import com.keao.edu.user.service.ExamRegistrationPaymentService;
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.security.access.prepost.PreAuthorize;
import org.springframework.util.DigestUtils;
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;
    @Autowired
    private EmployeeService employeeService;

    @ApiOperation(value = "缴费列表")
    @GetMapping(value = "pageList")
    @PreAuthorize("@pcs.hasPermissions('examOrder/pageList')")
    public HttpResponseResult<PageInfo<ExamRegistrationPaymentDto>> pageList(ExamRegistrationPaymentQueryInfo queryInfo) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (!sysUser.getIsSuperAdmin() && Objects.isNull(queryInfo.getOrganId())) {
            Employee employee = employeeService.get(sysUser.getId());
            if (Objects.nonNull(employee)) {
                queryInfo.setOrganId(employee.getOrganId());
            }
        }
        return succeed(examRegistrationPaymentService.pageList(queryInfo));
    }

    @ApiOperation("获取用户项目未支付的订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examinationBasicId", value = "项目id", required = true, dataType = "Integer")})
    @GetMapping(value = "/getExamIngOrder")
    public HttpResponseResult<ExamRegistrationPayment> getExamIngOrder(Long 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 notifyUrl, String orderSubject, String orderBody, String sign, String code, String platform) throws Exception {
        Map<String, Object> signParams = new LinkedHashMap<>();
        signParams.put("appId", ConfigInit.appId);
        signParams.put("amount", amount.setScale(2,BigDecimal.ROUND_HALF_UP));
        signParams.put("orderNo", orderNo);
//        signParams.put("notifyUrl", notifyUrl);
//        signParams.put("returnUrl", returnUrl);
        signParams.put("orderSubject", orderSubject);
        signParams.put("orderBody", orderBody);
        signParams.put("wxAppId", ConfigInit.wxAppId);

        String originalStr = JSONObject.toJSONString(signParams);
        String newSign = DigestUtils.md5DigestAsHex(originalStr.getBytes());
        if(!sign.equals(newSign)){
            return failed("请勿非法请求");
        }

        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().setScale(2,BigDecimal.ROUND_HALF_UP);

        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.setScale(2,BigDecimal.ROUND_HALF_UP));
        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.setScale(2,BigDecimal.ROUND_HALF_UP));//分佣金额
            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);
    }


    @ApiOperation(value = "获取订单状态及订单信息")
    @GetMapping(value = "/paymentResult")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNo", value = "订单编号", required = true, dataType = "String")})
    public HttpResponseResult<ExamPaymentInfo> getExamOrderInfo(String orderNo) {
        return succeed(examRegistrationPaymentService.getExamOrderInfo(orderNo));
    }

    @PostMapping("/notify")
    public Msg notify(@ModelAttribute Msg msg) throws Exception {
        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) {
            TransStatusEnum status = msg.getCode().equals("88") ? TransStatusEnum.SUCCESS : TransStatusEnum.FAILED;
            String channelType = notifyMap.get("channelType").equals("1") ? "WXPay" : (notifyMap.get("channelType").equals("2") ? "Alipay" : "quickPay");

            String memo = notifyMap.get("remarks");
            String orderNo = notifyMap.get("merMerOrderNo");
            String transNo = notifyMap.get("orderNo");

            notifyMap.put("channelType", channelType);
            notifyMap.put("memo", memo);
            notifyMap.put("transStatus", status.getCode());
            notifyMap.put("orderNo", orderNo);
            notifyMap.put("transNo", transNo);

            examRegistrationPaymentService.updateOrder(notifyMap);
            msg.setCode("000000");
            msg.setMsg("success");
        }
        return msg;
    }

    @PostMapping(value = "orderSuccess")
    public HttpResponseResult orderSuccess(String orderNo){
        Map<String, String> notifyMap = new HashMap<>();
        notifyMap.put("channelType", "Alipay");
        notifyMap.put("memo", "手动回调");
        notifyMap.put("transStatus", "SUCCESS");
        notifyMap.put("orderNo", orderNo);
        notifyMap.put("transNo", UUID.randomUUID().toString());
        examRegistrationPaymentService.updateOrder(notifyMap);
        return succeed();
    }

    @ApiOperation(value = "关闭订单")
    @PostMapping("/closeOrder")
    public HttpResponseResult closeOrder(String orderNo){
        return succeed(examRegistrationPaymentService.closeOrder(orderNo));
    }


}
