package com.izouma.nineth.service;

import com.izouma.nineth.domain.Project;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.ProjectRepo;
import com.izouma.nineth.utils.ApplicationContextUtil;
import com.izouma.nineth.utils.IPUtils;
import com.izouma.nineth.utils.JpaUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Service
@AllArgsConstructor
@Slf4j
public class ProjectService {

    private ProjectRepo projectRepo;

    /**
     * 列表数据
     * @param pageQuery
     * @return
     */
    public Page<Project> all(PageQuery pageQuery) {
        return projectRepo.findAll(JpaUtils.toSpecification(pageQuery, Project.class),
                JpaUtils.toPageRequest(pageQuery));
    }


    /**
     * 修改项目信息
     * @param project
     * @return
     */
    public Project save(Project project){
        project.setEnName(project.getEnName().trim());
        project.setChName(project.getChName().trim());
        project.setFrontAddr(project.getFrontAddr().trim());
        if(project.isEdit()){
            Project oldProject = projectRepo.findById(project.getId()).orElseThrow(new BusinessException("记录不存在"));
            BeanUtils.copyProperties(project, oldProject, new String[]{"del", "createdAt", "createdBy"});
            return projectRepo.save(oldProject);
        }else{
            Project oldProject = projectRepo.findById(project.getId()).orElse(null);
            if(oldProject != null){
                throw new BusinessException("项目ID记录重复，请重新设置");
            }
            return projectRepo.save(project);
        }

    }

    /**
     * 删除项目
     * @param project
     */
    public void delete(Project project){
        projectRepo.delete(project);
    }


    /**
     * 识别项目
     * @return
     */
    private Project identifyProject(){
        Project currentProject = null;
        HttpServletRequest request = ApplicationContextUtil.currentRequest();
        if(request != null){
            String fromIp = IPUtils.getIpAddr(request);
            String referer = request.getHeader("referer");
            String userAgent = request.getHeader("User-Agent");
            String projectIdStr = request.getHeader("projectId");
            Iterable<Project> iterable = projectRepo.findAll();
            List<Project> list = new ArrayList<>();
            iterable.forEach(item -> {
                list.add(item);
            });

            if (StringUtils.isNotBlank(projectIdStr)){
                Long projectId = Long.parseLong(projectIdStr);
                for (Project project : list) {
                    if (projectId.equals(project.getId())){
                        currentProject = project;
                        break;
                    }
                }
                return currentProject;
            }

            if(referer == null){
                log.info("项目识别来源,ip地址：{}, 引用页：{}, 用户代理：{}" , fromIp, referer, userAgent);
            }

            if(StringUtils.isNotEmpty(referer)){
                for(Project project : list){
                    String frontAddr = StringUtils.removeEnd(project.getFrontAddr(), "/");
                    frontAddr = StringUtils.removeEnd(frontAddr, "/home");
                    frontAddr = StringUtils.removeStart(frontAddr, "http://");
                    frontAddr = StringUtils.removeStart(frontAddr, "https://");
                    if(referer.contains(frontAddr)){
                        //获得项目信息
                        currentProject = project;
                        break;
                    }
                }
            }

            //无法识别时取默认
            if(currentProject == null && list.size() == 1){
                currentProject = list.get(0);
            }

        }

        return currentProject;
    }

    /**
     * 获取用户名前缀
     * @return
     */
    public String getUserPrefix(){
        String prefix = "";
        Project project = identifyProject();
        if(project != null){
            prefix = project.getUserPrefix();
        }

        if(prefix == null){
            prefix = "";
        }

        return prefix;
    }

    /**
     * 识别获取项目ID
     * @return
     */
    public int getProjectId(){
        int projectId = -1;
        Project project = identifyProject();
        if(project != null){
            projectId = project.getId().intValue();
        }

        if(projectId == -1){
            throw new BusinessException("无法识别用户请求平台");
        }

        return projectId;
    }

    

}
