package com.dxhy.core.service.ywgl.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dxhy.api.model.config.sys.SysEnterpriseConfigEntity;
import com.dxhy.api.model.invoice.TDxRecordInvoice;
import com.dxhy.common.constant.ConfigureConstant;
import com.dxhy.common.enums.FplxEnum;
import com.dxhy.common.enums.FpztEnum;
import com.dxhy.common.exception.BaseException;
import com.dxhy.common.util.JsonUtils;
import com.dxhy.common.utils.CommonUtil;
import com.dxhy.common.utils.DateUtils;
import com.dxhy.common.utils.R;
import com.dxhy.core.dao.CoreTDxRecordInvoiceDao;
import com.dxhy.core.service.ywgl.YwglService;
import com.dxhy.jxpt.baseService.config.dao.SysEnterpriseConfigDao;
import com.dxhy.lqchannel.constants.LqConfigurerInfo;
import com.dxhy.lqrpc.model.global.gj.FpztxxcxResp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;


@Service
@Slf4j
public class YwglServiceImpl implements YwglService {

    @Autowired
    private CoreTDxRecordInvoiceDao coreTDxRecordInvoiceDao;

    @Autowired
    private SysEnterpriseConfigDao sysEnterpriseConfigDao;

    @Override
    public Map<String, Object> fpsltj(Map<String, String> map) {
        Map<String, Object> retMap = new HashMap<>();
        AtomicInteger zsl = new AtomicInteger(0);
        List<Map<String, String>> fpsltj = getTjjg(map);
        fpsltj.stream().forEach(tjjg->{
            zsl.addAndGet(Integer.valueOf(tjjg.get("fpzsl")));
        });
        retMap.put("zsl", String.valueOf(zsl.get()));
        retMap.put("datas", fpsltj);
        return retMap;
    }

    @Override
    public List<Map<String, String>> getTjjg(Map<String, String> map) {
        List<Map<String, String>> fpsltj = new ArrayList<>();
        String nsrsbh = map.get("nsrsbh");
        String nsrmc = map.get("nsrmc");
        String kprqq = map.get("kprqq");
        String kprqz = map.get("kprqz");
        String fplx = map.get("fplx");
        String[] fplxs = fplx.split(",");
        List<String> months = DateUtils.splitDateByMonth(CommonUtil.dateConvert(kprqq), CommonUtil.dateConvert(kprqz));
        months.stream().forEach(month->{
            String[] split = month.split("@");
            String startTime = split[0];
            String endTime = split[1];
            Arrays.stream(fplxs).forEach(lx->{
                String time = startTime.substring(0, 7).replace("-", "");
                String fplxmc = FplxEnum.getFplxEnumByFplxdm(lx).getFplxMc(FplxEnum.getFplxEnumByFplxdm(lx).getIndex());
                AtomicInteger zcfpsl = new AtomicInteger(0);
                AtomicInteger skfpsl = new AtomicInteger(0);
                AtomicInteger zffpsl = new AtomicInteger(0);
                AtomicInteger ycfpsl = new AtomicInteger(0);
                AtomicInteger chfpsl = new AtomicInteger(0);
                AtomicInteger bfchfpsl = new AtomicInteger(0);
                AtomicInteger qbchfpsl = new AtomicInteger(0);
                AtomicInteger hzfpdqrsl = new AtomicInteger(0);
                List<TDxRecordInvoice> invoices = coreTDxRecordInvoiceDao.selectList(new QueryWrapper<TDxRecordInvoice>()
                        .eq("gf_tax_no", nsrsbh)
                        .eq("invoice_type", lx)
                        .ge("invoice_date", startTime)
                        .le("invoice_date", endTime));
                invoices.stream().forEach(invoice->{
                    if (FpztEnum.ZC.getFpztDm().equals(invoice.getInvoiceStatus())) {
                        zcfpsl.incrementAndGet();
                    }
                    if (FpztEnum.ZF.getFpztDm().equals(invoice.getInvoiceStatus())) {
                        zffpsl.incrementAndGet();
                    }
                    if (FpztEnum.SK.getFpztDm().equals(invoice.getInvoiceStatus())) {
                        skfpsl.incrementAndGet();
                    }
                    if (FpztEnum.YC.getFpztDm().equals(invoice.getInvoiceStatus())) {
                        ycfpsl.incrementAndGet();
                    }
                    if (FpztEnum.HC.getFpztDm().equals(invoice.getInvoiceStatus())) {
                        chfpsl.incrementAndGet();
                    }
                    if (FpztEnum.BFNC.getFpztDm().equals(invoice.getInvoiceStatus())) {
                        bfchfpsl.incrementAndGet();
                    }
                    if (FpztEnum.QEHC.getFpztDm().equals(invoice.getInvoiceStatus())) {
                        qbchfpsl.incrementAndGet();
                    }
                    if (FpztEnum.HZDQR.getFpztDm().equals(invoice.getInvoiceStatus())) {
                        hzfpdqrsl.incrementAndGet();
                    }
                });
                Map<String, String> tjMap = new HashMap<>();
                tjMap.put("gfmc",nsrmc);
                tjMap.put("gfsh",nsrsbh);
                tjMap.put("time",time);
                tjMap.put("fplxmc",fplxmc);
                tjMap.put("fpzsl",String.valueOf(invoices.size()));
                tjMap.put("zcfpsl",String.valueOf(zcfpsl.get()));
                tjMap.put("skfpsl",String.valueOf(skfpsl.get()));
                tjMap.put("zffpsl",String.valueOf(zffpsl.get()));
                tjMap.put("ycfpsl",String.valueOf(ycfpsl.get()));
                tjMap.put("chfpsl",String.valueOf(chfpsl.get()));
                tjMap.put("bfchfpsl",String.valueOf(bfchfpsl.get()));
                tjMap.put("qbchfpsl",String.valueOf(qbchfpsl.get()));
                tjMap.put("hzfpdqrsl",String.valueOf(hzfpdqrsl.get()));
                fpsltj.add(tjMap);
            });
        });
        return fpsltj;
    }

