package com.dxhy.jxpt.baseService.config.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dxhy.api.model.config.sys.SysEnterpriseConfigEntity;
import com.dxhy.api.model.config.sys.SysGroupConfigEntity;
import com.dxhy.api.model.config.sys.TdxLqQllsfpcjKzEntity;
import com.dxhy.api.model.config.sys.TdxLqQllshgjkscjKzEntity;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.service.impl.MpBaseServiceImpl;
import com.dxhy.common.utils.BaseContextHandler;
import com.dxhy.common.utils.DateUtils;
import com.dxhy.common.utils.R;
import com.dxhy.jxpt.baseService.config.dao.SysGroupConfigDao;
import com.dxhy.jxpt.baseService.config.dao.BaseServiceTdxLqQllsfpcjKzDao;
import com.dxhy.jxpt.baseService.config.dao.BaseServiceTdxLqQllshgjkscjKzDao;
import com.dxhy.jxpt.baseService.config.service.LqInitService;
import com.dxhy.jxpt.baseService.constants.LqConfigurerInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;


@Service("baseServicelqInitService")
@Slf4j
public class LqInitServiceImpl extends MpBaseServiceImpl<BaseServiceTdxLqQllshgjkscjKzDao, TdxLqQllshgjkscjKzEntity> implements LqInitService {

    @Autowired(required = false)
    private BaseServiceTdxLqQllsfpcjKzDao baseServiceTdxLqQllsfpcjKzDao;

    @Autowired(required = false)
    private BaseServiceTdxLqQllshgjkscjKzDao baseServiceTdxLqQllshgjkscjKzDao;

    @Autowired(required = false)
    private SysGroupConfigDao sysGroupConfigDao;

