package com.dxhy.erp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dxhy.api.model.config.sys.SysEnterpriseConfigEntity;
import com.dxhy.api.model.db.TDxLqApplyStatRecordEntity;
import com.dxhy.api.model.db.TdxDkTsCountDetailEntity;
import com.dxhy.api.model.db.TdxDkTsCountEntity;
import com.dxhy.common.util.pojo.Authorize;
import com.dxhy.common.util.pojo.GlobalInfo;
import com.dxhy.core.job.dao.TDxLqApplyStatRecordDao;
import com.dxhy.core.job.service.ApplyService;
import com.dxhy.erp.dao.BaseSysEnterpriseConfigErpDao;
import com.dxhy.erp.enums.GlobalReturnEnums;
import com.dxhy.erp.service.TsApplyService;
import com.dxhy.erp.utils.CommonUtils;
import com.dxhy.jxpt.baseService.dao.TdxDkTsCountDao;
import com.dxhy.jxpt.baseService.dao.TdxDkTsCountDetailDao;
import com.dxhy.pojo.obj.erp.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
* @Description 大企业退税确认业务 对外接口
* @Author wangruwei
* @Date 2024/3/20 14:23
**/
@Service
@Slf4j
public class TsApplyServiceImpl implements TsApplyService {
    private static final String  LOG_MSG ="（退税确认业务处理类）";

    @Autowired
    private BaseSysEnterpriseConfigErpDao sysEnterpriseConfigErpDao;

    @Resource
    private TdxDkTsCountDao tdxDkTsCountDao;

    @Resource
    private TdxDkTsCountDetailDao tdxDkTsCountDetailDao;

    @Resource
    private ApplyService applyService;
    @Resource
    private TDxLqApplyStatRecordDao tDxLqApplyStatRecordDao;

    /**
     * @Description 退税确认申请
     * @Author wangruwei
     * @Date 2024/3/20 14:23
     **/
    @Override
    public String refundApply(GlobalInfo globalInfo, Map<String, String> requestParam, HttpServletRequest request, HttpServletResponse response, Authorize authorize) {
        log.info("{} 退税确认申请开始",LOG_MSG);
        String content = requestParam.get("data");
        log.info("{} 业务报文：{}",LOG_MSG,content);
        TsApply tsApply = JSON.parseObject(content, TsApply.class);
        //请求参数校验
        Map<String,String> validMap = validRefundApplyReq(tsApply);
        if (validMap != null) {
            log.info("{} 退税确认申请请求参数校验失败：{}",LOG_MSG,validMap);
            return CommonUtils.packageReturnMsg(globalInfo,null, validMap.get("returnCode") ,validMap.get("returnMsg"));
        }

        SysEnterpriseConfigEntity enterpriseConfigEntity = sysEnterpriseConfigErpDao.selectOne(new LambdaQueryWrapper<SysEnterpriseConfigEntity>()
                .eq(SysEnterpriseConfigEntity::getNsrsbh, tsApply.getBuyerTaxNo()));

        //是大企业，才让调
        if(ObjectUtil.isNotEmpty(enterpriseConfigEntity)&&"1".equals(enterpriseConfigEntity.getJrfs())&&StringUtils.isNotBlank(enterpriseConfigEntity.getSydwptbm())){
            //是乐企，返回提示
            return CommonUtils.packageReturnMsg(globalInfo,null, GlobalReturnEnums.LQ_NOT_ALLOW.getCode() , GlobalReturnEnums.LQ_NOT_ALLOW.getMsg());
        }

        //查询
        TdxDkTsCountEntity tdxDkTsCountEntity = tdxDkTsCountDao.selectOne(new LambdaQueryWrapper<TdxDkTsCountEntity>()
                .eq(TdxDkTsCountEntity::getSkssq, tsApply.getBelongDate())
                .eq(TdxDkTsCountEntity::getTaxno, tsApply.getBuyerTaxNo())
        );

        Map<String,String> result = new HashMap();
        //如果没找到，说明还没申请，可点击按钮
        if(tdxDkTsCountEntity==null){
            log.info("判断是否有退税申请中的。有已申请且未获取结果的，则不让再次申请");
            TDxLqApplyStatRecordEntity n = tDxLqApplyStatRecordDao.selectOne(new LambdaQueryWrapper<TDxLqApplyStatRecordEntity>()
                    .eq(TDxLqApplyStatRecordEntity::getNsrsbh, tsApply.getBuyerTaxNo())
                    .eq(TDxLqApplyStatRecordEntity::getSkssq, tsApply.getBelongDate())
                    .eq(TDxLqApplyStatRecordEntity::getSqlx, "5")
                    .eq(TDxLqApplyStatRecordEntity::getResultStatus, "N")
            );
            if(ObjectUtil.isNotEmpty(n)){
                //已有还在申请中，不允许再次调。
                return CommonUtils.packageReturnMsg(globalInfo,null, GlobalReturnEnums.TS_APPLY_SQ_ING.getCode() , GlobalReturnEnums.TS_APPLY_SQ_ING.getMsg());
            }
            result = doDqyTsApply(tsApply.getBuyerTaxNo(),tsApply.getBelongDate());
        }else {
            //确认状态 0 未确认 1：确认中 2：确认成功 3：确认失败
            String qrStatus = tdxDkTsCountEntity.getQrStatus();
            if("2".equals(qrStatus)||"3".equals(qrStatus)){
                result = doDqyTsApply(tdxDkTsCountEntity.getTaxno(),tdxDkTsCountEntity.getSkssq());
            }else{
                //已有还在申请中，不允许再次调。
                return CommonUtils.packageReturnMsg(globalInfo,null, GlobalReturnEnums.TS_APPLY_SQ_ING.getCode() , GlobalReturnEnums.TS_APPLY_SQ_ING.getMsg());
            }
        }

        if(!"0000".equals(result.get("code"))){
            //申请失败
            return CommonUtils.packageReturnMsg(globalInfo,null, GlobalReturnEnums.TS_APPLY_ERROR.getCode() , result.get("msg"));
        }else{
            log.info("{} 退税确认申请完成",LOG_MSG);
            Map<String,String> resultData = new HashMap();
            resultData.put("batchNo", result.get("batchNo"));
            return CommonUtils.packageReturnMsg(globalInfo,JSON.toJSONString(resultData), GlobalReturnEnums.SUCCESS);
        }
    }


