package com.dxhy.base.service.invoicecheck;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dxhy.api.model.config.Tax;
import com.dxhy.base.dao.BaseTDxRecordInvoiceDao;
import com.dxhy.base.dao.BaseTDxTaxCurrentDao;
import com.dxhy.base.entity.BaseTDxDkCount;
import com.dxhy.base.entity.BaseTDxRecordInvoice;
import com.dxhy.base.entity.BaseTDxTaxCurrent;
import com.dxhy.base.model.BaseSmgxCxRespVO;
import com.dxhy.base.utils.InvoiceTypeUtils;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.FpqsjgEnum;
import com.dxhy.common.enums.FpztEnum;
import com.dxhy.common.service.TabulateRedisService;
import com.dxhy.common.service.impl.MpBaseServiceImpl;
import com.dxhy.common.util.AmountFormatUtil;
import com.dxhy.common.util.CheckInvoiceUtil;
import com.dxhy.common.util.MathUtil;
import com.dxhy.common.util.StringHelper;
import com.dxhy.common.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 扫码勾选查询service实现类
 *
 * @author kangzq
 * @date 2019年5月11日
 * @version 1.0
 */
@SuppressWarnings({"AlibabaLowerCamelCaseVariableNaming", "AlibabaUndefineMagicConstant", "AlibabaMethodTooLong"})
@Service("baseInvoiceScanCheckService")
public class BaseInvoiceScanCheckServiceImpl extends MpBaseServiceImpl<BaseTDxRecordInvoiceDao, BaseTDxRecordInvoice>
    implements BaseInvoiceScanCheckService {

    @Resource
    private BaseTDxTaxCurrentDao baseTDxTaxCurrentDao;
    @Resource
    private BaseTDxRecordInvoiceDao baseTDxRecordInvoiceDao;
    @Resource
    private TabulateRedisService tabulateRedisService;

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

        try {
            String company = (String)pramsMap.get("company");
            String menuId = (String)pramsMap.get("menuId");

            json = tabulateRedisService.getTabulateMenu(company, menuId);

            QueryWrapper<BaseTDxRecordInvoice> queryWrapper = new QueryWrapper<>();
            String invoiceCode = (String) pramsMap.get("invoiceCode");
            String uuid = (StringUtils.isBlank(invoiceCode)?"":invoiceCode) + (String)pramsMap.get("invoiceNo");
            queryWrapper.eq("uuid", uuid);
            BaseTDxRecordInvoice tDxRecordInvoice = baseTDxRecordInvoiceDao.selectOne(queryWrapper);
            String qsflag = (String)pramsMap.get("qsflag");
            String invoiceType = (String)pramsMap.get("invoiceType");
            // 转化为页面展示对象
            if (tDxRecordInvoice != null) {
                List<BaseSmgxCxRespVO> voList = new ArrayList<>();
                BaseSmgxCxRespVO vo = new BaseSmgxCxRespVO();
                vo.setSelect(true);
                vo.setId(String.valueOf(tDxRecordInvoice.getId()));
                vo.setInvoiceCode(tDxRecordInvoice.getInvoiceCode());
                vo.setInvoiceNo(tDxRecordInvoice.getInvoiceNo());
                vo.setEleInvoiceNo(tDxRecordInvoice.getEleInvoiceNo());
                String kprq = (String)pramsMap.get("invoiceDate");
                String je = (String)pramsMap.get("invoiceAmount");
                String jym = (String)pramsMap.get("checkCode");
                vo.setInvoiceDate(kprq);
                vo.setInvoiceAmount(je);
                if(ObjectUtil.isNotEmpty(tDxRecordInvoice.getTotalAmount())){
                    vo.setTotalAmount(AmountFormatUtil.fmtMicrometer(MathUtil.round(tDxRecordInvoice.getTotalAmount().toPlainString())));
                }

                //如果是代扣代缴，不验证以下逻辑
                if("4".equals(tDxRecordInvoice.getXxly())){
                    vo.setInvoiceAmount("");
                }else{
                    if (StringUtils.isNotBlank(je)) {
                        je = MathUtil.round(je);
                        String recordMoney = "";
                        if(CheckInvoiceUtil.isNeedTotalAmountByInvoiceType(tDxRecordInvoice.getInvoiceType())){
                            recordMoney =
                                    tDxRecordInvoice.getTotalAmount().setScale(2, BigDecimal.ROUND_DOWN).toPlainString();
                        }else{
                            recordMoney =
                                    tDxRecordInvoice.getInvoiceAmount().setScale(2, BigDecimal.ROUND_DOWN).toPlainString();
                        }
                        if (!je.equals(
                                recordMoney)) {
                            vo.setBkgxts("发票金额与底账数据不一致");
                            vo.setSelect(false);
                            voList.add(vo);
                            json.put("datalist", voList);
                            return super.responseResult(json);
                        }
                        vo.setInvoiceAmount(je);
                    } else {
                        vo.setInvoiceAmount(tDxRecordInvoice.getInvoiceAmount() + "");
                    }

                    String invoiceStatus="07";
                    if ( !invoiceStatus.contains(tDxRecordInvoice.getInvoiceStatus())){
                        for (FpztEnum e : FpztEnum.values()) {
                            if (tDxRecordInvoice.getInvoiceStatus().equals(e.getFpztDm())) {
                                vo.setBkgxts(e.getFpztMc(e.getIndex()) + "发票");
                                vo.setSelect(false);
                                voList.add(vo);
                                json.put("datalist", voList);
                                return super.responseResult(json);
                            }
                        }
                    }
                    if (tDxRecordInvoice.getInvoiceAmount().compareTo(BigDecimal.ZERO) < 0) {
                        vo.setBkgxts("金额小于0");
                        vo.setSelect(false);
                        voList.add(vo);
                        json.put("datalist", voList);
                        return super.responseResult(json);
                    }
                    if (tDxRecordInvoice.getTaxAmount().compareTo(BigDecimal.ZERO) < 0) {
                        vo.setBkgxts("税额小于0");
                        vo.setSelect(false);
                        voList.add(vo);
                        json.put("datalist", voList);
                        return super.responseResult(json);
                    }
                }


                vo.setCheckCode(jym);
                vo.setInvoiceType(tDxRecordInvoice.getInvoiceType());
                boolean krz = InvoiceTypeUtils.isKrz(tDxRecordInvoice.getInvoiceType(), tDxRecordInvoice.getLqTdyslxdm());
                if (!krz&&!"2".equals(tDxRecordInvoice.getYwlx())) {
                    vo.setBkgxts("发票类型有误");
                    vo.setSelect(false);
                    voList.add(vo);
                    json.put("datalist", voList);
                    return super.responseResult(json);
                }
                List<String> list = (List<String>)pramsMap.get("gfsh");

                if (list == null || !list.contains(tDxRecordInvoice.getGfTaxNo())) {
                    vo.setBkgxts("无该发票购方税号权限");
                    vo.setSelect(false);
                    voList.add(vo);
                    json.put("datalist", voList);
                    return super.responseResult(json);
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                if (StringUtils.isNotBlank(jym)) {
                    if (jym.equals(tDxRecordInvoice.getCheckCode())) {
                        vo.setCheckCode(tDxRecordInvoice.getCheckCode());
                    }
                }
                if ("1".equals(qsflag) && !"1".equals(tDxRecordInvoice.getQsStatus())) {
                    vo.setBkgxts("该发票未签收");
                    vo.setSelect(false);
                    voList.add(vo);
                    json.put("datalist", voList);
                    return super.responseResult(json);
                }
                // 获取税款所属期起止时间
                QueryWrapper<BaseTDxTaxCurrent> currentWrapper = new QueryWrapper<>();
                currentWrapper.eq("taxno", tDxRecordInvoice.getGfTaxNo());
                BaseTDxTaxCurrent current = baseTDxTaxCurrentDao.selectOne(currentWrapper);

                if (current != null && current.getCurrentTaxPeriod() != null) {
                    vo.setDqskssq(current.getCurrentTaxPeriod());
                } else {
                    vo.setBkgxts("无该发票税号属期信息");
                    vo.setSelect(false);
                    voList.add(vo);
                    json.put("datalist", voList);
                    return super.responseResult(json);
                }
                if (tDxRecordInvoice.getQsDate() != null) {
                    vo.setQsDate(sdf.format(tDxRecordInvoice.getQsDate()));
                }
                if (tDxRecordInvoice.getQsStatus().equals(FpqsjgEnum.YQS.getQsjgDm())) {
                    vo.setQsStatus(FpqsjgEnum.YQS.getQsjgMc(FpqsjgEnum.YQS.getIndex()));
                } else {
                    vo.setQsStatus(FpqsjgEnum.WQS.getQsjgMc(FpqsjgEnum.WQS.getIndex()));
                }
                if (StringUtils.isNotBlank(tDxRecordInvoice.getCheckCode())) {
                    vo.setCheckCode(
                        tDxRecordInvoice.getCheckCode().substring(tDxRecordInvoice.getCheckCode().length() - 6));
                } else {
                    vo.setCheckCode("");
                }
                vo.setInvoiceType(tDxRecordInvoice.getInvoiceType());
                if(ObjectUtil.isNotEmpty(tDxRecordInvoice.getTaxAmount())){
                    vo.setTaxAmount(AmountFormatUtil.fmtMicrometer(MathUtil.round(tDxRecordInvoice.getTaxAmount().toPlainString())));
                }
                List<Tax> taxList = (List<Tax>)pramsMap.get("taxList");
                List<String> taxnoList = new ArrayList<>();
                if (taxList != null && taxList.size() > 0) {
                    for (Tax tax : taxList) {
                        String upgradeStatus = tax.getUpgradeStatus();
                        if ("1".equals(upgradeStatus)) {
                            taxnoList.add(tax.getTaxno());
                        }
                    }
                }
                if (taxnoList.contains(tDxRecordInvoice.getGfTaxNo())) {
                    vo.setUpgradeStatus("1");
                    if(ObjectUtil.isNotEmpty(tDxRecordInvoice.getTaxAmount())){
                        vo.setDkTaxAmount(MathUtil.round(tDxRecordInvoice.getTaxAmount().toPlainString()));
                    }
                    if (tDxRecordInvoice.getDkTaxAmount() != null) {
                        vo.setDkTaxAmount(MathUtil.round(tDxRecordInvoice.getDkTaxAmount().toPlainString()));
                    }
                } else {
                    vo.setUpgradeStatus("0");
                    if(ObjectUtil.isNotEmpty(tDxRecordInvoice.getTaxAmount())){
                        vo.setDkTaxAmount(AmountFormatUtil
                                .fmtMicrometer(MathUtil.round(tDxRecordInvoice.getTaxAmount().toPlainString())));
                    }
                    if (tDxRecordInvoice.getDkTaxAmount() != null) {
                        vo.setDkTaxAmount(AmountFormatUtil
                            .fmtMicrometer(MathUtil.round(tDxRecordInvoice.getDkTaxAmount().toPlainString())));
                    }
                }
                if (current == null) {
                    vo.setBkgxts("企业属期表无该税号数据");
                    vo.setSelect(false);
                    voList.add(vo);
                    json.put("datalist", voList);
                    return super.responseResult(json);
                }
                // 设置不可勾选提示:"失控","作废","红冲","异常“等

                Map<String, Object> curMap = new HashMap<>(3);
                List<String> gfshList = new ArrayList<>();
                gfshList.add(tDxRecordInvoice.getGfTaxNo());
                curMap.put("gfsh", gfshList);
                List<BaseTDxDkCount> curList = baseTDxRecordInvoiceDao.selectDksh(curMap);
                for (BaseTDxDkCount cur : curList) {
                    String skssq = cur.getSkssq();
                    String year = skssq.substring(0, 4);
                    String mon = skssq.substring(4);
                    LocalDate localDate = LocalDate.of(Integer.parseInt(year), Integer.parseInt(mon), 1);
                    LocalDate localDate1 = localDate.plusMonths(1);
                    LocalDate localDate2 = LocalDate.now();
                    if (!"0".equals(cur.getTjStatus()) && !"3".equals(cur.getTjStatus())
                        && !localDate2.isBefore(localDate1)) {
                        vo.setBkgxts("该发票的购方税号已申请抵扣统计");
                        vo.setSelect(false);
                        voList.add(vo);
                        json.put("datalist", voList);
                        return super.responseResult(json);
                    }
                }

                String invoiceDate = sdf.format(tDxRecordInvoice.getInvoiceDate());
                if (!kprq.equals(invoiceDate)) {
                    vo.setBkgxts("开票日期与底账数据不一致");
                    vo.setSelect(false);
                    voList.add(vo);
                    json.put("datalist", voList);
                    return super.responseResult(json);
                }


                if (!StringHelper.isBlank(tDxRecordInvoice.getBdkStatus())) {
                    if ("2".equals(tDxRecordInvoice.getBdkStatus())
                        && "1234".contains(tDxRecordInvoice.getBdkStatus())) {
                        vo.setBkgxts("该发票已认证不抵扣");
                        vo.setSelect(false);
                        voList.add(vo);
                        json.put("datalist", voList);
                        return super.responseResult(json);
                    }
                    if ("1".equals(tDxRecordInvoice.getExportMark())) {
                        vo.setBkgxts("该发票为出口转内销发票");
                        vo.setSelect(false);
                        voList.add(vo);
                        json.put("datalist", voList);
                        return super.responseResult(json);
                    }
                    if ("3".equals(tDxRecordInvoice.getBdkStatus())
                        && "1234".contains(tDxRecordInvoice.getAuthStatus())) {
                        vo.setBkgxts("该发票已做退税认证");
                        vo.setSelect(false);
                        voList.add(vo);
                        json.put("datalist", voList);
                        return super.responseResult(json);
                    }
                }
                if ("1".equals(current.getLatchStatus())) {
                    vo.setBkgxts("该发票购方税号已锁定");
                    vo.setSelect(false);
                    voList.add(vo);
                    json.put("datalist", voList);
                    return super.responseResult(json);
                }
                if (!StringHelper.isBlank(tDxRecordInvoice.getAuthStatus())
                    && !StringHelper.isBlank(tDxRecordInvoice.getRzhYesorno())) {
                    if ("1".equals(tDxRecordInvoice.getRzhYesorno()) && "4".equals(tDxRecordInvoice.getAuthStatus())) {
                        vo.setBkgxts("该发票已认证并且认证成功");
                        vo.setSelect(false);
                        voList.add(vo);
                        json.put("datalist", voList);
                        return super.responseResult(json);
                    }
                }

                if ("1".equals(tDxRecordInvoice.getBdkStatus())) {
                    if ("1".equals(tDxRecordInvoice.getAuthStatus())) {
                        vo.setBkgxts("该发票已勾选");
                        vo.setSelect(false);
                        voList.add(vo);
                        json.put("datalist", voList);
                        return super.responseResult(json);
                    } else if ("2".equals(tDxRecordInvoice.getAuthStatus())) {
                        vo.setBkgxts("该发票已确认");
                        vo.setSelect(false);
                        voList.add(vo);
                        json.put("datalist", voList);
                        return super.responseResult(json);
                    } else if ("3".equals(tDxRecordInvoice.getAuthStatus())) {
                        vo.setBkgxts("该发票已发送认证");
                        vo.setSelect(false);
                        voList.add(vo);
                        json.put("datalist", voList);
                        return super.responseResult(json);
                    } else if ("4".equals(tDxRecordInvoice.getAuthStatus())) {
                        vo.setBkgxts("该发票已认证抵扣");
                        vo.setSelect(false);
                        voList.add(vo);
                        json.put("datalist", voList);
                        return super.responseResult(json);
                    }
                }

                if (current.getSelectStartDate() != null) {
                    if (tDxRecordInvoice.getInvoiceDate()
                        .compareTo(new SimpleDateFormat("yyyyMMdd").parse(current.getSelectStartDate())) < 0) {
                        vo.setBkgxts("发票逾期");
                        vo.setSelect(false);
                        voList.add(vo);
                        json.put("datalist", voList);
                        return super.responseResult(json);
                    }
                }
                if (StringUtils.isNotBlank(current.getSelectEndDate())) {
                    if (tDxRecordInvoice.getInvoiceDate()
                        .compareTo(DateUtils.strToDatePeriodFormate(current.getSelectEndDate()+"235959","yyyyMMddHHmmss")) > 0) {
                        vo.setBkgxts("发票未到期");
                        vo.setSelect(false);
                        voList.add(vo);
                        json.put("datalist", voList);
                        return super.responseResult(json);
                    }
                }
                voList.add(vo);
                // 设置总条数
                json.put("datalist", voList);
            } else {
                List<BaseSmgxCxRespVO> voList = new ArrayList<>();
                BaseSmgxCxRespVO vo = new BaseSmgxCxRespVO();
                vo.setBkgxts("无底账信息");
                vo.setSelect(false);
                vo.setInvoiceNo(pramsMap.get("invoiceNo").toString());
                vo.setInvoiceCode(pramsMap.get("invoiceCode").toString());
                vo.setInvoiceDate(pramsMap.get("invoiceDate").toString());
                vo.setInvoiceAmount(pramsMap.get("invoiceAmount") == null ? ""
                    : MathUtil.round(pramsMap.get("invoiceAmount").toString()));
                vo.setCheckCode(pramsMap.get("checkCode") == null ? "" : pramsMap.get("checkCode").toString());
                vo.setUpgradeStatus("0");
                vo.setInvoiceType(invoiceType);
                voList.add(vo);
                json.put("datalist", voList);
            }

        } catch (Exception e) {
            // 统一设置操作异常标识
            json = super.errorResult(e);
        }

        return super.responseResult(json);
    }
}
