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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.core.model.export.SettleInfoExportExcel;
import com.jeequan.jeepay.core.utils.ExcelUtil;
import com.jeequan.jeepay.db.entity.PayInterfaceDefine;
import com.jeequan.jeepay.db.entity.SettleInfo;
import com.jeequan.jeepay.mgr.ctrl.CommonCtrl;
import com.jeequan.jeepay.service.impl.PayInterfaceDefineService;
import com.jeequan.jeepay.service.impl.SettleInfoService;
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.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @author crystal
 * @date 2023/12/6 15:11
 */
@RestController
@RequestMapping("/api/settle")
public class SettleInfoController extends CommonCtrl {

    @Autowired private SettleInfoService settleInfoService;
    @Autowired private PayInterfaceDefineService payInterfaceDefineService;

    @GetMapping
    public ApiRes list() {
        SettleInfo info = getObject(SettleInfo.class);
        JSONObject paramJSON = getReqParamJSON();
        LambdaQueryWrapper<SettleInfo> wrapper = SettleInfo.gw();
        Page<SettleInfo> pages = settleInfoService.pageList(getIPage(), wrapper,info,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 (SettleInfo data:pages.getRecords()) {
            if(StringUtils.isNotBlank(data.getIfCode())){
                data.setIfName(ifCodeMap.get(data.getIfCode()));
            }
        }
        return ApiRes.page(pages);
    }

    /**
     * 结算信息导出
     */
    @RequestMapping(value="/exportExcel", method = RequestMethod.GET)
    public void exportExcel() {
        try {
            SettleInfo info = getObject(SettleInfo.class);
            JSONObject paramJSON = getReqParamJSON();
            LambdaQueryWrapper<SettleInfo> wrapper = SettleInfo.gw(info);
            Page<SettleInfo> pages = settleInfoService.pageList(getIPage(), wrapper,info,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());
                }
            }
            List<JSONObject> newList = new LinkedList<>();

            if (!pages.getRecords().isEmpty()){
                //成功交易总笔数
                List<SettleInfo> infoList = pages.getRecords().stream().filter(p -> p.getState() == 2).collect(Collectors.toList());
                //成功交易总金额
                BigDecimal allSuccessAmount = BigDecimal.ZERO;
                for (SettleInfo settleInfo : infoList) {
                    allSuccessAmount=allSuccessAmount.add(BigDecimal.valueOf(settleInfo.getSettleAmt()));
                }

                for (SettleInfo data:pages.getRecords()) {
                    if(StringUtils.isNotBlank(data.getIfCode())){
                        data.setIfName(ifCodeMap.get(data.getIfCode()));
                    }
                    JSONObject object = (JSONObject) JSONObject.toJSON(data);
                    newList.add(object);
                }
            }


            List<SettleInfoExportExcel> linkedList = JSONArray.parseArray(JSONArray.toJSONString(newList), SettleInfoExportExcel.class);
            // excel输出
            ExcelUtil.exportExcel(linkedList, "结算信息", "结算信息", SettleInfoExportExcel.class, "结算信息", response);
        }catch (Exception e){
            logger.error("导出excel失败", e);
            throw new BizException("导出结算信息失败！");
        }
    }

    @GetMapping("/count")
    public ApiRes getCount(){
        SettleInfo info = getObject(SettleInfo.class);
        LambdaQueryWrapper<SettleInfo> wrapper = SettleInfo.gw();
        // 时间范围条件
        Date[] dateRange = info.buildQueryDateRange();
        if (dateRange[0] != null) {
            wrapper.ge(SettleInfo::getUpdatedAt, dateRange[0]);
        }
        if (dateRange[1] != null) {
            wrapper.le(SettleInfo::getUpdatedAt, dateRange[1]);
        }
        List<SettleInfo> infoList = settleInfoService.list(wrapper);
        return settleInfoService.getCount(infoList);
    }
}
