package com.zhongshu.card.server.core.service.payment;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.github.microservice.components.data.base.util.PageEntityUtil;
import com.github.microservice.http.APIResponseModel;
import com.github.microservice.models.hxz.ConsumTransactionsModel;
import com.github.microservice.models.hxz.ConsumTransactionsResult;
import com.github.microservice.models.hxz.QRCodeTransactionModel;
import com.github.microservice.models.hxz.WxPayResult;
import com.github.microservice.models.hxz.base.IotBaseResult;
import com.github.microservice.models.type.OrderFromType;
import com.github.microservice.net.ResultContent;
import com.github.microservice.net.ResultMessage;
import com.github.microservice.types.OrderModeType;
import com.github.microservice.types.OrderState;
import com.github.microservice.types.payment.PaymentDeviceType;
import com.github.microservice.types.payment.PaymentType;
import com.zhongshu.card.client.model.base.SuperSearch;
import com.zhongshu.card.client.model.org.UserJoinBusOrgModel;
import com.zhongshu.card.client.model.payment.*;
import com.zhongshu.card.client.model.payment.statistic.BusinessMainStatisticModel;
import com.zhongshu.card.client.model.payment.statistic.StatisticItem;
import com.zhongshu.card.client.model.payment.statistic.StatisticSearch;
import com.zhongshu.card.client.model.school.AreaSimpleModel;
import com.zhongshu.card.client.service.payment.ExpenseFlowService;
import com.zhongshu.card.client.type.DataState;
import com.zhongshu.card.client.type.RefundState;
import com.zhongshu.card.client.type.StatisticType;
import com.zhongshu.card.client.type.UserState;
import com.zhongshu.card.client.type.payment.SettlementState;
import com.zhongshu.card.client.type.school.CardState;
import com.zhongshu.card.client.utils.DateUtils;
import com.zhongshu.card.server.core.dao.devices.DeviceInfoDao;
import com.zhongshu.card.server.core.dao.devices.DevicePermissDao;
import com.zhongshu.card.server.core.dao.org.OrganizationDao;
import com.zhongshu.card.server.core.dao.org.UserCountDao;
import com.zhongshu.card.server.core.dao.payment.ExpenseFlowDao;
import com.zhongshu.card.server.core.dao.school.CardInfoDao;
import com.zhongshu.card.server.core.domain.devices.DeviceInfo;
import com.zhongshu.card.server.core.domain.devices.permiss.DevicePermiss;
import com.zhongshu.card.server.core.domain.org.Organization;
import com.zhongshu.card.server.core.domain.org.UserAccount;
import com.zhongshu.card.server.core.domain.payment.ExpenseFlow;
import com.zhongshu.card.server.core.domain.school.CardInfo;
import com.zhongshu.card.server.core.httpRequest.ApiRequestService;
import com.zhongshu.card.server.core.service.base.SuperService;
import com.zhongshu.card.server.core.service.org.OrganizationServiceImpl;
import com.zhongshu.card.server.core.service.paySetting.ProjectPaySettingServiceImpl;
import com.zhongshu.card.server.core.service.school.AreaServiceImpl;
import com.zhongshu.card.server.core.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author TRX
 * @date 2024/6/17
 */
@Slf4j
@Service
public class ExpenseFlowServiceImpl extends SuperService implements ExpenseFlowService {

    @Autowired
    private ExpenseFlowDao expenseFlowDao;

    @Autowired
    private UserCountDao userCountDao;

    @Autowired
    private DeviceInfoDao deviceInfoDao;

    @Autowired
    private CardInfoDao cardInfoDao;

    @Autowired
    private ApiRequestService apiRequestService;

    @Autowired
    private OrganizationServiceImpl organizationService;

    @Autowired
    private OrganizationDao organizationDao;

    @Autowired
    private ProjectPaySettingServiceImpl projectPaySettingService;

    @Autowired
    private DevicePermissDao devicePermissDao;

    @Autowired
    private PayCallService payCallService;

    @Autowired
    private AreaServiceImpl areaService;

    /**
     * 创建流水
     *
     * @param mqttDataId
     * @return
     */
    public ExpenseFlow init(String mqttDataId) {
        ExpenseFlow expenseFlow = expenseFlowDao.init(mqttDataId, TokenUtil.create());
        return expenseFlow;
    }