    //调大企业退税申请接口
    private Map<String,String> doDqyTsApply(String taxno, String skssq) {
        //发票和缴款书明细数据
        Map<String,String> result = applyService.taxRefundApplyPage(taxno, skssq);
        return result;
    }

    /**
    * @Description 退税确认申请
    * @param tsApply
    * @Return java.util.Map<java.lang.String,java.lang.String>
    * @Author wangruwei
    * @Date 2024/3/20 14:39
    **/
    private Map<String, String> validRefundApplyReq(TsApply tsApply) {
        log.info("{} 退税确认申请校验。。。",LOG_MSG);
        if (tsApply == null) {
            log.info("{} 入账参数校验失败，入账参数为空",LOG_MSG);
            return CommonUtils.packageValidResult(GlobalReturnEnums.PARAM_NULL);
        }
        if (StringUtils.isBlank(tsApply.getBuyerTaxNo())) {
            log.info("{} 纳税人识别号不能为空",LOG_MSG);
            return CommonUtils.packageValidResult(GlobalReturnEnums.GHF_NSRSBH_NULL);
        }

        if (StringUtils.isBlank(tsApply.getBelongDate())) {
            log.info("{} 入账属期不能为空",LOG_MSG);
            return CommonUtils.packageValidResult(GlobalReturnEnums.TS_APPLY_SQ_NULL);
        }

        if (!CommonUtils.validMonth(tsApply.getBelongDate())) {
            log.info("{} 入账属期格式必须满足“YYYYMM”",LOG_MSG);
            return CommonUtils.packageValidResult(GlobalReturnEnums.TS_APPLY_SQ_FORMAT_ERROR);
        }

        return null;
    }


