package com.cf.imes.module.system.service.funds.organamount;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.cf.imes.framework.common.util.date.LocalDateTimeUtils;
import com.cf.imes.framework.security.core.util.SecurityFrameworkUtils;
import com.cf.imes.module.system.controller.admin.funds.organamount.vo.ManageAmountOverviewRespVO;
import com.cf.imes.module.system.controller.admin.funds.organamount.vo.OrganAmountGroupByCreateTimeRespVO;
import com.cf.imes.module.system.controller.admin.funds.organamount.vo.OrganFundsStatisticsReqVO;
import com.cf.imes.module.system.controller.admin.funds.organamount.vo.OrganProductOverviewRespVO;
import com.cf.imes.module.system.controller.admin.funds.organamount.vo.TotalSalesAmountRespVO;
import com.cf.imes.module.system.controller.admin.funds.purchase.vo.OrgEarliestPurchaseProductRespVO;
import com.cf.imes.module.system.dal.dataobject.funds.purchase.PurchaseRecordDO;
import com.cf.imes.module.system.dal.mysql.incomeandexpense.IncomeExpenseDetailsMapper;
import com.cf.imes.module.system.service.funds.invoice.InvoiceService;
import com.cf.imes.module.system.service.funds.purchase.PurchaseService;
import com.cf.imes.module.system.service.organ.OrganService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.hutool.core.date.DatePattern.NORM_DATETIME_FORMATTER;
import static com.cf.imes.framework.common.constants.StatisticsConstants.DATELIST_FIELD_NAME;
import static com.cf.imes.framework.common.constants.StatisticsConstants.SERIES_FIELD_NAME;
import static com.cf.imes.framework.common.util.time.StatisticsChangeUtils.generateDateRangeAxis;
import static com.cf.imes.framework.common.util.time.StatisticsChangeUtils.getDateList;

/**
 * @author 资金管理接口 实现类
 */
@Slf4j
@Service
public class OrganAmountServiceImpl implements OrganAmountService {


    @Resource
    private IncomeExpenseDetailsMapper incomeExpenseDetailsMapper;

    @Resource
    private OrganService organService;

    @Resource
    private InvoiceService invoiceService;

    @Resource
    private PurchaseService purchaseService;

    @Override
    public OrganProductOverviewRespVO getOrganProductOverview() {

        Long organId = SecurityFrameworkUtils.getUserOrganId();

        organService.validOrgan(organId);

        OrganProductOverviewRespVO organProductOverviewRespVO = new OrganProductOverviewRespVO();

        // 查询组织最晚还有效的产品购买记录
        OrgEarliestPurchaseProductRespVO orgEarliestProductDetail = purchaseService.getOrgEarliestProductDetail(organId);
        if (ObjectUtil.isNotNull(orgEarliestProductDetail)) {
            // 查询对应购买记录
            PurchaseRecordDO purchaseRecordDO = orgEarliestProductDetail.getPurchaseRecordDO();
            organProductOverviewRespVO.setProductEfficientDate(LocalDateTimeUtil.format(purchaseRecordDO.getEndTime(), NORM_DATETIME_FORMATTER));
            // 首购记录不展示时长
            if (!purchaseRecordDO.getInitial()) {
                organProductOverviewRespVO.setDuration(purchaseRecordDO.getPurchaseDuration());
                organProductOverviewRespVO.setDurationUnit(purchaseRecordDO.getPurchaseDurationUnit());
            }
        }

        // 查询可开票金额
        organProductOverviewRespVO.setInvoiceableAmount(purchaseService.getInvoicingAmount(organId));
        return organProductOverviewRespVO;

    }

    @Override
    public ManageAmountOverviewRespVO getOrganAmountAll() {
        ManageAmountOverviewRespVO respVO = new ManageAmountOverviewRespVO();

        TotalSalesAmountRespVO totalSales = purchaseService.getTotalSales();
        // 销售总额
        respVO.setTotalSalesAmount(totalSales.getAmount());
        // 可开票金额
        respVO.setToExamineAmount(invoiceService.getManageInvoiceAmount().getPendingInvoice());

        return respVO;
    }

    @Override
    public Map<String, Object> getConsumptionTrend(OrganFundsStatisticsReqVO reqVO, boolean queryOrg) {
        Map<String, Object> resultMap = new HashMap<>();
        // 所有的日期集合
        List<String> dateList = getDateList(reqVO);

        Long organId = SecurityFrameworkUtils.getUserOrganId();
        List<Map<String, Object>> series = new ArrayList<>();
        Map<String, Object> orgAmountSeriesItem = new HashMap<>();

        reqVO.setCreateTimeForQry(LocalDateTimeUtils.generateTimeSection(reqVO.getCreateTime()));
        // 查询组织收支趋势统计
        Map<String, List<OrganAmountGroupByCreateTimeRespVO>> organIncomeExpenseGroupByCreateTimeRespMap = incomeExpenseDetailsMapper.selectOrganIncomeExpenseTrendGroupByCreateTime(reqVO, queryOrg ? organId : null).stream()
                .sorted(Comparator.naturalOrder())
                .collect(Collectors.groupingBy(OrganAmountGroupByCreateTimeRespVO::getDate, LinkedHashMap::new, Collectors.toList()));

        BigDecimal[] amountArr = new BigDecimal[dateList.size()];
        // 遍历时间跨度列表，匹配数量存入数组，没有补0存入数组
        for (int i = 0; i < dateList.size(); i++) {
            String dateStr = dateList.get(i);

            List<OrganAmountGroupByCreateTimeRespVO> organIncomeExpenseGroupByCreateTimeRespVOS = organIncomeExpenseGroupByCreateTimeRespMap.get(dateStr);
            amountArr[i] = CollUtil.isNotEmpty(organIncomeExpenseGroupByCreateTimeRespVOS) ? organIncomeExpenseGroupByCreateTimeRespVOS.get(0).getAmount() : BigDecimal.ZERO;
        }

        orgAmountSeriesItem.put("data", amountArr);
        orgAmountSeriesItem.put("name", "收支金额");
        series.add(orgAmountSeriesItem);

        // x轴时间区间字符串
        resultMap.put(DATELIST_FIELD_NAME, dateList.stream().map(date -> generateDateRangeAxis(date, reqVO.getUnit())).toList());
        // 类别：类别：平方数数组
        resultMap.put(SERIES_FIELD_NAME, series);

        return resultMap;
    }
}