    /**
     * 创建订单 (订单信息 关联改变)
     *
     * @param iotParam
     * @return
     */
    public ResultContent<ExpenseFlow> createExpenseFlowByHxz(ConsumTransactionsModel iotParam, ExpenseFlow expenseFlow) {
        expenseFlow.setMqttDataId(iotParam.getMqttDataId());
        expenseFlow.setTimes();
        // 消费订单号
        expenseFlow.setOrderNo(iotParam.getOrder());
        // 卡片信息
        expenseFlow.setCardNo(iotParam.getCardNo());
        // 本地订单号
        String paymentNo = NextNoUtil.getNextPaymentNo(null);
        // 支付订单号
        expenseFlow.setPaymentNo(paymentNo);
        // 支付金额
        BigDecimal amount = CommonUtil.turnMoney2BigDecimal(iotParam.getAmount());
        expenseFlow.setPayAmount(amount);

        String deviceId = iotParam.getDeviceId();
        expenseFlow.setDeviceId(deviceId);
        // 支付来源  刷卡  二维码  刷脸
        expenseFlow.setOrderFromType(iotParam.getOrderFromType());
        // 传过来的参数
        expenseFlow.setParam(iotParam);
        // 支付来源设备产品类型
        expenseFlow.setPaymentDeviceType(PaymentDeviceType.HxzConsumTransactions);

        expenseFlow.setOrderState(OrderState.WAIT_PAYMENT);
        // 默认未结算状态
        expenseFlow.setSettlementState(SettlementState.Unsettled);

        // 验证参数、填充数据
        commonVerifyExpenseFlow(expenseFlow);
        return ResultContent.buildSuccess(expenseFlow);
    }

    /**
     * 订单支付
     *
     * @param entity
     * @return
     */
    public ResultContent<ExpenseFlow> orderPay(ExpenseFlow entity) {
        // 判断参数是否符合要求
        if (entity.getVerifyParamIsSuccess() == null || !entity.getVerifyParamIsSuccess()) {
            // 参数验证失败
            entity.setIsPaySuccess(Boolean.FALSE);
            entity.setPayRemark(entity.getVerifyParamMsg());
            entity.setPaymentStatus("支付失败");
            expenseFlowDao.save(entity);
            return ResultContent.buildSuccess(entity);
        }
        expenseFlowDao.save(entity);

        if (entity.getMode() != null) {
            if (entity.getMode() == 0) {
                // 支付模式
                entity.setOrderModeType(OrderModeType.Consume);
                // 支付
                payCallService.payOrder(entity);
            } else if (entity.getMode() == 2) {
                // 查询余额模式 因为只有钱包有余额，所以 默认默认为钱包支付渠道
                entity.setOrderModeType(OrderModeType.BalanceInquiry);
                entity.setPaymentStatus("查询余额");
                entity.setPayRemark("查询余额");
                entity.setOrderState(OrderState.PAID_ERROR);
                entity.setIsPaySuccess(Boolean.TRUE);
                entity.setPaymentType(PaymentType.UserWallet);
                expenseFlowDao.save(entity);
            }
        }
        return ResultContent.buildSuccess();
    }

    /**
     * 通过 付款码（二维码）支付接口 创建订单
     *
     * @param iotParam
     * @return
     */
    public ResultContent<ExpenseFlow> createExpenseFlowByHxz(QRCodeTransactionModel iotParam, ExpenseFlow expenseFlow) {
        expenseFlow.setMqttDataId(iotParam.getMqttDataId());
        // 支付方式 付款码
        String QR = iotParam.getQR();
        // 判断是否是平台的二维码
        String userId = "665fc0389083d203896d3541";
        if (StringUtils.isNotEmpty(QR) && QR.indexOf("userId") > 0) {
            JSONObject jsonObject = JSONUtil.parseObj(QR);
            userId = jsonObject.getStr("userId");
        }
        expenseFlow.setOrderFromType(OrderFromType.QrCode);
        expenseFlow.setUserId(userId);

        expenseFlow.setTimes();
        // 消费订单号
        String orderNo = NextNoUtil.getNextPaymentNo("W");
        expenseFlow.setOrderNo(orderNo);
        expenseFlow.setCardNo("");
        String paymentNo = NextNoUtil.getNextPaymentNo(null);
        // 支付订单号
        expenseFlow.setPaymentNo(paymentNo);
        // 消费金额
        BigDecimal amount = CommonUtil.turnMoney2BigDecimal(iotParam.getAmount());
        amount = amount.stripTrailingZeros();
        expenseFlow.setPayAmount(amount);

        String deviceId = iotParam.getDeviceId();
        expenseFlow.setDeviceId(deviceId);

        // 判断 是 微信、支付宝的付款码
        PaymentType paymentType = PaymentUtil.getPaymentTypeByQr(QR);
        expenseFlow.setQr(QR);
        expenseFlow.setPaymentType(paymentType);
        expenseFlow.setParam(iotParam);
        expenseFlow.setPaymentDeviceType(PaymentDeviceType.HxzConsumTransactions);

        commonVerifyExpenseFlow(expenseFlow);
        return ResultContent.buildSuccess(expenseFlow);
    }

