package com.dxhy.erp.service.impl;
import com.dxhy.common.enums.AuditStatusEnum;
import com.dxhy.common.utils.DateUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.QsfsEnum;
import com.dxhy.common.service.InvoiceLogService;
import com.dxhy.common.service.impl.MpBaseServiceImpl;
import com.dxhy.common.util.ScanIdUtils;
import com.dxhy.common.vo.InvoiceLog;
import com.dxhy.common.vo.UserInfo;
import com.dxhy.erp.dao.CustomsRecordDao;
import com.dxhy.erp.entity.SysDeptEntity;
import com.dxhy.erp.entity.TdxCustoms;
import com.dxhy.erp.entity.TdxCustomsRecord;
import com.dxhy.erp.model.ReimburseReq;
import com.dxhy.erp.service.CustomsService;
import com.dxhy.erp.service.CustomsSignService;
import com.dxhy.erp.utils.DateUtil;
import com.dxhy.erp.utils.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service("customsSignService")
@Slf4j
public class CustomsSignServiceImpl extends MpBaseServiceImpl<CustomsRecordDao, TdxCustomsRecord> implements CustomsSignService {
     @Resource
     private CustomsService customsService;

    @Resource
    private InvoiceLogService invoiceLogService;
    @Resource
    private ScanIdUtils scanIdUtils;
    @Override
    public ReimburseReq customsSignInvoice(ReimburseReq reimburseReq, SysDeptEntity deptEntity) {
        DynamicContextHolder.push(StringUtils.defaultString(ObjectUtil.fixNull(deptEntity.getDbName()), "business")
                + DbConstant.BUSINESS_READ);
        LambdaQueryWrapper<TdxCustoms> customsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        customsLambdaQueryWrapper.eq(TdxCustoms::getCustomsCode, reimburseReq.getInvoiceNo());
        TdxCustoms tDxCustoms = customsService.getOne(customsLambdaQueryWrapper);
        if (tDxCustoms != null && "1".equals(tDxCustoms.getQsStatus())) {
            reimburseReq.setNotes("发票已签收，重复推送");
            return reimburseReq;
        }
        if(StringUtils.isBlank(reimburseReq.getGfTaxNo())){
            reimburseReq.setNotes("缴款书缴款单位不能为空");
            reimburseReq.setQsStatus("0");
            return reimburseReq;
        }
        if(StringUtils.isBlank(reimburseReq.getInvoiceNo())){
            reimburseReq.setNotes("缴款书号码不能为空");
            reimburseReq.setQsStatus("0");
            return reimburseReq;
        }
        if(StringUtils.isBlank(reimburseReq.getInvoiceDate())){
            reimburseReq.setNotes("缴款书日期不能为空");
            reimburseReq.setQsStatus("0");
            return reimburseReq;
        }
        if(StringUtils.isBlank(reimburseReq.getTaxAmount())){
            reimburseReq.setNotes("缴款书税额不能为空");
            reimburseReq.setQsStatus("0");
            return reimburseReq;
        }
//        if (!ObjectUtil.checkData(reimburseReq.getGfTaxNo(), reimburseReq.getInvoiceNo(), reimburseReq.getInvoiceDate(),
//                reimburseReq.getTaxAmount())) {
//            reimburseReq.setNotes("数据不全");
//            reimburseReq.setQsStatus("0");
//            return reimburseReq;
//        }
        LambdaQueryWrapper<TdxCustomsRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TdxCustomsRecord::getCustomsCode, reimburseReq.getInvoiceNo());
        TdxCustomsRecord one = this.baseMapper.selectOne(wrapper);

