package com.artfess.query.manager.impl;

import com.alibaba.fastjson.JSON;
import com.artfess.base.exception.ApplicationException;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.base.util.DataSourceUtil;
import com.artfess.base.util.DateUtils;
import com.artfess.base.util.HttpUtil;
import com.artfess.base.util.StringUtil;
import com.artfess.dataShare.util.Constants;
import com.artfess.query.dao.BizQueryResultConditionDao;
import com.artfess.query.manager.*;
import com.artfess.query.model.*;
import com.artfess.query.vo.ParamVo;
import com.artfess.query.vo.QueryParamVo;
import com.artfess.uc.api.impl.util.ContextUtil;
import com.artfess.uc.api.model.IUser;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 查询结果配置信息（BIZ_QUERY_RESULT_CONDITION） 服务实现类
 *
 * @company 阿特菲斯信息技术有限公司
 * @author wh
 * @since 2025-02-17
 */
@Slf4j
@Service
public class BizQueryResultConditionManagerImpl extends BaseManagerImpl<BizQueryResultConditionDao, BizQueryResultCondition> implements BizQueryResultConditionManager {

    @Resource
    JdbcTemplate template;

    @Resource
    BizQueryTagManager tagManager;

    @Resource
    BizQueryResultMainManager resultMainManager;

    @Resource
    BizQueryTagHistoryManager tagHistoryManager;
    @Resource
    BizQueryMyFollowManager myFollowManager;