    /**
     * 同意验证 支付订单的数据是否符合要求
     *
     * @param entity
     */
    private void commonVerifyExpenseFlow(ExpenseFlow entity) {
        String deviceId = entity.getDeviceId();
        // 验证设备
        DeviceInfo deviceInfo = deviceInfoDao.findTopByDeviceId(deviceId);
        if (ObjectUtils.isEmpty(deviceInfo)) {
            entity.setVerifyError("业务设备未注册");
            return;
        }

        // 设备已停用
        if (deviceInfo.getState() != null && deviceInfo.getState() == DataState.Disable) {
            entity.setVerifyError(String.format("设备%s", deviceInfo.getState().getRemark()));
            return;
        }

        // 检查设备是否绑定机构
        if (StringUtils.isEmpty(deviceInfo.getBeLongOid())) {
            entity.setVerifyError(String.format("设备未绑定机构"));
            return;
        }
        // 设备所属的商户/机构
        entity.setShopOid(deviceInfo.getBeLongOid());
        // 设备区域
        entity.setArea(areaService.toSimpleModel(deviceInfo.getArea()));
        // 填充项目信息
        String projectOid = deviceInfo.getProjectOid();
        Organization projectInfo = organizationDao.findTopByOid(projectOid);
        if (ObjectUtils.isNotEmpty(projectInfo)) {
            entity.setProjectCode(projectInfo.getCode());
            entity.setProjectOid(projectInfo.getOid());
        }
        // 验证项目信息
        if (StringUtils.isEmpty(entity.getProjectCode())) {
            entity.setVerifyError("未绑定项目信息");
            return;
        }
        if (entity.getOrderFromType() == OrderFromType.Swipe) {
            CardInfo cardInfo = cardInfoDao.findByCode(entity.getCardNo());
            // 验证卡片
            if (ObjectUtils.isEmpty(cardInfo)) {
                entity.setVerifyError("卡片未注册");
                return;
            }
            entity.setCardInfo(cardInfo);
            entity.setUserId(cardInfo.getUserId());

            // 判断卡片是否可用
            if (cardInfo.getCardState() != CardState.Enable) {
                entity.setVerifyError(String.format("卡片%s", cardInfo.getCardState().getRemark()));
                return;
            }

            if (cardInfo.getIsCanceled() != null && cardInfo.getIsCanceled()) {
                entity.setVerifyError(String.format("卡片已作废"));
                return;
            }

            ConsumTransactionsModel iotParam = (ConsumTransactionsModel) entity.getParam();
            if ((iotParam.getMode() != 0 || iotParam.getMode() != 2) && iotParam.getPayType() != 0) {
                entity.setVerifyError("消费模式不支持");
                return;
            }
            entity.setMode(iotParam.getMode());
        }

        // 验证用户信息
        if (StringUtils.isEmpty(entity.getUserId())) {
            entity.setVerifyError("订单未找到用户");
            return;
        }

        UserAccount userAccount = userCountDao.findTopByUserId(entity.getUserId());
        if (ObjectUtils.isEmpty(userAccount)) {
            entity.setVerifyError("用户未注册");
            return;
        }
        entity.setUserName(userAccount.getName());
        entity.setUserAccount(userAccount);

        if (userAccount.getState() == UserState.Locked) {
            entity.setVerifyError("用户已锁定");
            return;
        }
        // 判断设备和用户是否绑定
        DevicePermiss devicePermiss = devicePermissDao.findTopByUserIdAndDeviceIdAndProjectOid(entity.getUserId(), entity.getDeviceId(), entity.getProjectOid());
        if (ObjectUtils.isEmpty(devicePermiss)) {
            entity.setVerifyError("用户没有使用设备权限");
            return;
        }
        if (devicePermiss.getDataState() == null || devicePermiss.getDataState() != DataState.Enable) {
            entity.setVerifyError("用户设备权限未启用");
            return;
        }
        // 消费设备信息
        if (deviceInfo.getDeviceType() != null) {
            entity.setPayType(deviceInfo.getDeviceType().getRemark());
        } else {
            entity.setPayType("消费");
        }

        // 金额判断
        BigDecimal payAmount = entity.getPayAmount();
        if (entity.getMode() == 0 && CommonUtil.bigDecimalIsEmpty(payAmount)) {
            entity.setVerifyError("消费金额不能小于等于0");
            return;
        }
        entity.setVerifyParamIsSuccess(Boolean.TRUE);
        entity.setVerifyParamMsg("参数验证成功");
    }

