package com.dxhy.jxpt.baseService.rzInvoice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.dxhy.api.model.config.sys.SysEnterpriseConfigEntity;
import com.dxhy.api.model.custom.TdxCustomsRecord;
import com.dxhy.api.model.rz.rzCustom.*;
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.impl.MpBaseServiceImpl;
import com.dxhy.common.util.AmountFormatUtil;
import com.dxhy.common.util.MathUtil;
import com.dxhy.jxpt.baseService.config.dao.SysEnterpriseConfigDao;
import com.dxhy.jxpt.baseService.rzInvoice.dao.RzRecordCustomDao;
import com.dxhy.jxpt.baseService.rzInvoice.dao.TdxCustomsRecordDao;
import com.dxhy.jxpt.baseService.rzInvoice.service.RzCustomService;
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 org.springframework.util.CollectionUtils;

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

/**
* @Description 大企业缴款书入账业务
* @Author wangruwei
* @Date 2023/9/21 16:20
**/
@Service("baseServicerzCustomService")
@Slf4j
public class RzCustomServiceImpl extends MpBaseServiceImpl<RzRecordCustomDao, TdxLqRzCustomEntity> implements RzCustomService {

    @Resource
    private DictdetaServcice dictdetaServcice;

    @Resource
    private RzRecordCustomDao rzRecordCustomDao;

    @Resource
    private TdxCustomsRecordDao tdxCustomsRecordDao;

    @Resource
    private SysEnterpriseConfigDao sysEnterpriseConfigDao;


    @Override
    public Object preRzCustomList(Map<String, Object> pramsMap, int curr, int size) {
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);

        JSONObject json = new JSONObject();
        try {

            if (CollectionUtils.isEmpty((List<String>)pramsMap.get("gfsh"))) {
                json.put("total", "0");
                json.put("datalist", new ArrayList<>());
                return super.responseResult(json);
            }

            // 合计信息,仅第一页时需要统计，减少数据库压力
            if (curr == 1) {
                String hjsl = "0";
                String hjse = "0";
                Map<String, Object> hjxx = super.baseMapper.preRzCustomHj(pramsMap);
                if (hjxx != null) {
                    hjsl = (long)hjxx.get("hjsl") + "";
                    if (!"0".equals(hjsl)) {
                        hjsl = AmountFormatUtil.fmtMicrometer(hjsl);
                        hjse = AmountFormatUtil.fmtMicrometer(MathUtil.round(hjxx.get("hjse") + ""));
                    }
                }
                json.put("hjsl", hjsl);
                json.put("hjse", hjse);
            }
            PageHelper.startPage(curr, size);
            List<JkszhcxRespVO> pageList = super.baseMapper.preRzCustomList(pramsMap);
            PageInfo<JkszhcxRespVO> 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).setXh(String.valueOf(i + start));
                    if(StringUtils.isNotEmpty(pageList.get(i).getTaxAmount())){
                        pageList.get(i)
                                .setTaxAmount(AmountFormatUtil.fmtMicrometer(MathUtil.round(pageList.get(i).getTaxAmount())));
                    }
                    if(StringUtils.isNotEmpty(pageList.get(i).getYxTaxAmount())){
                        pageList.get(i).setYxTaxAmount(
                                AmountFormatUtil.fmtMicrometer(MathUtil.round(pageList.get(i).getYxTaxAmount())));
                    }

                    pageList.get(i)
                            .setSelect(true);

