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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollectionUtil;
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.MchModifyApplyment;
import com.jeequan.jeepay.core.entity.PayOrderCount;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.interfaces.device.IPrinterService;
import com.jeequan.jeepay.core.interfaces.paychannel.IRefundService;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.core.model.DBOSSConfig;
import com.jeequan.jeepay.core.model.device.PayOrderInfo4Device;
import com.jeequan.jeepay.core.model.export.MchPayOrderExportExcel;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelRefundLimit;
import com.jeequan.jeepay.core.utils.*;
import com.jeequan.jeepay.db.entity.*;
import com.jeequan.jeepay.exception.JeepayException;
import com.jeequan.jeepay.mch.ctrl.CommonCtrl;
import com.jeequan.jeepay.model.PayOrderQueryReqModel;
import com.jeequan.jeepay.model.PayOrderQueryResModel;
import com.jeequan.jeepay.model.RefundOrderCreateReqModel;
import com.jeequan.jeepay.request.PayOrderQueryRequest;
import com.jeequan.jeepay.request.RefundOrderCreateRequest;
import com.jeequan.jeepay.response.PayOrderQueryResponse;
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.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 支付订单管理类
 *
 * @author zhuxiao
 *
 * @date 2021-04-27 15:50
 */
@RestController
@RequestMapping("/api/payOrder")
public class PayOrderController extends CommonCtrl {

    @Autowired private PayOrderService payOrderService;
    @Autowired private PayWayService payWayService;
    @Autowired private MchAppService mchAppService;
    @Autowired private SysConfigService sysConfigService;
    @Autowired private MchStoreDeviceService mchStoreDeviceService;
    @Autowired private MchInfoService mchInfoService;
    @Autowired private StatsTradeService statsTradeService;
    @Autowired private SysUserService sysUserService;
    @Autowired private MchModifyApplymentService mchModifyApplymentService;

    /**
     * @Author: ZhuXiao
     * @Description: 订单信息列表
     * @Date: 10:43 2021/5/13
    */
    @PreAuthorize("hasAuthority('ENT_ORDER_LIST')")
    @GetMapping
    public ApiRes list() {

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

        payOrder.setMchNo(getCurrentMchNo());

        // 门店条件
        List<String> storeIdList = getCurrentUser().getStoreIdList();
        if (CollectionUtil.isNotEmpty(storeIdList)) {
            payOrder.setStoreIdList(storeIdList);
        }
        IPage<PayOrder> pages = payOrderService.listByPage(getIPage(), payOrder, paramJSON);

        return ApiRes.page(pages);
    }

