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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.model.export.statistic.*;
import com.jeequan.jeepay.core.utils.ExcelUtil;
import com.jeequan.jeepay.db.entity.PayOrder;
import com.jeequan.jeepay.mch.ctrl.CommonCtrl;
import com.jeequan.jeepay.service.impl.StatsDeviceService;
import com.jeequan.jeepay.service.impl.StatsPayWayService;
import com.jeequan.jeepay.service.impl.StatsTradeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.List;

/**
 * 统计列表接口
 *
 * @author xiaoyu
 *
 * @date 2022/5/23 16:52
 */
@Slf4j
@RestController
@RequestMapping("/api/statistic/export")
public class ExportExcelStatisticController extends CommonCtrl {

    @Autowired private StatsTradeService statsTradeService;
    @Autowired private StatsPayWayService statsPayWayService;
    @Autowired private StatsDeviceService statsDeviceService;

    /**
     * @author: xiaoyu
     * @date: 2022/5/23 17:15
     * @describe: 统计列表
     */
    @PreAuthorize("hasAnyAuthority('ENT_STATISTIC_TRANSACTION', 'ENT_STATISTIC_MCH_STORE', 'ENT_STATISTIC_MCH_WAY', 'ENT_STATISTIC_MCH_TYPE')")
    @RequestMapping(value="", method = RequestMethod.GET)
    public void list() {
        JSONObject paramJSON = getReqParamJSON();
        PayOrder payOrder = getObject(PayOrder.class);
        String method = getValStringRequired("method");
        String mchNo = getCurrentMchNo();
        payOrder.setMchNo(mchNo);
        paramJSON.put("mchNo", mchNo);

        // 门店ID条件
        List<String> storeIdList = getCurrentUser().getStoreIdList();
        paramJSON.put("storeIdList", storeIdList);

        Page<PayOrderCount> countPage = null;
        switch (method) {
            case CS.STATISTIC_TYPE.TRANSACTION:
                countPage = statsTradeService.selectTransactionStatsList(payOrder, paramJSON, null);
                exportExcel(countPage, StatisticTransactionExportExcel.class, "交易报表");
                break;
            case CS.STATISTIC_TYPE.STORE:
                // 门店
                countPage = statsTradeService.selectStoreStatsList(paramJSON);
                exportExcel(countPage, StatisticStoreExportExcel.class, "门店统计");
                break;
            case CS.STATISTIC_TYPE.WAY_CODE:
                // 支付方式
                countPage = statsPayWayService.selectPayWayStatsList(paramJSON);
                exportExcel(countPage, StatisticWayCodeExportExcel.class, "支付方式统计");
                break;
            case CS.STATISTIC_TYPE.WAY_CODE_TYPE:
                // 支付类型
                countPage = statsPayWayService.selectWayCodeTypeStatsList(paramJSON);
                exportExcel(countPage, StatisticWayCodeTypeExportExcel.class, "支付类型统计");
                break;
            case CS.STATISTIC_TYPE.DEVICE:
                // 通道统计
                countPage = statsDeviceService.selectStatsList(paramJSON, null);
                exportExcel(countPage, StatisticDeviceExportExcel.class, "设备统计");
                break;
            case CS.STATISTIC_TYPE.MCH:
                //商户统计
                countPage = statsTradeService.selectByMch(paramJSON,null);
                exportExcel(countPage, StatisticMcMchExportExcel.class, "商户统计");
                break;
            default:
                break;
        }
    }

    /** 通用导出类 **/
    public void exportExcel(Page<PayOrderCount> mapPage, Class clazz, String title) {
        try {

            List<JSONObject> newList = new LinkedList<>();
            mapPage.getRecords().stream().forEach(record -> {
                JSONObject resItem = (JSONObject) JSONObject.toJSON(record);
                BigDecimal totalSuccAmt = BigDecimal.valueOf(record.getTotalSuccAmt()).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
                resItem.put("allAmount", totalSuccAmt);
                // 实收金额转换
                BigDecimal totalFinalAmt = BigDecimal.valueOf(record.getTotalFinalAmt()).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
                resItem.put("payAmount", totalFinalAmt);
                // 退款金额转换
                BigDecimal totalRefundAmt = BigDecimal.valueOf(record.getTotalRefundAmt()).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
                resItem.put("refundAmount", totalRefundAmt);
                // 成功率
                resItem.put("round", record.getSuccRate() + "%");
                //手续费
                if (record.getTotalFeeAmt() != null){
                    BigDecimal totalfeeamt = BigDecimal.valueOf(record.getTotalFeeAmt()).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
                    resItem.put("totalFeeAmt", totalfeeamt);
                }
                //手续费回退
                if (record.getTotalRefundFeeAmt() != null){
                    BigDecimal totalReFeeAmt= BigDecimal.valueOf(record.getTotalRefundFeeAmt()).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
                    resItem.put("totalRefundFeeAmt", totalReFeeAmt);
                }
                if (StringUtils.isNotBlank(record.getDeviceType())) {
                    resItem.put("deviceType", PayOrder.DEVICE_TYPE_MAP.get(record.getDeviceType()));
                }
                newList.add(resItem);
            });

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

    }

}
