package com.dxhy.jxpt.baseService.sign.service.qsgz.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dxhy.api.model.config.UserInfo;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.FplxEnum;
import com.dxhy.api.model.invoice.TDxRecordInvoice;
import com.dxhy.api.model.db.TDxTaxCurrentEntity;
import com.dxhy.jxpt.baseService.sign.service.qsgz.RulesService;
import com.dxhy.jxpt.baseService.sign.service.singletable.SignTaxCurrentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Service("1007")
@Slf4j
public class Rules1007ServiceImpl implements RulesService {

    @Resource
    private SignTaxCurrentService signTaxCurrentService;

    @Override
    public String validationRules(UserInfo userInfo, String qsType, Map<String, String> pramsMap, TDxRecordInvoice recordInvoice, String invoiceType) {
        // 1007 逾期校验
        pramsMap.put("dbName", userInfo.getDbName());
        boolean validOverdue = this.validOverdue(invoiceType, pramsMap, recordInvoice.getGfTaxNo(),
                recordInvoice.getInvoiceDate());
        if (!validOverdue) {
            return "发票已逾期，签收失败";
        }
        return "";
    }

    @Override
    public String getEdiType() {
        return "1007";
    }

    public boolean validOverdue(String invoiceType, Map<String, String> pramsMap, String taxNo, Date invoiceDate) {
        if (FplxEnum.ZP.getFplxDm().equals(invoiceType) || FplxEnum.TXF.getFplxDm().equals(invoiceType)
                || FplxEnum.JDC.getFplxDm().equals(invoiceType) || FplxEnum.DZZP.getFplxDm().equals(invoiceType)
                || FplxEnum.QDZZP.getFplxDm().equals(invoiceType)|| FplxEnum.ZZDZ.getFplxDm().equals(invoiceType)) {
            // 专票、机动车、通行费校验
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            Date start = null;
            DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
            QueryWrapper<TDxTaxCurrentEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("taxno", taxNo);
            TDxTaxCurrentEntity taxCurrent = signTaxCurrentService.getOne(queryWrapper);
            if (taxCurrent != null) {
                // 当前税款所属期勾选起始日期
                String startDate = taxCurrent.getSelectStartDate();
                startDate = startDate.substring(0, 4) + "-" + startDate.substring(4, 6) + "-" + startDate.substring(6);
                try {
                    start = df.parse(startDate);
                } catch (Exception e) {
                   log.info("业务处理异常：{}", e);
                }
            }
            return start == null || !invoiceDate.before(start);
        }
        return true;
    }
}
