package net.northking.cctp.dw.db.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.page.PageMethod;
import com.hzbank.testteam.autotest.dependencies.baseDefineDependency.exception.InvalidException;
import lombok.extern.slf4j.Slf4j;
import net.northking.cctp.common.cache.EntityNameCache;
import net.northking.cctp.common.cache.EntityNameCatalog;
import net.northking.cctp.common.db.DefaultPagination;
import net.northking.cctp.common.db.Pagination;
import net.northking.cctp.common.http.QueryByPage;
import net.northking.cctp.dw.db.dao.DwAtuPlanBatchDao;
import net.northking.cctp.dw.db.dao.DwAtuPlanInfoDao;
import net.northking.cctp.dw.db.dao.DwAtuPlanTaskDao;
import net.northking.cctp.dw.db.dao.DwAtuScriptInfoDao;
import net.northking.cctp.dw.db.service.UIDwAtuStatisticsService;
import net.northking.cctp.dw.dto.FirstExecuteInfoDto;
import net.northking.cctp.dw.dto.UIDwAtuScriptInfoQueryDto;
import net.northking.cctp.dw.dto.ValidScriptDTO;
import net.northking.cctp.dw.dto.atu.DwAtuScriptInfoDto;
import net.northking.cctp.dw.feign.CltTestTeamDto;
import net.northking.cctp.dw.feign.PlatformFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class UIDwAtuStatisticsServiceImpl implements UIDwAtuStatisticsService {
    @Autowired
    private DwAtuScriptInfoDao dwAtuScriptInfoDao;
    @Autowired
    private DwAtuPlanTaskDao dwAtuPlanTaskDao;
    @Autowired
    private DwAtuPlanBatchDao dwAtuPlanBatchDao;
    @Autowired
    private DwAtuPlanInfoDao dwAtuPlanInfoDao;
    @Autowired
    private EntityNameCache entityNameCache;
    @Autowired
    private PlatformFeignClient platformFeignClient;
    @Override
    public Pagination<DwAtuScriptInfoDto> pageQuery(QueryByPage<UIDwAtuScriptInfoQueryDto> queryByPage) {
        DefaultPagination<DwAtuScriptInfoDto> pagination = new DefaultPagination<>();
        if (StringUtils.hasText(queryByPage.getQuery().getStartTime())) {
            queryByPage.getQuery().setStartTime(queryByPage.getQuery().getStartTime()+" 00:00:00");
        }
        if (StringUtils.hasText(queryByPage.getQuery().getEndTime())) {
            queryByPage.getQuery().setEndTime(queryByPage.getQuery().getEndTime()+" 23:59:59");
        }
        if (queryByPage.getQuery().getIsPage()) {
            Page<DwAtuScriptInfoDto> page = PageMethod.startPage(queryByPage.getPageNo(),queryByPage.getPageSize());
            return buildPagination(pagination,queryByPage,page);
        } else {
            return buildPagination(pagination,queryByPage,null);
        }
    }

    /**
     * ATS获取UI自动化脚本编写明细信息
     *
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return UI自动化脚本编写明细信息
     */
    @Override
    public List<ValidScriptDTO> queryScriptDetail(String startTime, String endTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            if (StringUtils.hasText(startTime)) {
                sdf.parse(startTime);
            } else {
                startTime = null;
            }
            if (StringUtils.hasText(endTime)) {
                sdf.parse(endTime);
            } else {
                endTime = null;
            }
        } catch (ParseException e) {
            log.error("时间格式不正确");
            throw new InvalidException("时间格式不正确");
        }
        UIDwAtuScriptInfoQueryDto queryDto = new UIDwAtuScriptInfoQueryDto();
        queryDto.setStartTime(startTime);
        queryDto.setEndTime(endTime);
        List<DwAtuScriptInfoDto> dwAtuScriptInfoDtos = dwAtuScriptInfoDao.queryScriptDetail(queryDto);
        List<String> scriptIds = dwAtuScriptInfoDtos.stream().map(DwAtuScriptInfoDto::getScriptId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(scriptIds)) {
            return new ArrayList<>();
        }
        List<FirstExecuteInfoDto> firstExecuteInfoDtos = dwAtuPlanTaskDao.getFirstExecuteTimeByScriptIds(scriptIds);
        Map<String, FirstExecuteInfoDto> firstExecuteInfoDtoMap = firstExecuteInfoDtos.stream().collect(Collectors.toMap(FirstExecuteInfoDto::getScriptId, e -> e, (e1, e2) -> e1));
        List<ValidScriptDTO> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(dwAtuScriptInfoDtos)) {
            for (DwAtuScriptInfoDto dwAtuScriptInfoDto : dwAtuScriptInfoDtos) {
                FirstExecuteInfoDto firstExecuteInfoDto = firstExecuteInfoDtoMap.get(dwAtuScriptInfoDto.getScriptId());
                if (firstExecuteInfoDto == null || !StringUtils.hasText(firstExecuteInfoDto.getPlanId())) {
                    continue;
                }
                ValidScriptDTO dto = new ValidScriptDTO();
                dto.setProjectId(Long.valueOf(dwAtuScriptInfoDto.getProjectId()));
                dto.setFirstExecutionTime(firstExecuteInfoDto.getStartTime());
                dto.setPlanId(firstExecuteInfoDto.getPlanId());
                dto.setPlanName(firstExecuteInfoDto.getPlanName());
                dto.setScriptId(dwAtuScriptInfoDto.getScriptId());
                dto.setScriptCode(dwAtuScriptInfoDto.getScriptCode());
                dto.setScriptName(dwAtuScriptInfoDto.getScriptName());
                Long scriptManager = null;
                try {
                    scriptManager = Long.valueOf(dwAtuScriptInfoDto.getUserId());
                } catch (NumberFormatException e) {
                    log.error("用户Id类型转换异常", e);
                }
                dto.setScriptManager(scriptManager);
                dto.setScriptType(dwAtuScriptInfoDto.getScriptType().equals("5") ? 4 : 3 );

                result.add(dto);
            }
        }
        return result;
    }

    private DefaultPagination<DwAtuScriptInfoDto> buildPagination(DefaultPagination<DwAtuScriptInfoDto> pagination,QueryByPage<UIDwAtuScriptInfoQueryDto> queryByPage,Page<DwAtuScriptInfoDto> page) {
        List<DwAtuScriptInfoDto> dwAtuScriptInfoDtos = dwAtuScriptInfoDao.pageQuery(queryByPage.getQuery());
        if (!CollectionUtils.isEmpty(dwAtuScriptInfoDtos)) {
            dwAtuScriptInfoDtos.forEach(dwAtuScriptInfoDto -> {
                List<FirstExecuteInfoDto> firstExecuteInfoDtos = dwAtuPlanTaskDao.getFirstExecuteTime(dwAtuScriptInfoDto.getScriptId());
                dwAtuScriptInfoDto.setFirstExecutionTime(firstExecuteInfoDtos.get(0).getStartTime());
                String planId = dwAtuPlanBatchDao.getPlanId(firstExecuteInfoDtos.get(0).getBatchId());
                String planName = dwAtuPlanInfoDao.getPlanName(planId);
                dwAtuScriptInfoDto.setPlanName(planName);
                CltTestTeamDto cltTestTeamDto = platformFeignClient.getPlanTeamInfo(dwAtuScriptInfoDto.getUserId());
                if (cltTestTeamDto!=null) {
                    dwAtuScriptInfoDto.setTestGroup(cltTestTeamDto.getName());
                    if (StringUtils.hasText(cltTestTeamDto.getManagerId())) {
                        dwAtuScriptInfoDto.setTestGroupLeader(entityNameCache.translateById(EntityNameCatalog.MONSTER_USER,cltTestTeamDto.getManagerId()));
                    } else {
                        dwAtuScriptInfoDto.setTestGroupLeader("");
                    }
                } else {
                    dwAtuScriptInfoDto.setTestGroup("");
                    dwAtuScriptInfoDto.setTestGroupLeader("");
                }
            });
            pagination.setRecords(dwAtuScriptInfoDtos);

        } else {
            pagination.setRecords(new ArrayList<>());
        }
        if (queryByPage.getQuery().getIsPage()) {
            pagination.setPageNo(queryByPage.getPageNo());
            pagination.setPageSize(queryByPage.getPageSize());
            pagination.setRecordCount(page.getTotal());
        } else {
            pagination.setPageNo(1);
            pagination.setPageSize(10);
            pagination.setRecordCount(0);
        }
        return pagination;
    }
}
