package com.dxhy.base.service.tdxrecordinvoice;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dxhy.base.dao.BaseFpbrzDao;
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.BaseFpbrzRespVO;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.constant.DictConstant;
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 com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

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

/**
 *
 *
 * 发票不认证业务实现类
 *
 * @author zhanghong
 * @date 2019年5月11日
 *
 */
@SuppressWarnings({"AlibabaUndefineMagicConstant", "AlibabaMethodTooLong", "AlibabaCollectionInitShouldAssignCapacity",
    "AlibabaLowerCamelCaseVariableNaming"})
@Service("baseIFpbrzService")
@Slf4j
public class BaseFpbrzServiceImpl extends MpBaseServiceImpl<BaseFpbrzDao, BaseTDxRecordInvoice>
    implements BaseIFpbrzService {
    @Resource
    private BaseTDxTaxCurrentDao baseTDxTaxCurrentDao;
    @Resource
    private BaseTDxRecordInvoiceDao baseTDxRecordInvoiceDao;
    @Resource
    private InvoiceLogService invoiceLogService;
    @Resource
    private TabulateRedisService tabulateRedisService;
    @Resource
    private DictdetaServcice dictdetaServcice;

    @Override
    public String selectByFpbrz(Map<String, Object> pramsMap, int curr, int size) {

        String company = (String)pramsMap.get("company");
        String menuId = (String)pramsMap.get("menuId");
        JSONObject json = tabulateRedisService.getTabulateMenu(company, menuId);

        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);

        List<String> taxnoList = (List<String>)pramsMap.get("gfsh");
        if (taxnoList == null || taxnoList.size() == 0) {
            json.put("hjje", 0);
            json.put("hjse", 0);
            json.put("total", 0);
            json.put("datalist", new ArrayList<>());

            return super.responseResult(json);
        }

        List<BaseTDxDkCount> curList = baseTDxRecordInvoiceDao.selectDksh(pramsMap);
        List<String> gfshList = new ArrayList<>();
        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)) {
                gfshList.add(cur.getTaxno());
            }
        }
        if (curr == 1) {
            String hjje = "0.00";
            String hjse = "0.00";
            String total = "0";
            BaseTDxRecordInvoice recordInvoice = super.baseMapper.selectHjByFpbrz(pramsMap);
            if (recordInvoice != null) {
                total = recordInvoice.getId() + "";
                if (!"0".equals(total)) {
                    hjje = MathUtil.round(recordInvoice.getInvoiceAmount().toPlainString());
                    hjse = MathUtil.round(recordInvoice.getTaxAmount().toPlainString());
                }
            }
            json.put("hjje", AmountFormatUtil.fmtMicrometer(hjje));
            json.put("hjse", AmountFormatUtil.fmtMicrometer(hjse));
            // 设置记录总数
            json.put("total", AmountFormatUtil.fmtMicrometer(total));
        }
        PageHelper.startPage(curr, size);
        List<BaseTDxRecordInvoice> pageList = super.baseMapper.selectByFpbrz(pramsMap);
        PageInfo<BaseTDxRecordInvoice> pageInfo = new PageInfo<>(pageList);
        List<BaseTDxRecordInvoice> resultList = pageInfo.getList();

        List<Object> returnList = new ArrayList<>();
        if (resultList != null && resultList.size() > 0) {
            int start = new Long(pageInfo.getStartRow()).intValue();

            for (int i = 0; i < resultList.size(); i++) {
                BaseFpbrzRespVO brzlb = this.convertToFpbrzView(resultList.get(i), start + i);
                if (!gfshList.contains(brzlb.getGfsh())) {
                    //当前属期已统计
                    brzlb.setSelect(false);
                    if(StringUtils.isNotBlank(brzlb.getBkgxts())){
                        brzlb.setBkgxts(brzlb.getBkgxts()+"，当前属期已统计");
                    }else{
                        brzlb.setBkgxts("当前属期已统计");
                    }
                }
                String qsStatus = (String)pramsMap.get("isQs");
                if ("1".equals(qsStatus) && !"1".equals(resultList.get(i).getQsStatus())) {
                    //该发票未签收
                    brzlb.setSelect(false);
                    if(StringUtils.isNotBlank(brzlb.getBkgxts())){
                        brzlb.setBkgxts(brzlb.getBkgxts()+"，该发票未签收");
                    }else{
                        brzlb.setBkgxts("该发票未签收");
                    }
                }
                returnList.add(brzlb);

            }
        }
        json.put("total", pageInfo.getTotal());
        json.put("datalist", returnList);

        return super.responseResult(json);
    }

    private BaseFpbrzRespVO convertToFpbrzView(BaseTDxRecordInvoice tDxRecordInvoice, int i) {
        BaseFpbrzRespVO brzvo = new BaseFpbrzRespVO();
        if (tDxRecordInvoice.getDkTaxAmount() != null) {
            brzvo.setDkse(
                AmountFormatUtil.fmtMicrometer(MathUtil.round(tDxRecordInvoice.getDkTaxAmount().toPlainString())));
        } else {
            brzvo.setDkse(tDxRecordInvoice.getTaxAmount() == null ? ""
                : AmountFormatUtil.fmtMicrometer(MathUtil.round(tDxRecordInvoice.getTaxAmount().toPlainString())));
        }
        brzvo.setFpdm(tDxRecordInvoice.getInvoiceCode());
        brzvo.setGfmc(tDxRecordInvoice.getGfName());
        brzvo.setQsfs(tDxRecordInvoice.getQsType());
        brzvo.setGfsh(tDxRecordInvoice.getGfTaxNo());
        brzvo.setId(tDxRecordInvoice.getId().toString());
        brzvo.setBusinessName(tDxRecordInvoice.getDeptName());

        brzvo.setJe(tDxRecordInvoice.getInvoiceAmount() == null ? ""
            : AmountFormatUtil.fmtMicrometer(MathUtil.round(tDxRecordInvoice.getInvoiceAmount().toPlainString())));

        brzvo.setKprq(
            tDxRecordInvoice.getInvoiceDate() == null ? "" : DateUtils.dateToStr(tDxRecordInvoice.getInvoiceDate()));
        brzvo.setFphm(tDxRecordInvoice.getInvoiceNo());
        brzvo.setUuid(tDxRecordInvoice.getUuid());
        brzvo.setXh(String.valueOf(i));
        brzvo.setXfsh(tDxRecordInvoice.getXfTaxNo());
        brzvo.setXfmc(tDxRecordInvoice.getXfName());
        brzvo.setQsrq(tDxRecordInvoice.getQsDate() == null ? "" : DateUtils.dateToStr(tDxRecordInvoice.getQsDate()));
//        brzvo.setQszt(tDxRecordInvoice.getQsStatus() == null ? "" : "0".equals(tDxRecordInvoice.getQsStatus()) ? "未签收"
//            : "1".equals(tDxRecordInvoice.getQsStatus()) ? "已签收" : "");
        brzvo.setQsr(tDxRecordInvoice.getQsName());
//        if (tDxRecordInvoice.getQsType() != null) {
//            for (QsfsEnum e : QsfsEnum.values()) {
//                if (tDxRecordInvoice.getQsType().equals(e.getQsfsDm())) {
//                    brzvo.setQsfs(e.getQsfsMc(e.getIndex()));
//                }
//            }
//        }
        //字典转换
        brzvo.setQszt(dictdetaServcice.queryDictName(DictConstant.QS_STATUS,tDxRecordInvoice.getQsStatus()));
        if (tDxRecordInvoice.getQsType() != null) {
            brzvo.setQsfs(dictdetaServcice.queryDictName(DictConstant.QS_TYPE,tDxRecordInvoice.getQsType()));
        }
        brzvo.setSe(tDxRecordInvoice.getTaxAmount() == null ? ""
            : AmountFormatUtil.fmtMicrometer(MathUtil.round(tDxRecordInvoice.getTaxAmount().toPlainString())));
        if ("2".equals(tDxRecordInvoice.getBdkStatus())) {
//            brzvo.setBdkStatus("0".equals(tDxRecordInvoice.getAuthStatus()) ? "未申请"
//                : "1".equals(tDxRecordInvoice.getAuthStatus()) ? "已申请"
//                    : "2".equals(tDxRecordInvoice.getAuthStatus()) ? "已确认"
//                        : "3".equals(tDxRecordInvoice.getAuthStatus()) ? "已发送认证不抵扣"
//                            : "4".equals(tDxRecordInvoice.getAuthStatus()) ? "认证不抵扣成功"
//                                : "5".equals(tDxRecordInvoice.getAuthStatus()) ? "认证不抵扣失败" : "");
            brzvo.setBdkStatus(dictdetaServcice.queryDictName(DictConstant.BDK_AUTH_STATUS,tDxRecordInvoice.getAuthStatus()));
        } else {
            brzvo.setBdkStatus("未申请");
        }
//        brzvo.setCxbdkStatus("0".equals(tDxRecordInvoice.getCxbdkStatus()) ? "未申请"
//            : "1".equals(tDxRecordInvoice.getCxbdkStatus()) ? "已申请"
//                : "2".equals(tDxRecordInvoice.getCxbdkStatus()) ? "已发送撤销不抵扣"
//                    : "4".equals(tDxRecordInvoice.getCxbdkStatus()) ? "撤销不抵扣成功"
//                        : "5".equals(tDxRecordInvoice.getCxbdkStatus()) ? "撤销不抵扣失败" : "");
        brzvo.setCxbdkStatus(dictdetaServcice.queryDictName(DictConstant.BDK_UNDO_STATUS,tDxRecordInvoice.getCxbdkStatus()));
        brzvo.setSelect(true);
        List<String> bkgxtsList = new LinkedList();
        if (!"0".equals(tDxRecordInvoice.getAuthStatus()) && !"5".equals(tDxRecordInvoice.getAuthStatus())
            && !"4".equals(tDxRecordInvoice.getAuthStatus()) && !"6".equals(tDxRecordInvoice.getAuthStatus())) {
            brzvo.setSelect(false);
            bkgxtsList.add("认证中发票");
        }
        if (!"0".equals(tDxRecordInvoice.getCxbdkStatus()) && !"5".equals(tDxRecordInvoice.getCxbdkStatus())
            && !"4".equals(tDxRecordInvoice.getCxbdkStatus())) {
            brzvo.setSelect(false);
            bkgxtsList.add("撤销认证中发票");
        }
        if(bkgxtsList.size()>0){
            brzvo.setBkgxts(String.join("，", bkgxtsList));
        }
        brzvo.setInvoiceType(tDxRecordInvoice.getInvoiceType());
        brzvo.setRzhBelongDate(tDxRecordInvoice.getRzhBelongDate());
        brzvo.setEleInvoiceNo(tDxRecordInvoice.getEleInvoiceNo());
        brzvo.setBdkYy(tDxRecordInvoice.getBdkYy());
        brzvo.setBdkMessage(dictdetaServcice.queryDictName(DictConstant.bdkMessage,tDxRecordInvoice.getBdkMessage()));
        return brzvo;
    }

    public static void main(String[] args) {
        BigDecimal taxAmount = new BigDecimal(0);
        System.out.println(taxAmount);
        BigDecimal taxAmount1 = new BigDecimal(0.00);
        System.out.println(taxAmount1);
    }

    @Override
    public String updateByFpbrz(Map<String, Object> pramsMap) {
        JSONObject json = new JSONObject();
        String userName = (String)pramsMap.get("name");
        String uuids = (String)pramsMap.get("uuids");
        String bdkYy = (String) pramsMap.get("bdkYy");
        String bdkMessage = (String) pramsMap.get("bdkMessage");
        String[] uuidArray = uuids.split(",");
        int count = 0;
        BigDecimal taxAmount = new BigDecimal(0);
        BigDecimal invoiceAmount = new BigDecimal(0);
        List<InvoiceLog> logList = new ArrayList<>();
        List<String> taxList = new ArrayList<>();
        StringBuilder sb1 = new StringBuilder();
        sb1.append("以下税号已被锁定不可勾选不认证： \n ");
        boolean flag = false;
        for (String s : uuidArray) {
            try {
                DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
                QueryWrapper<BaseTDxRecordInvoice> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("uuid", s);
                BaseTDxRecordInvoice recordInvoice = super.baseMapper.selectOne(queryWrapper);
                QueryWrapper<BaseTDxTaxCurrent> currentWrapper = new QueryWrapper<>();
                currentWrapper.eq("taxno", recordInvoice.getGfTaxNo());
                BaseTDxTaxCurrent current = baseTDxTaxCurrentDao.selectOne(currentWrapper);
                if (current != null) {
                    if ("1".equals(current.getLatchStatus())) {
                        if (!taxList.contains(recordInvoice.getGfTaxNo())) {
                            taxList.add(recordInvoice.getGfTaxNo());
                            sb1.append(recordInvoice.getGfTaxNo()).append(" \n ");
                        }
                        flag = true;
                        continue;
                    }
                } else {
                    continue;
                }

                Map<String, Object> map = new HashMap<>();
                map.put("uuid", s);
                map.put("skssq", current.getCurrentTaxPeriod());
                map.put("userName", userName);
                map.put("bdkMessage", bdkMessage);
                if(StringUtils.isNotBlank(bdkYy)){
                    map.put("bdkYy", bdkYy);
                }
                DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_WRITE);
                super.baseMapper.updateByUuid(map);
                count++;
                taxAmount = taxAmount.add(recordInvoice.getTaxAmount());
                invoiceAmount = invoiceAmount.add(recordInvoice.getInvoiceAmount());
                InvoiceLog invoiceLog = new InvoiceLog();
                invoiceLog.setInvoiceCode(recordInvoice.getInvoiceCode());
                invoiceLog.setInvoiceNo(recordInvoice.getInvoiceNo());
                invoiceLog.setType("5");
                invoiceLog.setCreateDate(new Date());
                invoiceLog.setInputName((String)pramsMap.get("name"));
                invoiceLog.setInputStatus("7");
                logList.add(invoiceLog);
            } catch (Exception e) {
               log.info("业务处理异常：{}", e);
            }
        }
        if (logList.size() > 0) {
            invoiceLogService.toInvoiceLog(logList);
        }
        String message = "";
        if (flag) {
            message = message + sb1.toString() + "如需勾选不认证，请到企业税务信息菜单解除锁定";
        }
        json.put("message", message);
        json.put("total", count);
        json.put("invoiceAmount", invoiceAmount);
        json.put("taxAmount", taxAmount);
        json.put("dkTaxAmount", taxAmount);

        if (logList.size() > 0) {
            invoiceLogService.toInvoiceLog(logList);
        }
        return super.responseResult(json);
    }

    @Override
    public String updateByQxFpbrz(Map<String, Object> pramsMap) {
        JSONObject json = new JSONObject();
        String uuids = (String)pramsMap.get("uuids");
        String[] uuidArray = uuids.split(",");
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_WRITE);
        int count = 0;
        BigDecimal taxAmount = new BigDecimal(0);
        BigDecimal invoiceAmount = new BigDecimal(0);
        List<InvoiceLog> logList = new ArrayList<>();
        List<String> taxList = new ArrayList<>();
        StringBuilder sb1 = new StringBuilder();
        sb1.append("以下税号已被锁定不可撤销不认证： \n ");
        boolean flag = false;
        for (String s : uuidArray) {
            try {
                DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
                QueryWrapper<BaseTDxRecordInvoice> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("uuid", s);
                BaseTDxRecordInvoice recordInvoice = super.baseMapper.selectOne(queryWrapper);
                QueryWrapper<BaseTDxTaxCurrent> currentWrapper = new QueryWrapper<>();
                currentWrapper.eq("taxno", recordInvoice.getGfTaxNo());
                BaseTDxTaxCurrent current = baseTDxTaxCurrentDao.selectOne(currentWrapper);
                if (current != null) {
                    if ("1".equals(current.getLatchStatus())) {
                        if (!taxList.contains(recordInvoice.getGfTaxNo())) {
                            taxList.add(recordInvoice.getGfTaxNo());
                            sb1.append(recordInvoice.getGfTaxNo()).append(" \n ");
                        }
                        flag = true;
                        continue;
                    }
                } else {
                    continue;
                }
                Map<String, Object> map = new HashMap<>();
                map.put("uuid", s);
                map.put("skssq", current.getCurrentTaxPeriod());
                DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_WRITE);
                super.baseMapper.updateByUuidQxrz(map);
                count++;
                taxAmount = taxAmount.add(recordInvoice.getTaxAmount());
                invoiceAmount = invoiceAmount.add(recordInvoice.getInvoiceAmount());
                InvoiceLog invoiceLog = new InvoiceLog();
                invoiceLog.setInvoiceCode(recordInvoice.getInvoiceCode());
                invoiceLog.setInvoiceNo(recordInvoice.getInvoiceNo());
                invoiceLog.setType("5");
                invoiceLog.setCreateDate(new Date());
                invoiceLog.setInputName((String)pramsMap.get("name"));
                invoiceLog.setInputStatus("10");
                logList.add(invoiceLog);
            } catch (Exception e) {
               log.info("业务处理异常：{}", e);
            }
        }
        String message = "";
        if (flag) {
            message = message + sb1.toString() + "如需撤销不认证，请到企业税务信息菜单解除锁定";
        }
        json.put("message", message);
        json.put("total", count);
        json.put("invoiceAmount", invoiceAmount);
        json.put("taxAmount", taxAmount);
        json.put("dkTaxAmount", taxAmount);
        if (logList.size() > 0) {
            invoiceLogService.toInvoiceLog(logList);
        }
        return super.responseResult(json);
    }

}
