package com.dxhy.base.service.sqdktj;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dxhy.api.model.config.UserInfo;
import com.dxhy.api.model.config.sys.SysEnterpriseConfigEntity;
import com.dxhy.api.model.custom.TdxCustomsRecord;
import com.dxhy.api.model.db.TDxTaxCurrentEntity;
import com.dxhy.api.model.db.TdxLqDkCustomFpycxxEntity;
import com.dxhy.api.model.db.TdxLqDkFpycxxEntity;
import com.dxhy.api.model.db.TdxRecordInvoiceEntity;
import com.dxhy.base.dao.BaseTDxDkCountDao;
import com.dxhy.base.entity.BaseTDxDkCount;
import com.dxhy.base.service.fpxxrz.BaseCxrzfpService;
import com.dxhy.base.service.fpxxrz.BaseLqcxrzService;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.ApplyStatusEnum;
import com.dxhy.common.service.impl.MpBaseServiceImpl;
import com.dxhy.common.utils.R;
import com.dxhy.customs.dao.BasisSysEnterpriceConfigDao;
import com.dxhy.customs.dao.CustomsRecordDao;
import com.dxhy.customs.dao.CustomsTdxLqDkCustomFpycxxDao;
import com.dxhy.customs.entity.TdxLqDkCustomFpycxx;
import com.dxhy.customs.model.TdxCustomsRecordModelDTO;
import com.dxhy.customs.service.CustomsRecordDkrzService;
import com.dxhy.jxpt.baseService.dao.TdxLqDkCustomFpycxxDao;
import com.dxhy.jxpt.baseService.dao.TdxLqDkFpycxxDao;
import com.dxhy.jxpt.baseService.dao.TdxRecordInvoiceDao;
import com.dxhy.jxpt.baseService.ncpInvoice.dao.TdxTaxCurrentDao;
import com.dxhy.jxpt.baseService.rzInvoice.dao.TdxCustomsRecordDao;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 撤销抵扣统计service实现类
 *
 * @author kangzq
 * @date 2019年5月11日
 * @version 1.0
 */