    /**
     * @Description 保存或更新乐企票种信息
     * @param lqEnterList 乐企信息
     * @param paramPzList 新增的票种信息
     * @Return void
     * @Author wangruwei
     * @Date 2022/11/23 10:53
     **/
    @Override
    public ResponseEntity<?> saveUpdateLqFpzlDm(List<SysEnterpriseConfigEntity> lqEnterList, List<String> paramPzList){
        JSONObject resultMap = new JSONObject();
        for (SysEnterpriseConfigEntity sysEnterpriseConfig:lqEnterList) {
            try {
                log.info("开始处理税号:{}的票种信息",sysEnterpriseConfig.getNsrsbh());
                String nsrsbh = sysEnterpriseConfig.getNsrsbh();
                //处理 全量历史发票采集控制 开始 t_dx_lq_qllsfpcj_kz
                TdxLqQllsfpcjKzEntity tdxLqQllsfpcjKz = new TdxLqQllsfpcjKzEntity();
                tdxLqQllsfpcjKz.setNsrsbh(nsrsbh);
                //数据类型，1：进项票，2：销项票
                List<String> sjlxList = new LinkedList<String>();
                sjlxList.add("1");
                sjlxList.add("2");
                //发票类型
                //List<String> paramPzList = Arrays.asList(pzxz.split(","));
                List<String> pzxzList = new ArrayList(paramPzList);
                log.info("要保存的票种信息:{}",JSON.toJSONString(pzxzList));
                //所传日期到当前月的时间合集
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                SysGroupConfigEntity sysGroupConfig = sysGroupConfigDao.selectOne(new LambdaQueryWrapper<SysGroupConfigEntity>().eq(SysGroupConfigEntity::getCompany, sysEnterpriseConfig.getCompany()));

                Date firstCollectDate = sysGroupConfig.getFirstCollectDate();
                //2个自然年前的1月1日。传入20241021.得到20240101
                String twoyeasAgoFirstDay = DateUtils.getDateByYearFirst(-2);
                log.info("税号:{},配置表的开始日期：{}，距现在两年前的1月1日:{}",nsrsbh,firstCollectDate,twoyeasAgoFirstDay);
                if(ObjectUtil.isEmpty(firstCollectDate)){
                    firstCollectDate = DateUtils.strToDate(twoyeasAgoFirstDay, "yyyyMMdd");
                }else{
                    Date twoyeasAgoFirstDayDate = DateUtils.strToDate(twoyeasAgoFirstDay, "yyyyMMdd");
                    if(firstCollectDate.compareTo(twoyeasAgoFirstDayDate)<0){
                        firstCollectDate = twoyeasAgoFirstDayDate;
                    }
                }
                log.info("获取归集开始的时间:{}",firstCollectDate);
                List<String> starToNowMonthList = new ArrayList<>();
                try {
                    starToNowMonthList = DateUtils.getStarToNowMonth(firstCollectDate);
                } catch (ParseException e) {
                   log.info("业务处理异常：{}", e);
                    log.info("获取开始时间到当前时间的月份失败");
                }
                JSONObject result = new JSONObject();
                DynamicContextHolder.push(sysGroupConfig.getDbName() + DbConstant.BUSINESS_READ);
                //海关缴款书的单独入库
                if(pzxzList.contains(LqConfigurerInfo.FPLX_CUSTOM)){
                    log.info("处理海关缴款书采集控制");
                    //每个月开始结束
                    //新插入条数
                    int qllsInsertNum = 0;
                    //已存在条数
                    int qllsHaveNum = 0;
                    for(String startEnd:starToNowMonthList){
                        String[] startEndSz = startEnd.split("@");
                        //TdxLqQllsfpcjKz
                        LambdaQueryWrapper<TdxLqQllshgjkscjKzEntity> qllsfpcjKzWrapper = new LambdaQueryWrapper();
                        qllsfpcjKzWrapper.eq(TdxLqQllshgjkscjKzEntity::getNsrsbh, nsrsbh);
                        qllsfpcjKzWrapper.eq(TdxLqQllshgjkscjKzEntity::getTfrqq, startEndSz[0]);
                        qllsfpcjKzWrapper.eq(TdxLqQllshgjkscjKzEntity::getTfrqz, startEndSz[1]);
                        qllsfpcjKzWrapper.eq(TdxLqQllshgjkscjKzEntity::getRwlx, "1");
                        long selQllCustomKz = baseServiceTdxLqQllshgjkscjKzDao.selectCount(qllsfpcjKzWrapper);
                        //如果存在，不作任何处理，如果不存在，插入
                        if(selQllCustomKz==0){
                            TdxLqQllshgjkscjKzEntity insert = new TdxLqQllshgjkscjKzEntity();
                            insert.setNsrsbh(nsrsbh);
                            insert.setTfrqq(startEndSz[0]);
                            insert.setTfrqz(startEndSz[1]);
                            insert.setRwlx("1");
                            insert.setRwzxzt("0");
                            insert.setCzr(BaseContextHandler.getUsername());
                            insert.setCreateTime(new Date());
                            insert.setUpdateTime(new Date());
                            baseServiceTdxLqQllshgjkscjKzDao.insert(insert);
                            qllsInsertNum++;
                        }else{
                            qllsHaveNum++;
                        }
                    }
                    result.put("CustominsertNum", qllsInsertNum);
                    result.put("CustomexistNum",qllsHaveNum);
                    //取出海管缴款书代码
                    pzxzList.remove(LqConfigurerInfo.FPLX_CUSTOM);
                }

                if(pzxzList.size()>0){
                    log.info("开始入库发票的定时任务");
                    //新插入条数
                    int qllsInsertNum = 0;
                    //已存在条数
                    int qllsHaveNum = 0;
                    //数据类型，1：进项票，2：销项票

                    for (String sjlx :sjlxList) {
                        //每个月开始结束
                        for(String startEnd:starToNowMonthList){
                            String[] startEndSz = startEnd.split("@");
                            //发票类型
                            for (String fpzlDm:pzxzList) {
                                //TdxLqQllsfpcjKz
                                LambdaQueryWrapper<TdxLqQllsfpcjKzEntity> qllsfpcjKzWrapper = new LambdaQueryWrapper();
                                qllsfpcjKzWrapper.eq(TdxLqQllsfpcjKzEntity::getNsrsbh, nsrsbh);
                                qllsfpcjKzWrapper.eq(TdxLqQllsfpcjKzEntity::getSjlx, sjlx);
                                qllsfpcjKzWrapper.eq(TdxLqQllsfpcjKzEntity::getCjkssj, startEndSz[0]);
                                qllsfpcjKzWrapper.eq(TdxLqQllsfpcjKzEntity::getCjjssj, startEndSz[1]);
                                qllsfpcjKzWrapper.eq(TdxLqQllsfpcjKzEntity::getFplx, fpzlDm);
                                qllsfpcjKzWrapper.eq(TdxLqQllsfpcjKzEntity::getRwlx, "1");
                                long selQllsfpcjKz = baseServiceTdxLqQllsfpcjKzDao.selectCount(qllsfpcjKzWrapper);
                                //如果存在，不作任何处理，如果不存在，插入
                                if(selQllsfpcjKz==0){
                                    TdxLqQllsfpcjKzEntity insertPo = new TdxLqQllsfpcjKzEntity();
                                    insertPo.setNsrsbh(nsrsbh);
                                    insertPo.setSjlx(sjlx);
                                    insertPo.setCjkssj(startEndSz[0]);
                                    insertPo.setCjjssj(startEndSz[1]);
                                    insertPo.setFplx(fpzlDm);
                                    insertPo.setRwlx("1");
                                    insertPo.setRwzxzt("0");
                                    insertPo.setCzr(BaseContextHandler.getUsername());
                                    insertPo.setCreateTime(new Date());
                                    insertPo.setUpdateTime(new Date());
                                    baseServiceTdxLqQllsfpcjKzDao.insert(insertPo);
                                    qllsInsertNum++;
                                }else{
                                    qllsHaveNum++;
                                }
                            }
                        }
                    }
                    log.info("全量历史发票采集控制表插入了{}条,已存在{}条",qllsInsertNum,qllsHaveNum);

                    result.put("InvoiceinsertNum", qllsInsertNum);
                    result.put("InvoiceexistNum",qllsHaveNum);
                    //处理 全量历史发票采集控制 结束 t_dx_lq_qllsfpcj_kz
                }

                resultMap.put(sysEnterpriseConfig.getNsrsbh(), result);

            } catch (Exception e) {
               log.info("业务处理异常：{}", e);
                log.info("处理失败");
                return ResponseEntity.ok(R.error("处理失败"));
            }
        }
        return ResponseEntity.ok(R.ok().put("data", super.responseResult(resultMap)));
    }

