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

import cn.hutool.core.date.DateUtil;
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.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeequan.jeepay.core.constants.ApiCodeEnum;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.core.model.export.TransferOrderExportExcel;
import com.jeequan.jeepay.core.utils.AmountUtil;
import com.jeequan.jeepay.core.utils.ExcelUtil;
import com.jeequan.jeepay.db.entity.StatsTransferEntity;
import com.jeequan.jeepay.db.entity.TransferOrderEntity;
import com.jeequan.jeepay.mgr.ctrl.CommonCtrl;
import com.jeequan.jeepay.service.impl.StatsTransferService;
import com.jeequan.jeepay.service.impl.TransferOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

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


/**
* 转账订单api
*
* @author terrfly
*
* @date 2021/8/13 10:52
*/
@RestController
@RequestMapping("/api/transferOrders")
public class TransferOrderController extends CommonCtrl {

    @Autowired private TransferOrderService transferOrderService;

    @Autowired private StatsTransferService statsTransferService;

    /** list **/
    @PreAuthorize("hasAuthority('ENT_TRANSFER_ORDER_LIST')")
    @RequestMapping(value="", method = RequestMethod.GET)
    public ApiRes list() {

        TransferOrderEntity transferOrder = getObject(TransferOrderEntity.class);

        IPage<TransferOrderEntity> pages = transferOrderService.pageList(getIPage(),transferOrder);

        return ApiRes.page(pages);
    }

    /** detail **/
    @PreAuthorize("hasAuthority('ENT_TRANSFER_ORDER_VIEW')")
    @RequestMapping(value="/{recordId}", method = RequestMethod.GET)
    public ApiRes detail(@PathVariable("recordId") String transferId) {
        TransferOrderEntity refundOrder = transferOrderService.getById(transferId);
        if (refundOrder == null) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_SEARCH);
        }
        return ApiRes.ok(refundOrder);
    }

    /**
     * @author: xiaoyu
     * @date: 2022/1/14 9:45
     * @describe: 转账数据导出
     */
    @RequestMapping(value="/exportExcel", method = RequestMethod.GET)
    public void exportExcel() {
        try {
            TransferOrderEntity transferOrder = getObject(TransferOrderEntity.class);
            IPage<TransferOrderEntity> pages = transferOrderService.pageList(getIPage(true), transferOrder);

            List<JSONObject> newList = new LinkedList<>();
            for (TransferOrderEntity order:pages.getRecords()) {
                JSONObject object = (JSONObject) JSONObject.toJSON(order);
                object.put("entryType",order.getEntryType().replaceAll("_",""));
                object.put("amount", AmountUtil.convertCent2Dollar(order.getAmount()));
                newList.add(object);
            }

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

    }

    /**
     * @author: xiaoyu
     * @date: 2023/4/26 14:55
     * @describe: 数据统计
     */
    @PreAuthorize("hasAuthority('ENT_TRANSFER_ORDER_COUNT')")
    @RequestMapping(value="/count", method = RequestMethod.GET)
    public ApiRes count() {
        TransferOrderEntity transferOrder = getObject(TransferOrderEntity.class);
        LambdaQueryWrapper<TransferOrderEntity> wrapper = TransferOrderEntity.gw();

        transferOrder.setState(null);
        // 条件参数
        transferOrderService.selectParams(wrapper, transferOrder);
        Map result = transferOrderService.queryCount(wrapper);

        return ApiRes.ok(result);
    }

    @GetMapping("/statsData")
    public ApiRes statsData() {
        StatsTransferEntity condition = getObject(StatsTransferEntity.class);
        Date[] dateRange = condition.buildQueryDateRange();
        Date now  = new Date();
        boolean isToday = dateRange == null;
        boolean includeToday = false;
        if (dateRange != null && dateRange[1] != null) {
            includeToday = DateUtil.isSameDay(dateRange[1], now);
        }

        Page<StatsTransferEntity> page = getIPage();

        Page<StatsTransferEntity> resultPage;
        if (isToday) {
            resultPage = statsTransferService.pageRealTimeStat(page, condition, DateUtil.beginOfDay(now));

            return ApiRes.page(resultPage);
        }

        if (includeToday) {
            // 包含当日的，先获取当日数据
            resultPage = statsTransferService.pageRealTimeStat(page, condition, DateUtil.beginOfDay(now));

            if (resultPage.getRecords().size() == resultPage.getSize()) {
                return ApiRes.page(resultPage);
            }

            Page<StatsTransferEntity> historyPage = new Page<>(1, resultPage.getRecords().size() - resultPage.getSize());
            historyPage = statsTransferService.pageHistoryStat(historyPage, condition, dateRange);

            resultPage.getRecords().addAll(historyPage.getRecords());
        } else {
            resultPage = statsTransferService.pageHistoryStat(page, condition, dateRange);
        }

        return ApiRes.page(resultPage);
    }
}
