package com.hdkj.lt.job.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hdkj.lt.base.exception.BusinessException;
import com.hdkj.lt.core.bizms.modle.po.DwdShbDsFeederBase;
import com.hdkj.lt.core.sys.service.DwdShbDsFeederBaseService;
import com.hdkj.lt.job.entity.convert.EntityConvertor;
import com.hdkj.lt.job.entity.po.FeederBaseRequest;
import com.hdkj.lt.job.entity.po.FeederBaseResponse;
import com.hdkj.lt.job.service.IDealFeederBaseService;
import com.hdkj.lt.utils.cache.RedisUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author rj
 * @date 2025/12/22 15:21
 * @description
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DealFeederBaseServiceImpl implements IDealFeederBaseService {

    @Qualifier("")
    private final RestTemplate restTemplate;

    private final RedisUtil redisUtil;

    private final DwdShbDsFeederBaseService dwdShbDsFeederBaseService;

    @Value("${feeder.cityCode}")
    private List<String> cityCode;

    @Override
    public void dealFeederBase() {
        log.info("开始同步FeederBase的cityCode:{}", cityCode);
//        List<String> cityCode = Arrays.asList("42408", "42401", "4240917", "42402", "424090101", "4241105", "42405", "42409", "4240701", "42404", "42407", "42403", "42414", "42410", "42411", "42412", "42413", "4240605", "BD69707EA19E4FED85C595AFB5D06720", "A2EE03079A3A4D66A4036953EFDF782C", "E9BA9EE1E2814073BF8680780695261D", "67095412C3444BCE8FB3A8026C923EC0", "B25F17410548424D9AD6904A5F96CE7C", "22EC118826294148A4BAFA893AEA1B4C", "6592E8EEB2504C189B7C2F16DD177A31", "983CB2BA4CBA4526A8BAC471468831BD", "62F1D16638414148AFAD6AAA47154C9A", "A543F8924BAC46DC8B519E367EFC6231", "0BD945EF20A2424987DD2B411E873870", "6C36C5CFA9F947DFA88FED2B42E2816A", "E67DB57A13F342E1B45D5AF3641BA85C", "3D3F836CBD9F406185B96D37D3A04E5C", "424030302", "424070111", "4241206", "4241202", "424091701", "424110505", "4240401", "42406", "424060111", "4240603", "4240601", "4240311", "424070108", "4241401", "424080103", "424120212", "4240705", "424090106", "4241303", "4241302", "424060402", "4240604", "4241009", "424140101", "424060404", "424060304", "424120601", "4240901");
        cityCode.forEach(code -> {
            FeederBaseResponse feederBaseResponse = getFeederBaseDate(1, 100, code);
            List<DwdShbDsFeederBase> dwdShbDsFeederBaseList = toDwdShbDsFeederBaseList(feederBaseResponse);
            Integer pages = feederBaseResponse.getResult().getDkx().getPages();
            log.info("地市编码:{},共{}条", code, feederBaseResponse.getResult().getDkx().getTotal());
            for (Integer i = 2; i <= pages; i++) {
                dwdShbDsFeederBaseList.addAll(toDwdShbDsFeederBaseList(getFeederBaseDate(i, 100, code)));
            }
            dwdShbDsFeederBaseService.remove(new LambdaUpdateWrapper<DwdShbDsFeederBase>().eq(DwdShbDsFeederBase::getCity, code));
            dwdShbDsFeederBaseService.saveBatch(dwdShbDsFeederBaseList);
            log.info("地市编码:{}，{}条同步完成", code, dwdShbDsFeederBaseList.size());
        });
    }

    private List<DwdShbDsFeederBase> toDwdShbDsFeederBaseList(FeederBaseResponse feederBaseResponse) {
        List<DwdShbDsFeederBase> result = new ArrayList<>();
        feederBaseResponse.getResult().getDkx().getRecords().forEach(i -> {
            FeederBaseResponse.ResultDTO.DkxDTO.RecordsDTO.ResourceDTO resource = i.getResource();
            FeederBaseResponse.ResultDTO.DkxDTO.RecordsDTO.AssetsDTO assets = i.getAssets().get(0);
            DwdShbDsFeederBase feederBase = EntityConvertor.INSTANCE.toDwdShbDsFeederBase(resource, assets);
            feederBase.setDelFlag("0");
            result.add(feederBase);
        });
        return result;
    }


    private FeederBaseResponse getFeederBaseDate(Integer current, Integer pageSize, String cityCode) {
        String token;
        try {
            token = this.getToken();
        } catch (JsonProcessingException e) {
            throw new BusinessException("获取电网业务资源部token失败");
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("x-token", token);
        FeederBaseRequest.ParamsDTO.FiltersDTO filtersDTO = new FeederBaseRequest.ParamsDTO.FiltersDTO();
        filtersDTO.setCompare("in");
        filtersDTO.setFieldName("city");
        filtersDTO.setFieldValue(cityCode);
        FeederBaseRequest.ParamsDTO paramsDTO = new FeederBaseRequest.ParamsDTO();
        paramsDTO.setSize(pageSize);
        paramsDTO.setCurrent(current);
        paramsDTO.setFilters(Collections.singletonList(filtersDTO));
        FeederBaseRequest feederBaseRequest = new FeederBaseRequest();
        feederBaseRequest.setDistribution(0);
        feederBaseRequest.setPsrType("dkx");
        feederBaseRequest.setParams(paramsDTO);
        HttpEntity<String> entity = new HttpEntity<>(JSON.toJSONString(feederBaseRequest), headers);
        String s = restTemplate.postForObject("http://25.55.59.21:30002/PSRCenter/queryServices/listPropertiesByFilters", entity, String.class);
        return JSON.parseObject(s, FeederBaseResponse.class);
    }

    private String getToken() throws JsonProcessingException {
        String token = (String) redisUtil.get("PSRCenter_Token");
        if (token == null) {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> entity = new HttpEntity<>("{\n" +
                    "\t\"client_id\": \"HB9f177012e6e14351847e451d5816be\",\n" +
                    "\t\"client_secret\": \"uJdJDL/L82uHT7JYlTTXyfUzsu/9zG6GQYATpGqOCjkWSadcX0we2wffjyTUYGsK\",\n" +
                    "\t\"grant_type\": \"client_credentials\"\n" +
                    "}", headers);
            String s = restTemplate.postForObject("http://25.55.59.21:30002/baseCenter/oauth2/accessToken", entity, String.class);
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode resp = objectMapper.readTree(s);
            String newToken = resp.get("access_token").asText();
            redisUtil.set("PSRCenter_Token", newToken, 7200);
            return newToken;
        }
        return token;
    }
}