    /**
     * 消费机 B扫C的支付
     *
     * @param entity
     * @return
     */
    @Transactional
    public ResultContent<ExpenseFlow> expendPayQrCode(ExpenseFlow entity) {
        if (entity.getVerifyParamIsSuccess() == null || !entity.getVerifyParamIsSuccess()) {
            // 参数失败
            entity.setIsPaySuccess(Boolean.FALSE);
            entity.setPayRemark(entity.getVerifyParamMsg());
            entity.setPaymentStatus("支付失败");
            expenseFlowDao.save(entity);
            return ResultContent.buildSuccess(entity);
        }

        PaymentType paymentType = entity.getPaymentType();
        // 调用微信支付
        QRCodeTransactionModel payParam = (QRCodeTransactionModel) entity.getParam();
        // 微信支付
        String url = "https://jupan.5xryd.com//wxapi/pay/createQrCodeOrder";
        if (paymentType == PaymentType.ZfbQrCode) {
            // 支付宝支付
            url = "https://jupan.5xryd.com//wxapi/pay/createAliQrCodeOrder";
        }
        APIResponseModel apiResponseModel = apiRequestService.sendWxRequest(url, payParam);
        log.info("支付结果：{}", apiResponseModel);
        if (apiResponseModel.isSuccess()) {
            // 关联参数
            WxPayResult wxPayResult = apiResponseModel.toBean(WxPayResult.class);
            String tradeNo = wxPayResult.getTradeNo();
            if (StringUtils.isNotEmpty(tradeNo)) {
                entity.setOrderNo(tradeNo);
            }
            entity.setPaymentStatus("支付成功");
            entity.setIsPaySuccess(Boolean.TRUE);
            entity.setPayRemark("支付成功");
        } else {
            // 关联参数
            entity.setPaymentStatus("支付失败");
            entity.setIsPaySuccess(Boolean.FALSE);
            entity.setPayRemark(apiResponseModel.getMsg());
        }
        expenseFlowDao.save(entity);
        return ResultContent.buildSuccess(entity);
    }

    /**
     * 查询构建支付返回结果
     *
     * @param orderNo
     * @return
     */
    public ConsumTransactionsResult buildPayResult(String orderNo) {
        // 支付结果
        ConsumTransactionsResult result = new ConsumTransactionsResult();
        ExpenseFlow expenseFlow = expenseFlowDao.findTopByOrderNoOrderByCreateTimeDesc(orderNo);
        if (ObjectUtils.isNotEmpty(expenseFlow)) {
            if (expenseFlow.getOrderState() == OrderState.PAY_IN_PROGRESS) {
                // 支付中
                result.setStatus(-1);
                result.setMsg("支付中");
                return result;
            }
            Boolean isPaySuccess = expenseFlow.getIsPaySuccess();
            if (isPaySuccess != null && isPaySuccess) {
                result.setSuccess();
//                result.setText(expenseFlow.getPayRemark());
                if (expenseFlow.getPaymentType() == PaymentType.WxQrCode || expenseFlow.getPaymentType() == PaymentType.ZfbQrCode) {
                    result.setName("陈琰春");
                } else {
                    result.setName(expenseFlow.getUserName());
                }
                result.setCardNo(expenseFlow.getCardNo());
                // 金额 转为 元 单位
                result.setAmount(CommonUtil.turnMoney2Show(expenseFlow.getPayAmount()));

                BigDecimal number = payCallService.queryBalance(expenseFlow);
                // 余额
                result.setMoney(CommonUtil.turnMoney2Show(number));
            } else {
                result.setFailed(expenseFlow.getPayRemark());
            }
        } else {
            result.setFailed("未查询到订单");
        }
        return result;
    }