                    // 字典值转换
                    String auditStatus = pageList.get(i).getAuditStatus();
                    pageList.get(i)
                            .setAuditStatus(dictdetaServcice.queryDictName(DictConstant.AUDIT_STATUS, auditStatus));
                    String applyCheck = pageList.get(i).getApplyCheck();
                    pageList.get(i).setApplyCheck(dictdetaServcice.queryDictName(DictConstant.APPLY_CHECK, applyCheck));
                    String checkStatus = pageList.get(i).getCheckStatus();
                    pageList.get(i)
                            .setCheckStatus(dictdetaServcice.queryDictName(DictConstant.CHECK_STATUS, checkStatus));
                    if ("0".equals(pageList.get(i).getBdkStatus())) {
                        pageList.get(i).setBdkStatus("");
                    } else {
                        String bdkStatus = pageList.get(i).getBdkStatus();
                        pageList.get(i)
                                .setBdkStatus(dictdetaServcice.queryDictName(DictConstant.BDK_STATUS, bdkStatus));
                    }
                    String glzt = pageList.get(i).getGlzt();
                    pageList.get(i).setGlzt(dictdetaServcice.queryDictName(DictConstant.GLZT, glzt));
                    String qsStatus = pageList.get(i).getQsStatus();
                    pageList.get(i).setQsStatus(dictdetaServcice.queryDictName(DictConstant.QS_STATUS, qsStatus));
                    String authStatus = pageList.get(i).getAuthStatus();
                    pageList.get(i)
                            .setAuthStatus(dictdetaServcice.queryDictName(DictConstant.AUTH_STATUS_ALL, authStatus));
                    String qsType = pageList.get(i).getQsType();
                    pageList.get(i).setQsType(dictdetaServcice.queryDictName(DictConstant.QS_TYPE, qsType));
                    String rzhYesorno = pageList.get(i).getRzhYesorno();
                    pageList.get(i).setRzhYesorno(dictdetaServcice.queryDictName(DictConstant.DEDU_STATUS, rzhYesorno));
                }
            }
            // 设置记录总数
            json.put("total", pageInfo.getTotal());
            List<JkszhcxRespVO> resultList = pageInfo.getList();
            json.put("datalist", CollectionUtils.isEmpty(resultList) ? new ArrayList<>() : resultList);
        } catch (Exception e) {
            // 统一设置操作异常标识
            json = super.errorResult(e);
        }
        return super.responseResult(json);
    }

    @Override
    public Object rzCustomResultList(Map<String, Object> pramsMap, int curr, int size) {
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);

        JSONObject json = new JSONObject();
        try {

            if (CollectionUtils.isEmpty((List<String>)pramsMap.get("gfsh"))) {
                json.put("total", "0");
                json.put("datalist", new ArrayList<>());
                return super.responseResult(json);
            }

            // 合计信息,仅第一页时需要统计，减少数据库压力
            if (curr == 1) {
                String hjsl = "0";
                String hjse = "0";
                Map<String, Object> hjxx = super.baseMapper.rzCustomResultHj(pramsMap);
                if (hjxx != null) {
                    hjsl = (long)hjxx.get("hjsl") + "";
                    if (!"0".equals(hjsl)) {
                        hjsl = AmountFormatUtil.fmtMicrometer(hjsl);
                        hjse = AmountFormatUtil.fmtMicrometer(MathUtil.round(hjxx.get("hjse") + ""));
                    }
                }
                json.put("hjsl", hjsl);
                json.put("hjse", hjse);
            }
            PageHelper.startPage(curr, size);
            List<JkszhcxRespVO> pageList = super.baseMapper.rzCustomResultList(pramsMap);
            PageInfo<JkszhcxRespVO> 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).setXh(String.valueOf(i + start));
                    if(StringUtils.isNotEmpty(pageList.get(i).getTaxAmount())){
                        pageList.get(i)
                                .setTaxAmount(AmountFormatUtil.fmtMicrometer(MathUtil.round(pageList.get(i).getTaxAmount())));
                    }
                    if(StringUtils.isNotEmpty(pageList.get(i).getYxTaxAmount())){
                        pageList.get(i).setYxTaxAmount(
                                AmountFormatUtil.fmtMicrometer(MathUtil.round(pageList.get(i).getYxTaxAmount())));
                    }

                    //可勾选进行撤销的数据  4入账成功  7撤销失败
                    if("4".equals(pageList.get(i).getJksrzAuthStatus())||"7".equals(pageList.get(i).getJksrzAuthStatus())){
                        pageList.get(i).setSelect(true);
                    }else{
                        pageList.get(i).setSelect(false);
                    }


                    // 字典值转换
                    String auditStatus = pageList.get(i).getAuditStatus();
                    pageList.get(i)
                            .setAuditStatus(dictdetaServcice.queryDictName(DictConstant.AUDIT_STATUS, auditStatus));
                    String applyCheck = pageList.get(i).getApplyCheck();
                    pageList.get(i).setApplyCheck(dictdetaServcice.queryDictName(DictConstant.APPLY_CHECK, applyCheck));
                    String checkStatus = pageList.get(i).getCheckStatus();
                    pageList.get(i)
                            .setCheckStatus(dictdetaServcice.queryDictName(DictConstant.CHECK_STATUS, checkStatus));
                    if ("0".equals(pageList.get(i).getBdkStatus())) {
                        pageList.get(i).setBdkStatus("");
                    } else {
                        String bdkStatus = pageList.get(i).getBdkStatus();
                        pageList.get(i)
                                .setBdkStatus(dictdetaServcice.queryDictName(DictConstant.BDK_STATUS, bdkStatus));
                    }
                    String glzt = pageList.get(i).getGlzt();
                    pageList.get(i).setGlzt(dictdetaServcice.queryDictName(DictConstant.GLZT, glzt));
                    String qsStatus = pageList.get(i).getQsStatus();
                    pageList.get(i).setQsStatus(dictdetaServcice.queryDictName(DictConstant.QS_STATUS, qsStatus));
                    String authStatus = pageList.get(i).getAuthStatus();
                    pageList.get(i)
                            .setAuthStatus(dictdetaServcice.queryDictName(DictConstant.AUTH_STATUS_ALL, authStatus));
                    String qsType = pageList.get(i).getQsType();
                    pageList.get(i).setQsType(dictdetaServcice.queryDictName(DictConstant.QS_TYPE, qsType));
                    String rzhYesorno = pageList.get(i).getRzhYesorno();
                    pageList.get(i).setRzhYesorno(dictdetaServcice.queryDictName(DictConstant.DEDU_STATUS, rzhYesorno));

                    String jksrzAuthStatus = pageList.get(i).getJksrzAuthStatus();
                    pageList.get(i)
                            .setJksrzAuthStatus(dictdetaServcice.queryDictName(DictConstant.INACCOUNT_GLZT, jksrzAuthStatus));
                    //入账状态
                    /*String rzzt = pageList.get(i).getRzzt();
                    pageList.get(i)
                            .setRzzt(dictdetaServcice.queryDictName(DictConstant.INACCOUNTSTATUS, rzzt));*/

                    //入账状态
                    //入账申请状态：1申请入账，2发送入账请求，3入账失败，4入账成功，5申请撤销，6发送撤销申请，7撤销失败，8撤销成功
                    //4 5 6 7 属于入账成功
                    //1 2 3 8 属于入账失败
                    if("4".equals(jksrzAuthStatus)||"5".equals(jksrzAuthStatus)||"6".equals(jksrzAuthStatus)||"7".equals(jksrzAuthStatus)){
                        pageList.get(i)
                                .setRzzt("已入账");
                    }else{
                        pageList.get(i)
                                .setRzzt("未入账");
                    }

                    //入账用途
                    String Jksrzlx = pageList.get(i).getJksrzlx();
                    pageList.get(i)
                            .setJksrzlx(dictdetaServcice.queryDictName(DictConstant.INACCOUNT_YT_RZPAGE, Jksrzlx));

                }
            }
            // 设置记录总数
            json.put("total", pageInfo.getTotal());
            List<JkszhcxRespVO> resultList = pageInfo.getList();
            json.put("datalist", CollectionUtils.isEmpty(resultList) ? new ArrayList<>() : resultList);
        } catch (Exception e) {
            // 统一设置操作异常标识
            json = super.errorResult(e);
        }
        return super.responseResult(json);
    }

    @Override
    public boolean rzCustomReq(RzCustomPageReq req, String userName) {
        try {
            List<RzCustomPageReqItem> customList = req.getCustomList();
            //按税号分组
            Map<String, List<RzCustomPageReqItem>> groupBySh = customList.stream().collect(Collectors.groupingBy(RzCustomPageReqItem::getGfTaxNo));

            Set<String> gfList = customList.stream().map(RzCustomPageReqItem::getGfTaxNo).collect(Collectors.toSet());

            DynamicContextHolder.push(DbConstant.BASICS_READ);
            List<SysEnterpriseConfigEntity> qyDtoList = sysEnterpriseConfigDao.selectList(new LambdaQueryWrapper<SysEnterpriseConfigEntity>().in(SysEnterpriseConfigEntity::getNsrsbh, gfList));
            DynamicContextHolder.push("business" + DbConstant.BUSINESS_READ);
            Set<String> shSet = new HashSet<>();
            //把对号对应的企业类型查到
            groupBySh.keySet().forEach(key -> {
                shSet.add(key);
                String tdlx = qyDtoList.stream().filter(e->e.getNsrsbh().equals(key)).findFirst().get().getJrfs();

                //InvoiceRzInfo iri = new InvoiceRzInfo();
                ////把税号这些放进去
                //iri.setNsrsbh(key);
                //iri.setPclsh(UUID.randomUUID().toString().replace("-", ""));
                //iri.setRzlx(req.getRzlx());
                //iri.setRzsq(req.getRzsq());
                List<RzCustomPageReqItem> rzInvoicePageReqItems = groupBySh.get(key);

                rzInvoicePageReqItems.stream().forEach(jkshm->{
                    //查询发票入账表
                    TdxLqRzCustomEntity trc = rzRecordCustomDao.selectOne(new QueryWrapper<TdxLqRzCustomEntity>().eq("customs_code", jkshm.getCustomsCode()));
                    if (trc != null) {
                        if (    req.getRzlx().equals("02")||
                                req.getRzlx().equals("03")||
                                req.getRzlx().equals("04")||
                                req.getRzlx().equals("05")) {
                            //接口申请入账处理流程

                            if (trc.getJksrzAuthStatus().equals("4")||trc.getJksrzAuthStatus().equals("7")) {
                                //如果是入账成功则不处理数据
                                return;
                            }

                            if (trc.getJksrzAuthStatus().equals("3")||trc.getJksrzAuthStatus().equals("8")) {
                                //未入账  更新入账数据
                                updateRzJks(trc,req,userName);
                            }
                        }

                        if (req.getRzlx().equals("06")) {
                            //接口申请入账撤销处理流程
                            if (trc.getJksrzAuthStatus().equals("3")||trc.getJksrzAuthStatus().equals("8")) {
                                //如果是未入账则不处理数据
                                return;
                            }

                            if (trc.getJksrzAuthStatus().equals("4")||trc.getJksrzAuthStatus().equals("7")) {
                                //已入账  更新入账数据
                                updateRzJks(trc,req,userName);
                            }
                        }
                    } else {
                        //查询抵账表
                        TdxCustomsRecord tcr = tdxCustomsRecordDao.selectOne(new QueryWrapper<TdxCustomsRecord>().eq("customs_code", jkshm.getCustomsCode()));
                        //插入
                        TdxLqRzCustomEntity tlrc = new TdxLqRzCustomEntity();
                        tlrc.setGfTaxNo(key);
                        tlrc.setCustomsCode(tcr.getCustomsCode());
                        tlrc.setFillInDate(tcr.getFillInDate());
                        tlrc.setJksrzsq(req.getRzsq());
                        //判断入账类型是否为撤销入账 设置入账申请状态
                        tlrc.setJksrzAuthStatus(req.getRzlx().equals("06") ? "5" : "1");
                        tlrc.setJksrzlx(req.getRzlx());
                        tlrc.setRzr(userName);
                        tlrc.setCreateTime(new Date());
                        log.info("保存缴款书入账表:{}",tlrc);
                        rzRecordCustomDao.insert(tlrc);
                        //更新缴款书抵账表入账状态
                        tdxCustomsRecordDao.update(null, new LambdaUpdateWrapper<TdxCustomsRecord>()
                                .set(TdxCustomsRecord::getRzzt, req.getRzlx().equals("06") ? "05" : "04")
                                .eq(TdxCustomsRecord::getCustomsCode, tcr .getCustomsCode()));
                    }
                });

            });
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            return false;
        }
        return true;
    }

    private void updateRzJks(TdxLqRzCustomEntity trc, RzCustomPageReq cri, String userName) {
        //缴款书入账表有数据则更新
        log.info("更新缴款书入账表");
        trc.setJksrzsq(cri.getRzsq());
        trc.setJksrzlx(cri.getRzlx());
        //判断入账类型是否为撤销入账 设置入账申请状态
        trc.setJksrzAuthStatus(cri.getRzlx().equals("06") ? "5" : "1");
        trc.setJksrzsbyy("");
        trc.setJksrzsj("");
        trc.setRzr(userName);
        trc.setUpdateTime(new Date());
        log.info("更新缴款书入账表:{}",trc);
        rzRecordCustomDao.updateById(trc);

        //更新缴款书抵账表入账状态
        tdxCustomsRecordDao.update(null, new LambdaUpdateWrapper<TdxCustomsRecord>()
                .set(TdxCustomsRecord::getRzzt, cri.getRzlx().equals("06") ? "05" : "04")
                .eq(TdxCustomsRecord::getCustomsCode, trc.getCustomsCode()));
    }
}
