package com.dxhy.base.service.fpxxrz;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dxhy.base.dao.BaseFpxxZhDao;
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.dxhy.common.vo.Tax;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *
 *
 * 发票认证综合查询
 *
 * @author kangzq
 * @date 2019年4月24日
 *
 */
@SuppressWarnings({"AlibabaLowerCamelCaseVariableNaming", "AlibabaUndefineMagicConstant", "AlibabaMethodTooLong"})
@Slf4j
@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;

    @Override
    public String selectByPramsMap(Map<String, Object> pramsMap, int curr, int size) {
        log.info("认证查询列表-传入的参数为:{}",pramsMap);
        long enter = System.currentTimeMillis();
        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");
//            log.info("购方税号{}",gfshList != null && !gfshList.isEmpty());
            List<Tax> taxList = (List<Tax>)pramsMap.get("taxList");
            List<String> orgList = new ArrayList<>();
            for (Tax t : taxList) {
                String upgradeStatus = t.getUpgradeStatus();
                if ("1".equals(upgradeStatus)) {
                    orgList.add(t.getTaxno());
                }
            }
            log.info("orgList======>{}",orgList);

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

                    String hjsl = "0";
                    String hjje = "0";
                    String hjse = "0";
                    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));
                }

                log.info("认证查询-查询首页合计信息耗时:{}",System.currentTimeMillis()-enter);

                List<String> gfshList1 = new ArrayList<>();
                List<BaseTDxDkCount> curList = baseTDxRecordInvoiceDao.selectDksh(pramsMap);
                log.info("认证查询列表-返回的所属期列表为:{}",curList);
                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());
                    }
                }
                PageHelper.startPage(curr, size);
                List<BaseFpRzRespVO> pageList = super.baseMapper.selectByPramsMap(pramsMap);
                log.info("认证查询-查询列表信息耗时:{}",System.currentTimeMillis()-enter);
                PageInfo<BaseFpRzRespVO> pageInfo = new PageInfo<>(pageList);
                // 用于页面返回list对象
                if (pageList.size() > 0) {
                    int start = new Long(pageInfo.getStartRow()).intValue();

                    for (int i = 0; i < pageList.size(); i++) {
                        pageList.get(i).setSelect(false);
                        String taxno = pageList.get(i).getGfsh();
                        if (orgList.contains(taxno) && "1".equals(pageList.get(i).getRzzt())) {
                            pageList.get(i).setSelect(true);
                            log.info("rzzt和orgList设置成true");
                        }
                        String skssq = pageList.get(i).getSkssq();
                        QueryWrapper<BaseTDxTaxCurrent> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("taxno", pageList.get(i).getGfsh());
                        BaseTDxTaxCurrent taxCurrent = baseTDxTaxCurrentDao.selectOne(queryWrapper);
                        if (taxCurrent != null) {
                            if (!taxCurrent.getCurrentTaxPeriod().equals(skssq)
                                || !"1".equals(pageList.get(i).getRzzt())) {
                                pageList.get(i).setSelect(false);
                                log.info("skssq设置为false");
                            }
                        }

                        pageList.get(i).setId(pageList.get(i).getId());
//                        pageList.get(i).setInAccountStatus(pageList.get(i).getInAccountStatus());
                        pageList.get(i).setBzdh(pageList.get(i).getBzdh());
                        pageList.get(i).setXh(String.valueOf(i + start));
                        pageList.get(i).setTaxAmount(
                            AmountFormatUtil.fmtMicrometer(MathUtil.round(pageList.get(i).getTaxAmount())));
                        pageList.get(i).setDkTaxAmount(
                            AmountFormatUtil.fmtMicrometer(MathUtil.round(pageList.get(i).getDkTaxAmount())));
                        pageList.get(i).setInvoiceAmount(
                            AmountFormatUtil.fmtMicrometer(MathUtil.round(pageList.get(i).getInvoiceAmount())));

                        if (!"0".equals(pageList.get(i).getCxrzStatus())
                            && !"5".equals(pageList.get(i).getCxrzStatus())) {
                            pageList.get(i).setSelect(false);
                            log.info("撤销认证状态设置false");
                        }
                        String sign = (String) pramsMap.get("sign");
                        if (!"88".equals(sign)){
                            if (!gfshList1.contains(pageList.get(i).getGfsh())) {
                                log.info("税号一申请抵扣");
                                pageList.get(i).setSelect(false);
                            }
                        }

                        if ("1".equals(pageList.get(i).getOutStatus()) || "2".equals(pageList.get(i).getOutStatus())) {
                            pageList.get(i).setSelect(false);
                            log.info("转出状态设置false");
                        }

                        // 字典转换
                        pageList.get(i).setPaymentStatus(
                            dictdetaServcice.queryDictName(DictConstant.FK_STATUS, pageList.get(i).getPaymentStatus()));
                        pageList.get(i).setCxrzStatus(
                            dictdetaServcice.queryDictName(DictConstant.CXRZ_STATUS, pageList.get(i).getCxrzStatus()));
                        pageList.get(i).setInvoiceStatus(dictdetaServcice.queryDictName(DictConstant.INVOICE_STATUS,
                            pageList.get(i).getInvoiceStatus()));
                        pageList.get(i)
                            .setQszt(dictdetaServcice.queryDictName(DictConstant.QS_STATUS, pageList.get(i).getQszt()));
                        pageList.get(i).setRzzt(
                            dictdetaServcice.queryDictName(DictConstant.DEDU_STATUS, pageList.get(i).getRzzt()));
                        pageList.get(i).setRzclzt(
                            dictdetaServcice.queryDictName(DictConstant.AUTH_STATUS_ALL, pageList.get(i).getRzclzt()));
                        pageList.get(i).setRzlx(
                            dictdetaServcice.queryDictName(DictConstant.BDK_STATUS, pageList.get(i).getBdkStatus()));
                        pageList.get(i)
                            .setQsfs(dictdetaServcice.queryDictName(DictConstant.QS_TYPE, pageList.get(i).getQsfs()));
                        // if (dkztModels != null && dkztModels.size() > 0) {
                        // for (DictdetaModel model : dkztModels) {
                        // if (model.getDictcode().equals(pageList.get(i).getInAccountStatus())) {
                        // pageList.get(i).setInAccountStatus(model.getDictname());
                        // }
                        // }
                        // }
//                        pageList.get(i).setInAccountStatus(dictdetaServcice.queryDictName(DictConstant.INACCOUNT_STATUS,
//                            pageList.get(i).getInAccountStatus()));
                        if ("1".equals(pageList.get(i).getInAccountStatus())){
                            pageList.get(i).setInAccountStatus("已入账");
                        }else {
                            pageList.get(i).setInAccountStatus("未入账");
                        }
                        pageList.get(i).setRzsj(pageList.get(i).getRzsj());
                        pageList.get(i).setSkssq(pageList.get(i).getSkssq());
                        pageList.get(i).setTaxRate(pageList.get(i).getTaxRate());
                    }
                }

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

                List<BaseFpRzRespVO> resultList = pageInfo.getList();
                log.info("resultList {}",resultList);
                json.put("datalist", resultList);
                log.info("认证查询-合计耗时:{}",System.currentTimeMillis()-enter);
            }

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

        return super.responseResult(json);
    }

}