    /**
     * 构建支付返回数据
     *
     * @param result
     * @return
     */
    public String buildPayResultStr(IotBaseResult result) {
        if (ObjectUtils.isEmpty(result)) {
            return new JSONObject().toString();
        }
        return JSONUtil.toJsonStr(result);
    }

    /**
     * 查询分页数据
     *
     * @param param
     * @param pageable
     * @return
     */
    @Override
    public ResultContent<Page<ExpenseFlowModel>> page(ExpenseFlowSearch param, Pageable pageable) {
        initOidSearchParamNoCheckOid(param);
        Page<ExpenseFlow> page = expenseFlowDao.page(pageable, param);
        return ResultContent.buildSuccess(PageEntityUtil.concurrent2PageModel(page, this::toModel));
    }

    @Override
    public ResultContent<Page<ExpenseFlowModel>> busPage(ExpenseFlowSearch param, Pageable pageable) {
        param.setIsPaySuccess(Boolean.TRUE);
        param.setOrderModeType(OrderModeType.Consume);

        initSearchProjectOid(param);
        // 用户搜索的商户
        List<String> shopOids = getSearchAllShopOid(param);
        if (ObjectUtils.isEmpty(shopOids)) {
            return ResultContent.buildFail("请选择查询商户或所有的");
        }
        param.setShopOids(shopOids);
        Page<ExpenseFlow> page = expenseFlowDao.page(pageable, param);
        return ResultContent.buildSuccess(PageEntityUtil.concurrent2PageModel(page, this::toModel));
    }

    private void initSearchProjectOid(SuperSearch param) {
        if (param != null) {
            String projectOid = param.getProjectOid();
            if (StringUtils.isEmpty(projectOid)) {
                projectOid = getCurrentProjectOid();
            }
            param.setProjectOid(projectOid);
        }
    }

    /**
     * 商户订单查询
     *
     * @param param
     * @param pageable
     * @return
     */
    @Override
    public ResultContent<Page<ExpenseFlowModel>> pageBusMainOrder(ExpenseFlowSearch param, Pageable pageable) {
        // 查询支付成功的
        param.setIsPaySuccess(Boolean.TRUE);
        param.setOrderModeType(OrderModeType.Consume);

        initSearchProjectOid(param);
        // 用户搜索的商户
        List<String> shopOids = getSearchAllShopOid(param);
        if (ObjectUtils.isEmpty(shopOids)) {
            return ResultContent.buildFail("请选择查询商户或所有的");
        }
        param.setShopOids(shopOids);
        Page<ExpenseFlow> page = expenseFlowDao.page(pageable, param);
        return ResultContent.buildSuccess(PageEntityUtil.concurrent2PageModel(page, this::toModel));
    }

    /**
     * 查询搜索条件
     *
     * @param param
     * @return
     */
    public List<String> getSearchAllShopOid(ExpenseFlowSearch param) {
        List<String> shopOids = new ArrayList<String>();
        if (param.getIsAllBusinessMain() != null && param.getIsAllBusinessMain()) {
            List<UserJoinBusOrgModel> list = organizationService.getUserAboutShopList(getCurrentUserId());
            if (ObjectUtils.isNotEmpty(list)) {
                shopOids = list.stream().map(it -> it.getBusOid()).collect(Collectors.toList());
            }
//            // 查询当前用户所有的商户信息
//            List<Organization> orgs = organizationService.getUserAllOrgs(getCurrentUserId(), AuthType.BusinessMain);
//            if (ObjectUtils.isNotEmpty(orgs)) {
//                shopOids = orgs.stream().map(it -> it.getOid()).collect(Collectors.toList());
//            }
        } else {
            if (StringUtils.isNotEmpty(param.getShopOid())) {
                shopOids.add(param.getShopOid());
            }
        }
        return shopOids;
    }

    /**
     * 统计用户支出总数
     *
     * @param param
     * @return
     */
    @Override
    public ResultContent<ExpenseFlowCount> countUserPayment(ExpenseFlowSearch param) {
        return ResultContent.buildSuccess(expenseFlowDao.countUserPayment(param));
    }

