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

import cn.hutool.core.bean.BeanUtil;
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.agent.ctrl.CommonCtrl;
import com.jeequan.jeepay.core.aop.MethodLog;
import com.jeequan.jeepay.core.constants.ApiCodeEnum;
import com.jeequan.jeepay.core.constants.CS;
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.model.ApiRes;
import com.jeequan.jeepay.core.model.DBOSSConfig;
import com.jeequan.jeepay.core.model.device.PayOrderInfo4Device;
import com.jeequan.jeepay.core.model.export.PayOrderExportExcel;
import com.jeequan.jeepay.core.utils.AmountUtil;
import com.jeequan.jeepay.core.utils.ExcelUtil;
import com.jeequan.jeepay.core.utils.SpringBeansUtil;
import com.jeequan.jeepay.db.entity.*;
import com.jeequan.jeepay.exception.JeepayException;
import com.jeequan.jeepay.model.PayOrderQueryReqModel;
import com.jeequan.jeepay.model.PayOrderQueryResModel;
import com.jeequan.jeepay.request.PayOrderQueryRequest;
import com.jeequan.jeepay.response.PayOrderQueryResponse;
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.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

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

/**
 * 支付订单管理类
 *
 * @author zhuxiao
 * @site https://www.jeequan.com
 * @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 SysConfigService sysConfigService;
    @Autowired private MchStoreDeviceService mchStoreDeviceService;
    @Autowired private AgentInfoService agentInfoService;
    @Autowired private OrderProfitSettRecordService orderProfitSettRecordService;
    @Autowired private StatsTradeService statsTradeService;
    @Autowired private MchAppService mchAppService;

    /**
     * @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();
        if (StringUtils.isEmpty(payOrder.getAgentNo())) {
            List<String> allSubAgentNoList = agentInfoService.queryAllSubAgentNo(getCurrentAgentNo());
            payOrder.setSubAgentNoList(allSubAgentNoList);

        }else {
            if ("onlyOne".equals(payOrder.getAgentNo())) {
                payOrder.setAgentNo(getCurrentAgentNo());
            }
        }

        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);
        }
        List<String> allSubAgentNoList = agentInfoService.queryAllSubAgentNo(getCurrentAgentNo());
        if (!allSubAgentNoList.contains(payOrder.getAgentNo())) {
            return ApiRes.fail(ApiCodeEnum.SYS_PERMISSION_ERROR);
        }
        if (StringUtils.isNotBlank(payOrder.getChannelOrderNo())) {
            DBOSSConfig ossConfig = sysConfigService.getOssConfig();
            payOrder.addExt("channelOrderNoBar", ossConfig.getOssPublicSiteUrl() + "/bar/" + payOrder.getChannelOrderNo());
        }

        // 查询订单分润情况
        List<OrderProfitSettRecord> profitList = orderProfitSettRecordService.getBaseMapper().queryOrderProfitSum(payOrderId, getCurrentAgentNo(), CS.SYS_ROLE_TYPE.AGENT);
        payOrder.addExt("profitAmount", profitList.isEmpty() ? null : profitList.get(0).getCalProfitAmount());

        return ApiRes.ok(payOrder);
    }



    /**
     * @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);
        List<String> allAgentNoList = null;
        if (StringUtils.isEmpty(payOrder.getAgentNo())) {
            allAgentNoList = agentInfoService.queryAllSubAgentNo(getCurrentAgentNo());
        }else if ("onlyOne".equals(payOrder.getAgentNo())) {
            allAgentNoList = Arrays.asList(getCurrentAgentNo());
        }else {
            allAgentNoList = Arrays.asList(payOrder.getAgentNo());
        }
        payOrder.setAgentNo(null);
        JSONObject paramJSON = getReqParamJSON();
        paramJSON.put("allAgentNoList", allAgentNoList);
        // 查询支付、退款金额 笔数
        PayOrderCount orderCount = statsTradeService.selectTotalByTransaction(paramJSON, allAgentNoList);
        return ApiRes.ok(orderCount);
    }

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

            PayOrder payOrder = getObject(PayOrder.class);

            if (StringUtils.isEmpty(payOrder.getAgentNo())) {
                List<String> allSubAgentNoList = agentInfoService.queryAllSubAgentNo(getCurrentAgentNo());
                payOrder.setSubAgentNoList(allSubAgentNoList);

            }else if ("onlyOne".equals(payOrder.getAgentNo())) {
                payOrder.setAgentNo(getCurrentAgentNo());
            }else {
                payOrder.setAgentNo(payOrder.getAgentNo());
            }
            payOrder.setAgentNo(null);

            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("导出订单失败！");
        }

    }

    /**
     * @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.getAgentNo().equals(getCurrentAgentNo())) {
            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;
        }
    }

    @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());
        }
    }

}