    @Override
    public List<Map<String, String>> fpztSgtb(String fpdm,String fphm,String sdhm) {
        List<Map<String, String>> retList = new ArrayList<>();
        TDxRecordInvoice invoice = null;
        if (StringUtils.isNotBlank(sdhm)) {
            invoice = coreTDxRecordInvoiceDao.selectOne(new QueryWrapper<TDxRecordInvoice>().eq("ele_invoice_no", sdhm));
        } else {
            invoice = coreTDxRecordInvoiceDao.selectOne(new QueryWrapper<TDxRecordInvoice>().eq("invoice_code", fpdm).eq("invoice_no",fphm));
        }

        if (invoice == null) {
            log.info("底账库不存在该发票");
            throw new BaseException("底账库不存在该发票");
        }

        SysEnterpriseConfigEntity enterpriseConfig = sysEnterpriseConfigDao.selectOne(new QueryWrapper<SysEnterpriseConfigEntity>().eq("nsrsbh", invoice.getGfTaxNo()));
        if (enterpriseConfig == null) {
            log.info("未查询到该购方税号：{}的配置信息",invoice.getGfTaxNo());
            throw new BaseException("未查询到该购方税号:"+invoice.getGfTaxNo()+"的配置信息");
        }

        if (!enterpriseConfig.getJrfs().equals(ConfigureConstant.STRING_1)) {
            log.info("该购方税号：{}非乐企用户",invoice.getGfTaxNo());
            throw new BaseException("该购方税号："+invoice.getGfTaxNo()+"非乐企用户");
        }

        getFpztTbjg(enterpriseConfig.getSydwptbm(),retList,invoice);
        return retList;
    }

