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.sys.DictdetaModel;
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.BaseSggxCxRespVO;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.service.DictdetaServcice;
import com.dxhy.common.service.InvoiceLogService;
import com.dxhy.common.service.TabulateRedisService;
import com.dxhy.common.service.impl.MpBaseServiceImpl;
import com.dxhy.common.util.AmountFormatUtil;
import com.dxhy.common.util.MathUtil;
import com.dxhy.common.utils.DateUtils;
import com.dxhy.common.vo.InvoiceLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;

/**
 * @author jiaohongyang
 */
@SuppressWarnings({"AlibabaLowerCamelCaseVariableNaming", "AlibabaMethodTooLong", "AlibabaUndefineMagicConstant",
    "AlibabaCollectionInitShouldAssignCapacity"})
@Service("baseIntelligentizeCheckService")
@Slf4j
public class BaseIntelligentizeCheckServiceImpl extends MpBaseServiceImpl<BaseTDxRecordInvoiceDao, BaseTDxRecordInvoice>
    implements BaseIntelligentizeCheckService {

    @Resource
    private BaseTDxRecordInvoiceDao baseTDxRecordInvoiceDao;
    @Resource
    private BaseTDxTaxCurrentDao baseTDxTaxCurrentDao;
    @Resource
    private InvoiceLogService invoiceLogService;
    @Resource
    private TabulateRedisService tabulateRedisService;
    @Resource
    private DictdetaServcice dictdetaServcice;

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

            QueryWrapper<BaseTDxTaxCurrent> currentWrapper = new QueryWrapper<>();
            currentWrapper.eq("taxno", pramsMap.get("gfsh"));
            BaseTDxTaxCurrent current = baseTDxTaxCurrentDao.selectOne(currentWrapper);
            if (current != null) {
                if ("1".equals(current.getLatchStatus())) {
                    json.put("message", "此税号已被锁定，如需勾选，请到企业税务信息菜单解除锁定");
                    json.put("msgcode", "3");
                    return super.responseResult(json);
                }
            } else {
                json.put("message", "该税号没有属期信息");
                json.put("msgcode", "2");
                return super.responseResult(json);
            }

            Map<String, Object> curMap = new HashMap<>();
            List<String> shList = new ArrayList<>();
            shList.add((String)pramsMap.get("gfsh"));
            curMap.put("gfsh", shList);
            List<BaseTDxDkCount> curList = baseTDxRecordInvoiceDao.selectDksh(curMap);
            BaseTDxDkCount cur = curList.get(0);
            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)) {
                json.put("message", "此税号已申请抵扣统计，请撤销统计后重新操作");
                json.put("msgcode", "3");
                return super.responseResult(json);
            }

            List<BaseTDxRecordInvoice> list = baseTDxRecordInvoiceDao.selectZngx(pramsMap);
            if (list == null || list.size() == 0) {
                json.put("message", "没有可操作的数据");
                json.put("msgcode", "0");
                return super.responseResult(json);
            }
            int count = 0;
            BigDecimal taxAmount = new BigDecimal(0);
            BigDecimal invoiceAmount = new BigDecimal(0);
            BigDecimal floatTax = new BigDecimal((String)pramsMap.get("floatTax"));
            BigDecimal maxTax = new BigDecimal((String)pramsMap.get("maxTax"));
            List<String> ids = new ArrayList<>();
            for (int i = 1; i <= list.size(); i++) {

                if(ObjectUtil.isNotEmpty(list.get(i - 1).getTaxAmount())){
                    taxAmount = taxAmount.add(list.get(i - 1).getTaxAmount());
                }

                if(ObjectUtil.isNotEmpty(list.get(i - 1).getInvoiceAmount())){
                    invoiceAmount = invoiceAmount.add(list.get(i - 1).getInvoiceAmount());
                }

                if (taxAmount.compareTo(maxTax.add(floatTax)) > 0) {

                    taxAmount = taxAmount.subtract(list.get(i - 1).getTaxAmount());

                    invoiceAmount = invoiceAmount.subtract(list.get(i - 1).getInvoiceAmount());
                } else {
                    count++;
                    ids.add(list.get(i - 1).getId() + "");
                }
            }
            if (count == 0) {
                json.put("message", "没有可操作的数据");
                json.put("msgcode", "0");
                return super.responseResult(json);
            }
            json.put("msgcode", "1");
            json.put("taxAmount", AmountFormatUtil.fmtMicrometer(MathUtil.round(taxAmount.toPlainString())));
            json.put("dkTaxAmount", AmountFormatUtil.fmtMicrometer(MathUtil.round(taxAmount.toPlainString())));
            json.put("invoiceAmount", AmountFormatUtil.fmtMicrometer(MathUtil.round(invoiceAmount.toPlainString())));
            json.put("total", AmountFormatUtil.fmtMicrometer(Integer.toString(count)));
            json.put("ids", ids);
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            json = super.errorResult(e);
        }

        return super.responseResult(json);
    }

    @Override
    public String updatezngx(Map<String, Object> pramsMap) {
        String company = (String)pramsMap.get("company");
        String menuId = (String)pramsMap.get("menuId");
        JSONObject json = tabulateRedisService.getTabulateMenu(company, menuId);

        List<String> ids = (List<String>)pramsMap.get("ids");
        List<BaseSggxCxRespVO> list = new ArrayList<>();
        int count = 0;
        BigDecimal taxAmount = new BigDecimal(0);
        BigDecimal invoiceAmount = new BigDecimal(0);
        List<DictdetaModel> fpztModels = dictdetaServcice.selectDictdeta("INVOICE_STATUS");
        List<DictdetaModel> qsztModels = dictdetaServcice.selectDictdeta("qsStatus");
        List<DictdetaModel> qsfsModels = dictdetaServcice.selectDictdeta("qsType");
        List<InvoiceLog> logList = new ArrayList<>();
        for (String id : ids) {
            try {
                DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
                BaseTDxRecordInvoice recordInvoice = super.baseMapper.selectById(Long.parseLong(id));
                DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_WRITE);
                Map<String, Object> map = new HashMap<>();
                map.put("gxType", "3");
                map.put("dkTaxAmount", recordInvoice.getTaxAmount());
                map.put("userAccount", pramsMap.get("userName"));
                map.put("id", id);
                map.put("bdkStatus", "1");
                super.baseMapper.updateGx(map);
                count++;
                if(ObjectUtil.isNotEmpty(recordInvoice.getTaxAmount())){
                    taxAmount = taxAmount.add(recordInvoice.getTaxAmount());
                }
                if(ObjectUtil.isNotEmpty(recordInvoice.getInvoiceAmount())){
                    invoiceAmount = invoiceAmount.add(recordInvoice.getInvoiceAmount());
                }

                BaseSggxCxRespVO vo = new BaseSggxCxRespVO();
                if(ObjectUtil.isNotEmpty(recordInvoice.getTaxAmount())){
                    vo.setDkse(
                            AmountFormatUtil.fmtMicrometer(MathUtil.round(recordInvoice.getTaxAmount().toPlainString())));
                }

                vo.setBusinessName(recordInvoice.getDeptName());
                vo.setId(recordInvoice.getId() + "");
                vo.setXh(count + "");
                if(ObjectUtil.isNotEmpty(recordInvoice.getInvoiceAmount())){
                    vo.setInvoiceAmount(
                            AmountFormatUtil.fmtMicrometer(MathUtil.round(recordInvoice.getInvoiceAmount().toPlainString())));
                }
                if(ObjectUtil.isNotEmpty(recordInvoice.getTaxAmount())){
                    vo.setTaxAmount(
                            AmountFormatUtil.fmtMicrometer(MathUtil.round(recordInvoice.getTaxAmount().toPlainString())));
                }

                vo.setInvoiceCode(recordInvoice.getInvoiceCode());
                vo.setInvoiceNo(recordInvoice.getInvoiceNo());
                vo.setInvoiceDate(DateUtils.dateToStr(recordInvoice.getInvoiceDate()));
                if (fpztModels!=null){
                    for (DictdetaModel model:fpztModels){
                        if (model.getDictcode().equals(recordInvoice.getInvoiceStatus())){
                            vo.setInvoiceStatus(model.getDictname());
                        }
                    }
                }
                vo.setInvoiceType(recordInvoice.getInvoiceType());
                // 签收方式为已经签收时展示签收信息
                if ("1".equals(recordInvoice.getQsStatus())) {
                    if (recordInvoice.getQsDate() != null) {
                        vo.setQsrq(DateUtils.dateToStr(recordInvoice.getQsDate()));
                    }
                    if (recordInvoice.getQsType() != null) {
                        if (qsfsModels!=null){
                            for (DictdetaModel model:qsfsModels){
                                if (model.getDictcode().equals(recordInvoice.getQsType())){
                                    vo.setQsfs(model.getDictname());
                                }
                            }
                        }
                    }
                    vo.setQsr(recordInvoice.getQsName());
                }
                if (recordInvoice.getQsStatus() != null) {
                    if (qsztModels!=null){
                        for (DictdetaModel model:qsztModels){
                            if (model.getDictcode().equals(recordInvoice.getQsStatus())){
                                vo.setQszt(model.getDictname());
                            }
                        }
                    }
                }
                vo.setGfmc(recordInvoice.getGfName());
                vo.setXfmc(recordInvoice.getXfName());
                vo.setEleInvoiceNo(recordInvoice.getEleInvoiceNo());
                list.add(vo);
                InvoiceLog invoiceLog = new InvoiceLog();
                invoiceLog.setInvoiceCode(recordInvoice.getInvoiceCode());
                invoiceLog.setInvoiceNo(recordInvoice.getInvoiceNo());
                invoiceLog.setType("2");
                invoiceLog.setCreateDate(new Date());
                invoiceLog.setInputName((String)pramsMap.get("userName"));
                invoiceLog.setInputStatus("13");
                invoiceLog.setRzType("3");
                logList.add(invoiceLog);
            } catch (Exception e) {
               log.info("业务处理异常：{}", e);
            }
        }
        try {
            if (logList.size() > 0) {
                invoiceLogService.toInvoiceLog(logList);
            }
            json.put("total", count);
            json.put("taxAmount", AmountFormatUtil.fmtMicrometer(MathUtil.round(taxAmount.toPlainString())));
            json.put("dkTaxAmount", AmountFormatUtil.fmtMicrometer(MathUtil.round(taxAmount.toPlainString())));
            json.put("invoiceAmount", AmountFormatUtil.fmtMicrometer(MathUtil.round(invoiceAmount.toPlainString())));
            json.put("datalist", list);
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
        }

        return super.responseResult(json);
    }
}
