package com.dxhy.base.service.invoicecheck;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.dxhy.base.dao.SysDeptAuthDao;
import com.dxhy.base.entity.SysDeptEntity;
import com.dxhy.common.constant.DictConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.BaseBeforegxRespVO;
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.TabulateRedisService;
import com.dxhy.common.service.impl.MpBaseServiceImpl;
import com.dxhy.common.util.AmountFormatUtil;
import com.dxhy.common.util.MathUtil;
import com.dxhy.common.util.StringHelper;
import com.dxhy.common.vo.Business;
import com.dxhy.common.vo.Tax;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * 手动勾选查询service实现类
 *
 * @author kangzq
 * @version 1.0
 * @date 2019年5月11日
 */
@SuppressWarnings({"AlibabaLowerCamelCaseVariableNaming", "AlibabaUndefineMagicConstant", "AlibabaMethodTooLong"})
@Slf4j
@Service("baseInvoiceManualCheckService")
public class BaseInvoiceManualCheckServiceImpl extends MpBaseServiceImpl<BaseTDxRecordInvoiceDao, BaseTDxRecordInvoice>
        implements BaseInvoiceManualCheckService {
    @Resource
    private BaseTDxTaxCurrentDao baseTDxTaxCurrentDao;
    @Resource
    private BaseTDxRecordInvoiceDao baseTDxRecordInvoiceDao;
    @Resource
    private SysDeptAuthDao sysDeptAuthDao;
    @Resource
    private DictdetaServcice dictdetaServcice;
    @Resource
    private TabulateRedisService tabulateRedisService;

    @Override
    public String selectByManualCheck(Map<String, Object> pramsMap, int curr, int size) {
        long enter = System.currentTimeMillis();
        log.info("入参是:{}", 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);

            List<BaseSggxCxRespVO> voList = new ArrayList<>();
            List<String> gfshList = (List<String>) pramsMap.get("gfsh");
            log.info("购方税号{}", gfshList);
            String qsflag = (String) pramsMap.get("qsflag");
            List<String> gfshList1 = new ArrayList<>();
            if (gfshList.size() > 0) {
                List<BaseTDxDkCount> curList = super.baseMapper.selectDksh(pramsMap);
                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)) {
                        gfshList1.add(cur.getTaxno());
                    }
                }
            } else {
                json.put("hjsl", "0");
                json.put("hjje", "0");
                json.put("hjse", "0");
                json.put("total", 0);
                json.put("datalist", new ArrayList<>());
                return super.responseResult(json);
            }

            // 合计信息,仅第一页时需要统计，减少数据库压力
            if (curr == 1) {
                String hjsl = "0";
                String hjje = "0";
                String hjse = "0";
                long start = System.currentTimeMillis();
                List<BaseTDxRecordInvoice> hjList = super.baseMapper.selectHj(pramsMap);
                log.info("手工认证 查询统计信息耗时:{}", System.currentTimeMillis() - start);
                BaseTDxRecordInvoice hjxx = hjList.get(0);
                hjsl = hjxx.getSfygx();
                if (!"0".equals(hjsl)) {
                    hjje = AmountFormatUtil.fmtMicrometer(MathUtil.round(hjxx.getInvoiceAmount().toPlainString()));
                    hjse = AmountFormatUtil.fmtMicrometer(MathUtil.round(hjxx.getTaxAmount().toPlainString()));
                }
                json.put("hjsl", AmountFormatUtil.fmtMicrometer(hjsl));
                json.put("hjje", hjje);
                json.put("hjse", hjse);
                if ("0".equals(hjsl)) {
                    json.put("total", 0);
                    json.put("datalist", voList);
                    return super.responseResult(json);
                }
            }

            log.info("查询合计耗时:{}", System.currentTimeMillis() - enter);
            PageHelper.startPage(curr, size);
