package com.dxhy.base.service.fpxxrz;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dxhy.api.model.config.Tax;
import com.dxhy.api.model.ncp.ncpJjkcInvoice.TdxInvoiceNcpJjkcEntity;
import com.dxhy.base.dao.BaseFpxxZhDao;
import com.dxhy.base.dao.BaseNcpJjkcRecordInvoiceDao;
import com.dxhy.base.dao.BaseTDxRecordInvoiceDao;
import com.dxhy.base.dao.BaseTDxTaxCurrentDao;
import com.dxhy.base.entity.BaseTDxDkCount;
import com.dxhy.base.entity.BaseTDxTaxCurrent;
import com.dxhy.base.model.BaseFpRzRespVO;
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.MathUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 *
 *
 * 发票认证综合查询
 *
 * @author kangzq
 * @date 2019年4月24日
 *
 */
@SuppressWarnings({"AlibabaLowerCamelCaseVariableNaming", "AlibabaUndefineMagicConstant", "AlibabaMethodTooLong"})
@Service("baseRzFpxxService")
public class BaseRzFpxxServiceImpl extends MpBaseServiceImpl<BaseFpxxZhDao, BaseFpRzRespVO>
    implements BaseRzFpxxService {
    @Resource
    private BaseTDxRecordInvoiceDao baseTDxRecordInvoiceDao;
    @Resource
    private BaseTDxTaxCurrentDao baseTDxTaxCurrentDao;
    @Resource
    private DictdetaServcice dictdetaServcice;
    @Resource
    private TabulateRedisService tabulateRedisService;
    @Resource
    private BaseNcpJjkcRecordInvoiceDao baseNcpJjkcRecordInvoiceDao;

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

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

        try {
            String company = (String)pramsMap.get("company");
            String menuId = (String)pramsMap.get("menuId");
            json = tabulateRedisService.getTabulateMenu(company, menuId);
            // 合计信息,仅第一页时需要统计，减少数据库压力
            List<String> gfshList = (List<String>)pramsMap.get("gfsh");

            if (gfshList.size() == 0) {
                // 未从getUserInfo()获取到购方税号信息
                json.put("hjsl", "0");
                json.put("hjje", "0.00");
                json.put("hjse", "0.00");
                json.put("total", "0");
                json.put("datalist", new ArrayList<BaseFpRzRespVO>());
            } else {
                if (curr == 1) {

                    String hjsl = "0";
                    String hjje = "0.00";
                    String hjse = "0.00";
                    List<BaseFpRzRespVO> hjList = super.baseMapper.selectRzfpHj(pramsMap);
                    BaseFpRzRespVO hjxx = hjList.get(0);
                    hjsl = hjxx.getId();
                    if (!"0".equals(hjsl)) {
                        hjje = MathUtil.add(hjje, MathUtil.round(hjxx.getInvoiceAmount()));
                        hjse = MathUtil.add(hjse, MathUtil.round(hjxx.getTaxAmount()));
                    }
                    json.put("hjsl", AmountFormatUtil.fmtMicrometer(hjsl));
                    json.put("hjje", AmountFormatUtil.fmtMicrometer(hjje));
                    json.put("hjse", AmountFormatUtil.fmtMicrometer(hjse));
                }
                List<String> gfshList1 = new ArrayList<>();
                Map<String, String> skssqMap = new HashMap<>();
                List<BaseTDxDkCount> curList = baseTDxRecordInvoiceDao.selectDksh(pramsMap);
                curList.stream().forEach(cur->{
                    String skssq = cur.getSkssq();
                    skssqMap.put(cur.getTaxno(), skssq);
                    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());
                    }
                });

                PageHelper.startPage(curr, size);
                List<BaseFpRzRespVO> pageList = super.baseMapper.selectByPramsMap(pramsMap);
                PageInfo<BaseFpRzRespVO> pageInfo = new PageInfo<>(pageList);
                // 用于页面返回list对象
                if (pageList.size() > 0) {
                    int start = new Long(pageInfo.getStartRow()).intValue();

//                    QueryWrapper<BaseTDxTaxCurrent> queryWrapper = new QueryWrapper<>();
//                    queryWrapper.in("taxno", gfshList);
//                    List<BaseTDxTaxCurrent> baseTDxTaxCurrents = baseTDxTaxCurrentDao.selectList(queryWrapper);
//                    Map<String, List<BaseTDxTaxCurrent>> groupTaxCurrent = baseTDxTaxCurrents.stream()
//                            .collect(Collectors.groupingBy(BaseTDxTaxCurrent::getTaxno));

                    for (int i = 0; i < pageList.size(); i++) {
                        BaseFpRzRespVO bfrv = pageList.get(i);
                        bfrv.setSelect(false);
//                        String taxno = bfrv.getGfsh();
                        if ("1".equals(bfrv.getRzzt())) {
                            bfrv.setSelect(true);
                        }
//                        String skssq = bfrv.getSkssq();

                        /*BaseTDxTaxCurrent taxCurrent = baseTDxTaxCurrentDao.selectOne(queryWrapper);
                        if (taxCurrent != null) {
                            if (!taxCurrent.getCurrentTaxPeriod().equals(skssq)
                                || !"1".equals(bfrv.getRzzt())) {
                                bfrv.setSelect(false);
                            }
                        }*/
//                        List<BaseTDxTaxCurrent> taxCurrentList = groupTaxCurrent.get(taxno);
//                        if(!CollectionUtils.isEmpty(taxCurrentList)){
//                            BaseTDxTaxCurrent taxCurrent = taxCurrentList.get(0);
//                            if (!taxCurrent.getCurrentTaxPeriod().equals(skssq)
//                                    || !"1".equals(bfrv.getRzzt())) {
//                                bfrv.setSelect(false);
//                            }
//                        }

                        //成品油发票走这个逻辑
                        if ("2".equals(bfrv.getYwlx())) {
                            //当前属期，此发票如果是加计成功，则不让勾选
                            TdxInvoiceNcpJjkcEntity tdxCustomsNcpJjkcEntity = baseNcpJjkcRecordInvoiceDao.selectOne(new LambdaQueryWrapper<TdxInvoiceNcpJjkcEntity>()
                                    .eq(TdxInvoiceNcpJjkcEntity::getJjssq, skssqMap.get(bfrv.getGfsh()))
                                    .eq(TdxInvoiceNcpJjkcEntity::getInvoiceCode, bfrv.getInvoiceCode())
                                    .eq(TdxInvoiceNcpJjkcEntity::getInvoiceNo, bfrv.getInvoiceNo())
                            );
                            if(ObjectUtils.isNotEmpty(tdxCustomsNcpJjkcEntity)){
                                if("4".equals(tdxCustomsNcpJjkcEntity.getClzt())){
                                    bfrv.setSelect(false);
                                }
                            }
                        }

                        bfrv.setXh(String.valueOf(i + start));
                        if(StringUtils.isNotEmpty(bfrv.getTaxAmount())){
                            bfrv.setTaxAmount(
                                    AmountFormatUtil.fmtMicrometer(MathUtil.round(bfrv.getTaxAmount())));
                        }
                        if(StringUtils.isNotEmpty(bfrv.getDkTaxAmount())){
                            bfrv.setDkTaxAmount(
                                    AmountFormatUtil.fmtMicrometer(MathUtil.round(bfrv.getDkTaxAmount())));
                        }
                        if(StringUtils.isNotEmpty(bfrv.getInvoiceAmount())){
                            bfrv.setInvoiceAmount(
                                    AmountFormatUtil.fmtMicrometer(MathUtil.round(bfrv.getInvoiceAmount())));
                        }

                        if (!"0".equals(bfrv.getCxrzStatus())
                            && !"5".equals(bfrv.getCxrzStatus())) {
                            bfrv.setSelect(false);
                        }
                        if (!gfshList1.contains(bfrv.getGfsh())) {
                            bfrv.setSelect(false);
                        }
                        if ("1".equals(bfrv.getOutStatus()) || "2".equals(bfrv.getOutStatus())) {
                            bfrv.setSelect(false);
                        }

                        bfrv.setCxrzStatus(
                            dictdetaServcice.queryDictName(DictConstant.CXRZ_STATUS, bfrv.getCxrzStatus()));
                        bfrv.setInvoiceStatus(dictdetaServcice.queryDictName(DictConstant.INVOICE_STATUS,
                            bfrv.getInvoiceStatus()));
                        bfrv
                            .setQszt(dictdetaServcice.queryDictName(DictConstant.QS_STATUS, bfrv.getQszt()));
                        bfrv.setRzzt(
                            dictdetaServcice.queryDictName(DictConstant.DEDU_STATUS, bfrv.getRzzt()));
                        bfrv.setRzclzt(
                            dictdetaServcice.queryDictName(DictConstant.AUTH_STATUS_ALL, bfrv.getRzclzt()));
                        bfrv.setRzlx(
                            dictdetaServcice.queryDictName(DictConstant.BDK_STATUS, bfrv.getBdkStatus()));
                        bfrv
                            .setQsfs(dictdetaServcice.queryDictName(DictConstant.QS_TYPE, bfrv.getQsfs()));
                        // if (dkztModels != null && dkztModels.size() > 0) {
                        // for (DictdetaModel model : dkztModels) {
                        // if (model.getDictcode().equals(bfrv.getInAccountStatus())) {
                        // bfrv.setInAccountStatus(model.getDictname());
                        // }
                        // }
                        // }
                    }
                }

                // 设置记录总数
                json.put("total", pageInfo.getTotal());

                List<BaseFpRzRespVO> resultList = pageInfo.getList();
                json.put("datalist", resultList);
            }

        } catch (Exception e) {
            // 统一设置操作异常标识
            json = super.errorResult(e);
        }

        return super.responseResult(json);
    }

    public static void main(String[] args) {
        List<String> list = new LinkedList<String>();
        list.add("1");
        boolean empty = CollectionUtils.isEmpty(list);
        System.out.println(empty);
    }

}