        if (one == null) {
            reimburseReq.setNotes("签收失败！无此票据，需数据采集");
            reimburseReq.setQsStatus("0");
            customsSignInvoice(one, deptEntity,reimburseReq);
            return reimburseReq;
        }
         //填发日期校验
        if (!DateUtil.compare(one.getFillInDate(), DateUtil.strToDate(reimburseReq.getInvoiceDate()))) {
            reimburseReq.setNotes("签收失败！填发日期与底账不一致");
            reimburseReq.setQsStatus("0");
             customsSignInvoice(one, deptEntity,reimburseReq);
            return reimburseReq;
        }
        //金额校验
        Double oTaxAmount = Double.valueOf(one.getTaxAmount());
        Double pTaxAmount = Double.valueOf(reimburseReq.getTaxAmount());
        if (!oTaxAmount.equals(pTaxAmount)) {
            reimburseReq.setNotes("签收失败！税款金额与底账不一致");
            reimburseReq.setQsStatus("0");
            customsSignInvoice(one, deptEntity,reimburseReq);
            return reimburseReq;
        }
        //缴款单位税号校验
        if (!reimburseReq.getGfTaxNo().trim().equals(one.getGfTaxNo())) {
            reimburseReq.setNotes("签收失败！缴款单位与底账不一致");
            reimburseReq.setQsStatus("0");
            customsSignInvoice(one, deptEntity,reimburseReq);
            return reimburseReq;
        }
        // 采集数据
        if ("0".equals(one.getDataSources())) {
            if (!"0".equals(one.getGlzt())) {
                reimburseReq.setNotes("签收失败！管理状态异常");
                reimburseReq.setQsStatus("0");
                customsSignInvoice(one, deptEntity,reimburseReq);
                return reimburseReq;
            } else if (!"0".equals(one.getEntryDiscrepancy())) {
                reimburseReq.setNotes("签收失败！含录入不符项");
                reimburseReq.setQsStatus("0");
                customsSignInvoice(one, deptEntity,reimburseReq);
                return reimburseReq;
            }
        } else {
            // 录入数据
            if ("2".equals(one.getCollectUploadStatus())) {
                // 上传税局成功
                if (!"1".equals(one.getAuditStatus()) && "0".equals(one.getApplyCheck())) {
                    reimburseReq.setNotes("签收失败！稽核状态不相符,稽核状态为"+ AuditStatusEnum.getVal(one.getAuditStatus()));
                    reimburseReq.setQsStatus("0");
                    customsSignInvoice(one, deptEntity,reimburseReq);
                    return reimburseReq;
                } else if ("1".equals(one.getApplyCheck()) && "1".equals(one.getCheckStatus())) {
                    reimburseReq.setNotes("签收失败！核查结果为不允许抵扣/退税");
                    reimburseReq.setQsStatus("0");
                    customsSignInvoice(one, deptEntity,reimburseReq);
                    return reimburseReq;
                }
            } else {// 还未成功上传税局
                reimburseReq.setNotes("签收失败！核查结果为不允许抵扣/退税");
                reimburseReq.setQsStatus("0");
                customsSignInvoice(one, deptEntity,reimburseReq);
                return reimburseReq;
            }
        }
        //签收成功
        reimburseReq.setQsStatus("1");
        reimburseReq.setNotes("签收成功");
        sign(one, reimburseReq);
        customsSignInvoice(one, deptEntity,reimburseReq);
        this.baseMapper.updateById(one);
        return reimburseReq;
    }
    //缴款书数据存储
    private void customsSignInvoice(TdxCustomsRecord record, SysDeptEntity deptEntity,ReimburseReq reimburseReq) {
        DynamicContextHolder.push(StringUtils.defaultString(ObjectUtil.fixNull(deptEntity.getDbName()), "business")
                + DbConstant.BUSINESS_WRITE);
        LambdaQueryWrapper<TdxCustoms> tdxCustomsWrapper = new LambdaQueryWrapper<>();
        tdxCustomsWrapper.eq(TdxCustoms::getCustomsCode, reimburseReq.getInvoiceNo());
        TdxCustoms tDxCustoms = customsService.getOne(tdxCustomsWrapper);
        if (tDxCustoms == null) {
            tDxCustoms = getTdxCustoms(record, deptEntity,reimburseReq);
            tDxCustoms.setCreateDate(new Date());
            tDxCustoms.setNotes(reimburseReq.getNotes());
            tDxCustoms.setScanId(UUID.randomUUID().toString());
            tDxCustoms.setInvoiceSerialNo(Long.valueOf(scanIdUtils.createSerialNum()));
            sign(tDxCustoms, QsfsEnum.JKTS.getQsfsDm(), reimburseReq.getQsStatus());
            customsService.save(tDxCustoms);
        } else {
            Long id = tDxCustoms.getId();
            tDxCustoms = getTdxCustoms(record, deptEntity,reimburseReq);
            tDxCustoms.setUpdateDate(new Date());
            tDxCustoms.setId(id);
            sign(tDxCustoms, QsfsEnum.JKTS.getQsfsDm(), reimburseReq.getQsStatus());
            tDxCustoms.setNotes(reimburseReq.getNotes());
            customsService.updateById(tDxCustoms);
        }
        InvoiceLog log = new InvoiceLog();
        log.setInputName(reimburseReq.getQsName());
        if("0".equals(reimburseReq.getQsStatus())){
            log.setInputStatus("2");
        }else {
            log.setInputStatus("1");
        }
        log.setInvoiceCode(reimburseReq.getInvoiceCode());
        log.setInvoiceNo(reimburseReq.getInvoiceNo());
        log.setQsType(QsfsEnum.JKTS.getQsfsDm());
        log.setType("3");
        log.setCreateDate(new Date());
        List<InvoiceLog> logs = new ArrayList<>();
        logs.add(log);
        invoiceLogService.toInvoiceLog(logs);
    }

    private TdxCustoms getTdxCustoms(TdxCustomsRecord record, SysDeptEntity deptEntity, ReimburseReq reimburseReq) {
        TdxCustoms entity = new TdxCustoms();
        if (record == null) {
            entity.setNotes(reimburseReq.getNotes());
            entity.setQsStatus(reimburseReq.getQsStatus());
            entity.setCustomsCode(reimburseReq.getInvoiceNo());
            entity.setGfTaxNo(reimburseReq.getGfTaxNo());
            entity.setCreateDate(DateUtils.getSqlDateLong());
            entity.setFillInDate(DateUtils.strToDate(reimburseReq.getInvoiceDate()));
            entity.setTaxAmount(reimburseReq.getTaxAmount());
            entity.setCompany(deptEntity.getCompany());
            entity.setUserName(reimburseReq.getQsName());
            entity.setUserAccount(reimburseReq.getQsName());
            entity.setScanId(UUID.randomUUID().toString());
            entity.setInvoiceSerialNo(Long.valueOf(scanIdUtils.createSerialNum()));
            entity.setQsDate(DateUtils.getSqlDateLong());
            entity.setQsType(QsfsEnum.DRQS.getQsfsDm());
            entity.setDataType(reimburseReq.getInvoiceType());
            return entity;
        }
        entity.setGfName(record.getGfName());
        entity.setGfTaxNo(record.getGfTaxNo());
        entity.setCustomsCode(record.getCustomsCode());
        entity.setPayerOneTaxno(record.getPayerOneTaxno());
        entity.setPayerOneName(record.getPayerOneName());
        entity.setPayerTwoTaxno(record.getPayerTwoTaxno());
        entity.setPayerTwoName(record.getPayerTwoName());
        entity.setFillInDate(record.getFillInDate());
        entity.setDataType(record.getDataType());
        entity.setTaxAmount(record.getTaxAmount());
        entity.setAuditStatus(record.getAuditStatus());
        entity.setApplyCheck(record.getApplyCheck());
        entity.setCheckStatus(record.getCheckStatus());
        entity.setEntryDiscrepancy(record.getEntryDiscrepancy());
        entity.setDeptId(record.getDeptId());
        entity.setDeptName(record.getDeptName());
        entity.setGlzt(record.getGlzt());
        entity.setXxly(record.getXxly());
        entity.setDataSources(record.getDataSources());
        entity.setCompany(deptEntity.getCompany());
        entity.setUserName(reimburseReq.getQsName());
        entity.setUserAccount(reimburseReq.getQsName());
        return entity;
    }
    private void sign(TdxCustoms record, String qsType, String qsStatus) {
        record.setQsStatus(qsStatus);
        record.setQsDate(new Date());
        record.setQsType(qsType);
    }
    private void sign(TdxCustomsRecord record, ReimburseReq reimburseReq) {
        record.setQsStatus("1");
        record.setQsDate(new Date());
        record.setQsUser(reimburseReq.getQsName());
        record.setQsType(QsfsEnum.JKTS.getQsfsDm());
    }
}
