package com.jeequan.jeepay.agent.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.agent.ctrl.CommonCtrl;
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.MchRefundOrderExportExcel;
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.service.impl.AgentInfoService;
import com.jeequan.jeepay.service.impl.RefundOrderService;
import com.jeequan.jeepay.service.impl.StatsTradeService;
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.Collections;
import java.util.LinkedList;
import java.util.List;

/***
* 退款订单管理
*
* @author terrfly
* @date 2022/3/16 20:37
*/
@RestController
@RequestMapping("/api/refundOrder")
public class RefundOrderController extends CommonCtrl {

    @Autowired private RefundOrderService refundOrderService;
    @Autowired private AgentInfoService agentInfoService;
    @Autowired
    private StatsTradeService statsTradeService;

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

        RefundOrder refundOrder = getObject(RefundOrder.class);
        JSONObject paramJSON = getReqParamJSON();
        LambdaQueryWrapper<RefundOrder> wrapper = RefundOrder.gw();
        if (StringUtils.isEmpty(refundOrder.getAgentName())) {
            List<String> allSubAgentNoList = agentInfoService.queryAllSubAgentNo(getCurrentAgentNo());
            wrapper.in(RefundOrder::getAgentNo, allSubAgentNoList);
        }else {
            if ("onlyOne".equals(refundOrder.getAgentNo())) {
                //refundOrder.setAgentNo(getCurrentAgentNo());
                refundOrder.setAgentName(getCurrentAgentNo());
            }
        }

        IPage<RefundOrder> pages = refundOrderService.pageList(getIPage(), wrapper, refundOrder, paramJSON);
        setIfName(pages.getRecords());

        return ApiRes.page(pages);
    }

    /**
     * @Author: ZhuXiao
     * @Description: 退款订单信息
     * @Date: 10:44 2021/5/13
    */
    @PreAuthorize("hasAuthority('ENT_REFUND_ORDER_VIEW')")
    @GetMapping("/{refundOrderId}")
    public ApiRes detail(@PathVariable("refundOrderId") String refundOrderId) {
        RefundOrder refundOrder = refundOrderService.getById(refundOrderId);
        if (refundOrder == null) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_SEARCH);
        }
        List<String> allSubAgentNoList = agentInfoService.queryAllSubAgentNo(getCurrentAgentNo());
        if (!allSubAgentNoList.contains(refundOrder.getAgentNo())) {
            return ApiRes.fail(ApiCodeEnum.SYS_PERMISSION_ERROR);
        }

        return ApiRes.ok(refundOrder);
    }


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

            JSONObject paramJSON = getReqParamJSON();
            LambdaQueryWrapper<RefundOrder> wrapper = RefundOrder.gw();
            RefundOrder refundOrder = getObject(RefundOrder.class);

            if (StringUtils.isEmpty(refundOrder.getAgentNo())) {
                List<String> allSubAgentNoList = agentInfoService.queryAllSubAgentNo(getCurrentAgentNo());
                wrapper.in(RefundOrder::getAgentNo, allSubAgentNoList);

            }else if ("onlyOne".equals(refundOrder.getAgentNo())) {
                wrapper.in(RefundOrder::getAgentNo, getCurrentAgentNo());
            }else {
                wrapper.in(RefundOrder::getAgentNo, refundOrder.getAgentNo());
            }
            refundOrder.setAgentNo(null);

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

    }

    /**
     * @author: xiaoyu
     * @date: 2022/2/10 17:00
     * @describe: 退款列表统计
     */
    @PreAuthorize("hasAuthority('ENT_REFUND_ORDER_COUNT')")
    @RequestMapping(value = "/count", method = RequestMethod.GET)
    public ApiRes count() {
        RefundOrder refundOrder = getObject(RefundOrder.class);
        List<String> allAgentNoList = null;
        if (StringUtils.isEmpty(refundOrder.getAgentNo())) {
            allAgentNoList = agentInfoService.queryAllSubAgentNo(getCurrentAgentNo());
        } else if ("onlyOne".equals(refundOrder.getAgentNo())) {
            allAgentNoList = Collections.singletonList(getCurrentAgentNo());
        } else {
            allAgentNoList = Collections.singletonList(refundOrder.getAgentNo());
        }
        refundOrder.setAgentNo(null);
        JSONObject paramJSON = getReqParamJSON();
        paramJSON.put("allAgentNoList", allAgentNoList);
        // 查询支付、退款金额 笔数
        PayOrderCount resMap = statsTradeService.selectTotalByTransaction(paramJSON, allAgentNoList);
        return ApiRes.ok(resMap);
    }
}
