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.Business;
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.BaseBeforegxRespVO;
import com.dxhy.base.model.BaseSggxCxRespVO;
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.TabulateRedisService;
import com.dxhy.common.service.impl.MpBaseServiceImpl;
import com.dxhy.common.util.AmountFormatUtil;
import com.dxhy.common.util.JsonUtils;
import com.dxhy.common.util.MathUtil;
import com.dxhy.common.util.StringHelper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

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

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

    @Override
    public String selectByManualCheck(Map<String, Object> pramsMap, int curr, int size) {
        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");
            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.00");
                json.put("hjse", "0.00");
                json.put("total", 0);
                json.put("datalist", new ArrayList<>());
                return super.responseResult(json);
            }

            // 合计信息,仅第一页时需要统计，减少数据库压力
            if (curr == 1) {
                String hjsl = "0";
                String hjje = "0.00";
                String hjse = "0.00";
                List<BaseTDxRecordInvoice> hjList = super.baseMapper.selectHj(pramsMap);
                BaseTDxRecordInvoice hjxx = hjList.get(0);
                hjsl = hjxx.getSfygx();
                if (!"0".equals(hjsl)) {
                    if(ObjectUtil.isNotEmpty(hjxx.getInvoiceAmount())){
                        hjje = AmountFormatUtil.fmtMicrometer(MathUtil.round(hjxx.getInvoiceAmount().toPlainString()));
                    }
                    if(ObjectUtil.isNotEmpty(hjxx.getTaxAmount())){
                        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);
                }
            }

            PageHelper.startPage(curr, size);
            List<BaseTDxRecordInvoice> pageList = super.baseMapper.selectSggxcx(pramsMap);
            PageInfo<BaseTDxRecordInvoice> pageInfo = new PageInfo<>(pageList);

            // 转化为页面展示对象
            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");

                List<Business> businessList = JsonUtils.getInstance().jsonToList(JsonUtils.getInstance().toJsonString(pramsMap.get("business")), Business.class);
                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 {
                            if(ObjectUtil.isNotEmpty(pageList.get(i).getTaxAmount())){
                                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 {
                            if(ObjectUtil.isNotEmpty(pageList.get(i).getTaxAmount())){
                                vo.setDkse(AmountFormatUtil
                                        .fmtMicrometer(MathUtil.round(pageList.get(i).getTaxAmount().toString())));
                            }

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

                    vo.setVoucherNumber(pageList.get(i).getVoucherNumber());
                    vo.setId(String.valueOf(pageList.get(i).getId()));
                    vo.setXh(String.valueOf(start + i));
                    if(ObjectUtil.isNotEmpty(pageList.get(i).getInvoiceAmount())){
                        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());
                    if(ObjectUtil.isNotEmpty(pageList.get(i).getTaxAmount())){
                        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());
                    // 签收方式为已经签收时展示签收信息
                    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()));
                    }
//                    if ("1".equals(pageList.get(i).getPaymentStatus())) {
//                        vo.setPaymentStatus("已付款");
//                    } else if ("0".equals(pageList.get(i).getPaymentStatus())) {
//                        vo.setPaymentStatus("未付款");
//                    }
                    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());
                    String dkzt= dictdetaServcice.queryDictName(DictConstant.DK_STATUS,pageList.get(i).getInAccountStatus());
                    pageList.get(i).setInAccountStatus(dkzt);
                    vo.setInAccountStatus(dkzt);
                    vo.setSelect(true);
                    LinkedHashSet<String> bkgxtsList = new LinkedHashSet<>();
                    if (!"1".equals(pageList.get(i).getAuthStatus())) {
                        //此字段是用开票日期是否在属期勾选范围内判断的
                        bkgxtsList.add("非已勾选未确认");
                        vo.setSelect(false);
                    }
                    String invoiceStatus="07";
                    if ( !invoiceStatus.contains(pageList.get(i).getInvoiceStatus())) {
                        bkgxtsList.add("发票状态异常");
                        vo.setSelect(false);
                        vo.setUpgradeStatus("0");
                    }
                    if(ObjectUtil.isNotEmpty(pageList.get(i).getInvoiceAmount())&&pageList.get(i).getInvoiceAmount().compareTo(new BigDecimal(0)) < 0){
                        bkgxtsList.add("负数发票");
                        vo.setSelect(false);
                        vo.setUpgradeStatus("0");
                    }
                    if(ObjectUtil.isNotEmpty(pageList.get(i).getTaxAmount())&&pageList.get(i).getTaxAmount().compareTo(new BigDecimal(0)) < 0){
                        bkgxtsList.add("负数发票");
                        vo.setSelect(false);
                        vo.setUpgradeStatus("0");
                    }

                    if (!gfshList1.contains(pageList.get(i).getGfTaxNo())) {
                        vo.setSelect(false);
                        bkgxtsList.add("当前属期已统计");
                    }
                    if ("1".equals(qsflag) && !"1".equals(pageList.get(i).getQsStatus())) {
                        vo.setSelect(false);
                        bkgxtsList.add("该发票未签收");
                    }
                    if(bkgxtsList.size()>0){
                        vo.setBkgxts(String.join("，", bkgxtsList));
                    }

                    voList.add(vo);
                }
            }
            json.put("total", pageInfo.getTotal());
            json.put("datalist", voList);
        } catch (Exception e) {
            // 统一设置操作异常标识
            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;
    }

}