    private void getFpztTbjg(String sydwptbm, List<Map<String, String>> retList,TDxRecordInvoice invoice) {
        FpztxxcxResp fpztxxcx = com.dxhy.lqchannel.utils.CommonUtil.callFpztxx(com.dxhy.lqchannel.utils.CommonUtil.conversionInvoiceTypeToLQ(invoice.getInvoiceType())
                , invoice.getEleInvoiceNo()
                , invoice.getInvoiceCode()
                , invoice.getInvoiceNo()
                , new SimpleDateFormat("yyyyMMdd").format(invoice.getInvoiceDate())
                , sydwptbm);
        log.info("乐企发票状态信息查询结果：{}", JsonUtils.getInstance().toJsonString(fpztxxcx));
        if (fpztxxcx != null && LqConfigurerInfo.RETURNCODE_SUCCESS.equals(fpztxxcx.getReturncode())) {
            //发票状态转换
            String invoiceStatus = invoice.getInvoiceStatus();
            if (StringUtils.isNotBlank(fpztxxcx.getFpzt())) {
                invoice.setInvoiceStatus(fpztxxcx.getFpzt());
            }
            //扩展信息乐企红字锁定标识转换
            if (StringUtils.isNotBlank(fpztxxcx.getHzsdbs())) {
                invoice.setLqHzsdbs(StringUtils.isBlank(fpztxxcx.getHzsdbs())?"N":fpztxxcx.getHzsdbs());
/*                if ("Y".equals(fpztxxcx.getHzsdbs())) {
                    invoice.setInvoiceStatus("80");
                }*/
            }
            //发票管理状态转换
            if (StringUtils.isNotBlank(fpztxxcx.getYcpzzt())) {
                //管理状态转换
                if ("01".equals(fpztxxcx.getYcpzzt())) {
                    invoice.setGlzt("0");
                } else if ("02".equals(fpztxxcx.getYcpzzt())) {
                    invoice.setGlzt("1");
                } else if ("03".equals(fpztxxcx.getYcpzzt())) {
                    invoice.setGlzt("2");
                }else {
                    invoice.setGlzt("0");
                }
                if ("02".equals(fpztxxcx.getYcpzzt()) || "03".equals(fpztxxcx.getYcpzzt())) {
                    invoice.setInvoiceStatus("4");
                }
            }
            if (!invoiceStatus.equals(invoice.getInvoiceStatus())) {
                invoice.setStatusUpdateDate(new Date());
            }

            Map<String,String> map = com.dxhy.lqchannel.utils.CommonUtil.fpytConvert(fpztxxcx.getFpyt());
            //根据发票用途转换抵账表发票状态
            if (!("1".equals(invoice.getAuthStatus())
                    ||"2".equals(invoice.getAuthStatus())
                    ||"3".equals(invoice.getAuthStatus())
                    ||"1".equals(invoice.getCxrzStatus())
                    ||"2".equals(invoice.getCxrzStatus())
                    ||"1".equals(invoice.getCxbdkStatus())
                    ||"2".equals(invoice.getCxbdkStatus()))) {
                if (StringUtils.isNotBlank(fpztxxcx.getFpyt())) {
                    invoice.setLqFpyt(fpztxxcx.getFpyt());

                    if (StringUtils.isNotBlank(map.get(LqConfigurerInfo.FPZT_RZHYESORNO))) {
                        invoice.setRzhYesorno(map.get(LqConfigurerInfo.FPZT_RZHYESORNO));
                    }
                    if (StringUtils.isNotBlank(map.get(LqConfigurerInfo.FPZT_SFYGX))) {
                        invoice.setSfygx(map.get(LqConfigurerInfo.FPZT_SFYGX));
                    }
                    if (StringUtils.isNotBlank(map.get(LqConfigurerInfo.FPZT_AUTHSTATUS))) {
                        invoice.setAuthStatus(map.get(LqConfigurerInfo.FPZT_AUTHSTATUS));
                    }
                    if (StringUtils.isNotBlank(map.get(LqConfigurerInfo.FPZT_RZLX))) {
                        invoice.setRzlx(map.get(LqConfigurerInfo.FPZT_RZLX));
                    }
                    if (StringUtils.isNotBlank(map.get(LqConfigurerInfo.FPZT_BDKSTATUS))) {
                        invoice.setBdkStatus(map.get(LqConfigurerInfo.FPZT_BDKSTATUS));
                    }
                    if (StringUtils.isNotBlank(map.get(LqConfigurerInfo.FPZT_SFDBTS))) {
                        invoice.setSfdbts(map.get(LqConfigurerInfo.FPZT_SFDBTS));
                    }
                }
            }

            //入账状态转换
            if (StringUtils.isNotBlank(fpztxxcx.getRzzt())&&!"04".equals(invoice.getLqRzzt())&&!"05".equals(invoice.getLqRzzt())) {
                invoice.setLqRzzt(fpztxxcx.getRzzt());
            }
            //成品油异常标识转换
            if (StringUtils.isNotBlank(fpztxxcx.getCpyycbs())) {
                invoice.setLqCpyycbs(fpztxxcx.getCpyycbs());
            }
            //出口退税类代码转换
            if (StringUtils.isNotBlank(fpztxxcx.getCktsldm())) {
                invoice.setLqCktsldm(fpztxxcx.getCktsldm());
            }
            //增值税优惠用途（农产品加计扣除）
            if (StringUtils.isNotBlank(fpztxxcx.getZzsyhyt())) {
                invoice.setLqZzsyhyt(fpztxxcx.getZzsyhyt());
            }
            //消费税用途
            if (StringUtils.isNotBlank(fpztxxcx.getXfsyt())) {
                invoice.setLqXfsyt(fpztxxcx.getXfsyt());
            }
            //机动车异常标识
            if (StringUtils.isNotBlank(fpztxxcx.getJdcycbs())) {
                invoice.setLqJdcycbs(fpztxxcx.getJdcycbs());
            }
            //税款所属期
            if (StringUtils.isNotBlank(fpztxxcx.getSkssq())) {
                invoice.setRzhBelongDate(fpztxxcx.getSkssq());
            }
            coreTDxRecordInvoiceDao.updateById(invoice);
            //组织返回数据
            Map<String, String> retMap = new HashMap<>();
            retMap.put("fplxmc", FplxEnum.getFplxEnumByFplxdm(invoice.getInvoiceType()).getFplxMc(FplxEnum.getFplxEnumByFplxdm(invoice.getInvoiceType()).getIndex()));
            retMap.put("fpdm", invoice.getInvoiceCode());
            retMap.put("fphm", invoice.getInvoiceNo());
            retMap.put("sdhm", invoice.getEleInvoiceNo());
            retMap.put("kprq", DateUtils.dateToStr(invoice.getInvoiceDate()));
            retMap.put("fpzt", CommonUtil.fpztzhz(invoice.getInvoiceStatus()));
            retMap.put("glzt", CommonUtil.glztzhz(invoice.getGlzt()));
            retMap.put("rzlx", CommonUtil.rzlxzhz(map.get(LqConfigurerInfo.FPZT_RZLX)));
            retMap.put("rzzt", "0".equals(map.get(LqConfigurerInfo.FPZT_RZHYESORNO))?"未认证":"已认证");
            retMap.put("rzhBelongDate", invoice.getRzhBelongDate());
            retMap.put("cwrzzt","02".equals(fpztxxcx.getRzzt())?"已入账":"未入账");
            retMap.put("cpyycbs",CommonUtil.cpyycbszhz(fpztxxcx.getCpyycbs()));
            retMap.put("cktsldm", CommonUtil.cktsldmzhz(fpztxxcx.getCktsldm()));
            retMap.put("zzsyhyt", CommonUtil.zzsyhytzhz(fpztxxcx.getZzsyhyt()));
            retMap.put("xfsyt", CommonUtil.xfsytzhz(fpztxxcx.getXfsyt()));
            retMap.put("jdcycbs", CommonUtil.jdcycbszhz(fpztxxcx.getJdcycbs()));
            retList.add(retMap);
        } else {
            log.info("乐企未查询到发票状态信息");
            throw new RuntimeException("乐企未查询到发票状态信息");
        }
    }

