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

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.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.*;
import com.jeequan.jeepay.mch.ctrl.CommonCtrl;
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 zhuxiao
 *
 * @date 2021-04-27 15:50
 */
@RestController
@RequestMapping("/api/refundOrder")
public class RefundOrderController extends CommonCtrl {

    @Autowired private RefundOrderService refundOrderService;
    @Autowired private PayInterfaceDefineService payInterfaceDefineService;
    @Autowired private MchAppService mchAppService;
    @Autowired private PayOrderService payOrderService;
    @Autowired private IsvInfoService isvInfoService;
    @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();
        wrapper.eq(RefundOrder::getMchNo, getCurrentMchNo());

        // 门店条件
        List<String> storeIdList = getCurrentUser().getStoreIdList();
        if (CollectionUtil.isNotEmpty(storeIdList)) {
            wrapper.in(RefundOrder::getStoreId, storeIdList);
        }

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

        Map<String, String> ifCodeMap = new HashMap<>();
        List<PayInterfaceDefine> list = payInterfaceDefineService.list();
        if(!list.isEmpty()){
            for (PayInterfaceDefine define:list) {
                ifCodeMap.put(define.getIfCode(), define.getIfName());
            }
        }
        for (RefundOrder order:pages.getRecords()) {
            if(StringUtils.isNotBlank(order.getIfCode())){
                order.setIfName(ifCodeMap.get(order.getIfCode()));
            }
        }
        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);
        }
        if (!refundOrder.getMchNo().equals(getCurrentUser().getSysUser().getBelongInfoId())) {
            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 {

            RefundOrder refundOrder = getObject(RefundOrder.class);
            refundOrder.setMchNo(getCurrentMchNo());

            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()));
                //增加订单表数据
                PayOrder payOrder = payOrderService.getById(order.getPayOrderId());
                if (payOrder != null){
                    object.put("platformOrderNo", payOrder.getPlatformOrderNo());
                    object.put("mchOrderNo", payOrder.getMchOrderNo());
                    object.put("platformMchOrderNo", payOrder.getPlatformMchOrderNo());
                }
                //增加应用数据
                if (StringUtils.isNotEmpty(order.getAppId())){
                    MchAppEntity mchAppEntity = mchAppService.getById(order.getAppId());
                    if (mchAppEntity != null){
                        object.put("appName", mchAppEntity.getAppName());
                    }
                }
                //增加支付接口数据
                if (StringUtils.isNotEmpty(order.getIfCode())){
                    PayInterfaceDefine payInterfaceDefine = payInterfaceDefineService.getById(order.getIfCode());
                    if (payInterfaceDefine != null){
                        object.put("ifName", payInterfaceDefine.getIfName());
                    }
                }
                //增加渠道数据
                if (StringUtils.isNotEmpty(order.getIsvNo())){
                    IsvInfoEntity isvInfoEntity = isvInfoService.getById(order.getIsvNo());
                    if (isvInfoEntity != null){
                        object.put("isvName", isvInfoEntity.getIsvName());
                    }
                }
                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("导出订单失败！");
        }

    }

    /**
     * 获取退款统计数据
     * @return
     */
    @GetMapping("/count")
    public ApiRes count(){
        JSONObject paramJSON = getReqParamJSON();
        paramJSON.put("mchNo",getCurrentMchNo());
        // 查询支付、退款金额 笔数
        PayOrderCount resMap = statsTradeService.selectTotalByTransaction(paramJSON, null);
        return ApiRes.ok(resMap);
    }
}
