/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package com.unis.dataQualityAssessmen.info.modular.dqaDataAnalysis.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
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.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.microsoft.schemas.office.visio.x2012.main.ConnectsType;
import com.unis.basic.info.modular.unitInfo.entity.UnitInfo;
import com.unis.basic.info.modular.unitInfo.service.UnitInfoService;
import com.unis.dataQualityAssessmen.info.modular.dqaCountryInterface.entity.DqaCountryInterface;
import com.unis.dataQualityAssessmen.info.modular.dqaCountryInterface.service.DqaCountryInterfaceService;
import com.unis.dataQualityAssessmen.info.modular.dqaDataAnalysis.entity.vo.DqaDataAnalysisVo;
import com.unis.enterpriseCreditManagement.info.modular.ecmCreditData.entity.vo.EcmCreditDataVo;
import com.unis.policy.info.modular.alPolicyFileReport.entity.AlPolicyFileReport;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.unis.common.enums.CommonSortOrderEnum;
import com.unis.common.exception.CommonException;
import com.unis.common.page.CommonPageRequest;
import com.unis.dataQualityAssessmen.info.modular.dqaDataAnalysis.entity.DqaDataAnalysis;
import com.unis.dataQualityAssessmen.info.modular.dqaDataAnalysis.mapper.DqaDataAnalysisMapper;
import com.unis.dataQualityAssessmen.info.modular.dqaDataAnalysis.param.DqaDataAnalysisAddParam;
import com.unis.dataQualityAssessmen.info.modular.dqaDataAnalysis.param.DqaDataAnalysisEditParam;
import com.unis.dataQualityAssessmen.info.modular.dqaDataAnalysis.param.DqaDataAnalysisIdParam;
import com.unis.dataQualityAssessmen.info.modular.dqaDataAnalysis.param.DqaDataAnalysisPageParam;
import com.unis.dataQualityAssessmen.info.modular.dqaDataAnalysis.service.DqaDataAnalysisService;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 数据质量考核-统计分析-数据分析表表Service接口实现类
 *
 * @author TS
 * @date  2024/05/21 15:21
 **/
