package com.dxhy.base.service.fpxxrz;

import java.time.LocalDate;
import java.util.*;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
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.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.service.InvoiceLogService;
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;

/**
 * 撤销已认证发票service实现类
 *
 * @author kangzq
 * @date 2019年5月11日
 * @version 1.0
 */
@SuppressWarnings({"AlibabaMethodTooLong", "AlibabaCollectionInitShouldAssignCapacity",
    "AlibabaLowerCamelCaseVariableNaming"})
@Service("baseCxrzfpService")
public class BaseCxrzfpServiceImpl extends MpBaseServiceImpl<BaseTDxRecordInvoiceDao, BaseTDxRecordInvoice>
    implements BaseCxrzfpService {
    @Resource
    private BaseTDxRecordInvoiceDao baseTDxRecordInvoiceDao;
    @Resource
    private BaseTDxTaxCurrentDao baseTDxTaxCurrentDao;
    @Resource
    private InvoiceLogService invoiceLogService;

    @Override
    public String updateByIds(Map<String, Object> paramMap) {
        JSONObject json = new JSONObject();
        String[] cxids = paramMap.get("cxids").toString().split(",");
        int hjsl = 0;
        String hjje = "0";
        String hjse = "0";
        String hjdk = "0";
        StringBuilder sb = new StringBuilder();
        sb.append("以下税号已申请抵扣统计，请撤销统计后重新操作： \n ");
        StringBuilder sb1 = new StringBuilder();
        sb1.append("以下税号已被锁定不可撤销认证： \n ");
        StringBuilder sb2 = new StringBuilder();
        sb2.append("以下发票已做进项税转出，请取消转出后操作： \n ");
        List<String> taxList = new ArrayList<>();
        List<String> latchList = new ArrayList<>();
        List<String> invoiceList = new ArrayList<>();
        boolean taxFlag = false;
        boolean latchFlag = false;
        boolean invoiceFlag = false;
        List<InvoiceLog> logList = new ArrayList<>();
        for (String cxid : cxids) {
            try {
                DynamicContextHolder.push(paramMap.get("dbName") + DbConstant.BUSINESS_READ);
                QueryWrapper<BaseTDxRecordInvoice> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("id", cxid);
                BaseTDxRecordInvoice recordInvoice = baseTDxRecordInvoiceDao.selectOne(queryWrapper);
                if ("1".equals(recordInvoice.getOutStatus()) || "2".equals(recordInvoice.getOutStatus())) {
                    if (!invoiceList.contains(recordInvoice.getUuid())) {
                        invoiceList.add(recordInvoice.getUuid());
                        sb2.append("发票代码：" + recordInvoice.getInvoiceCode() + ",发票号码：" + recordInvoice.getInvoiceNo())
                            .append(" \n ");
                    }
                    invoiceFlag = true;
                    continue;
                }
                QueryWrapper<BaseTDxTaxCurrent> currentWrapper = new QueryWrapper<>();
                currentWrapper.eq("taxno", recordInvoice.getGfTaxNo());
                BaseTDxTaxCurrent current = baseTDxTaxCurrentDao.selectOne(currentWrapper);
                if (current != null) {
                    if ("1".equals(current.getLatchStatus())) {
                        if (!latchList.contains(recordInvoice.getGfTaxNo())) {
                            sb1.append(recordInvoice.getGfTaxNo()).append(" \n ");
                            latchList.add(recordInvoice.getGfTaxNo());
                        }
                        latchFlag = true;
                        continue;
                    }
                } else {
                    continue;
                }
                Map<String, Object> curMap = new HashMap<>();
                List<String> shList = new ArrayList<>();
                shList.add(recordInvoice.getGfTaxNo());
                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)) {
                    if (!taxList.contains(recordInvoice.getGfTaxNo())) {
                        sb.append(recordInvoice.getGfTaxNo()).append(" \n ");
                        taxList.add(recordInvoice.getGfTaxNo());
                    }
                    taxFlag = true;
                    continue;
                }
                UpdateWrapper<BaseTDxRecordInvoice> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("id", cxid);
                BaseTDxRecordInvoice entity = new BaseTDxRecordInvoice();
                entity.setRzlx("5");
                entity.setCxrzStatus("1");
                entity.setCxrzCurrentPeriod(current.getCurrentTaxPeriod());
                entity.setCxrzDate(DateUtils.getSqlDate());
                DynamicContextHolder.push(paramMap.get("dbName") + DbConstant.BUSINESS_WRITE);
                boolean flag = super.update(entity, updateWrapper);
                if (flag) {
                    InvoiceLog invoiceLog = new InvoiceLog();
                    invoiceLog.setInvoiceCode(recordInvoice.getInvoiceCode());
                    invoiceLog.setInvoiceNo(recordInvoice.getInvoiceNo());
                    invoiceLog.setType("2");
                    invoiceLog.setCreateDate(new Date());
                    invoiceLog.setInputName((String)paramMap.get("name"));
                    invoiceLog.setInputStatus("15");
                    logList.add(invoiceLog);
                    hjsl = hjsl + 1;
                    hjje = MathUtil.round(MathUtil.add(hjje, recordInvoice.getInvoiceAmount().toPlainString()));
                    hjse = MathUtil.round(MathUtil.add(hjse, recordInvoice.getTaxAmount().toPlainString()));
                    hjdk = MathUtil.round(MathUtil.add(hjdk, recordInvoice.getDkTaxAmount().toPlainString()));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (logList.size() > 0) {
            invoiceLogService.toInvoiceLog(logList);
        }
        String message = "";
        if (taxFlag) {
            message = sb.toString();
        }
        if (latchFlag) {
            message = message + sb1.toString() + "如需撤销认证，请到企业税务信息菜单解除锁定";
        }
        if (invoiceFlag) {
            message = message + sb2.toString();
        }
        json.put("message", message);
        json.put("hjsl", AmountFormatUtil.fmtMicrometer(hjsl + ""));
        json.put("hjje", AmountFormatUtil.fmtMicrometer(hjje));
        json.put("hjse", AmountFormatUtil.fmtMicrometer(hjse));
        json.put("hjdk", AmountFormatUtil.fmtMicrometer(hjdk));
        json.put("total", cxids.length);

        return super.responseResult(json);

    }
}