    /**
     * @Author: ZhuXiao
     * @Description: 支付订单信息
     * @Date: 10:43 2021/5/13
    */
    @PreAuthorize("hasAuthority('ENT_PAY_ORDER_VIEW')")
    @GetMapping("/{payOrderId}")
    public ApiRes detail(@PathVariable("payOrderId") String payOrderId) {
        PayOrder payOrder = payOrderService.getDetails(payOrderId);
        if (payOrder == null) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_SEARCH);
        }
        if (!payOrder.getMchNo().equals(getCurrentMchNo())) {
            return ApiRes.fail(ApiCodeEnum.SYS_PERMISSION_ERROR);
        }
        if (StringUtils.isNotBlank(payOrder.getChannelOrderNo())) {
            DBOSSConfig ossConfig = sysConfigService.getOssConfig();
            payOrder.addExt("channelOrderNoBar", ossConfig.getOssPublicSiteUrl() + "/bar/" + payOrder.getChannelOrderNo());
        }
        if (payOrder.getStoreUserId() != null) {
            SysUserEntity sysUserEntity = sysUserService.getById(payOrder.getStoreUserId());
            payOrder.addExt("storeUserName", sysUserEntity.getRealname());
        }
        return ApiRes.ok(payOrder);
    }

    /**
     * 是否支持平台户退款
     * @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);
    }

    /**
     * 平台账户申请接口
     * @param payOrderId
     * @return
     */
    @PostMapping("/refunds/apply/{payOrderId}")
    public ApiRes applyRefund(@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());
        if(refundLimit.getIsPlatAccount() && ChannelRefundLimit.SUCCESS == refundLimit.getBindStatus()){
            throw new BizException("当前通道支持平台退款，无需重复申请");
        }
        mchModifyApplymentService.commonApply(getCurrentMchNo(),payOrder.getMchExtNo(),MchModifyApplyment.MODIFY_TYPE_REFUND_ACCOUNT_TYPE);
        return ApiRes.ok();
    }


    /**
     * 发起订单退款
     * @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");
        String refundPassword = Base64.decodeStr(getValStringRequired("refundPassword"));
        //退款模式 “1”收款商户号退款,"2"平台一般户退款
        String refundModel = getValStringRequired("refundModel");

        //验证当前密码是否正确
        MchInfo mchInfo = mchInfoService.getById(getCurrentMchNo());
        if(StringUtils.isEmpty(mchInfo.getSipw())){
            throw new BizException("当前未设置支付密码，请进入[账号中心-系统配置-安全管理]设置支付密码");
        }

        if(!new BCryptPasswordEncoder().matches(refundPassword, mchInfo.getSipw())){
            throw new BizException("支付密码验证失败！");
        }

        PayOrder payOrder = payOrderService.getById(payOrderId);
        if (payOrder == null || !payOrder.getMchNo().equals(getCurrentMchNo())) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_SEARCH);
        }

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

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

        if (!mchInfo.getRefundMode().contains(MchInfo.REFUND_MODEL_PLAT)) {
            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");
        String paySiteUrl = sysConfigService.getDBApplicationConfig().getPaySiteUrl();
//        String paySiteUrl = "http://192.168.1.24:9216";
        MchAppEntity mchAppEntity = mchAppService.getById(payOrder.getAppId());
        JeepayClient jeepayClient = new JeepayClient(paySiteUrl, 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());
        }
    }

    @MethodLog(remark = "订单状态刷新")
    @PreAuthorize("hasAuthority('ENT_PAY_ORDER_REFRESH')")
    @PostMapping("/refresh/{payOrderId}")
    public ApiRes refresh(@PathVariable("payOrderId") String payOrderId) {
        PayOrder payOrder = payOrderService.getById(payOrderId);
        if(payOrder == null){
            throw new BizException("订单数据异常");
        }
        if(PayOrder.STATE_ING != payOrder.getState()){
            throw new BizException("订单状态不支持该操作");
        }
        MchAppEntity mchAppEntity = mchAppService.getById(payOrder.getAppId());
        PayOrderQueryRequest request = new PayOrderQueryRequest();
        PayOrderQueryReqModel model = new PayOrderQueryReqModel();
        model.setPas(SysConfigService.PLATFORM_API_SECRET); // 通信秘钥
        model.setMchNo(payOrder.getMchNo());     // 商户号
        model.setAppId(payOrder.getAppId());
        model.setPayOrderId(payOrderId);
        request.setBizModel(model);
        JeepayClient jeepayClient = new JeepayClient(sysConfigService.getDBApplicationConfig().getPaySiteUrl(), mchAppEntity.getAppSecret());
        try {
            PayOrderQueryResponse response = jeepayClient.execute(request);
            if(response.getCode() != 0){
                throw new BizException(response.getMsg());
            }
            PayOrderQueryResModel respData = response.get();
            if(respData.getState() == PayOrder.STATE_SUCCESS){
                return ApiRes.ok("订单刷新成功");
            }
            return ApiRes.customFail("订单状态一致，无需当前操作");
        } catch (JeepayException e) {
            throw new BizException(e.getMessage());
        }
    }

    /**
     * @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);
        payOrder.setMchNo(getCurrentMchNo());
        JSONObject paramJSON = getReqParamJSON();
        paramJSON.put("mchNo", getCurrentMchNo());
        // 门店ID条件
        List<String> storeIdList = getCurrentUser().getStoreIdList();
        paramJSON.put("storeIdList", storeIdList);
        // 查询支付、退款金额 笔数
        PayOrderCount orderCount = statsTradeService.selectTotalByTransaction(paramJSON, null);
        return ApiRes.ok(orderCount);
    }

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

            PayOrder payOrder = getObject(PayOrder.class);
            payOrder.setMchNo(getCurrentMchNo());
            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<MchPayOrderExportExcel> linkedList = JSONArray.parseArray(JSONArray.toJSONString(newList), MchPayOrderExportExcel.class);
            // excel输出
            ExcelUtil.exportExcel(linkedList, "支付订单", "支付订单", MchPayOrderExportExcel.class, "支付订单", response);
        }catch (Exception e) {
            logger.error("导出excel失败", e);
            throw new BizException("导出订单失败！");
        }

    }

    /**
     * @Author: ZhuXiao
     * @Description: 订单打印
     * @Date: 10:43 2022/01/13
     */
    @PreAuthorize("hasAuthority('ENT_PAY_ORDER_VIEW')")
    @GetMapping("/print/{payOrderId}")
    public ApiRes print(@PathVariable("payOrderId") String payOrderId) {
        PayOrder payOrder = payOrderService.getById(payOrderId);
        if (payOrder == null) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_SEARCH);
        }
        if (!payOrder.getMchNo().equals(getCurrentMchNo())) {
            return ApiRes.fail(ApiCodeEnum.SYS_PERMISSION_ERROR);
        }

        PayOrderInfo4Device printPayOrderInfo = new PayOrderInfo4Device();
        BeanUtil.copyProperties(payOrder, printPayOrderInfo);

        try {
            // 查询打印设备
            List<JSONObject> deviceList = mchStoreDeviceService.selectAvailableDeviceList(payOrder.getMchNo(), payOrder.getStoreId(), Arrays.asList(DeviceProvideConfig.DEVICE_TYPE_PRINTER));
            if (CollectionUtils.isEmpty(deviceList)) {
                return ApiRes.customFail("打印机未配置");
            }

            // 循环调用单个设备播报
            for (JSONObject deviceParams : deviceList) {

                // 设备类型
                String provider = deviceParams.getString("provider");
                IPrinterService printerService = SpringBeansUtil.getBean(provider + "PrinterService", IPrinterService.class);

                printerService.send(deviceParams, printPayOrderInfo);
            }

            return ApiRes.ok();
        } catch (BizException e) {
            throw e;
        }
    }
}