@Service
public class DqaDataAnalysisServiceImpl extends ServiceImpl<DqaDataAnalysisMapper, DqaDataAnalysis> implements DqaDataAnalysisService {
    @Autowired
    private DqaCountryInterfaceService dqaCountryInterfaceService;
    @Autowired
    private UnitInfoService unitInfoService;
    @Resource
    private DqaDataAnalysisMapper dqaDataAnalysisMapper;
    @Override
    public Page<DqaDataAnalysis> page(DqaDataAnalysisPageParam dqaDataAnalysisPageParam) {
        QueryWrapper<DqaDataAnalysis> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isAllNotEmpty(dqaDataAnalysisPageParam.getSortField(), dqaDataAnalysisPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(dqaDataAnalysisPageParam.getSortOrder());
            queryWrapper.orderBy(true, dqaDataAnalysisPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(dqaDataAnalysisPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(DqaDataAnalysis::getId);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(DqaDataAnalysisAddParam dqaDataAnalysisAddParam) {
        DqaDataAnalysis dqaDataAnalysis = BeanUtil.toBean(dqaDataAnalysisAddParam, DqaDataAnalysis.class);
        this.save(dqaDataAnalysis);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(DqaDataAnalysisEditParam dqaDataAnalysisEditParam) {
        DqaDataAnalysis dqaDataAnalysis = this.queryEntity(dqaDataAnalysisEditParam.getId());
        BeanUtil.copyProperties(dqaDataAnalysisEditParam, dqaDataAnalysis);
        this.updateById(dqaDataAnalysis);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<DqaDataAnalysisIdParam> dqaDataAnalysisIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(dqaDataAnalysisIdParamList, DqaDataAnalysisIdParam::getId));
    }

    @Override
    public DqaDataAnalysis detail(DqaDataAnalysisIdParam dqaDataAnalysisIdParam) {
        return this.queryEntity(dqaDataAnalysisIdParam.getId());
    }

    @Override
    public DqaDataAnalysis queryEntity(String id) {
        DqaDataAnalysis dqaDataAnalysis = this.getById(id);
        if(ObjectUtil.isEmpty(dqaDataAnalysis)) {
            throw new CommonException("数据质量考核-统计分析-数据分析表表不存在，id值为：{}", id);
        }
        return dqaDataAnalysis;
    }

    /**
     * 定时处理接口数据
     */
    @Override
    public void taskdAction() {
        QueryWrapper<UnitInfo> unitInfoQueryWrapper = new QueryWrapper<>();
        unitInfoQueryWrapper.select("id");
        //所有单位,不包括逻辑删除的
        List<UnitInfo> unitInfos = unitInfoService.list(unitInfoQueryWrapper);

        //查询所有接口
        List<DqaCountryInterface> interfaceList = dqaCountryInterfaceService.list();

        ///查询对应的接口总条数据
        long count = this.count();

        //如果数据总条数据=单位数*接口数，则只更新接口总条数据
        if(unitInfos.size()*interfaceList.size() != count){
            for (int i = 0; i < unitInfos.size(); i++) {
                 UnitInfo unitInfo = unitInfos.get(i);
                for (int j = 0; j < interfaceList.size(); j++) {
                    DqaCountryInterface countryInterface = interfaceList.get(j);
                    QueryWrapper<DqaDataAnalysis> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().eq(DqaDataAnalysis::getUnitInfoId,unitInfo.getId())
                            .eq(DqaDataAnalysis::getInterfaceNumber,countryInterface.getInterfaceNumber())
                            .eq(DqaDataAnalysis::getInterfaceName,countryInterface.getInterfaceName());

                    DqaDataAnalysis dataAnalysis = this.getOne(queryWrapper,false);
                    if (dataAnalysis == null){
                        dataAnalysis = new DqaDataAnalysis();
                        dataAnalysis.setInterfaceName(countryInterface.getInterfaceName());
                        dataAnalysis.setInterfaceNumber(countryInterface.getInterfaceNumber());
                        dataAnalysis.setUnitInfoId(unitInfo.getId());
                        dataAnalysis.setStatisticsDate(new Date());
                        dataAnalysis.setNonNullFieldCount(countryInterface.getCountryTableColumnNonEmptyCount());
                        dataAnalysis.setInterfaceFieldCount(countryInterface.getCountryTableColumnCount());
                        dataAnalysis.setErrorDataCount(0); //默认0
                        dataAnalysis.setErrorDataCount(0); //默认0
                        dataAnalysis.setDataRecordCount(0); //默认0
                        dataAnalysis.setLastUpdateTime(new Date());

                    }
                    //设置总条数与最后更新时间
                    Map<String,Object> countByTb = dqaDataAnalysisMapper.selectCountByTableNameAndUnitId(countryInterface.getCountryTableName(),unitInfo.getId());
                    if (countByTb != null){
                        dataAnalysis.setDataRecordCount(Integer.parseInt(countByTb.getOrDefault("conunt","0").toString())); //默认0
                        String date = countByTb.getOrDefault("zhgsxj","").toString();
                        if (StringUtils.isNotBlank(date))
                            dataAnalysis.setLastUpdateTime(DateUtil.parseDateTime(date));
                    }
                    this.saveOrUpdate(dataAnalysis);

                }
            }
        }else {
            for (int i = 0; i < interfaceList.size(); i++) {
                DqaCountryInterface countryInterface = interfaceList.get(i);
                //设置总条数与最后更新时间
                List<Map<String,Object>> countsByTb = dqaDataAnalysisMapper.selectCountByTableName(countryInterface.getCountryTableName());
                for (int j = 0; j < countsByTb.size(); j++) {
                    Map<String,Object> map = countsByTb.get(j);

                    UpdateWrapper<DqaDataAnalysis> wrapper = new UpdateWrapper<>();
                    wrapper.lambda().eq(DqaDataAnalysis::getInterfaceNumber,countryInterface.getInterfaceNumber())
                            .eq(DqaDataAnalysis::getInterfaceName,countryInterface.getInterfaceName())
                            .eq(DqaDataAnalysis::getUnitInfoId,map.get("unitId").toString());
                    wrapper.lambda().set(DqaDataAnalysis::getDataRecordCount,Integer.parseInt(map.getOrDefault("conunt","0").toString()));
                    String date = map.getOrDefault("zhgsxj","").toString();
                    if (StringUtils.isNotBlank(date))
                        wrapper.lambda().set(DqaDataAnalysis::getLastUpdateTime,DateUtil.parseDateTime(date));
                    else
                        wrapper.lambda().set(DqaDataAnalysis::getDataRecordCount,new Date());

                    //更新数据
                    this.update(wrapper);
                }

            }
        }

        UpdateWrapper<DqaDataAnalysis> wrapper = new UpdateWrapper<>();
        wrapper.lambda().set(DqaDataAnalysis::getStatisticsDate,new Date());
        //更新数据统计日期
        this.update(wrapper);

    }

    /**
     * 获取数据质量考核-统计分析-数据量自定义分页
     *
     * @param pageParam
     * @return
     */
    @Override
    public IPage<DqaDataAnalysisVo> findCountPage(DqaDataAnalysisPageParam pageParam) {
                //条形查询器
                QueryWrapper<AlPolicyFileReport> queryWrapper = new QueryWrapper<>();
                //分页相关
                if(StringUtils.isNotBlank(pageParam.getInterfaceName())){
                    queryWrapper.like("a.interface_name ",pageParam.getInterfaceName() );
                }
                if(StringUtils.isNotBlank(pageParam.getZcdzCityName())){
                    queryWrapper.like("city.DICT_LABEL  ",pageParam.getZcdzCityName() );
                }
                if(StringUtils.isNotBlank(pageParam.getZcdzAreaName())){
                    queryWrapper.like("area.DICT_LABEL ",pageParam.getZcdzAreaName() );
                }
                Page<DqaDataAnalysisVo> p =new Page<>(pageParam.getCurrent(),pageParam.getSize());
                IPage<DqaDataAnalysisVo> page = dqaDataAnalysisMapper.findCountPage(p,queryWrapper);
                return page;
    }

    /**
     * 获获取数据质量考核-统计分析-数据量详情自定义分页
     *
     * @param pageParam
     * @return
     */
    @Override
    public IPage<DqaDataAnalysisVo> findCountDetailPage(DqaDataAnalysisPageParam pageParam) {
            //条形查询器
            QueryWrapper<AlPolicyFileReport> queryWrapper = new QueryWrapper<>();
            //分页相关
            if(StringUtils.isNotBlank(pageParam.getInterfaceName())){
                queryWrapper.eq("a.interface_name ",pageParam.getInterfaceName().trim() );
            }else {
                return  null;
            }
            if(StringUtils.isNotBlank(pageParam.getUnitName())){
                queryWrapper.like("b.dwmc ",pageParam.getUnitName() );
            }
            if(StringUtils.isNotBlank(pageParam.getZcdzCityName())){
                queryWrapper.like("city.DICT_LABEL  ",pageParam.getZcdzCityName() );
            }
            if(StringUtils.isNotBlank(pageParam.getZcdzAreaName())){
                queryWrapper.like("area.DICT_LABEL ",pageParam.getZcdzAreaName() );
            }
            Page<DqaDataAnalysisVo> p =new Page<>(pageParam.getCurrent(),pageParam.getSize());
            IPage<DqaDataAnalysisVo> page = dqaDataAnalysisMapper.findCountDetailPage(p,queryWrapper);
            return page;
    }

    /**
     * 获获取数据质量考核-统计分析-完整性自定义分页
     *
     * @param pageParam
     * @return
     */
    @Override
    public IPage<DqaDataAnalysisVo> findComplePage(DqaDataAnalysisPageParam pageParam) {
            //条形查询器
            QueryWrapper<AlPolicyFileReport> queryWrapper = new QueryWrapper<>();
            //分页相关
            if(StringUtils.isNotBlank(pageParam.getInterfaceName())){
                queryWrapper.like("a.interface_name ",pageParam.getInterfaceName() );
            }
            Page<DqaDataAnalysisVo> p =new Page<>(pageParam.getCurrent(),pageParam.getSize());
            IPage<DqaDataAnalysisVo> page = dqaDataAnalysisMapper.findComplePage(p,queryWrapper);
            return page;
    }

    /**
     * 获取数据质量考核-统计分析-完整性详情自定义分页
     *
     * @param pageParam
     * @return
     */
    @Override
    public IPage<DqaDataAnalysisVo> findCompleDetailPage(DqaDataAnalysisPageParam pageParam) {
            //条形查询器
            QueryWrapper<AlPolicyFileReport> queryWrapper = new QueryWrapper<>();
            //分页相关
            if(StringUtils.isNotBlank(pageParam.getInterfaceName())){
                queryWrapper.eq("a.interface_name ",pageParam.getInterfaceName().trim() );
            }else {
                return  null;
            }
            if(StringUtils.isNotBlank(pageParam.getUnitName())){
                queryWrapper.like("b.dwmc ",pageParam.getUnitName() );
            }
            Page<DqaDataAnalysisVo> p =new Page<>(pageParam.getCurrent(),pageParam.getSize());
            IPage<DqaDataAnalysisVo> page = dqaDataAnalysisMapper.findCompleDetailPage(p,queryWrapper);
            return page;
    }

    /**
     * 获取数据质量考核-统计分析-正确性详情自定义分页
     *
     * @param pageParam
     * @return
     */
    @Override
    public IPage<DqaDataAnalysisVo> findAccuracyPage(DqaDataAnalysisPageParam pageParam) {
            //条形查询器
            QueryWrapper<AlPolicyFileReport> queryWrapper = new QueryWrapper<>();
            //分页相关
            if(StringUtils.isNotBlank(pageParam.getInterfaceName())){
                queryWrapper.like("a.interface_name ",pageParam.getInterfaceName() );
            }
            Page<DqaDataAnalysisVo> p =new Page<>(pageParam.getCurrent(),pageParam.getSize());
            IPage<DqaDataAnalysisVo> page = dqaDataAnalysisMapper.findAccuracyPage(p,queryWrapper);
            return page;
    }

    /**
     * 获取数据质量考核-统计分析-正确性详情自定义分页
     *
     * @param pageParam
     * @return
     */
    @Override
    public IPage<DqaDataAnalysisVo> findAccuracyDetailPage(DqaDataAnalysisPageParam pageParam) {
            QueryWrapper<AlPolicyFileReport> queryWrapper = new QueryWrapper<>();
            //分页相关
            if (StringUtils.isNotBlank(pageParam.getInterfaceName())) {
                queryWrapper.eq("a.interface_name ", pageParam.getInterfaceName().trim());
            } else {
                return null;
            }
            if (StringUtils.isNotBlank(pageParam.getUnitName())) {
                    queryWrapper.like("city.DICT_LABEL ", pageParam.getUnitName());
            }
            Page<DqaDataAnalysisVo> p = new Page<>(pageParam.getCurrent(), pageParam.getSize());
            IPage<DqaDataAnalysisVo> page = dqaDataAnalysisMapper.findAccuracyDetailPage(p, queryWrapper);
            return page;
    }

    /**
     * 获取数据质量考核-统计分析-自动考核自定义分页
     *
     * @param pageParam
     * @return
     */
    @Override
    public IPage<DqaDataAnalysisVo> findAtuoPage(DqaDataAnalysisPageParam pageParam) {
            QueryWrapper<AlPolicyFileReport> queryWrapper = new QueryWrapper<>();
            //分页相关
            if (StringUtils.isNotBlank(pageParam.getUnitName())) {
                queryWrapper.like("b.dwmc ", pageParam.getUnitName());
            }
            if (StringUtils.isNotBlank(pageParam.getUnitName())) {
                queryWrapper.like("b.zcdz_city ", pageParam.getZcdzCityName());
            }
            if (StringUtils.isNotBlank(pageParam.getYear())) {
                queryWrapper.like("DATE_FORMAT(last_update_time,'%Y') ", pageParam.getYear());
            }
            if (StringUtils.isNotBlank(pageParam.getQuarter())) {
                queryWrapper.like("QUARTER(last_update_time) ", pageParam.getQuarter());
            }
            if (StringUtils.isNotBlank(pageParam.getMonth())) {
                queryWrapper.like("DATE_FORMAT(last_update_time,'%m') ", pageParam.getMonth());
            }
            Page<DqaDataAnalysisVo> p = new Page<>(pageParam.getCurrent(), pageParam.getSize());
            IPage<DqaDataAnalysisVo> page = dqaDataAnalysisMapper.findAtuoPage(p, queryWrapper);
            return page;
    }

    /**
     * 获取数据质量考核-统计分析-自动考核详情自定义分页
     *
     * @param pageParam
     * @return
     */
    @Override
    public IPage<DqaDataAnalysisVo> findAtuoDetailPage(DqaDataAnalysisPageParam pageParam) {
            QueryWrapper<AlPolicyFileReport> queryWrapper = new QueryWrapper<>();
            //分页相关
            if (StringUtils.isNotBlank(pageParam.getUnitName())) {
                queryWrapper.like("b.dwmc ", pageParam.getUnitName());
            }else{
                return null;
            }
            Page<DqaDataAnalysisVo> p = new Page<>(pageParam.getCurrent(), pageParam.getSize());
            IPage<DqaDataAnalysisVo> page = dqaDataAnalysisMapper.findAtuoDetailPage(p, queryWrapper);
            return page;
    }

    /**
     * 导出数据
     *
     * @param pageParam
     * @return
     */
    @Override
    public List<Map<String, Object>> exportByEntity(DqaDataAnalysisPageParam pageParam) {
        {
            QueryWrapper<AlPolicyFileReport> queryWrapper = new QueryWrapper<>();
            //分页相关
            if (StringUtils.isNotBlank(pageParam.getUnitName())) {
                queryWrapper.like("b.dwmc ", pageParam.getUnitName());
            }
            if (StringUtils.isNotBlank(pageParam.getYear())) {
                queryWrapper.like("DATE_FORMAT(last_update_time,'%Y') ", pageParam.getYear());
            }
            if (StringUtils.isNotBlank(pageParam.getMonth())) {
                queryWrapper.like("DATE_FORMAT(last_update_time,'%m') ", pageParam.getMonth());
            }
            if (StringUtils.isNotBlank(pageParam.getQuarter())) {
                queryWrapper.like("QUARTER(last_update_time) ", pageParam.getQuarter());
            }

            List<Map<String, Object>> list = dqaDataAnalysisMapper.exportByEntity(queryWrapper);
            return list;
        }
    }
}
