package com.dxhy.erp.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dxhy.common.enums.FplxEnum;
import com.dxhy.common.service.impl.MpBaseServiceImpl;
import com.dxhy.erp.dao.SignRecordInvoiceDao;
import com.dxhy.erp.entity.TDxRecordInvoiceDetail;
import com.dxhy.erp.entity.TdxRecordInvoiceStatistics;
import com.dxhy.erp.entity.TdxRecordInvoice;
import com.dxhy.erp.service.SignFpqsService;
import com.dxhy.erp.service.SignSaveInvoiceInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 发票签收业务逻辑处理实现类
 *
 * @author jiaohongyang
 */
@Service("signFpqsService")
@Slf4j
@SuppressWarnings({"AlibabaUndefineMagicConstant", "AlibabaMethodTooLong", "AlibabaCollectionInitShouldAssignCapacity",
        "AlibabaStringConcat", "AlibabaCollectionInitShouldAssignCapacity"})
public class SignFpqsServiceImpl extends MpBaseServiceImpl<SignRecordInvoiceDao, TdxRecordInvoice>
        implements SignFpqsService {

    /**
     * 构建统计实体集
     *
     * @param queryInvoiceResult
     *            响应实体
     * @return 抵账统计实体
     */
    @Override
    public List<TdxRecordInvoiceStatistics> buildRecordInvoiceStatisticsList(JSONObject queryInvoiceResult) {
        List<TDxRecordInvoiceDetail> recordInvoiceDetail = getRecordInvoiceDetail(queryInvoiceResult);
        // 定义返回值
        final List<TdxRecordInvoiceStatistics> recordInvoiceStatisticsList = new ArrayList<>();
        // 最终要的结果
        final Map<String, List<TDxRecordInvoiceDetail>> resultMap = new HashMap<>();
        // 按税率分组
        recordInvoiceDetail.forEach(dataItem -> {
            if (!"原价合计".equals(dataItem.getGoodsName().trim()) && !"折扣额合计".equals(dataItem.getGoodsName().trim())
                    && !"(详见销货清单)".equals(dataItem.getGoodsName().trim())
                    && !"（详见销货清单）".equals(dataItem.getGoodsName().trim())
                    && org.apache.commons.lang.StringUtils.isNotEmpty(dataItem.getTaxRate())) {
                if (resultMap.containsKey(dataItem.getTaxRate())) {
                    resultMap.get(dataItem.getTaxRate()).add(dataItem);
                } else {
                    final List<TDxRecordInvoiceDetail> list = new ArrayList<>();
                    list.add(dataItem);
                    resultMap.put(dataItem.getTaxRate(), list);
                }
            }
        });
        String invoiceType = queryInvoiceResult.getString("invoiceType");
        // 循环遍历map获取每组明细，并循环遍历每组里的明细组装抵账统计数据
        for (Map.Entry<String, List<TDxRecordInvoiceDetail>> entry : resultMap.entrySet()) {
            // 获取每组明细
            final List<TDxRecordInvoiceDetail> detailList = entry.getValue();
            // 定义抵账统计实体
            final TdxRecordInvoiceStatistics recordInvoiceStatistics = new TdxRecordInvoiceStatistics();
            // 税额
            BigDecimal taxAmount = new BigDecimal("0.0");
            // 金额
            BigDecimal detailAmount = new BigDecimal("0.0");
            // 循环赋值
            for (TDxRecordInvoiceDetail invoiceDetail : detailList) {
                BigDecimal bigDecimal;
                try {
                    bigDecimal = new BigDecimal(invoiceDetail.getTaxAmount());
                } catch (Exception e) {
                    bigDecimal = new BigDecimal("0");
                }
                taxAmount = taxAmount.add(bigDecimal);
                detailAmount = detailAmount.add(new BigDecimal(invoiceDetail.getDetailAmount()));

            }
            // 价税合计
            final BigDecimal totalAmount = taxAmount.add(detailAmount);
            // 税率
            recordInvoiceStatistics.setTaxRate(entry.getKey());
            if(FplxEnum.QDZZP.getFplxDm().equals(invoiceType) || FplxEnum.QDPP.getFplxDm().equals(invoiceType)){
                // 发票号码
                recordInvoiceStatistics.setInvoiceNo(queryInvoiceResult.getString("invoiceCode")+queryInvoiceResult.getString("invoiceNo"));
            }else {
                // 发票号码
                recordInvoiceStatistics.setInvoiceNo(queryInvoiceResult.getString("invoiceNo"));
                // 发票代码
                recordInvoiceStatistics.setInvoiceCode(queryInvoiceResult.getString("invoiceCode"));
            }
            // 税额
            recordInvoiceStatistics.setTaxAmount(taxAmount.toString());
            // 金额
            recordInvoiceStatistics.setDetailAmount(detailAmount);
            // 价税合计
            recordInvoiceStatistics.setTotalAmount(totalAmount);
            // 放入集合
            recordInvoiceStatisticsList.add(recordInvoiceStatistics);
        }
        // 返回
        return recordInvoiceStatisticsList;
    }

    public List<TDxRecordInvoiceDetail> getRecordInvoiceDetail(JSONObject queryInvoiceResult) {
        if (queryInvoiceResult.containsKey("detailList")) {
            JSONArray dataArray = queryInvoiceResult.getJSONArray("detailList");
            if (dataArray != null && dataArray.size() > 0) {
                String invoiceType = queryInvoiceResult.getString("invoiceType");
                String invoiceCode = queryInvoiceResult.getString("invoiceCode");
                String invoiceNo = queryInvoiceResult.getString("invoiceNo");
                String uuid = invoiceCode + invoiceNo;
                List<TDxRecordInvoiceDetail> invoiceDetailList = new ArrayList<>(dataArray.size());
                for (int i = 0; i < dataArray.size(); i++) {
                    JSONObject invoiceDetailQuery = dataArray.getJSONObject(i);
                    TDxRecordInvoiceDetail invoiceDetail = new TDxRecordInvoiceDetail();
                    invoiceDetail.setUuid(uuid);
                    if(FplxEnum.QDZZP.getFplxDm().equals(invoiceType) || FplxEnum.QDPP.getFplxDm().equals(invoiceType)){
                        invoiceDetail.setInvoiceNo(uuid);
                    }else {
                        invoiceDetail.setInvoiceCode(invoiceCode);
                        invoiceDetail.setInvoiceNo(invoiceNo);
                    }
                    invoiceDetail.setDetailNo(invoiceDetailQuery.getString("detailNo"));
                    invoiceDetail.setGoodsName(invoiceDetailQuery.getString("goodsName"));
                    invoiceDetail.setModel(invoiceDetailQuery.getString("specificationModel"));
                    invoiceDetail.setUnit(invoiceDetailQuery.getString("unit"));
                    invoiceDetail.setNum(invoiceDetailQuery.getString("num"));
                    invoiceDetail.setUnitPrice(invoiceDetailQuery.getString("unitPrice"));
                    invoiceDetail.setDetailAmount(invoiceDetailQuery.getString("detailAmount"));
                    invoiceDetail.setTaxRate(invoiceDetailQuery.getString("taxRate"));
                    invoiceDetail.setTaxAmount(invoiceDetailQuery.getString("taxAmount"));
                    if (FplxEnum.TXF.getFplxDm().equals(invoiceType)) {
                        // 通行费发票
                        invoiceDetail.setCph(invoiceDetailQuery.getString("cph"));
                        invoiceDetail.setLx(invoiceDetailQuery.getString("lx"));
                        invoiceDetail.setTxrqq(invoiceDetailQuery.getString("txrqq"));
                        invoiceDetail.setTxrqz(invoiceDetailQuery.getString("txrqz"));
                    }
                    invoiceDetailList.add(invoiceDetail);
                }
                return invoiceDetailList;
            } else {
                return null;
            }
        } else {
            return null;
        }
    }
}