//            pramsMap.put("curr",(curr -1) * size);
//            pramsMap.put("size", size);
            long start1 = System.currentTimeMillis();
            List<BaseTDxRecordInvoice> pageList = super.baseMapper.selectSggxcx(pramsMap);
            log.info("手工认证 查询列表信息耗时:{}", System.currentTimeMillis() - start1);
            PageInfo<BaseTDxRecordInvoice> pageInfo = new PageInfo<>(pageList);

            log.info("返回的列表为:{}", pageList);
            log.info("查询耗时:{}", System.currentTimeMillis() - enter);
            // 转化为页面展示对象
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if (pageList.size() > 0) {
                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());
                        }
                    }
                }
                List<Business> businessList = (List<Business>) pramsMap.get("business");
                int start = new Long(pageInfo.getStartRow()).intValue();
                for (int i = 0; i < pageList.size(); i++) {
                    BaseSggxCxRespVO vo = new BaseSggxCxRespVO();
                    if (taxnoList.contains(pageList.get(i).getGfTaxNo())) {
                        vo.setUpgradeStatus("1");
                        if (pageList.get(i).getDkTaxAmount() != null) {
                            vo.setDkse(AmountFormatUtil.fmtMicrometer(MathUtil.round(pageList.get(i).getDkTaxAmount().toString())));
                        } else {
                            vo.setDkse(AmountFormatUtil.fmtMicrometer(MathUtil.round(pageList.get(i).getTaxAmount().toString())));
                        }
                    } else {
                        vo.setUpgradeStatus("0");
                        if (pageList.get(i).getDkTaxAmount() != null) {
                            vo.setDkse(AmountFormatUtil
                                    .fmtMicrometer(MathUtil.round(pageList.get(i).getDkTaxAmount().toString())));
                        } else {
                            vo.setDkse(AmountFormatUtil
                                    .fmtMicrometer(MathUtil.round(pageList.get(i).getTaxAmount().toString())));
                        }
                    }

                    String businessCode = pageList.get(i).getDeptId();
                    String businessName = this.getBusinessName(businessCode, businessList);

                    log.info("businessName={}", businessName);
                    vo.setVoucherNumber(pageList.get(i).getVoucherNumber());
                    vo.setSnVoucherNumber(pageList.get(i).getSnVoucherNumber());
                    vo.setImageNumber(pageList.get(i).getImageNumber());
                    vo.setPostingTime(pageList.get(i).getPostingTime());
                    vo.setAccountPeriod(pageList.get(i).getAccountPeriod());
                    vo.setId(String.valueOf(pageList.get(i).getId()));
                    vo.setXh(String.valueOf(start + i));
                    vo.setInvoiceAmount(
                            AmountFormatUtil.fmtMicrometer(MathUtil.round(pageList.get(i).getInvoiceAmount().toString())));
                    vo.setInvoiceCode(pageList.get(i).getInvoiceCode());
                    vo.setInvoiceDate(sdf.format(pageList.get(i).getInvoiceDate()));
                    vo.setInvoiceNo(pageList.get(i).getInvoiceNo());
                    vo.setSettlementNo(pageList.get(i).getSettlementNo());
                    vo.setTaxAmount(
                            AmountFormatUtil.fmtMicrometer(MathUtil.round(pageList.get(i).getTaxAmount().toString())));
                    vo.setInvoiceStatus(dictdetaServcice.queryDictName(DictConstant.INVOICE_STATUS, pageList.get(i).getInvoiceStatus()));
                    vo.setInvoiceType(pageList.get(i).getInvoiceType());
                    //报账单号和入账状态
//                    vo.setInAccountStatus(pageList.get(i).getInvoiceStatus());
                    vo.setBzdh(pageList.get(i).getBzdh());
                    vo.setCompCode(pageList.get(i).getCompCode());
                    // 签收方式为已经签收时展示签收信息
                    if ("1".equals(pageList.get(i).getQsStatus())) {
                        if (pageList.get(i).getQsDate() != null) {
                            vo.setQsrq(sdf.format(pageList.get(i).getQsDate()));
                        }
                        if (pageList.get(i).getQsType() != null) {
                            vo.setQsfs(dictdetaServcice.queryDictName(DictConstant.QS_TYPE, pageList.get(i).getQsType()));
                        }
                        vo.setQsr(pageList.get(i).getQsName());
                    }
                    if (pageList.get(i).getQsStatus() != null) {
                        vo.setQszt(dictdetaServcice.queryDictName(DictConstant.QS_STATUS, pageList.get(i).getQsStatus()));
                    }
                    log.info("inaccountStatus==>{}", pageList.get(i).getInAccountStatus());
                    if ("1".equals(pageList.get(i).getInAccountStatus())) {
                        vo.setInAccountStatus("已入账");
                    } else {
                        vo.setInAccountStatus("未入账");
                    }
                    String suspendStatus = pageList.get(i).getSuspendStatus();
                    if ("1".equals(suspendStatus)) {
                        vo.setSuspendStatus("是");
                    } else {
                        vo.setSuspendStatus("否");
                    }
                    vo.setSuspendDate(pageList.get(i).getSuspendDate());
                    vo.setBzr(pageList.get(i).getBzr());
                    vo.setPaymentStatus(dictdetaServcice.queryDictName(DictConstant.FK_STATUS, pageList.get(i).getPaymentStatus()));
                    vo.setPaymentDate(pageList.get(i).getPaymentDate());
                    vo.setGfmc(pageList.get(i).getGfName());
                    vo.setXfmc(pageList.get(i).getXfName());
                    vo.setBusinessName(businessName);
                    vo.setEleInvoiceNo(pageList.get(i).getEleInvoiceNo());
                    vo.setTaxRate(pageList.get(i).getTaxRate());
//                    String dkzt= dictdetaServcice.queryDictName(DictConstant.INACCOUNT_STATUS,pageList.get(i).getInAccountStatus());
//                    pageList.get(i).setInAccountStatus(dkzt);
//                    vo.setInAccountStatus(dkzt);
                    vo.setSelect(false);
                    if ("1".equals(pageList.get(i).getAuthStatus())) {
                        vo.setSelect(true);
                    }

                    log.info("手工勾选查询返回对象VO {}", vo);

                    String invoiceStatus = "07";
                    if (pageList.get(i).getInvoiceStatus() != null && !invoiceStatus.contains(pageList.get(i).getInvoiceStatus())
                            || pageList.get(i).getInvoiceAmount() != null && pageList.get(i).getInvoiceAmount().compareTo(new BigDecimal(0)) < 0
                            || pageList.get(i).getTaxAmount() != null && pageList.get(i).getTaxAmount().compareTo(new BigDecimal(0)) < 0) {
                        vo.setSelect(false);
                        vo.setUpgradeStatus("0");
                    }

                    String sign = (String) pramsMap.get("sign");
                    if (!"88".equals(sign)) {
                        if (!gfshList1.contains(pageList.get(i).getGfTaxNo())) {
                            vo.setSelect(false);
                            vo.setBkgxts("该发票税号已申请抵扣统计");
                            voList.add(vo);
                            continue;
                        }
                    }

                    if ("1".equals(qsflag) && !"1".equals(pageList.get(i).getQsStatus())) {
                        vo.setSelect(false);
                        vo.setBkgxts("该发票未签收");
                        voList.add(vo);
                        continue;
                    }

                    voList.add(vo);
                }
            }
            json.put("total", pageInfo.getTotal());
            json.put("datalist", voList);
        } catch (Exception e) {
            // 统一设置操作异常标识
            log.info("错误信息为:{}", e.getMessage());
            json = super.errorResult(e);
        }

        return super.responseResult(json);
    }

    /**
     * 根据businessCode获取对应名称用于页面显示
     *
     * @param businessCode 业务单元
     * @param businessList 业务单元list
     * @return 返回
     */
    private String getBusinessName(String businessCode, List<Business> businessList) {
        String businessName = "";
        if (!StringHelper.isBlank(businessCode) && businessList != null && businessList.size() > 0) {
            for (Business business : businessList) {
                if (!StringHelper.isBlank(business.getBusinessCode())
                        && business.getBusinessCode().equals(businessCode)) {
                    businessName = StringHelper.trim(business.getBusinessName(), "");
                    break;
                }
            }
        }
        return businessName;
    }

    @Override
    public List<BaseBeforegxRespVO> beforegx(String[] ids) throws ParseException {
        List<BaseBeforegxRespVO> voList = new ArrayList<>();
        for (String id : ids) {
            // 获取税号和税款所属期
            QueryWrapper<BaseTDxRecordInvoice> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", id);
            BaseTDxRecordInvoice recordInvoice = baseTDxRecordInvoiceDao.selectOne(queryWrapper);
            QueryWrapper<BaseTDxTaxCurrent> invoiceWrapper = new QueryWrapper<>();
            invoiceWrapper.eq("taxno", recordInvoice.getGfTaxNo());
            BaseTDxTaxCurrent current = baseTDxTaxCurrentDao.selectOne(invoiceWrapper);

            String gfsh = recordInvoice.getGfTaxNo();
            String skssq = current.getCurrentTaxPeriod();

            // 获取税款所属期次月第一天：
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String skssq1 = skssq.substring(0, 4) + "-" + skssq.substring(4, 6) + "-" + "01";
            Date date = new SimpleDateFormat("yyyy-MM-dd").parse(skssq1);
            Calendar cd = Calendar.getInstance();
            cd.setTime(date);
            cd.add(Calendar.MONTH, 1);
            String cydyt = sdf.format(cd.getTime());

            BaseBeforegxRespVO vo = new BaseBeforegxRespVO();
            vo.setCydyt(cydyt);
            vo.setGfsh(gfsh);
            vo.setSkssq(skssq);
            voList.add(vo);
        }
        return voList;
    }

    @Override
    public JSONObject beforetj(Map<String, Object> pramsMap) {
        String[] gfshs = pramsMap.get("gfshs").toString().split(",");
        String[] skssqs = pramsMap.get("skssqs").toString().split(",");
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        JSONObject json = new JSONObject();

        boolean flag = true;
        StringBuffer tsxx = new StringBuffer();
        tsxx.append("以下税号不能申请统计,请先处理完认证发票再进行申请抵扣统计: \n ");
        for (int i = 0; i < gfshs.length; i++) {
            Map<String, Object> pramMap = new HashMap<>(16);
            pramMap.put("gfsh", gfshs[i]);
            pramMap.put("skssq", skssqs[i]);
            List<BaseTDxRecordInvoice> pageList = super.baseMapper.selectBeforeTj(pramMap);
            List<BaseTDxRecordInvoice> pageList2 = super.baseMapper.selectExportBeforeTj(pramMap);
            List<BaseTDxRecordInvoice> pageList1 = super.baseMapper.selectCustomsBeforeTj(pramMap);
            List<BaseTDxRecordInvoice> pageList3 = super.baseMapper.selectExportCustomsBeforeTj(pramMap);

            // 逾期申请已取消此功能
            int hgsl = pageList1.get(0).getId().intValue();
            int exporthgsl = pageList3.get(0).getId().intValue();
            int sl = pageList.get(0).getId().intValue();
            int exportsl = pageList2.get(0).getId().intValue();
            if (sl > 0) {
                tsxx.append(gfshs[i]).append(" \n ");
                flag = false;
                continue;
            }
            if (exportsl > 0) {
                tsxx.append(gfshs[i]).append(" \n ");
                flag = false;
                continue;
            }
            if (hgsl > 0) {
                tsxx.append(gfshs[i]).append(" \n ");
                flag = false;
                continue;
            }
            if (exporthgsl > 0) {
                tsxx.append(gfshs[i]).append(" \n ");
                flag = false;
            }

        }
        json.put("tsxx", tsxx);
        String rejson = super.responseResult(json);
        JSONObject json1 = new JSONObject();
        json1.put("rejson", rejson);
        json1.put("flag", flag);
        return json1;
    }

    @Override
    public JSONObject beforeqr(Map<String, Object> pramsMap) {
        JSONObject json = new JSONObject();
        String[] gfshs = pramsMap.get("gfshs").toString().split(",");
        pramsMap.put("gfsh", gfshs);
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        List<BaseTDxDkCount> curList = baseTDxRecordInvoiceDao.selectDksh(pramsMap);
        StringBuilder tsxx = new StringBuilder();
        StringBuilder tsxx1 = new StringBuilder();
        tsxx.append("以下税号请次月1号之后再进行确认统计： \n ");
        tsxx1.append("以下税号不能确认统计,请撤销统计后重新申请统计再执行确认统计： \n ");
        boolean tsflag = false;
        boolean ts1flag = false;
        List<String> taxList = new ArrayList<>();
        List<String> taxList1 = new ArrayList<>();
        boolean flag = false;
        for (BaseTDxDkCount cur : curList) {
            String tjDate = cur.getTjDate();
            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 (localDate2.isBefore(localDate1)) {
                if (!taxList.contains(cur.getTaxno())) {
                    tsxx.append(cur.getTaxno()).append(" \n ");
                    taxList.add(cur.getTaxno());
                }
                flag = true;
                tsflag = true;
            } else {
                LocalDate tjsj = LocalDate.of(Integer.parseInt(tjDate.substring(0, 4)),
                        Integer.parseInt(tjDate.substring(4, 6)), Integer.parseInt(tjDate.substring(6, 8)));
                if (tjsj.isBefore(localDate1)) {
                    if (!taxList1.contains(cur.getTaxno())) {
                        tsxx1.append(cur.getTaxno()).append(" \n ");
                        taxList1.add(cur.getTaxno());
                    }
                    flag = true;
                    ts1flag = true;
                }
            }
        }
        String message = "";
        if (tsflag) {
            message = tsxx.toString();
        }
        if (ts1flag) {
            message = message + tsxx1.toString();
        }
        json.put("tsxx", message);
        String rejson = super.responseResult(json);
        JSONObject json1 = new JSONObject();
        json1.put("rejson", rejson);
        json1.put("flag", flag);
        return json1;
    }

    @Override
    public String inTellingCheck(Map<String, Object> pramsMap) {
        log.info("入参是:{}", pramsMap);
        JSONObject json = new JSONObject();
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        try {
            String company = (String) pramsMap.get("company");
            String menuId = (String) pramsMap.get("menuId");
            if (StringUtils.isNotBlank(menuId)) {
                json = tabulateRedisService.getTabulateMenu(company, menuId);
            }

            List<String> gfshList = (List<String>) pramsMap.get("gfsh");
            String sign = (String) pramsMap.get("sign");

            //如果有自己的税号则选择出在未申请抵扣的税号
            if (!"88".equals(sign)) {
                List<String> gfshList1 = new ArrayList<>();
                if (gfshList.size() > 0) {
                    List<BaseTDxDkCount> curList = super.baseMapper.selectDksh(pramsMap);
                    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)) {
                            gfshList1.add(cur.getTaxno());
                        }
                    }
                    if (ObjectUtils.isEmpty(gfshList1) || gfshList1.size() == 0) {
                        json.put("code", "501");
                        json.put("message", "税号已经申请抵扣");
                        return super.responseResult(json);
                    } else {
                        pramsMap.put("gfsh", gfshList1);
                    }
                } else {
                    json.put("code", "501");
                    json.put("message", "账号下无可用税号");
                    return super.responseResult(json);
                }
            }


            String hjsl = "0";
            String hjje = "0";
            String hjse = "0";
            List<BaseTDxRecordInvoice> hjList = super.baseMapper.selectChooseHj(pramsMap);
            BaseTDxRecordInvoice hjxx = hjList.get(0);
            hjsl = hjxx.getSfygx();
            if (!"0".equals(hjsl)) {
                hjje = AmountFormatUtil.fmtMicrometer(MathUtil.round(hjxx.getInvoiceAmount().toPlainString()));
                hjse = AmountFormatUtil.fmtMicrometer(MathUtil.round(hjxx.getTaxAmount().toPlainString()));
            }
            json.put("hjsl", AmountFormatUtil.fmtMicrometer(hjsl));
            json.put("hjje", hjje);
            json.put("hjse", hjse);
            if ("0".equals(hjsl)) {
                json.put("message", "无可操作的数据");
                json.put("code", "501");
                return super.responseResult(json);
            }

            String isChooseAll = (String) pramsMap.get("isChooseAll");

            if ("N".equals(isChooseAll)) {
                int total = Integer.parseInt(hjsl);

                int curr = (int) pramsMap.get("curr");
                int size = (int) pramsMap.get("size");
                int totalPage = total % size == 0 ? total / size : total / size + 1;

                if (curr < 1) {
                    curr = 1;
                }
                if (curr > totalPage) {
                    curr = totalPage;
                }
                curr = (curr - 1) * size;
                pramsMap.put("curr", curr);
            }

            List<BaseTDxRecordInvoice> pageList = super.baseMapper.selectInTellingCheck(pramsMap);

            if (pageList == null || pageList.size() == 0) {
                json.put("message", "无可操作的数据");
                json.put("code", "501");
                return super.responseResult(json);
            }
            PageInfo<BaseTDxRecordInvoice> pageInfo = new PageInfo<>(pageList);

            log.info("返回的列表为:{}", pageList);

            // 转化为页面展示对象
            List<BaseSggxCxRespVO> returnList = new ArrayList<>();
            //记录数量
            int count = 1;
            //税额上限
            List<Business> businessList = (List<Business>) pramsMap.get("business");

            if (pageList.size() > 0) {
                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());
                        }
                    }
                }
                for (int i = 0; i < pageList.size(); i++) {
                    BaseSggxCxRespVO vo = getBaseSggxCxRespVO(pageList.get(i), count, taxnoList, businessList);
                    count++;
                    log.info("returnList添加vo");
                    returnList.add(vo);
                }

            }

            json.put("total", hjsl);
            json.put("datalist", returnList);

        } catch (Exception e) {
            // 统一设置操作异常标识
            log.info("错误信息为:{}", e.getMessage());
            json = super.errorResult(e);
        }

        return super.responseResult(json);
    }

    @Override
    public List<String> getGfshList(List<String> gfshList, List<String> companyCodes) {
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        List<SysDeptEntity> taxnoList = sysDeptAuthDao.queryTaxnoList();
        List<SysDeptEntity> parentIdList = sysDeptAuthDao.queryParentIdList();

        Map<String, String> taxnoMap = taxnoList.stream().collect(Collectors.toMap(SysDeptEntity::getDeptId, SysDeptEntity::getTaxno));
        Map<String, String> parentIdMap = parentIdList.stream().collect(Collectors.toMap(SysDeptEntity::getDeptId, e -> e.getParentId() == null ? "" : e.getParentId()));

        log.info("taxnoMap={},parentIdMap={}", taxnoMap, parentIdMap);

        String gfsh = "";
        for (String companyCode : companyCodes) {
            QueryWrapper<SysDeptEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("org_code", companyCode);
            List<SysDeptEntity> sysDeptEntityList = sysDeptAuthDao.selectList(wrapper);
            SysDeptEntity sysDeptEntity = sysDeptEntityList.get(0);
            if (sysDeptEntity != null) {
                String dId = sysDeptEntity.getDeptId();
                log.info("获取deptId为:{}", dId);
                if (StringUtils.isNotEmpty(dId)) {
                    gfsh = getGfsh(dId, taxnoMap, parentIdMap);
                    if (StringUtils.isNotEmpty(gfsh))
                        gfshList.add(gfsh);
                    log.info("获取的税号为：{}", gfsh);
                }
            }
        }
        log.info("购方税号list为：{}", gfshList);


        return gfshList.stream().distinct().collect(Collectors.toList());
    }

    private String getGfsh(String deptId, Map<String, String> taxnoMap, Map<String, String> parentIdMap) {
        String taxno = "";
        if (StringUtils.isNotEmpty(deptId)) {
            log.info("deptId={}", deptId);
            taxno = taxnoMap.get(deptId);

            if (StringUtils.isEmpty(taxno)) {
                deptId = parentIdMap.get(deptId);
                log.info("获取map中的deptId:{}", deptId);
                getGfsh(deptId, taxnoMap, parentIdMap);
            }
        }
        return taxno;
    }

    public BaseSggxCxRespVO getBaseSggxCxRespVO(BaseTDxRecordInvoice baseTDxRecordInvoice, int count, List<String> taxnoList, List<Business> businessList) {
        BaseSggxCxRespVO vo = new BaseSggxCxRespVO();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (taxnoList.contains(baseTDxRecordInvoice.getGfTaxNo())) {
            vo.setUpgradeStatus("1");
            if (baseTDxRecordInvoice.getDkTaxAmount() != null) {
                vo.setDkse(AmountFormatUtil.fmtMicrometer(MathUtil.round(baseTDxRecordInvoice.getDkTaxAmount().toString())));
            } else {
                vo.setDkse(AmountFormatUtil.fmtMicrometer(MathUtil.round(baseTDxRecordInvoice.getTaxAmount().toString())));
            }
        } else {
            vo.setUpgradeStatus("0");
            if (baseTDxRecordInvoice.getDkTaxAmount() != null) {
                vo.setDkse(AmountFormatUtil
                        .fmtMicrometer(MathUtil.round(baseTDxRecordInvoice.getDkTaxAmount().toString())));
            } else {
                vo.setDkse(AmountFormatUtil
                        .fmtMicrometer(MathUtil.round(baseTDxRecordInvoice.getTaxAmount().toString())));
            }
        }

        String businessCode = baseTDxRecordInvoice.getDeptId();
        String businessName = this.getBusinessName(businessCode, businessList);

//                        log.info("businessName={}",businessName);
        vo.setUuid(baseTDxRecordInvoice.getUuid());
        vo.setVoucherNumber(baseTDxRecordInvoice.getVoucherNumber());
        vo.setSnVoucherNumber(baseTDxRecordInvoice.getSnVoucherNumber());
        vo.setImageNumber(baseTDxRecordInvoice.getImageNumber());
        vo.setPostingTime(baseTDxRecordInvoice.getPostingTime());
        vo.setAccountPeriod(baseTDxRecordInvoice.getAccountPeriod());
        vo.setId(String.valueOf(baseTDxRecordInvoice.getId()));
        vo.setXh(String.valueOf(count));
        vo.setInvoiceAmount(
                AmountFormatUtil.fmtMicrometer(MathUtil.round(baseTDxRecordInvoice.getInvoiceAmount().toString())));
        vo.setInvoiceCode(baseTDxRecordInvoice.getInvoiceCode());
        vo.setInvoiceDate(sdf.format(baseTDxRecordInvoice.getInvoiceDate()));
        vo.setInvoiceNo(baseTDxRecordInvoice.getInvoiceNo());
        vo.setSettlementNo(baseTDxRecordInvoice.getSettlementNo());
        vo.setTaxAmount(
                AmountFormatUtil.fmtMicrometer(MathUtil.round(baseTDxRecordInvoice.getTaxAmount().toString())));
        vo.setInvoiceStatus(dictdetaServcice.queryDictName(DictConstant.INVOICE_STATUS, baseTDxRecordInvoice.getInvoiceStatus()));
        vo.setInvoiceType(baseTDxRecordInvoice.getInvoiceType());
        //报账单号和入账状态
//                    vo.setInAccountStatus(pageList.get(i).getInvoiceStatus());
        vo.setBzdh(baseTDxRecordInvoice.getBzdh());
        vo.setCompCode(baseTDxRecordInvoice.getCompCode());
        // 签收方式为已经签收时展示签收信息
        if ("1".equals(baseTDxRecordInvoice.getQsStatus())) {
            if (baseTDxRecordInvoice != null) {
                vo.setQsrq(sdf.format(baseTDxRecordInvoice.getQsDate()));
            }
            if (baseTDxRecordInvoice.getQsType() != null) {
                vo.setQsfs(dictdetaServcice.queryDictName(DictConstant.QS_TYPE, baseTDxRecordInvoice.getQsType()));
            }
            vo.setQsr(baseTDxRecordInvoice.getQsName());
        }
        if (baseTDxRecordInvoice.getQsStatus() != null) {
            vo.setQszt(dictdetaServcice.queryDictName(DictConstant.QS_STATUS, baseTDxRecordInvoice.getQsStatus()));
        }
        if ("1".equals(baseTDxRecordInvoice.getInAccountStatus())) {
            vo.setInAccountStatus("已入账");
        } else {
            vo.setInAccountStatus("未入账");
        }
        if ("1".equals(vo.getSuspendStatus())) {
            vo.setSuspendStatus("是");
        } else {
            vo.setSuspendStatus("否");
            vo.setSuspendDate("");
        }
        vo.setPaymentStatus(dictdetaServcice.queryDictName(DictConstant.FK_STATUS, baseTDxRecordInvoice.getPaymentStatus()));
        vo.setPaymentDate(baseTDxRecordInvoice.getPaymentDate());
        vo.setGfmc(baseTDxRecordInvoice.getGfName());
        vo.setXfmc(baseTDxRecordInvoice.getXfName());
        vo.setBusinessName(businessName);
        vo.setEleInvoiceNo(baseTDxRecordInvoice.getEleInvoiceNo());
        vo.setSelect(true);
        return vo;
    }

}