    @Override
    public ResponseEntity<R> fpztdrtb(List<Map<String, String>> reqList) {
        List<String> errorMsgList = checkDrParam(reqList);
        if (!CollectionUtils.isEmpty(errorMsgList)) {
            log.info("参数校验未通过");
            return ResponseEntity.ok(R.error(9998, "参数校验未通过").put("data", errorMsgList));
        }

        List<Map<String, String>> retList = new ArrayList<>();

        reqList.stream().forEach(param->{
            try {
                String fpdm = param.get("fpdm");
                String fphm = param.get("fphm");
                String sdhm = null;
                if (StringUtils.isBlank(fpdm) && StringUtils.isNotBlank(fphm) && fphm.length() == 20) {
                    //判断为数电号码
                    sdhm = fphm;
                }
                TDxRecordInvoice invoice = null;
                if (StringUtils.isNotBlank(sdhm)) {
                    invoice = coreTDxRecordInvoiceDao.selectOne(new QueryWrapper<TDxRecordInvoice>().eq("ele_invoice_no", sdhm));
                } else {
                    invoice = coreTDxRecordInvoiceDao.selectOne(new QueryWrapper<TDxRecordInvoice>().eq("invoice_code", fpdm).eq("invoice_no",fphm));
                }
                SysEnterpriseConfigEntity enterpriseConfig = sysEnterpriseConfigDao.selectOne(new QueryWrapper<SysEnterpriseConfigEntity>().eq("nsrsbh", invoice.getGfTaxNo()));
                getFpztTbjg(enterpriseConfig.getSydwptbm(),retList,invoice);
            } catch (Exception e) {
                log.info("业务处理异常：{}", e);
                return;
            }
        });
        log.info("导入同步完成");
        return ResponseEntity.ok(R.ok().put("data", retList));
    }

