package com.dxhy.erp.service.impl;

import com.alibaba.fastjson.JSON;
import com.dxhy.api.model.config.sys.SysEnterpriseConfigDto;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.ReturnCodeEnum;
import com.dxhy.common.util.MathUtil;
import com.dxhy.common.util.pojo.Authorize;
import com.dxhy.common.util.pojo.GlobalInfo;
import com.dxhy.erp.dao.DeclareDao;
import com.dxhy.erp.dao.SysEnterpriseConfigErpDao;
import com.dxhy.erp.entity.ReportStatisticsPo;
import com.dxhy.erp.entity.ReportTransferStatisticsPo;
import com.dxhy.erp.model.*;
import com.dxhy.erp.model.auth.InterfaceCode;
import com.dxhy.erp.service.DeclareService;
import com.dxhy.erp.utils.CheckUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author yangmy
 */
@Service("declareService")
@Slf4j
public class DeclareServiceImpl implements DeclareService {

    @Autowired
    private SysEnterpriseConfigErpDao enterpriseConfigErpDao;

    @Autowired
    private DeclareDao declareDao;

    @Override
    public String getTransferStatistics(GlobalInfo globalInfo, Map<String, String> map, HttpServletRequest request,
                                        HttpServletResponse response, Authorize authorize) {
        ReturnStateInfo run = new ReturnStateInfo();
        ReportTransferStatisticsModel reportStatisticsModel =new ReportTransferStatisticsModel();
        InterfaceCode interfaceCode = new InterfaceCode();
        ReportTransferStatisticsPo data ;
        try {
            data = JSON.parseObject(map.get("data"), ReportTransferStatisticsPo.class);
            log.info("----申报进项转出入参----transferData:{}", JSON.toJSONString(data));
            run = getCheck(data);
            if (run.getReturnCode() != null || run.getReturnMessage() != null) {
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(run);
                log.info("申报进项转出执行失败:{}", JSON.toJSONString(interfaceCode));
                return JSON.toJSONString(interfaceCode);
            }
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            SysEnterpriseConfigDto deptEntity = enterpriseConfigErpDao.getOrg(data.getBuyerTaxNo());
            String dbName;
            if(deptEntity!=null && deptEntity.getDbName()!=null){
                dbName = deptEntity.getDbName();
            }else {
                ReturnStateInfo runInfo = new ReturnStateInfo();
                runInfo.setReturnCode(ReturnCodeEnum.JTSHBF.getFhzDm());
                runInfo.setReturnMessage(ReturnCodeEnum.JTSHBF.getFhzMc(ReturnCodeEnum.JTSHBF.getIndex()));
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(runInfo);
                return JSON.toJSONString(interfaceCode);
            }
            String resultData = "";
            //获取进项转出数据信息
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
            List<TransferStatisticsModel> transferStatistics = declareDao.getTransferStatistics(data);
            //组合拼装返回的实体信息
            reportStatisticsModel.setBuyerTaxNo(data.getBuyerTaxNo());
            reportStatisticsModel.setBelongDate(data.getBelongDate());
            reportStatisticsModel.setInvoices(transferStatistics);
            resultData = JSON.toJSONString(reportStatisticsModel);
            log.info("----申报进项转出出参----transferResultData:{}",resultData);
            run.setReturnCode(ReturnCodeEnum.CLCG.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.CLCG.getFhzMc(ReturnCodeEnum.CLCG.getIndex()));
            interfaceCode.setReturnStateInfo(run);
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setData(Base64.encodeBase64String(resultData.getBytes(StandardCharsets.UTF_8)));
            return JSON.toJSONString(interfaceCode);
        }catch (Exception e){
            run.setReturnCode(ReturnCodeEnum.CLSB.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.CLSB.getFhzMc(ReturnCodeEnum.CLSB.getIndex()));
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setReturnStateInfo(run);
            log.error("申报进项转出执行失败:{}", e.getMessage());
            return JSON.toJSONString(interfaceCode);
        }
    }

    @Override
    public String getReportStatistics(GlobalInfo globalInfo, Map<String, String> map, HttpServletRequest request,
                                      HttpServletResponse response, Authorize authorize) {
        ReturnStateInfo run = new ReturnStateInfo();
        ReportStatisticsModel reportStatisticsModel = new ReportStatisticsModel();
        InterfaceCode interfaceCode = new InterfaceCode();
        ReportStatisticsPo data;
        try {
            data = JSON.parseObject(map.get("data"), ReportStatisticsPo.class);
            log.info("-----申报统计接口入参-----reportStatistics:{}", JSON.toJSON(data));
            run = getCheck(data);
            if (run.getReturnCode() != null || run.getReturnMessage() != null) {
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(run);
                log.info("申报统计执行失败：{}", JSON.toJSON(interfaceCode));
                return JSON.toJSONString(interfaceCode);
            }
            String dbName;
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            SysEnterpriseConfigDto deptEntity = enterpriseConfigErpDao.getOrg(data.getBuyerTaxNo());
            if (deptEntity != null && deptEntity.getDbName() != null) {
                dbName = deptEntity.getDbName();
            } else {
                ReturnStateInfo runInfo = new ReturnStateInfo();
                runInfo.setReturnCode(ReturnCodeEnum.JTSHBF.getFhzDm());
                runInfo.setReturnMessage(ReturnCodeEnum.JTSHBF.getFhzMc(ReturnCodeEnum.JTSHBF.getIndex()));
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(runInfo);
                return JSON.toJSONString(interfaceCode);
            }
            String resultData = "";
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
            //根据统计类型获取数据信息
            List<ReportInvoiceStatisticsModel> reportStatistics = reportStatistics(data);
            //组合拼装返回实体信息
            reportStatisticsModel.setBuyerTaxNo(data.getBuyerTaxNo());
            reportStatisticsModel.setBelongDate(data.getBelongDate());
            reportStatisticsModel.setStatisticsType(data.getStatisticsType());
            reportStatisticsModel.setInvoices(reportStatistics);
            resultData = JSON.toJSONString(reportStatisticsModel);
            log.info("-----申报统计接口出参-----reportStatisticsData:{}", resultData);
            run.setReturnCode(ReturnCodeEnum.CLCG.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.CLCG.getFhzMc(ReturnCodeEnum.CLCG.getIndex()));
            interfaceCode.setReturnStateInfo(run);
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setData(Base64.encodeBase64String(resultData.getBytes(StandardCharsets.UTF_8)));
            return JSON.toJSONString(interfaceCode);
        } catch (Exception e) {
            run.setReturnCode(ReturnCodeEnum.CLSB.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.CLSB.getFhzMc(ReturnCodeEnum.CLSB.getIndex()));
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setReturnStateInfo(run);
            log.error("申报统计接口执行失败:{}", e.getMessage());
            return JSON.toJSONString(interfaceCode);
        }
    }