    public Map<String,Object> queryDataList(QueryParamVo queryParamVo) throws Exception {
        BizQueryTag tag=tagManager.getById(queryParamVo.getTagId());
        if(null==tag){
            throw new ApplicationException("未查询导对应标签。");
        }
        JdbcTemplate jdbcTemplate = DataSourceUtil.getJdbcTempByDsAlias(tag.getDatasourcesAlias());
        //JdbcTemplate jdbcTemplate = DataSourceUtil.getJdbcTempByDsAlias(Constants.DWD_DATA_SOURCE_ALIAS);
        /*String mainTable="dw_dwd_enterprise_commercial_info";
        if("1".equals(queryParamVo.getType())){
            //改任人员主表
            mainTable="dw_dwd_enterprise_commercial_info";
        }*/
        String mainTable=queryParamVo.getTableName();
        //查询条件
        StringBuffer queryWhere=new StringBuffer("where ");
        //查询表条件
        StringBuffer sql=new StringBuffer("select t.* from ");
        sql.append(mainTable).append(" t ");

        List<ParamVo> queryParamVos = queryParamVo.getParamVoList();
        String searchContent = "";
        for(int i=0;i<queryParamVos.size();i++){
            ParamVo paramVo = queryParamVos.get(i);
            //String tableName=paramVo.getTableName();
            String field=paramVo.getField();
            String value=paramVo.getValue();
            if(field.equals(tag.getSearchFieldCode())){
                searchContent = value;
            }
            String con=paramVo.getCon();
            //String alias="t"+i;
            //sql.append(" left join ").append(tableName).append(" ").append(alias).append(" on ").append("t.ENTERPRISE_TYSHXYDM_ = ").append(alias).append(".ENTERPRISE_TYSHXYDM_");
            if(value.indexOf(",")==-1) {
                /*if("eq".equals(con)){
                    queryWhere.append(" ").append(alias).append(".").append(field).append(" = '").append(value).append("'");
                }else if("seem".equals(con)){
                    queryWhere.append(" ").append(alias).append(".").append(field).append(" like '%").append(value).append("%'");
                }else{
                    queryWhere.append(" ").append(alias).append(".").append(field).append(" = '").append(value).append("'");
                }*/
                if("eq".equals(con)){
                    if(queryWhere.toString().equals("where ")){
                        queryWhere.append(field).append(" = '").append(value).append("'");
                    }else{
                        queryWhere.append(" and ").append(field).append(" = '").append(value).append("'");
                    }

                }else if("seem".equals(con)){
                    if(queryWhere.toString().equals("where ")){
                        queryWhere.append(field).append(" like '%").append(value).append("%'");
                    }else{
                        queryWhere.append(" and ").append(field).append(" like '%").append(value).append("%'");
                    }

                }else{
                    if(queryWhere.toString().equals("where ")){
                        queryWhere.append(field).append(" = '").append(value).append("'");
                    }else{
                        queryWhere.append(" and ").append(field).append(" = '").append(value).append("'");
                    }
                }
            }else if("scope".equals(con)){
                String[] v=value.split(",");
                if(queryWhere.toString().equals("where ")){
                    queryWhere.append(field).append(" > ").append(v[0]).append(" and ").append(field).append(" < ").append(v[1]);
                }else{
                    queryWhere.append(" and ").append(field).append(" > ").append(v[0]).append(" and ").append(field).append(" < ").append(v[1]);
                }

            }else if("in".equals(con)){
                if(queryWhere.toString().equals("where ")){
                    queryWhere.append(field).append(" in ('").append(value.replace(",","','")).append("')");
                }else{
                    queryWhere.append(" and ").append(field).append(" in ('").append(value.replace(",","','")).append("')");
                }

            }
        }
        if(!"where ".equals(queryWhere.toString())) {
            sql.append(" ").append(queryWhere);
        }
        sql.append(" limit ").append((queryParamVo.getPageNo()-1)*queryParamVo.getPageSize()).append(" , ").append(queryParamVo.getPageSize());
        log.info(sql.toString());
        //搜索记录历史日志表
        IUser user= ContextUtil.getCurrentUser();
        QueryWrapper<BizQueryTagHistory> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("SEARCH_CONTENT_", searchContent);
        queryWrapper.eq("USER_ID_", user.getUserId());
        queryWrapper.eq("date(SEARCH_TIME_)", DateUtils.nowDate());
        queryWrapper.orderByDesc("SEARCH_TIME_");
        List<BizQueryTagHistory> tagHistoryList=tagHistoryManager.list(queryWrapper);
        if(CollectionUtils.isEmpty(tagHistoryList) && StringUtil.isNotEmpty(searchContent) ){
            BizQueryTagHistory tagHistory=new BizQueryTagHistory();
            tagHistory.setType(tag.getType());
            tagHistory.setUserId(user.getUserId());
            tagHistory.setTagId(tag.getId());
            tagHistory.setUserCard(user.getAccount());
            tagHistory.setUserName(user.getUsername());
            tagHistory.setUserPhone(user.getMobile());
            tagHistory.setSearchContent(searchContent);
            tagHistory.setSearchTime(LocalDateTime.now());
            HttpServletRequest request = HttpUtil.getRequest();
            tagHistory.setIpAddress(getIpAddress(request));
            tagHistoryManager.create(tagHistory);
        }else if(!CollectionUtils.isEmpty(tagHistoryList) ) {
            BizQueryTagHistory tagHistory = tagHistoryList.get(0);
            tagHistory.setSearchTime(LocalDateTime.now());
            HttpServletRequest request = HttpUtil.getRequest();
            tagHistory.setIpAddress(getIpAddress(request));
            tagHistoryManager.updateById(tagHistory);
        }
        Integer count = 0;
        List<Map<String,Object>> resultList = jdbcTemplate.queryForList(sql.toString());
        if(!CollectionUtils.isEmpty(resultList)){
            String countSQl = "select count(*) from "+mainTable+" "+queryWhere;
            count = jdbcTemplate.queryForObject(countSQl, Integer.class);

            QueryWrapper<BizQueryMyFollow> followWrapper = new QueryWrapper<>();
            followWrapper.eq("USER_ID_",user.getUserId());
            followWrapper.eq("TAG_ID_",tag.getId());
            List<BizQueryMyFollow> followList = this.myFollowManager.list(followWrapper);
            if(!CollectionUtils.isEmpty(followList)){
                for(Map<String,Object> map:resultList){
                    map.put("focus", 0);
                    for(BizQueryMyFollow follow:followList){
                        if(follow.getSearchContent().equals(map.get(tag.getSearchFieldCode()))){
                            map.put("focus", 1);
                            map.put("followId", follow.getId());
                            break;
                        }
                    }
                }
            }
        }
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("total",count);
        resultMap.put("data",resultList);
        return resultMap;
    }

    @Override
    public List<Map<String,Object>> queryDataById(String tagId,String tableName,String fieldName,String fieldValue) throws Exception{
        //JdbcTemplate jdbcTemplate = DataSourceUtil.getJdbcTempByDsAlias(Constants.DWD_DATA_SOURCE_ALIAS);
        BizQueryTag tag=tagManager.getById(tagId);
        JdbcTemplate jdbcTemplate = DataSourceUtil.getJdbcTempByDsAlias(tag.getDatasourcesAlias());

        StringBuffer sql=new StringBuffer("select * from ");
        //sql.append(tableName).append(" where ENTERPRISE_TYSHXYDM_ = ").append("'").append(id).append("'");
        sql.append(tableName).append(" where ").append(fieldName).append(" = ").append("'").append(fieldValue).append("'");
        return jdbcTemplate.queryForList(sql.toString());
    }



