package com.dxhy.base.service.sqdktj;

import cn.hutool.core.util.ObjectUtil;
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.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dxhy.api.model.config.Tax;
import com.dxhy.api.model.config.sys.SysEnterpriseConfigEntity;
import com.dxhy.base.dao.*;
import com.dxhy.base.entity.BaseTDxDkCount;
import com.dxhy.base.entity.TdxLqDkCustomFpycxx;
import com.dxhy.base.entity.TdxLqDkFpycxx;
import com.dxhy.base.model.BaseBeforegxRespVO;
import com.dxhy.base.model.BaseTDxDkCountDetailSumVO;
import com.dxhy.base.model.BaseTDxDkCountRespVO;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.constant.DictConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.ApplyStatusEnum;
import com.dxhy.common.enums.QsStatusEnum;
import com.dxhy.common.enums.SfdqskssqEnum;
import com.dxhy.common.enums.TjStatusEnum;
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.utils.DateUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

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

/**
 * 统计的企业信息service实现类
 *
 * @author kangzq
 * @date 2019年5月11日
 * @version 1.0
 */
@SuppressWarnings({"AlibabaUndefineMagicConstant", "AlibabaMethodTooLong", "AlibabaLowerCamelCaseVariableNaming"})
@Service("baseStatisticalEnterpriseService")
public class BaseStatisticalEnterpriseServiceImpl extends MpBaseServiceImpl<BaseTDxDkCountDao, BaseTDxDkCount>
    implements BaseStatisticalEnterpriseService {
    @Resource
    private BaseTDxRecordInvoiceDao baseTDxRecordInvoiceDao;
    @Resource
    private TabulateRedisService tabulateRedisService;
    @Resource
    private DictdetaServcice dictdetaServcice;

    @Resource
    private BaseSysEnterpriseConfigDao baseSysEnterpriseConfigDao;
    @Resource
    private BaseLqDkFpycxxDao baseLqDkFpycxxDao;

    @Resource
    private BaseLqDkCustomFpycxxDao baseLqDkCustomFpycxxDao;

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

        try {
            String tjflag = (String)pramsMap.get("tjflag");

            String company = (String)pramsMap.get("company");
            String menuId = (String)pramsMap.get("menuId");
            json = tabulateRedisService.getTabulateMenu(company, menuId);

            List<String> gfsh = (List<String>)pramsMap.get("gfsh");
            if (gfsh == null || gfsh.size() == 0) {
                json.put("total", 0);
                json.put("datalist", new ArrayList<BaseTDxDkCountRespVO>());
                return super.responseResult(json);
            }
            PageHelper.startPage(curr, size);

            List<BaseTDxDkCountRespVO> pageList = super.baseMapper.selectByDkCount(pramsMap);
            PageInfo<BaseTDxDkCountRespVO> pageInfo = new PageInfo<>(pageList);
            List<BaseTDxDkCountRespVO> resultList = pageInfo.getList();
            // 用于页面展示的对象
            List<BaseTDxDkCountRespVO> voList = new ArrayList<>();
            List<Tax> orgCodeList = (List<Tax>)pramsMap.get("orgCodeList");
            for (int i = 0; i < resultList.size(); i++) {
                BaseTDxDkCountRespVO vo = new BaseTDxDkCountRespVO();
                vo.setId(String.valueOf(i + 1));
                vo.setXh(String.valueOf(pageInfo.getStartRow() + i));
                vo.setTaxno(resultList.get(i).getTaxno());
                vo.setSelect(true);
                if (StringUtils.isNotBlank(resultList.get(i).getTjDate())) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                    Date date = sdf.parse(resultList.get(i).getTjDate());
                    vo.setTjDate(DateUtils.dateToStrLong(date));

                }
                vo.setTjUser(resultList.get(i).getTjUser());
                vo.setQrDate(resultList.get(i).getQrDate());
                vo.setQrUser(resultList.get(i).getQrUser());
                vo.setInvoiceNum(AmountFormatUtil.fmtMicrometer(resultList.get(i).getInvoiceNum()));
                vo.setTaxname(resultList.get(i).getTaxname());
                vo.setSkssq(resultList.get(i).getSkssq());
                vo.setTaxname(resultList.get(i).getTaxname());
                if (StringUtils.isNotBlank(resultList.get(i).getDksehj())) {
                    vo.setDksehj(AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getDksehj())));
                } else {
                    vo.setDksehj(resultList.get(i).getDksehj());
                }
                if (!"1".equals(resultList.get(i).getSfdqskssq())) {
                    vo.setSelect(false);
                }
                for (SfdqskssqEnum e : SfdqskssqEnum.values()) {
                    if (e.getSfdqskssqDm().equals(resultList.get(i).getSfdqskssq())) {
                        vo.setSfdqskssq(e.getSfdqskssqMc(e.getIndex()));
                    }
                }
