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.core.constants.ApiCodeEnum;
import com.jeequan.jeepay.core.entity.PayOrderCount;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.core.model.export.RefundOrderExportExcel;
import com.jeequan.jeepay.core.utils.AmountUtil;
import com.jeequan.jeepay.core.utils.ExcelUtil;
import com.jeequan.jeepay.db.entity.RefundOrder;
import com.jeequan.jeepay.mgr.ctrl.CommonCtrl;
import com.jeequan.jeepay.service.impl.RefundOrderService;
import com.jeequan.jeepay.service.impl.StatsTradeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

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

/**
 * 退款订单类
 */
@RestController
@RequestMapping("/api/refundOrder")
public class RefundOrderController extends CommonCtrl {

    @Autowired private RefundOrderService refundOrderService;

    @Autowired private StatsTradeService statsTradeService;

    /**
     * 退款订单信息列表
     */
    @PreAuthorize("hasAuthority('ENT_REFUND_LIST')")
    @RequestMapping(value="", method = RequestMethod.GET)
    public ApiRes list() {

        RefundOrder refundOrder = getObject(RefundOrder.class);
        JSONObject paramJSON = getReqParamJSON();
        LambdaQueryWrapper<RefundOrder> wrapper = RefundOrder.gw();
        IPage<RefundOrder> pages = refundOrderService.pageList(getIPage(), wrapper, refundOrder, paramJSON);

        setIfName(pages.getRecords());

        return ApiRes.page(pages);
    }

    /**
     * 退款订单信息
     */
    @PreAuthorize("hasAuthority('ENT_REFUND_ORDER_VIEW')")
    @RequestMapping(value="/{refundOrderId}", method = RequestMethod.GET)
    public ApiRes detail(@PathVariable("refundOrderId") String refundOrderId) {
        RefundOrder refundOrder = refundOrderService.getById(refundOrderId);
        if (refundOrder == null) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_SEARCH);
        }
        return ApiRes.ok(refundOrder);
    }


    /**
     * 退款列表数据导出
     */
    @RequestMapping(value="/exportExcel", method = RequestMethod.GET)
    public void exportExcel() {
        try {

            RefundOrder refundOrder = getObject(RefundOrder.class);
            JSONObject paramJSON = getReqParamJSON();
            LambdaQueryWrapper<RefundOrder> wrapper = RefundOrder.gw();
            IPage<RefundOrder> pages = refundOrderService.pageList(getIPage(true), wrapper, refundOrder, paramJSON);

            List<JSONObject> newList = new LinkedList<>();
            for (RefundOrder order:pages.getRecords()) {
                JSONObject object = (JSONObject) JSONObject.toJSON(order);
                object.put("payAmount", AmountUtil.convertCent2Dollar(order.getPayAmount()));
                object.put("refundAmount", AmountUtil.convertCent2Dollar(order.getRefundAmount()));
                object.put("refundFeeAmount", AmountUtil.convertCent2Dollar(order.getRefundFeeAmount()));
                newList.add(object);
            }

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

    }

    @PreAuthorize("hasAuthority('ENT_REFUND_ORDER_COUNT')")
    @GetMapping("/count")
    public ApiRes count() {
        RefundOrder refundOrder = getObject(RefundOrder.class);

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