@SuppressWarnings("AlibabaCollectionInitShouldAssignCapacity")
@Service
@Slf4j
public class BaseCancelApplicationServiceImpl extends MpBaseServiceImpl<BaseTDxDkCountDao, BaseTDxDkCount>
    implements BaseCancelApplicationService {

    @Resource
    private BaseDktjService baseDktjService;

    @Resource
    private BaseStatisticalEnterpriseService baseStatisticalEnterpriseService;

    @Resource
    private TdxLqDkFpycxxDao tdxLqDkFpycxxDao;

    @Resource
    private TdxRecordInvoiceDao tdxRecordInvoiceDao;

    /**
     * 撤销已认证发票
     */
    @Resource
    private BaseCxrzfpService baseCxrzfpService;

    @Resource
    private BaseLqcxrzService baseLqcxrzService;

    @Resource
    private TdxLqDkCustomFpycxxDao tdxLqDkCustomFpycxxDao;

    @Resource
    private TdxCustomsRecordDao tdxCustomsRecordDao;

    @Resource
    private CustomsRecordDkrzService tDxCustomsRecordService;

    @Resource
    private BasisSysEnterpriceConfigDao basisSysEnterpriceConfigDao;

    @Resource
    private CustomsRecordDao customsRecordDao;

    @Resource
    private CustomsTdxLqDkCustomFpycxxDao customsTdxLqDkCustomFpycxxDao;

    @Resource
    private TdxTaxCurrentDao taxCurrentDao;

    @Resource
    private BaseTDxDkCountDao baseTDxDkCountDao;

    @Override
    public String deleteByGfshAndSkssq(Map<String, Object> pramsMap) {
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);

        String[] gfshs = pramsMap.get("gfshs").toString().split(",");
        String[] skssqs = pramsMap.get("skssqs").toString().split(",");

        JSONObject json;
        json = baseDktjService.selectCxtjHjxx(pramsMap);

        for (int i = 0; i < gfshs.length; i++) {

            Map<String, Object> pramMap = new HashMap<>();
            pramMap.put("taxno", gfshs[i]);
            pramMap.put("tj_month", skssqs[i]);
            // 删除抵扣统计明细

            Map<String, Object> updatepramMap = new HashMap<>(16);
            updatepramMap.put("gfsh", pramMap.get("taxno"));
            updatepramMap.put("skssq", pramMap.get("tj_month"));
            updatepramMap.put("dbName", pramsMap.get("dbName"));

            // 更新相关的数据
            BaseTDxDkCount delentity = new BaseTDxDkCount();
            delentity.setApplyStatus(ApplyStatusEnum.WSQ.getApplyStatusDm());
            delentity.setApplyType("1");
            delentity.setCxtjStatus("1");
            delentity.setApplyStatus("0");
            delentity.setCxtjUser((String)pramsMap.get("czr"));
            baseStatisticalEnterpriseService.updateByGfshAndSkssq(updatepramMap, delentity);
        }
        json.put("tsxx", "已申请撤销统计，请稍后查询撤销结果");
        return super.responseResult(json);
    }

    @Override
    public String deleteQsByGfshAndSkssq(Map<String, Object> pramsMap) {
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);

        String[] gfshs = pramsMap.get("gfshs").toString().split(",");
        String[] skssqs = pramsMap.get("skssqs").toString().split(",");

        JSONObject json;
        json = baseDktjService.selectCxtjHjxx(pramsMap);

        for (int i = 0; i < gfshs.length; i++) {

            Map<String, Object> pramMap = new HashMap<>();
            pramMap.put("taxno", gfshs[i]);
            pramMap.put("tj_month", skssqs[i]);
            // 删除抵扣统计明细

            Map<String, Object> updatepramMap = new HashMap<>(16);
            updatepramMap.put("gfsh", pramMap.get("taxno"));
            updatepramMap.put("skssq", pramMap.get("tj_month"));
            updatepramMap.put("dbName", pramsMap.get("dbName"));

            // 更新相关的数据
            BaseTDxDkCount delentity = new BaseTDxDkCount();
            delentity.setApplyStatus(ApplyStatusEnum.WSQ.getApplyStatusDm());
            delentity.setApplyType("1");
            delentity.setCxqsStatus("1");
            delentity.setApplyStatus("0");
            delentity.setCxqrUser((String)pramsMap.get("czr"));
            baseStatisticalEnterpriseService.updateByGfshAndSkssq(updatepramMap, delentity);
        }
        json.put("tsxx", "已申请撤销确认，请稍后查询撤销结果");
        return super.responseResult(json);
    }
    /**
     * @Description 异常发票，缴款书撤销接口--弹框验证
     * @param map
     * @Return java.lang.Object
     * @Author wangruwei
     * @Date 2024/8/23 15:18
     **/
    @Override
    public Object cxycFpJksAlert(Map<String, String> map) {
        //查找发票和缴款书
        String nsrsbh = map.get("nsrsbh");
        String skssq = map.get("skssq");
        //验证是否可撤销
        //2.1.1.1.校验属期是否等于当前属期，如果不是当前属期则 toast提醒“企业当前属期为YYYYMM 不可撤销属期为 YYYYMM 已认证发票”
        TDxTaxCurrentEntity taxCurrent = taxCurrentDao.selectOne(new LambdaQueryWrapper<TDxTaxCurrentEntity>().eq(TDxTaxCurrentEntity::getTaxno, nsrsbh));
        if (taxCurrent != null) {
            String currskssq = taxCurrent.getCurrentTaxPeriod();
            if(!currskssq.equals(skssq)){
                return ResponseEntity.ok(R.error("企业当前属期为"+currskssq+" 不可撤销属期为 "+skssq+" 已认证发票"));
            }
        }else{
            return ResponseEntity.ok(R.error("未找到购方企业信息！"));
        }
        //2.1.1.2.如果当前属期等于异常发票认证属期，则校验当前属期统计状态是否为未统计,如果不为未统计则 toast 提醒“当前属期为已统计状态请先撤销统计后再执行当前操作”
        BaseTDxDkCount baseTDxDkCount = baseTDxDkCountDao.selectOne(new LambdaQueryWrapper<BaseTDxDkCount>().eq(BaseTDxDkCount::getTaxno, nsrsbh)
                .eq(BaseTDxDkCount::getSkssq, skssq)
        );
        if(baseTDxDkCount!=null){
            if("0".equals(baseTDxDkCount.getTjStatus())||"3".equals(baseTDxDkCount.getTjStatus())){
                //继续走撤销逻辑
            }else{
                return ResponseEntity.ok(R.error("当前属期为已统计状态请先撤销统计后再执行当前操作！"));
            }
        }else{
            return ResponseEntity.ok(R.error("未找到企业统计信息！"));
        }
        return ResponseEntity.ok(R.ok(""));

    }

    /**
     * @Description 异常发票，缴款书撤销接口
     * @param map
     * @Return java.lang.Object
     * @Author wangruwei
     * @Date 2024/8/23 15:18
     **/
    @Override
    public Object cxycFpJks(Map<String, Object> map) {
        //查找发票和缴款书
        String nsrsbh = (String)map.get("nsrsbh");
        String skssq =(String) map.get("skssq");

        //发票的异常信息
        List<TdxLqDkFpycxxEntity> tdxLqDkFpycxxEntities = tdxLqDkFpycxxDao.selectList(new LambdaQueryWrapper<TdxLqDkFpycxxEntity>().eq(TdxLqDkFpycxxEntity::getNsrsbh, nsrsbh)
                .eq(TdxLqDkFpycxxEntity::getDqskssq, skssq)
        );
        if(tdxLqDkFpycxxEntities.size()>0){
            //查询底账
            List<TdxRecordInvoiceEntity> tdxRecordInvoiceEntities = tdxRecordInvoiceDao.selectList(new LambdaQueryWrapper<TdxRecordInvoiceEntity>().select(TdxRecordInvoiceEntity::getId).in(TdxRecordInvoiceEntity::getUuid, tdxLqDkFpycxxEntities.stream().map(TdxLqDkFpycxxEntity::getUuid).collect(Collectors.toList())));
            if(tdxRecordInvoiceEntities.size()>0){
                List<String> idsList = tdxRecordInvoiceEntities.stream().map(e->String.valueOf(e.getId())).collect(Collectors.toList());
                log.info("查询到异常发票信息的id集合是:{}",idsList);
                String cxids = String.join(",", idsList);
                map.put("cxids", cxids);
                log.info("调乐企发票-撤销认证的方法");
                ResponseEntity<?> result = baseLqcxrzService.lqcxrz(map);
                log.info("撤销乐企发票-认证发票返回:{}", JSON.toJSONString(result));
            }else{
                log.info("异常发票在底账里没有，不做处理");
            }
        }else{
            log.info("没有异常发票");
        }

        //缴款书的异常信息
        List<TdxLqDkCustomFpycxxEntity> tdxLqDkCustomFpycxxEntities = tdxLqDkCustomFpycxxDao.selectList(new LambdaQueryWrapper<TdxLqDkCustomFpycxxEntity>()
                .eq(TdxLqDkCustomFpycxxEntity::getNsrsbh, nsrsbh)
                .eq(TdxLqDkCustomFpycxxEntity::getSkssq, skssq)
        );
        if(tdxLqDkCustomFpycxxEntities.size()>0){
            List<TdxCustomsRecord> tdxRecordCustomsEntities = tdxCustomsRecordDao.selectList(new LambdaQueryWrapper<TdxCustomsRecord>().select(TdxCustomsRecord::getId).in(TdxCustomsRecord::getCustomsCode, tdxLqDkCustomFpycxxEntities.stream().map(TdxLqDkCustomFpycxxEntity::getJkshm).collect(Collectors.toList())));
            if(tdxRecordCustomsEntities.size()>0){
                List<String> idsList = tdxRecordCustomsEntities.stream().map(e->String.valueOf(e.getId())).collect(Collectors.toList());
                log.info("查询到异常缴款书信息的id集合是:{}",idsList);
                log.info("调撤销认证缴款书的方法");
                UserInfo userInfo = (UserInfo) map.get("userInfo");
                TdxCustomsRecordModelDTO dto = new TdxCustomsRecordModelDTO();
                dto.setIds(idsList);
                dto.setGfsh(nsrsbh);

                String result = tDxCustomsRecordService.approveCxrz(dto, userInfo);
                log.info("调撤销缴款书返回:{}",Base64.decodeStr(result));
                //调用完成后，处理异常发票
                dealYcJks(dto,result,userInfo);
            }else{
                log.info("异常发票在底账里没有，不做处理");
            }
        }else{
            log.info("没有异常缴款书");
        }
        return ResponseEntity.ok(R.ok("申请成功"));
    }

    private void dealYcJks(TdxCustomsRecordModelDTO dto, String result, UserInfo userInfo) {
        if(StringUtils.isNotBlank(dto.getGfsh())){
            log.info("调完");
            //判断是否为大企业税号
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            SysEnterpriseConfigEntity enterpriseConfigEntity = basisSysEnterpriceConfigDao.selectOne(new LambdaQueryWrapper<SysEnterpriseConfigEntity>()
                    .eq(SysEnterpriseConfigEntity::getNsrsbh, dto.getGfsh())
                    .eq(SysEnterpriseConfigEntity::getJrfs,"1")
            );
            if (enterpriseConfigEntity != null) {
                String resultJsonStr = Base64.decodeStr(result);
                log.info("乐企税号调原有撤销认证不抵扣接口返回:{},解析出:{}",result,resultJsonStr);
                int customCxrzNum=0;
                JSONObject jsonObject = JSONObject.parseObject(resultJsonStr);
                //如果是空，撤销成功，删除异常表中对应数据
                if(StringUtils.isEmpty(jsonObject.getString("message"))){
                    log.info("海关缴款书撤销抵扣或不抵扣，成功后，删除lqcustomFpycxx表数据");
                    DynamicContextHolder
                            .push(StringUtils.defaultString(userInfo.getDbName(), "business") + DbConstant.BUSINESS_READ);
                    for (String idstr : dto.getIds()) {
                        TdxCustomsRecord byId = customsRecordDao.selectById(idstr);
                        LambdaQueryWrapper<TdxLqDkCustomFpycxx> fpycxxWrapper = new LambdaQueryWrapper<>();
                        fpycxxWrapper.eq(TdxLqDkCustomFpycxx::getJkshm, byId.getCustomsCode());
                        customsTdxLqDkCustomFpycxxDao.delete(fpycxxWrapper);
                        customCxrzNum++;
                    }
                    log.info("删除lqcustomFpycxx表数据条数:{}",customCxrzNum);
                }

            }
        }
    }

}