    private List<String> checkDrParam(List<Map<String, String>> reqList) {
        int index = 0;
        List<String> errorMsgList = new ArrayList<>();
        for (Map<String, String> param : reqList) {
            String error = null;
            index ++;
            String fpdm = param.get("fpdm");
            String fphm = param.get("fphm");
            String sdhm = null;
            if (StringUtils.isNotBlank(fpdm)) {
                if (fpdm.length() != 10 && fpdm.length() != 12) {
                    error = "第"+index+ "条数据：发票代码不为空时，发票代码长度应为10或者12";
                    log.info("error");
                    errorMsgList.add(error);
                    continue;
                }
                if (!CommonUtil.checkStrNum(fpdm)) {
                    error = "第"+index+ "条数据：发票代码不为空时，发票代码必须为数字";
                    log.info("error");
                    errorMsgList.add(error);
                    continue;
                }
                if (StringUtils.isBlank(fphm) || fphm.length() != 8) {
                    error = "第"+index+ "条数据：发票代码不为空时，发票号码长度必须为8";
                    log.info("error");
                    errorMsgList.add(error);
                    continue;
                }
            }else{
                if (StringUtils.isBlank(fphm) || fphm.length() != 20) {
                    error = "第"+index+ "条数据：发票代码为空时，发票号码长度必须为20";
                    log.info("error");
                    errorMsgList.add(error);
                    continue;
                }
            }
            if (!CommonUtil.checkStrNum(fphm)) {
                error = "第"+index+ "条数据：发票号码必须为数字";
                log.info("error");
                errorMsgList.add(error);
                continue;
            }

            if (StringUtils.isBlank(fpdm) && StringUtils.isNotBlank(fphm) && fphm.length() == 20) {
                //判断为数电号码
                sdhm = fphm;
            }

            TDxRecordInvoice invoice = null;
            if (StringUtils.isNotBlank(sdhm)) {
                invoice = coreTDxRecordInvoiceDao.selectOne(new QueryWrapper<TDxRecordInvoice>().eq("ele_invoice_no", sdhm));
            } else {
                invoice = coreTDxRecordInvoiceDao.selectOne(new QueryWrapper<TDxRecordInvoice>().eq("invoice_code", fpdm).eq("invoice_no",fphm));
            }

            if (invoice == null) {
                error = "第"+index+ "条数据：底账库不存在该发票";
                log.info("error");
                errorMsgList.add(error);
                continue;
            }

            SysEnterpriseConfigEntity enterpriseConfig = sysEnterpriseConfigDao.selectOne(new QueryWrapper<SysEnterpriseConfigEntity>().eq("nsrsbh", invoice.getGfTaxNo()));
            if (enterpriseConfig == null) {
                error = "第"+index+ "条数据：未查询到该购方税号："+invoice.getGfTaxNo()+"的配置信息";
                log.info("error");
                errorMsgList.add(error);
                continue;
            }

            if (!enterpriseConfig.getJrfs().equals(ConfigureConstant.STRING_1)) {
                error = "第"+index+ "条数据：该购方税号：："+invoice.getGfTaxNo()+"非乐企用户";
                log.info("error");
                errorMsgList.add(error);
                continue;
            }
        }
        return errorMsgList;
    }
}
