package com.hz.pm.api.projectdeclared.manage;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import com.ningdatech.basic.util.CollUtils;
import com.hz.pm.api.common.model.constant.BizConst;
import com.hz.pm.api.common.util.CryptUtils;
import com.hz.pm.api.common.util.HttpUtil;
import com.hz.pm.api.irs.manage.AppIrsManage;
import com.hz.pm.api.irs.model.dto.ApiApplyDTO;
import com.hz.pm.api.irs.model.dto.ForwardDTO;
import com.hz.pm.api.irs.utils.RefreshTokenUtil;
import com.hz.pm.api.projectdeclared.model.entity.IrsApplication;
import com.hz.pm.api.projectdeclared.model.entity.NdPiotTasks;
import com.hz.pm.api.projectdeclared.model.vo.IrsApplicationVO;
import com.hz.pm.api.projectdeclared.model.vo.PiotTasksVO;
import com.hz.pm.api.projectdeclared.service.INdPiotTasksService;
import com.hz.pm.api.projectdeclared.service.IrsApplicationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Classname IrsManage
 * @Description
 * @Date 2023/3/1 14:48
 * @Author PoffyZhang
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class IrsManage {

    @Value("${irs.is-search-app}")
    private Boolean isSearchApp;

    private final IrsApplicationService irsApplicationService;

    private final INdPiotTasksService piotTasksService;

    private final AppIrsManage appIrsManage;


    public List<IrsApplicationVO> applicationList(String areaCode) {
        //不请求IRS
        if(!isSearchApp) {
            List<IrsApplication> list = irsApplicationService.list();
            if(CollUtil.isEmpty(list)){
                return Collections.emptyList();
            }
            return CollUtils.convert(list,app -> BeanUtil.copyProperties(app,IrsApplicationVO.class));
        }

        try {
            ApiApplyDTO apiApplay = new ApiApplyDTO();
            apiApplay.setAreaCode(areaCode);
            JSONArray jsonArray = appIrsManage.searchApps(apiApplay);
            if(CollUtil.isNotEmpty(jsonArray)){
                return jsonArray.stream().map(apply -> {
                    JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(apply));
                    IrsApplicationVO vo = new IrsApplicationVO();
                    vo.setApplicationCode(jsonObject.getString("appId"));
                    vo.setApplicationName(jsonObject.getString("name"));
                    return vo;
                }).collect(Collectors.toList());
            }
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        return Collections.emptyList();
    }

    public List<PiotTasksVO> listPiotTasks() {
        List<NdPiotTasks> list = piotTasksService.list();
        if(CollUtil.isEmpty(list)){
            return Collections.emptyList();
        }
        return CollUtils.convert(list,task -> BeanUtil.copyProperties(task,PiotTasksVO.class));
    }

    public String getCreditCode() throws NoSuchAlgorithmException {
        String appSecret = RefreshTokenUtil.refrshByAppScret();
        String appkey = "8fb070a1f1194b2ebffdc6f596bb8a96";
        String dataName = "丽水市大数据";
        long timestamp = System.currentTimeMillis();
        String sign = CryptUtils.MD5Encode(appkey + appSecret + timestamp);
        String url = "https://interface.ls.local/a/api/shared/1689239219101?data_name=" + dataName + "&appKey=" + appkey +
                "&sign=" + sign + "&requestTime=" + timestamp;
        RestTemplate restTemplate = new RestTemplate(HttpUtil.generateHttpRequestFactory());
        log.info("url:" + url);
        ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);
        log.info(forEntity.getBody());
        return forEntity.getBody();
    }

    /**
     * 转发IRS请求
     * @param dto
     * @return
     */
    public String forward(ForwardDTO dto) {
        try{
            String url = dto.getUrl();
            url = url + "?" +  asUrlParams(dto.getData());
            log.info("url :{}",url);
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);
            log.info(forEntity.getBody());
            return forEntity.getBody();
        }catch (Exception e){
            log.error("e:" + e);
        }
        return BizConst.OP_FAIL;
    }

    public static String asUrlParams(Map<String, Object> source){
        return Joiner.on("&")
                // 用指定符号代替空值,key 或者value 为null都会被替换
                .useForNull("")
                .withKeyValueSeparator("=")
                .join(source);
    }
}
