package com.jeequan.jeepay.mgr.ctrl.order;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jeequan.jeepay.JeepayClient;
import com.jeequan.jeepay.core.aop.MethodLog;
import com.jeequan.jeepay.core.constants.ApiCodeEnum;
import com.jeequan.jeepay.core.entity.PayOrderCount;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.interfaces.paychannel.IRefundService;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.core.model.export.PayOrderExportExcel;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelRefundLimit;
import com.jeequan.jeepay.core.utils.*;
import com.jeequan.jeepay.db.entity.MchAppEntity;
import com.jeequan.jeepay.db.entity.PayOrder;
import com.jeequan.jeepay.db.entity.PayWay;
import com.jeequan.jeepay.exception.JeepayException;
import com.jeequan.jeepay.mgr.ctrl.CommonCtrl;
import com.jeequan.jeepay.model.RefundOrderCreateReqModel;
import com.jeequan.jeepay.request.RefundOrderCreateRequest;
import com.jeequan.jeepay.response.RefundOrderCreateResponse;
import com.jeequan.jeepay.service.impl.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 支付订单类
 *
 * @author pangxiaoyu
 * @date 2021-06-07 07:15
 */
@RestController
@RequestMapping("/api/payOrder")
public class PayOrderController extends CommonCtrl {

    @Autowired private PayOrderService payOrderService;
    @Autowired private PayWayService payWayService;
    @Autowired private SysConfigService sysConfigService;
    @Autowired private MchAppService mchAppService;
    @Autowired private OrderProfitSettRecordService orderProfitSettRecordService;
    @Autowired private StatsTradeService statsTradeService;

    /**
     * @author: pangxiaoyu
     * @date: 2021/6/7 16:15
     * @describe: 订单信息列表
     */
    @PreAuthorize("hasAuthority('ENT_ORDER_LIST')")
    @RequestMapping(value="", method = RequestMethod.GET)
    public ApiRes list() {

        PayOrder payOrder = getObject(PayOrder.class);
        JSONObject paramJSON = getReqParamJSON();
        IPage<PayOrder> pages = payOrderService.listByPage(getIPage(), payOrder, paramJSON);
        return ApiRes.page(pages);
    }

    /**
     * @author: xiaoyu
     * @date: 2022/2/10 17:00
     * @describe: 订单列表统计
     */
    @PreAuthorize("hasAuthority('ENT_ORDER_COUNT')")
    @RequestMapping(value="/count", method = RequestMethod.GET)
    public ApiRes count() {
        PayOrder payOrder = getObject(PayOrder.class);
        JSONObject paramJSON = getReqParamJSON();
        // JSONObject resMap = payOrderService.orderCount(payOrder, paramJSON, null);

        // 查询支付、退款金额 笔数
        PayOrderCount orderCount = statsTradeService.selectTotalByTransaction(paramJSON, null);
        return ApiRes.ok(orderCount);
    }