    /**
     * @Description 保存或更新乐企特殊票种
     * @param lqEnterList
     * @param tspxList
     * @Return org.springframework.http.ResponseEntity<?>
     * @Author wangruwei
     * @Date 2023/12/1 14:27
     **/
    @Override
    public ResponseEntity<?> saveUpdateLqTspzXz(List<SysEnterpriseConfigEntity> lqEnterList, List<String> tspxList) {
        JSONObject resultMap = new JSONObject();
        for (SysEnterpriseConfigEntity sysEnterpriseConfig:lqEnterList) {
            try {
                log.info("开始处理税号:{}的票种信息",sysEnterpriseConfig.getNsrsbh());
                String nsrsbh = sysEnterpriseConfig.getNsrsbh();
                //处理 全量历史发票采集控制 开始 t_dx_lq_qllsfpcj_kz
                TdxLqQllsfpcjKzEntity tdxLqQllsfpcjKz = new TdxLqQllsfpcjKzEntity();
                tdxLqQllsfpcjKz.setNsrsbh(nsrsbh);
                //发票类型
                //List<String> paramPzList = Arrays.asList(pzxz.split(","));
                List<String> pzxzList = new ArrayList(tspxList);
                log.info("要保存的票种信息，只有增值税代扣代缴完税凭证会入采集表:{}",JSON.toJSONString(pzxzList));

                //增值税代扣代缴完税凭证
                if(pzxzList.contains(LqConfigurerInfo.ZZSDKDJWSPZ)){
                    log.info("处理--增值税代扣代缴完税凭证--采集控制");
                    //所传日期到当前月的时间合集
                    DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                    SysGroupConfigEntity sysGroupConfig = sysGroupConfigDao.selectOne(new LambdaQueryWrapper<SysGroupConfigEntity>().eq(SysGroupConfigEntity::getCompany, sysEnterpriseConfig.getCompany()));

                    Date firstCollectDate = sysGroupConfig.getFirstCollectDate();
                    String twoyeasAgoFirstDay = DateUtils.getDateByYearFirst(-2);
                    log.info("税号:{},配置表的开始日期：{}，距现在两年前的1月1日:{}，当月第一天{}",nsrsbh,firstCollectDate,twoyeasAgoFirstDay);
                    if(ObjectUtil.isEmpty(firstCollectDate)){
                        firstCollectDate = DateUtils.strToDate(twoyeasAgoFirstDay, "yyyyMMdd");
                    }else{
                        Date twoyeasAgoFirstDayDate = DateUtils.strToDate(twoyeasAgoFirstDay, "yyyyMMdd");
                        if(firstCollectDate.compareTo(twoyeasAgoFirstDayDate)<0){
                            firstCollectDate = twoyeasAgoFirstDayDate;
                        }
                    }
                    /**
                     * 例：当前操作时间20240329。 两年前的当月1号是20220301(A)
                     * 1：基础设置没采集日期值，用两年前的当月1号，即20220301
                     * 2：基础设置有采集日期值B。
                     *   2.1 如果B小于等于A，则用A   （如B 2017-01） 用A 20220301
                     *   2.2 如果B大于A，则用B  （如B 2023-01） 用B 2023-01(数据库)
                     **/

                    log.info("获取归集开始的时间:{}",firstCollectDate);
                    List<String> starToNowMonthList = new ArrayList<>();
                    try {
                        starToNowMonthList = DateUtils.getStarToNowMonth(firstCollectDate);
                    } catch (ParseException e) {
                       log.info("业务处理异常：{}", e);
                        log.info("获取开始时间到当前时间的月份失败");
                    }
                    JSONObject result = new JSONObject();
                    DynamicContextHolder.push(sysGroupConfig.getDbName() + DbConstant.BUSINESS_READ);


                    //每个月开始结束
                    //新插入条数
                    int qllsInsertNum = 0;
                    //已存在条数
                    int qllsHaveNum = 0;
                    for(String startEnd:starToNowMonthList){
                        String[] startEndSz = startEnd.split("@");

                        //TdxLqQllsfpcjKz
                        LambdaQueryWrapper<TdxLqQllsfpcjKzEntity> qllsfpcjKzWrapper = new LambdaQueryWrapper();
                        qllsfpcjKzWrapper.eq(TdxLqQllsfpcjKzEntity::getNsrsbh, nsrsbh);
                        qllsfpcjKzWrapper.eq(TdxLqQllsfpcjKzEntity::getCjkssj, startEndSz[0]);
                        qllsfpcjKzWrapper.eq(TdxLqQllsfpcjKzEntity::getCjjssj, startEndSz[1]);
                        qllsfpcjKzWrapper.eq(TdxLqQllsfpcjKzEntity::getRwlx, "4");
                        long selQllsfpcjKz = baseServiceTdxLqQllsfpcjKzDao.selectCount(qllsfpcjKzWrapper);
                        //如果存在，不作任何处理，如果不存在，插入
                        if(selQllsfpcjKz==0){
                            TdxLqQllsfpcjKzEntity insertPo = new TdxLqQllsfpcjKzEntity();
                            insertPo.setNsrsbh(nsrsbh);
                            insertPo.setCjkssj(startEndSz[0]);
                            insertPo.setCjjssj(startEndSz[1]);
                            insertPo.setRwlx("4");
                            insertPo.setRwzxzt("0");
                            insertPo.setCzr(BaseContextHandler.getUsername());
                            insertPo.setCreateTime(new Date());
                            insertPo.setUpdateTime(new Date());
                            baseServiceTdxLqQllsfpcjKzDao.insert(insertPo);
                            qllsInsertNum++;
                        }else{
                            qllsHaveNum++;
                        }
                    }
                    result.put("DkdjInsertNum", qllsInsertNum);
                    result.put("DkdjExistNum",qllsHaveNum);
                    //取出增值税代扣代缴完税凭证
                    pzxzList.remove(LqConfigurerInfo.ZZSDKDJWSPZ);

                    resultMap.put(sysEnterpriseConfig.getNsrsbh(), result);
                }

            } catch (Exception e) {
               log.info("业务处理异常：{}", e);
                log.info("处理失败");
                return ResponseEntity.ok(R.error("处理失败"));
            }
        }
        return ResponseEntity.ok(R.ok().put("data", super.responseResult(resultMap)));
    }

}
