package com.yeejoin.amos.boot.module.statistcs.biz.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.common.api.enums.UnitTypeEnum;
import com.yeejoin.amos.boot.module.statistics.api.mapper.EnterpriseBizMapper;
import com.yeejoin.amos.boot.module.ymt.api.dto.TzBaseEnterpriseInfoDto;
import com.yeejoin.amos.boot.module.ymt.api.entity.PageParam;
import com.yeejoin.amos.boot.module.ymt.api.mapper.TzBaseEnterpriseInfoMapper;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;

import java.util.*;

/**
 * @author Administrator
 */
@Service
public class EnterpriseBizServiceImpl {

    private RedisUtils redisUtils;

    private StCommonServiceImpl stCommonService;

    private TzBaseEnterpriseInfoMapper tzBaseEnterpriseInfoMapper;

    private EnterpriseBizMapper enterpriseBizMapper;

    private RestHighLevelClient restHighLevelClient;


    private Logger logger = LoggerFactory.getLogger(EnterpriseBizServiceImpl.class);

    public EnterpriseBizServiceImpl(RedisUtils redisUtils, StCommonServiceImpl stCommonService,
                                    TzBaseEnterpriseInfoMapper tzBaseEnterpriseInfoMapper, EnterpriseBizMapper enterpriseBizMapper,
                                    RestHighLevelClient restHighLevelClient) {
        this.redisUtils = redisUtils;
        this.stCommonService = stCommonService;
        this.tzBaseEnterpriseInfoMapper = tzBaseEnterpriseInfoMapper;
        this.enterpriseBizMapper = enterpriseBizMapper;
        this.restHighLevelClient = restHighLevelClient;
    }

    public IPage<TzBaseEnterpriseInfoDto> page(PageParam pageParam, TzBaseEnterpriseInfoDto tzBaseEnterpriseInfoDto) {
        List<String> orgCodeList = new ArrayList<>();
        if (tzBaseEnterpriseInfoDto.getSuperviseKey() != null) {
            FeignClientResult<CompanyModel> result = Privilege.companyClient
                    .seleteOne(Long.valueOf(tzBaseEnterpriseInfoDto.getSuperviseKey()));
            if (result.getResult() != null) {
                tzBaseEnterpriseInfoDto.setSuperviseOrgCode(result.getResult().getOrgCode());
            }
        }
        Page<TzBaseEnterpriseInfoDto> page = new Page<>(pageParam.getCurrent(), pageParam.getSize());
        List<JSONObject> companyType1 = this.getCompanyType();
        if (!ValidationUtil.isEmpty(companyType1)) {
            for (JSONObject jsonObject : companyType1) {
                String orgCode = jsonObject.getString("orgCode");
                if (!ValidationUtil.isEmpty(orgCode)) {
                    orgCodeList.add(orgCode);
                }
            }
        }

        if (tzBaseEnterpriseInfoDto.getCityCode() != null) {
            String orgCode = stCommonService.getAndSetOrgCode(tzBaseEnterpriseInfoDto.getCityCode());
            if (orgCode == null) {
                return page;
            }
            orgCodeList.add(orgCode);
        }

        List<String> unitTypeList = new ArrayList<>();
        unitTypeList.add(tzBaseEnterpriseInfoDto.getUnitType());
        if (tzBaseEnterpriseInfoDto.getUnitType().equals(UnitTypeEnum.SYDW.getName())) {
            unitTypeList.add(UnitTypeEnum.GRZT.getName());
        }

        if(tzBaseEnterpriseInfoDto.getUnitType().contains(UnitTypeEnum.JYJCJG.getName())){
            if(!ObjectUtils.isEmpty(tzBaseEnterpriseInfoDto.getJyjcStatus())){
                String jyjcStatus = tzBaseEnterpriseInfoDto.getJyjcStatus();
                String[] array = jyjcStatus.split("-");
                tzBaseEnterpriseInfoDto.setJyjcStatus(array[0]);
                if(array.length > 1){
                    tzBaseEnterpriseInfoDto.setJyjcType(array[1]);
                }
            }
        }


        IPage<TzBaseEnterpriseInfoDto> tzBaseEnterpriseInfoDtoIPage = tzBaseEnterpriseInfoMapper.pageList2(page, tzBaseEnterpriseInfoDto, orgCodeList, unitTypeList);
        if (ValidationUtil.isEmpty(tzBaseEnterpriseInfoDtoIPage.getRecords())) {
            logger.info("查询到的数据为空");
            return tzBaseEnterpriseInfoDtoIPage;
        }

        if (tzBaseEnterpriseInfoDto.getUnitType().contains(UnitTypeEnum.CZDW.getName())) {
            SearchRequest searchRequest = new SearchRequest("idx_biz_view_jg_all");
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

            // 构建查询条件
            searchSourceBuilder.query(
                    QueryBuilders.boolQuery()
                            .must(QueryBuilders.termQuery("EQU_CATEGORY_CODE", "2300"))
                            // 只统计已纳管设备
                            .must(QueryBuilders.termQuery("IS_INTO_MANAGEMENT", Boolean.TRUE))
                            // 按照管辖机构区域信息模糊查询
                            .must(QueryBuilders.wildcardQuery("ORG_BRANCH_CODE.keyword", QueryParser.escape(orgCodeList.get(0)) + "*"))
            );
            TermsAggregationBuilder aggregation = AggregationBuilders.terms("USE_UNIT_CREDIT_CODE").field("USE_UNIT_CREDIT_CODE.keyword").size(10);
            searchSourceBuilder.aggregation(aggregation);
            searchRequest.source(searchSourceBuilder);
            try {
                // 执行搜索并获取响应
                SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
                // 处理聚合结果
                // 这里只是打印出聚合的名称和桶的数量，你需要根据自己的需求来处理这些数据
                Terms terms = searchResponse.getAggregations().get("USE_UNIT_CREDIT_CODE");
                List<Map<String, Object>> dataList = new ArrayList<>();
                for (Terms.Bucket bucket : terms.getBuckets()) {
                    tzBaseEnterpriseInfoDtoIPage.getRecords().stream().filter(dto -> dto.getUseUnitCode().equals(bucket.getKeyAsString())).forEach(newDto -> {
                        newDto.setGasCount(String.valueOf(bucket.getDocCount()));
                    });
                }
            } catch (Exception e) {
                logger.error("查询机构：{}下的气瓶数量失败，错误信息：{}", orgCodeList.get(0), e);
            }
        }
        return tzBaseEnterpriseInfoDtoIPage;
    }

    /**
     * 获取当前登录人单位类型
     *
     * @return
     */

    public List<JSONObject> getCompanyType() {


        ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        List<CompanyModel> companys = reginParams.getUserModel().getCompanys();

        List<JSONObject> objectList = new ArrayList<>();
        for (CompanyModel company : companys) {
            JSONObject object = new JSONObject();
            object.put("level", company.getLevel());
            object.put("orgCode", company.getOrgCode());
            object.put("companyCode", company.getCompanyCode());
            objectList.add(object);
        }
        return objectList;
    }
}