    /**
     * @author: pangxiaoyu
     * @date: 2021/6/7 16:15
     * @describe: 支付订单信息
     */
    @PreAuthorize("hasAuthority('ENT_PAY_ORDER_VIEW')")
    @RequestMapping(value="/{payOrderId}", method = RequestMethod.GET)
    public ApiRes detail(@PathVariable("payOrderId") String payOrderId) {
        PayOrder payOrder = payOrderService.getDetails(payOrderId);
        if (payOrder == null) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_SEARCH);
        }

        // 查询订单分润情况
        payOrder.addExt("profitList", orderProfitSettRecordService.getBaseMapper().queryOrderProfitSum(payOrderId, null, null));

        return ApiRes.ok(payOrder);
    }


    /**
     * 发起订单退款
     * @author terrfly
     * @date 2021/6/17 16:38
     */
    @MethodLog(remark = "发起订单退款")
    @PreAuthorize("hasAuthority('ENT_PAY_ORDER_REFUND')")
    @PostMapping("/refunds/{payOrderId}")
    public ApiRes refund(@PathVariable("payOrderId") String payOrderId) {

        Long refundAmount = getRequiredAmountL("refundAmount");
        String refundReason = getValStringRequired("refundReason");

        //退款模式 “1”收款商户号退款,"2"平台一般户退款
        String refundModel = getValString("refundModel");

        PayOrder payOrder = payOrderService.getById(payOrderId);
        if (payOrder == null) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_SEARCH);
        }

        if(payOrder.getState() != PayOrder.STATE_SUCCESS){
            throw new BizException("订单状态不正确");
        }

        if(payOrder.getRefundAmount() + refundAmount > payOrder.getAmount()){
            throw new BizException("退款金额超过订单可退款金额！");
        }


        RefundOrderCreateRequest request = new RefundOrderCreateRequest();
        RefundOrderCreateReqModel model = new RefundOrderCreateReqModel();
        model.setPas(SysConfigService.PLATFORM_API_SECRET); // 通信秘钥
        model.setExtParam(refundModel);
        request.setBizModel(model);

        model.setMchNo(payOrder.getMchNo());     // 商户号
        model.setAppId(payOrder.getAppId());
        model.setPayOrderId(payOrderId);
        model.setMchRefundNo(SeqKit.genMhoOrderId());
        model.setRefundAmount(refundAmount);
        model.setRefundReason(refundReason);
        model.setCurrency("CNY");

        MchAppEntity mchAppEntity = mchAppService.getById(payOrder.getAppId());

        JeepayClient jeepayClient = new JeepayClient(sysConfigService.getDBApplicationConfig().getPaySiteUrl(), mchAppEntity.getAppSecret());

        try {
            RefundOrderCreateResponse response = jeepayClient.execute(request);
            if(response.getCode() != 0){
                throw new BizException(response.getMsg());
            }
            return ApiRes.ok(response.get());
        } catch (JeepayException e) {
            throw new BizException(e.getMessage());
        }
    }

    /**
     * 是否支持平台户退款
     * @param payOrderId
     * @return
     */
    @GetMapping("/refunds/limit/{payOrderId}")
    public ApiRes isPlatCheck(@PathVariable("payOrderId") String payOrderId) {
        PayOrder payOrder = payOrderService.getById(payOrderId);
        if (payOrder == null) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_SEARCH);
        }
        //获取退款接口
        IRefundService refundService = SpringBeansUtil.getBean(JeepayKit.getIfCodeOrigin(payOrder.getIfCode()) + "RefundService", IRefundService.class);
        if(refundService == null){
            return ApiRes.fail(ApiCodeEnum.SYSTEM_ERROR,"未获取到退款接口");
        }
        ChannelRefundLimit refundLimit = refundService.isRefundLimit(payOrder.getSettleType(), payOrder.getMchExtNo());
        return ApiRes.ok(refundLimit);
    }

    /**
     * @author: xiaoyu
     * @date: 2022/1/14 9:45
     * @describe: 订单列表数据导出
     */
    @RequestMapping(value="/exportExcel", method = RequestMethod.GET)
    public void exportExcel() {
        try {

            PayOrder payOrder = getObject(PayOrder.class);
            JSONObject paramJSON = getReqParamJSON();

            IPage<PayOrder> pages = payOrderService.listByPage(getIPage(true), payOrder, paramJSON);
            List<JSONObject> newList = new LinkedList<>();
            for (PayOrder order:pages.getRecords()) {
                JSONObject object = (JSONObject) JSONObject.toJSON(order);
                object.put("amount", AmountUtil.convertCent2Dollar(order.getAmount()));
                object.put("refundAmount", AmountUtil.convertCent2Dollar(order.getRefundAmount()));
                object.put("mchFeeAmount", AmountUtil.convertCent2Dollar(order.getMchFeeAmount()));
                object.put("mchOrderFeeAmount", AmountUtil.convertCent2Dollar(order.getMchOrderFeeAmount()));
                newList.add(object);
            }

            List<PayOrderExportExcel> linkedList = JSONArray.parseArray(JSONArray.toJSONString(newList), PayOrderExportExcel.class);
            // excel输出
            ExcelUtil.exportExcel(linkedList, "支付订单", "支付订单", PayOrderExportExcel.class, "支付订单", response);
        }catch (Exception e) {
            logger.error("导出excel失败", e);
            throw new BizException("导出订单失败！");
        }

    }

}