    @Override
    public ResultContent<ExpenseFlowCount> countBusPayment(ExpenseFlowSearch param) {
        initSearchProjectOid(param);
        // 用户搜索的商户
        List<String> shopOids = getSearchAllShopOid(param);
        if (ObjectUtils.isEmpty(shopOids)) {
            return ResultContent.buildFail("请选择查询商户或所有的");
        }
        param.setShopOids(shopOids);
        return ResultContent.buildSuccess(expenseFlowDao.countUserPayment(param));
    }

    /**
     * 统计用户今天支付的总金额
     *
     * @param userId 用户ID
     * @return
     */
    public ResultContent<ExpenseFlowCount> countToDayPayment(String userId) {
        ExpenseFlowSearch param = new ExpenseFlowSearch();
        param.setStartTime(DateUtils.getDayStartTime(System.currentTimeMillis()));
        param.setEndTime(DateUtils.getDayEndTime(System.currentTimeMillis()));
        param.setUserId(userId);
        param.setIsPaySuccess(Boolean.TRUE);
        return ResultContent.buildSuccess(expenseFlowDao.countUserPayment(param));
    }

    /**
     * 统计商户的数据
     *
     * @param param
     * @return
     */
    public ResultContent<ExpenseFlowCount> countBuinessMainPayment(ExpenseFlowSearch param) {
        // 查询支付成功的
        param.setIsPaySuccess(Boolean.TRUE);
        param.setOrderModeType(OrderModeType.Consume);

        initSearchProjectOid(param);
//        // 用户搜索的商户
        List<String> shopOids = getSearchAllShopOid(param);
        if (ObjectUtils.isEmpty(shopOids)) {
            return ResultContent.buildFail("请选择查询商户或所有的");
        }
        param.setShopOids(shopOids);
        ExpenseFlowCount flowCount = expenseFlowDao.countBuinessMainPayment(param);
        return ResultContent.buildSuccess(flowCount);
    }

    /**
     * 商户首页统计
     *
     * @param statisticSearch
     * @return
     */
    public ResultContent<BusinessMainStatisticModel> businessMainPageStatistic(StatisticSearch statisticSearch) {
        BusinessMainStatisticModel statisticModel = new BusinessMainStatisticModel();

        ExpenseFlowSearch param = new ExpenseFlowSearch();
        param.setIsPaySuccess(Boolean.TRUE);
        param.setOrderModeType(OrderModeType.Consume);
        BeanUtils.copyProperties(statisticSearch, param);
        // 查询当前项目的
        initSearchProjectOid(param);

        List<String> shopOids = getSearchAllShopOid(param);
        if (ObjectUtils.isEmpty(shopOids)) {
            return ResultContent.buildFail("请选择查询商户或所有的");
        }
        param.setShopOids(shopOids);
        log.info("shopOids; {}", shopOids);

        param.setYear(DateUtils.getCurrentYear());
        // 统计模型，按 月、周
        StatisticType statisticType = param.getStatisticType();
        if (statisticType != null) {
            param.setFieldName(statisticType.getFieldName());
        }

        List<StatisticItem> items = new ArrayList<>();
        // 统计项
        Map<String, BigDecimal> map = expenseFlowDao.statisticItems(param);
        if (statisticType != null) {
            // 构建item
            if (statisticType == StatisticType.Month) {
                // 按月
                int month = DateUtils.getCurrentMonthInYear();
                for (int i = 1; i <= month; i++) {
                    String key = String.valueOf(i);
                    BigDecimal value = BigDecimal.ZERO;
                    if (map.containsKey(key)) {
                        value = map.get(key);
                    }
                    StatisticItem item = StatisticItem.builder().name(key).amount(value).build();
                    items.add(item);
                }
                param.setMonth(month);
                ExpenseFlowCount count = expenseFlowDao.countBuinessMainPayment(param);
                statisticModel.setTotal(count.getTotal());
                statisticModel.setAmount(count.getPayAmount());

                if (month > 1) {
                    param.setMonth(month - 1);
                    count = expenseFlowDao.countBuinessMainPayment(param);
                    statisticModel.setPreTotal(count.getTotal());
                    statisticModel.setPreAmount(count.getPayAmount());
                }
            } else if (statisticType == StatisticType.Week) {
                // 按月
                int week = DateUtils.getCurrentWeekInYear();
                for (int i = 1; i <= week; i++) {
                    String key = String.valueOf(i);
                    BigDecimal value = BigDecimal.ZERO;
                    if (map.containsKey(key)) {
                        value = map.get(key);
                    }
                    StatisticItem item = StatisticItem.builder().name(key).amount(value).build();
                    items.add(item);
                }
                param.setWeek(week);
                ExpenseFlowCount count = expenseFlowDao.countBuinessMainPayment(param);
                statisticModel.setTotal(count.getTotal());
                statisticModel.setAmount(count.getPayAmount());

                if (week > 1) {
                    param.setWeek(week - 1);
                    count = expenseFlowDao.countBuinessMainPayment(param);
                    statisticModel.setPreTotal(count.getTotal());
                    statisticModel.setPreAmount(count.getPayAmount());
                }
            }
        }
        statisticModel.setItems(items);

        return ResultContent.buildSuccess(statisticModel);
    }