    /**
     * @Description 退税确认结果获取--只支持大企业
     * @Author wangruwei
     * @Date 2024/3/20 14:23
     **/
    @Override
    public String refundApplyResult(GlobalInfo globalInfo, Map<String, String> requestParam, HttpServletRequest request, HttpServletResponse response, Authorize authorize) {
        log.info("{} 退税确认结果获取开始",LOG_MSG);
        String content = requestParam.get("data");
        log.info("{} 业务报文：{}",LOG_MSG,content);
        TsApplyResultGet tsApply = JSON.parseObject(content, TsApplyResultGet.class);
        //请求参数校验
        Map<String,String> validMap = validRefundApplyResultGetReq(tsApply);
        if (validMap != null) {
            log.info("{} 退税确认申请结果获取-请求参数校验失败：{}",LOG_MSG,validMap);
            return CommonUtils.packageReturnMsg(globalInfo,null, validMap.get("returnCode") ,validMap.get("returnMsg"));
        }

        TsApplyResultResult tsApplyResultResult = new TsApplyResultResult();
        tsApplyResultResult.setBatchState("N");

        //1，先查t_dx_lq_apply_stat_record 表是否存在，存在则看结果
        TDxLqApplyStatRecordEntity tDxLqApplyStatRecordEntity = tDxLqApplyStatRecordDao.selectOne(new LambdaQueryWrapper<TDxLqApplyStatRecordEntity>()
                .eq(TDxLqApplyStatRecordEntity::getPclsh, tsApply.getBatchNo())
        );
        if(ObjectUtil.isEmpty(tDxLqApplyStatRecordEntity)){
            return CommonUtils.packageReturnMsg(globalInfo,null, GlobalReturnEnums.TS_APPLY_RESULT_GET_PCH_DATANULL.getCode() , GlobalReturnEnums.TS_APPLY_RESULT_GET_PCH_DATANULL.getMsg());
        }

        //2，判断当前状态是什么
        String resultStatus = tDxLqApplyStatRecordEntity.getResultStatus();
        if("N".equals(resultStatus)){
            return CommonUtils.packageReturnMsg(globalInfo,tsApplyResultResult, GlobalReturnEnums.SUCCESS);
        }else{
            //获取结果的定时任务已经跑完,走下面的逻辑
        }

        //3，如果已获取结果，查询t_dx_dk_ts_count。
        TdxDkTsCountEntity tdxDkTsCountEntity = tdxDkTsCountDao.selectOne(new LambdaQueryWrapper<TdxDkTsCountEntity>()
                .eq(TdxDkTsCountEntity::getTaxno, tDxLqApplyStatRecordEntity.getNsrsbh())
                .eq(TdxDkTsCountEntity::getSkssq, tDxLqApplyStatRecordEntity.getSkssq())
        );
        if(ObjectUtil.isEmpty(tdxDkTsCountEntity)){
            return CommonUtils.packageReturnMsg(globalInfo,tsApplyResultResult, GlobalReturnEnums.SUCCESS);
        }else{
            tsApplyResultResult.setBatchState("Y");
            TdxDkTsCountRespVo tdxDkTsCountRespVo = new TdxDkTsCountRespVo();
            BeanUtil.copyProperties(tdxDkTsCountEntity, tdxDkTsCountRespVo);
            tsApplyResultResult.setTsCount(tdxDkTsCountRespVo);
            List<TdxDkTsCountDetailEntity> tdxDkTsCountDetailEntities = tdxDkTsCountDetailDao.selectList(new LambdaQueryWrapper<TdxDkTsCountDetailEntity>()
                    .eq(TdxDkTsCountDetailEntity::getTaxno, tdxDkTsCountEntity.getTaxno())
                    .eq(TdxDkTsCountDetailEntity::getQrMonth, tdxDkTsCountEntity.getSkssq())
            );
            List<TdxDkTsCountDetailRespVo> showlist = new LinkedList();
            for (int i = 0; i < tdxDkTsCountDetailEntities.size(); i++) {
                TdxDkTsCountDetailRespVo item = new TdxDkTsCountDetailRespVo();
                BeanUtil.copyProperties(tdxDkTsCountDetailEntities.get(i), item);
                showlist.add(item);
            }
            tsApplyResultResult.getTsCount().setTsCountDetails(showlist);
            //判断当前状态。如果是成功，返回具体数据。
            log.info("当前ts_count确认状态:{}",tdxDkTsCountEntity.getQrStatus());
            if("2".equals(tdxDkTsCountEntity.getQrStatus())||"3".equals(tdxDkTsCountEntity.getQrStatus())){
                return CommonUtils.packageReturnMsg(globalInfo,JSON.toJSONString(tsApplyResultResult), GlobalReturnEnums.SUCCESS);
            }else{
                tsApplyResultResult.setBatchState("N");
                tsApplyResultResult.setTsCount(null);
                return CommonUtils.packageReturnMsg(globalInfo,tsApplyResultResult, GlobalReturnEnums.SUCCESS);
            }
        }
    }

    private Map<String, String> validRefundApplyResultGetReq(TsApplyResultGet tsApply) {
        log.info("{} 退税确认结果获取申请校验。。。",LOG_MSG);
        if (tsApply == null) {
            log.info("{} 入账参数校验失败，入账参数为空",LOG_MSG);
            return CommonUtils.packageValidResult(GlobalReturnEnums.PARAM_NULL);
        }
        if (StringUtils.isBlank(tsApply.getBatchNo())) {
            log.info("{} 请求批次号不能为空",LOG_MSG);
            return CommonUtils.packageValidResult(GlobalReturnEnums.TS_APPLY_RESULT_GET_PCH_NULL);
        }
        return null;
    }
}