    //根据搜索标签查询详情页各个分类下面分类下的各表数据
    @Override
    public List<Map<String,Object>> queryGroupDataByTag(String tagId,String groupName, String fieldName,String fieldValue) throws Exception{
        Assert.hasText(tagId, "标签ID不能为空！");
        Assert.hasText(groupName, "分类不能为空！");
        Assert.hasText(fieldName, "关联字段的名称不能为空！");
        Assert.hasText(fieldValue, "关联字段的值不能为空！");

        QueryWrapper<BizQueryResultMain> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("TAG_ID_",tagId);
        queryWrapper.eq("GROUP_NAME_",groupName);
        queryWrapper.ne("SHOW_TYPE_", 3);
        queryWrapper.orderByAsc("SN_");
        List<BizQueryResultMain> resultMains= resultMainManager.list(queryWrapper);
        List<Map<String,Object>> resultList=new ArrayList<>();;
        for(BizQueryResultMain item : resultMains){
            Map<String,Object> result=new LinkedHashMap<>();
            String tableCode = item.getTableCode();
            String tableDesc = item.getTableDesc();
            StringBuffer sql=new StringBuffer();
            JdbcTemplate jdbcTemplate = DataSourceUtil.getJdbcTempByDsAlias(item.getDatasourcesAlias());
            sql.append(" select * from ").append(tableCode).append(" where ").append(fieldName).append(" = ").append("'").append(fieldValue).append("'");
            if(item.getShowType()==1){ //列表展示的时候需要分页
                sql.append(" limit ").append(0).append(" , ").append(10);
                StringBuffer countSql=new StringBuffer();
                countSql.append(" select count(*) from ").append(tableCode).append(" where ").append(fieldName).append(" = ").append("'").append(fieldValue).append("'");
                Integer count = jdbcTemplate.queryForObject(countSql.toString(), Integer.class);
                result.put("total",count);
                result.put("pageNo", 1);
                result.put("pageSize", 10);
            }else{
                sql.append(" limit 1 ");
            }
            List<Map<String, Object>> dataList = jdbcTemplate.queryForList(sql.toString());
            result.put("groupName",item.getGroupName());
            result.put("showType",item.getShowType());
            result.put("tableDesc",tableDesc);
            result.put("tableCode",tableCode);
            result.put("dataList",dataList);
            resultList.add(result);
        }
        return resultList;
    }

    @Override
    public Map<String,List<Map<String, Object>>> queryGroupCountByTag(String tagId, String fieldName, String fieldVal) throws Exception {
        Assert.hasText(tagId, "标签ID不能为空！");
        Assert.hasText(fieldName, "关联字段的名称不能为空！");
        Assert.hasText(fieldVal, "关联字段的值不能为空！");
        QueryWrapper<BizQueryResultMain> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("TAG_ID_",tagId);
        queryWrapper.ne("SHOW_TYPE_",3);
        queryWrapper.orderByAsc("SN_");
        List<BizQueryResultMain> mainList =this.resultMainManager.list(queryWrapper);
        if(CollectionUtils.isEmpty(mainList)){
            return null;
        }
        List<Map<String, Object>> resultList = new ArrayList<>();
        for(BizQueryResultMain main:mainList){
            StringBuffer sql=new StringBuffer();
            sql.append(" select '"+main.getGroupName()+"' groupName,'"+main.getTableDesc()+"' tableDesc,'"+main.getTableCode()+"' tableCode,'"+main.getSn()+"' sn, count(*) total ")
                    .append(" from ").append(main.getTableCode())
                    .append(" where ").append(fieldName).append(" = '").append(fieldVal).append("'");
            JdbcTemplate jdbcTemplate = DataSourceUtil.getJdbcTempByDsAlias(main.getDatasourcesAlias());
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql.toString());
            resultList.addAll(list);
        }
        if(CollectionUtils.isEmpty(resultList)){
            return null;
        }
        // 按照 groupName 分组
        Map<String, List<Map<String, Object>>> grouped = resultList.stream()
                .collect(Collectors.groupingBy(map -> (String) map.get("groupName")));

        // 对每个分组内的数据按照 sn 进行排序
        Map<String, List<Map<String, Object>>> sortedWithinGroup = grouped.entrySet().stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry -> entry.getValue().stream()
                                .sorted(Comparator.comparing(map -> (String) map.get("sn")))
                                .collect(Collectors.toList()),
                        (e1, e2) -> e1,
                        LinkedHashMap::new
                ));

        // 以每组的第一个对象的 sn 属性对分组进行排序
        Map<String, List<Map<String, Object>>> groupedAndSorted = sortedWithinGroup.entrySet().stream()
                .sorted(Comparator.comparing(entry -> (String) entry.getValue().get(0).get("sn")))
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (e1, e2) -> e1,
                        LinkedHashMap::new
                ));
        return groupedAndSorted;
    }

    public static String getIpAddress(HttpServletRequest request) {

        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        @SuppressWarnings("rawtypes")
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            System.err.println(key+"---------"+value);
        }
        return ip;
    }
}