    /**
     * 得到详情
     *
     * @param id
     * @return
     */
    public ResultContent<ExpenseFlowAreaModel> getDetail(String id) {
        ExpenseFlow entity = expenseFlowDao.findTopById(id);
        if (ObjectUtils.isEmpty(entity)) {
            return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, id));
        }
        ExpenseFlowAreaModel model = toAreaModel(entity);
        return ResultContent.buildSuccess(model);
    }

    /**
     * 根据订单号查询订单信息
     *
     * @param paymentNo
     * @return
     */
    public ResultContent<ExpenseFlowAreaModel> getDetailByPaymentNo(String paymentNo) {
        ExpenseFlow entity = expenseFlowDao.findTopByPaymentNo(paymentNo);
        if (ObjectUtils.isEmpty(entity)) {
            return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, paymentNo));
        }
        ExpenseFlowModel model = toAreaModel(entity);
        return ResultContent.buildSuccess(model);
    }

    /**
     * 商家端用户退款
     *
     * @param param
     * @return
     */
    public ResultContent expenseShopRefund(ExpenseRefundParam param) {
        ExpenseFlow expenseFlow = expenseFlowDao.findTopById(param.getId());
        if (ObjectUtils.isEmpty(expenseFlow)) {
            return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, param.getId()));
        }
        if (expenseFlow.getOrderState() == OrderState.REFUNDED) {
            return ResultContent.buildFail("已退款，不能重复操作");
        }
        if (expenseFlow.getOrderState() != OrderState.HAVE_PAID) {
            return ResultContent.buildFail(String.format("未支付成功，不能退款"));
        }
        if (expenseFlow.getSettlementState() == SettlementState.AlreadySettled) {
            return ResultContent.buildFail("订单已结算，不能退款");
        }
        if (expenseFlow.getRefundState() == RefundState.Refunding) {
            return ResultContent.buildFail("退款中，不能重复发起");
        }

        // 开始调用退款方法
        ResultContent resultContent = payCallService.refund(expenseFlow, param);
        if (resultContent.isFailed()) {
            return ResultContent.buildFail(resultContent.getMsg());
        }
        return ResultContent.buildSuccess();
    }

    /**
     * 模型转换
     *
     * @param entity
     * @return
     */
    public ExpenseFlowModel toModel(ExpenseFlow entity) {
        ExpenseFlowModel model = new ExpenseFlowModel();
        if (ObjectUtils.isNotEmpty(entity)) {
            BeanUtils.copyProperties(entity, model);
            // 卡片信息
            // 用户信息
        }
        return model;
    }

    /**
     * 包含区域的model
     *
     * @param entity
     * @return
     */
    public ExpenseFlowAreaModel toAreaModel(ExpenseFlow entity) {
        ExpenseFlowAreaModel model = new ExpenseFlowAreaModel();
        if (ObjectUtils.isNotEmpty(entity)) {
            BeanUtils.copyProperties(entity, model);
            // 卡片信息
            // 用户信息
            AreaSimpleModel simpleModel = entity.getArea();
            if (ObjectUtils.isNotEmpty(simpleModel)) {
                List<AreaSimpleModel> areas = areaService.getParents(simpleModel.getId());
                if (ObjectUtils.isNotEmpty(areas)) {
                    Collections.reverse(areas);
                    List<String> names = areas.stream().map(it -> it.getName()).collect(Collectors.toList());
                    model.setAreaNames(String.join("/", names));
                }
            }
        }
        return model;
    }

}
