/*
 * Copyright (c) 京北方信息技术股份有限公司 Corporation 2021 . All rights reserved.
 *
 */
package net.northking.cctp.project.db.impl;

import com.alibaba.fastjson.JSONObject;
import com.hzbank.testteam.autotest.dependencies.authDependency.utils.RequestUtil;
import com.hzbank.testteam.autotest.dependencies.monsterDependency.dto.ProjectDTO;
import com.hzbank.testteam.autotest.dependencies.monsterDependency.dto.SystemDTO;
import net.northking.cctp.common.exception.PlatformRuntimeException;
import net.northking.cctp.common.saas.cache.SaaSTenantCache;
import net.northking.cctp.common.security.authentication.NKSecurityContext;
import net.northking.cctp.common.util.DateUtil;
import net.northking.cctp.project.bus.feign.HzBankFeign;
import net.northking.cctp.project.config.TaskSyncConfig;
import net.northking.cctp.project.constants.ProjectAppError;
import net.northking.cctp.project.db.entity.CpProject;
import net.northking.cctp.project.db.service.CpProjectService;
import net.northking.cctp.project.dto.project.ProjectSimpleInfo;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.*;


/**
 * 系统基本信息表
 *
 * <p>文件内容由代码生成器产生，请不要手动修改！ <br>
 * createdate:  2021-09-09 01:37:28  <br>
 *
 * @author: maven-cctp-plugin  <br>
 * @since: 1.0 <br>
 */
@Service
@ConditionalOnMissingBean(name = "CpProjectServiceImpl")
public class CpProjectServiceImpl implements CpProjectService {
    private static final Logger logger = LoggerFactory.getLogger(CpProjectServiceImpl.class);

    @Autowired
    private SaaSTenantCache tenantCache;

    @Autowired
    private HzBankFeign hzBankFeign;

    @Autowired
    private TaskSyncConfig taskSyncConfig;

    public CpProject createEntity() {
        return new CpProject();
    }


    @Override
    public List<ProjectSimpleInfo> queryAllProjectByTenant() throws ParseException {
        List<Long> allProjectIdList = new ArrayList<>();
        // 普通用户查询权限下系统，管理员查询全部系统
        if (!RequestUtil.getAdminFlag()) {
            allProjectIdList = hzBankFeign.getProjectIdsByUserId(Long.parseLong(NKSecurityContext.getUserId()));
        } else {
            List<SystemDTO> preResultList = this.hzBankFeign.getActiveProjectByIds(new ArrayList<>());
            Set<Long> set = new HashSet<>();
            for (SystemDTO systemDTO : preResultList) {
                if (systemDTO.getId()!=null) {
                    set.add(systemDTO.getId());
                }
            }
            allProjectIdList = new ArrayList<>(set);
        }
        logger.info("用户操作员权限,{},系统列表size,{}",RequestUtil.getAdminFlag(),allProjectIdList.size());
        if (!allProjectIdList.isEmpty()) {
            List<SystemDTO> resultList = this.hzBankFeign.getActiveProjectByIds(allProjectIdList);
            List<ProjectSimpleInfo> projectSimpleInfoList = Lists.newArrayList();
            for (SystemDTO systemDTO : resultList){
                ProjectSimpleInfo projectSimpleInfo = new ProjectSimpleInfo();
                projectSimpleInfo.setId(String.valueOf(systemDTO.getId()));
                projectSimpleInfo.setParentId("TOP");
                projectSimpleInfo.setRootId(String.valueOf(systemDTO.getId()));
                projectSimpleInfo.setChildren(null);
                projectSimpleInfo.setLeaf(true);
                projectSimpleInfo.setTenantId(taskSyncConfig.getTenantId());
                projectSimpleInfo.setCode(systemDTO.getSysCode());
                projectSimpleInfo.setName(systemDTO.getName());
                projectSimpleInfo.setStartTime(new Date());
                projectSimpleInfo.setProductionTime(DateUtil.parse("2099-01-01"));
                projectSimpleInfo.setStatus(systemDTO.getStatus());
                projectSimpleInfoList.add(projectSimpleInfo);
            }
            return projectSimpleInfoList;
        }
        return new ArrayList<>();
    }

    @Override
    public List<ProjectSimpleInfo> queryProByDevice(String tenantId) throws ParseException {

        List<SystemDTO> preResultList = this.hzBankFeign.getActiveProjectByIds(new ArrayList<>());
        Set<Long> set = new HashSet<>();
        for (SystemDTO systemDTO : preResultList) {
            if (systemDTO.getId()!=null) {
                set.add(systemDTO.getId());
            }
        }
        List<Long> allProjectIdList = new ArrayList<>(set);
        if (!allProjectIdList.isEmpty()) {
            List<SystemDTO> resultList = this.hzBankFeign.getActiveProjectByIds(allProjectIdList);
            List<ProjectSimpleInfo> projectSimpleInfoList = Lists.newArrayList();
            for (SystemDTO systemDTO : resultList){
                ProjectSimpleInfo projectSimpleInfo = new ProjectSimpleInfo();
                projectSimpleInfo.setId(String.valueOf(systemDTO.getId()));
                projectSimpleInfo.setParentId("TOP");
                projectSimpleInfo.setRootId(String.valueOf(systemDTO.getId()));
                projectSimpleInfo.setChildren(null);
                projectSimpleInfo.setLeaf(true);
                projectSimpleInfo.setTenantId(NKSecurityContext.getTenantId());
                projectSimpleInfo.setCode(systemDTO.getSysCode());
                projectSimpleInfo.setName(systemDTO.getName());
                projectSimpleInfo.setStartTime(new Date());
                projectSimpleInfo.setProductionTime(DateUtil.parse("2099-01-01"));
                projectSimpleInfo.setStatus(systemDTO.getStatus());
                projectSimpleInfoList.add(projectSimpleInfo);
            }
            return projectSimpleInfoList;
        }
        return new ArrayList<>();
    }

    @Override
    public ProjectSimpleInfo getProjectInfo(CpProject project) {
        if (project == null || StringUtils.isBlank(project.getId())) {
            throw new PlatformRuntimeException(ProjectAppError.PROJECT_ID_IS_EMPTY);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id",Long.parseLong(project.getId()));
        jsonObject.put("deleted",1);
        SystemDTO systemDTO = hzBankFeign.selectOneByMap(jsonObject);
        if (systemDTO != null) {
            ProjectSimpleInfo projectSimpleInfo = new ProjectSimpleInfo();
            projectSimpleInfo.setId(project.getId());
            projectSimpleInfo.setTenantId(taskSyncConfig.getTenantId());
            projectSimpleInfo.setLeaf(true);
            projectSimpleInfo.setName(systemDTO.getName());
            projectSimpleInfo.setRootId(String.valueOf(systemDTO.getId()));
            projectSimpleInfo.setParentId("TOP");
            return projectSimpleInfo;
        }
        return null;
    }

    @Override
    public List<ProjectDTO> queryProjectWolfProjectList() {
        return hzBankFeign.getProjectOptionList();
    }

    @Override
    public String queryProCode(String proId) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id",Long.parseLong(proId));
        SystemDTO systemDTO = hzBankFeign.selectOneByMap(jsonObject);
        if (systemDTO != null) {
            return systemDTO.getCode();
        }
        return null;
    }

}