    public List<ReportInvoiceStatisticsModel> reportStatistics( ReportStatisticsPo data){
        List<ReportInvoiceStatisticsModel> reportStatistics = new ArrayList<>();
        /**
         * 1-认证抵扣类： 统计本期认证抵扣税额合计值、金额合计值、抵扣发票张数
         * 增值税专用发票、增值税电子专用发票、通行费电子普通发票、机动车销售统一发票
         */
        if("1".equals(data.getStatisticsType())){
            reportStatistics =  declareDao.getVatStatistics(data);
        }
        /**
         * 2-实名客票计算抵扣类:统计本期计算抵扣税额合计值、金额合计值、抵扣发票张数
         *火车票 、航空客运电子客票行程单、公路运输（实名）、水路运输（实名）、其他运输（实名）、增值税电子普通发票（旅客运输相关）
         */
        if("2".equals(data.getStatisticsType())){
            reportStatistics = declareDao.getTicketStatistics(data);
        }
        /**
         * 3-代扣代缴计算抵扣类:统计本期计算抵扣税额（票据详情中增值税额项）合计值、抵扣发票张数；
         * 代扣代缴税收通用缴款书、完税证明
         */
        if("3".equals(data.getStatisticsType())){
            reportStatistics = declareDao.getWithholdingStatistics(data);
        }
        /**
         * 4-桥闸计算抵扣类：:统计本期计算抵扣税额合计值、金额合计值、抵扣发票张数
         * 过路过桥发票-通行类型：过桥过闸
         */
        if("4".equals(data.getStatisticsType())){
            reportStatistics =  declareDao.getBridgeStatistics(data);
        }
        /**
         * 5-海关进口增值税专用缴款书:统计本期认证抵扣税额合计值、抵扣发票张数
         * 海关进口增值税专用缴款书
         */
        if("5".equals(data.getStatisticsType())){
            reportStatistics = declareDao.getCustomStatistics(data);
        }
        //调整参数保留位
        reportStatistics.stream().forEach(reportInvoiceStatisticsModel->{
            reportInvoiceStatisticsModel.setInvoiceAmoutSum(MathUtil.round(reportInvoiceStatisticsModel.getInvoiceAmoutSum()));
            reportInvoiceStatisticsModel.setDkTaxAmount(MathUtil.round(reportInvoiceStatisticsModel.getDkTaxAmount()));
        });
        return reportStatistics;
    }
    public ReturnStateInfo getCheck(ReportTransferStatisticsPo data) {
        ReturnStateInfo run = new ReturnStateInfo();

        if (CheckUtils.isNullOrEmpty(data.getBuyerTaxNo())) {
            run.setReturnCode(ReturnCodeEnum.SHBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.SHBNWK.getFhzMc(ReturnCodeEnum.SHBNWK.getIndex()));
        }
        if (CheckUtils.isNullOrEmpty(data.getBelongDate()) || (!CheckUtils.stringLength(data.getBelongDate(), 6))) {
            run.setReturnCode(ReturnCodeEnum.SKSSQ.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.SKSSQ.getFhzMc(ReturnCodeEnum.SKSSQ.getIndex()));
        }
        return run;
    }

    public ReturnStateInfo getCheck(ReportStatisticsPo data) {
        ReturnStateInfo run = new ReturnStateInfo();

        if (CheckUtils.isNullOrEmpty(data.getBuyerTaxNo())) {
            run.setReturnCode(ReturnCodeEnum.SHBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.SHBNWK.getFhzMc(ReturnCodeEnum.SHBNWK.getIndex()));
        }
        if (CheckUtils.isNullOrEmpty(data.getBelongDate()) || (!CheckUtils.stringLength(data.getBelongDate(), 6))) {
            run.setReturnCode(ReturnCodeEnum.SKSSQ.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.SKSSQ.getFhzMc(ReturnCodeEnum.SKSSQ.getIndex()));
        }
        if (CheckUtils.isNullOrEmpty(data.getStatisticsType())) {
            run.setReturnCode(ReturnCodeEnum.TJLXWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.TJLXWK.getFhzMc(ReturnCodeEnum.TJLXWK.getIndex()));
        }
        return run;
    }
}