//                for (QsStatusEnum e : QsStatusEnum.values()) {
//                    if (e.getQsStatusDm().equals(resultList.get(i).getQsStatus())) {
//                        vo.setQsStatus(e.getQsStatusMc(e.getIndex()));
//                    }
//                }

                //字典转换
                String qsStatus = resultList.get(i).getQsStatus();
                vo.setQsStatus(dictdetaServcice.queryDictName(DictConstant.QRQM_STATUS,qsStatus));
                String tjStatus = resultList.get(i).getTjStatus();
                vo.setTjStatus(dictdetaServcice.queryDictName(DictConstant.DKTJ_STATUS,tjStatus));
                if ("3".equals(resultList.get(i).getCxtjStatus()) || "3".equals(tjStatus)) {
                    String applyMsg = resultList.get(i).getApplyMsg();
                    vo.setApplyMsg(dictdetaServcice.queryDictName(DictConstant.DKTJSBYY,applyMsg));
                }

                if ("3".equals(resultList.get(i).getCxqsStatus()) || "3".equals(resultList.get(i).getQsStatus())) {
                    String applyMsg = resultList.get(i).getApplyMsg();
                    vo.setApplyMsg(dictdetaServcice.queryDictName(DictConstant.QRQMSBYY,applyMsg));
                }
                vo.setCxtjStatus(dictdetaServcice.queryDictName(DictConstant.CXTJ_STATUS,resultList.get(i).getCxtjStatus()));
                vo.setCxqsStatus(dictdetaServcice.queryDictName(DictConstant.CXTJ_STATUS,resultList.get(i).getCxqsStatus()));

                String skssq = resultList.get(i).getSkssq();
                LocalDate localDate =
                    LocalDate.of(Integer.parseInt(skssq.substring(0, 4)), Integer.parseInt(skssq.substring(4)), 1);
                localDate = localDate.plusMonths(1);
                LocalDate localDate1 = LocalDate.now();
                if (localDate1.isBefore(localDate)) {
                    vo.setTjStatus("未到期");
                    vo.setQsStatus("未到期");
                    vo.setSelect(false);
                }
                vo.setDetailFlag("2".equals(resultList.get(i).getTjStatus()));

                if ("1".equals(tjflag)) {
                    if (StringUtils.isNotBlank(resultList.get(i).getCxtjStatus())
                        && !"0".equals(resultList.get(i).getCxtjStatus())
                        && !"3".equals(resultList.get(i).getCxtjStatus())) {
                        vo.setSelect(false);
                    }
                    if ("1".equals(resultList.get(i).getQsStatus())) {
                        vo.setSelect(false);
                    }
                } else {
                    if (StringUtils.isNotBlank(resultList.get(i).getTjStatus())
                        && !"0".equals(resultList.get(i).getTjStatus()) && !"3".equals(resultList.get(i).getTjStatus())
                        && !"2".equals(resultList.get(i).getTjStatus())) {
                        vo.setSelect(false);
                    }
                    if (StringUtils.isNotBlank(resultList.get(i).getQsStatus())
                        && !"0".equals(resultList.get(i).getQsStatus())
                        && !"3".equals(resultList.get(i).getQsStatus())) {
                        vo.setSelect(false);
                    }
                }
                for (Tax orgCode : orgCodeList) {
                    if (vo.getTaxno().equals(orgCode.getTaxno())) {
                        DynamicContextHolder.push(DbConstant.BASICS_READ);
                        vo.setPassword(this.baseMapper.getPassword(orgCode.getTaxno()));
                    }
                }

                //查询统计 分数，抵扣税额统计
                BaseTDxDkCountDetailSumVO detailSumVO = super.baseMapper.selectSumCountDetail(resultList.get(i).getTaxno(),resultList.get(i).getSkssq());
                if(ObjectUtil.isNotEmpty(detailSumVO)){
                    vo.setInvoiceNum(detailSumVO.getInvoiceNum());
                    vo.setDksehj(detailSumVO.getDksehj());
                }

           //乐企判断是否有异常信息
                LambdaQueryWrapper<SysEnterpriseConfigEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(SysEnterpriseConfigEntity::getNsrsbh, vo.getTaxno());
                DynamicContextHolder.push( DbConstant.BASICS_READ);
                SysEnterpriseConfigEntity enterpriseConfigEntity = baseSysEnterpriseConfigDao.selectOne(lambdaQueryWrapper);
                //如果是乐企，再去查异常数据库
                if(ObjectUtil.isNotEmpty(enterpriseConfigEntity)&&"1".equals(enterpriseConfigEntity.getJrfs())){
                    vo.setIsLq("1");
                    DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
                    LambdaQueryWrapper<TdxLqDkFpycxx> fpycxxQuery = new LambdaQueryWrapper<>();
                    fpycxxQuery.eq(TdxLqDkFpycxx::getNsrsbh, vo.getTaxno());
                    fpycxxQuery.eq(TdxLqDkFpycxx::getDqskssq, vo.getSkssq());
                    Long fpycxxCount = baseLqDkFpycxxDao.selectCount(fpycxxQuery);
                    LambdaQueryWrapper<TdxLqDkCustomFpycxx> customfpycxxQuery = new LambdaQueryWrapper<>();
                    customfpycxxQuery.eq(TdxLqDkCustomFpycxx::getNsrsbh, vo.getTaxno());
                    customfpycxxQuery.eq(TdxLqDkCustomFpycxx::getDqskssq, vo.getSkssq());
                    Long customYcxxCount = baseLqDkCustomFpycxxDao.selectCount(customfpycxxQuery);

                    if((fpycxxCount+customYcxxCount)>0){
                        vo.setYcxxCount(fpycxxCount+customYcxxCount);
                        if (!"1".equals(tjflag)) {
                            vo.setSelect(false);
                        }
                    }
                }else{
                    vo.setYcxxCount(0L);
                    vo.setIsLq("0");
                }
                voList.add(vo);
            }

            // 设置总条数
            json.put("total", pageInfo.getTotal());
            json.put("datalist", voList);

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

        return super.responseResult(json);
    }


    @Override
    public BaseTDxDkCount selectByBeforeRespVO(BaseBeforegxRespVO vo) {
        Page<BaseTDxDkCount> page = new Page<>(1, 1);
        QueryWrapper<BaseTDxDkCount> queryWrapper = new QueryWrapper<>();

        if (!StringHelper.isBlank(vo.getSkssq())) {
            queryWrapper.eq("skssq", vo.getSkssq());
        }
        if (!StringHelper.isBlank(vo.getGfsh())) {
            queryWrapper.eq("taxno", vo.getGfsh());
        }

        IPage<BaseTDxDkCount> pageInfo = super.page(page, queryWrapper);

        BaseTDxDkCount dk = new BaseTDxDkCount();
        if (pageInfo.getTotal() > 0) {
            dk = pageInfo.getRecords().get(0);
        }
        return dk;

    }

    @Override
    public void updateByGfshAndSkssq(Map<String, Object> pramMap, BaseTDxDkCount entity) {
        DynamicContextHolder.push(pramMap.get("dbName") + DbConstant.BUSINESS_WRITE);
        UpdateWrapper<BaseTDxDkCount> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("taxno", pramMap.get("gfsh"));
        updateWrapper.eq("skssq", pramMap.get("skssq"));
        super.baseMapper.update(entity, updateWrapper);
    }

    @Override
    public String updateBySqtj(Map<String, Object> pramsMap) {
        JSONObject json = new JSONObject();
        String[] gfshs = pramsMap.get("gfshs").toString().split(",");
        String[] skssqs = pramsMap.get("skssqs").toString().split(",");

        for (int i = 0; i < gfshs.length; i++) {
            String gfsh = gfshs[i];
            String skssq = skssqs[i];

            // 更新申请状态
            UpdateWrapper<BaseTDxDkCount> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("taxno", gfsh).eq("skssq", skssq);

            BaseTDxDkCount tdentity = new BaseTDxDkCount();
            tdentity.setApplyStatus(ApplyStatusEnum.WSQ.getApplyStatusDm());
            tdentity.setApplyType("0");
            tdentity.setTjStatus(TjStatusEnum.SQZ.getTjStatusDm());
            tdentity.setCxtjStatus("0");
            tdentity.setCxqsStatus("0");
            tdentity.setTjUser((String)pramsMap.get("czr"));
            DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_WRITE);
            super.baseMapper.update(tdentity, updateWrapper);
        }
        json.put("tsxx", "已申请报表统计，请稍后查询统计报表");
        return super.responseResult(json);
    }

    @Override
    public String updateByQrsqtj(Map<String, Object> pramsMap) {
        JSONObject json = new JSONObject();
        String[] gfshs = pramsMap.get("gfshs").toString().split(",");
        String[] skssqs = pramsMap.get("skssqs").toString().split(",");
        String password = (String)pramsMap.get("password");
        for (int i = 0; i < gfshs.length; i++) {
            String gfsh = gfshs[i];
            String skssq = skssqs[i];
            // 更新申请状态
            UpdateWrapper<BaseTDxDkCount> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("taxno", gfsh).eq("skssq", skssq);
            BaseTDxDkCount tdentity = new BaseTDxDkCount();
            tdentity.setApplyType("0");
            tdentity.setApplyStatus("0");
            tdentity.setQsStatus(QsStatusEnum.QRZ.getQsStatusDm());
            tdentity.setCxqsStatus("0");
            tdentity.setQrUser((String)pramsMap.get("czr"));
            DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_WRITE);
            super.baseMapper.update(tdentity, updateWrapper);
            if (StringUtils.isNotBlank(password)) {
                baseTDxRecordInvoiceDao.updatePwd(password, gfsh);
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                baseTDxRecordInvoiceDao.updatePassword(password, gfsh);
            }

        }
        json.put("tsxx", "已申请确认统计，请稍后查询确认结果");
        return super.responseResult(json);
    }
}
