package com.malk.aiwei.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.malk.aiwei.service.GZT_PN;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.dingtalk.DDConf;
import com.malk.server.dingtalk.DDR_New;
import com.malk.service.aliwork.YDClient;
import com.malk.service.dingtalk.DDClient;
import com.malk.service.dingtalk.DDService;
import com.malk.utils.UtilDateTime;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@EnableScheduling
@Service
@Slf4j
public class GZT_PNImpl implements GZT_PN {

    private Map portal_cache = new HashMap();
    @Autowired
    private YDClient ydClient;

    @Override
    public List<Map> getPortalList(String section) {
        return _portalList(section);
    }

    @Override
    public void getDataList() {
        try {

            portal_cache = new HashMap();
            getPortalList("派能资讯");
            getPortalList("能量派送");
            getPortalList("人资资讯");
            getPortalList("内部资讯");

        } catch (Exception e) {
            // 记录错误信息
            e.printStackTrace();
        }
    }

    private List<Map> _portalList(String type) {
        List<Map> pList = UtilMap.getList(portal_cache, type);
        try {
            if (pList.isEmpty()) {
                List<Map> dataList = (List<Map>) ydClient.queryData(YDParam.builder()
                        .appType("APP_OM7HTYCXYQYCKJ046D9V")
                        .systemToken("BN766KC1CS9Q2LJQDAKIN82VVUHT2J07ALF3M7R2")
                        .formUuid("FORM-918FE77C2E8248069B7CA497C6B2E4C6XD4B")
                        .pageSize(5)
                        .searchFieldJson(JSONObject.toJSONString(UtilMap.map("selectField_m17kv4an", type)))
                        .build(), YDConf.FORM_QUERY.retrieve_search_form).getData();

                dataList.sort(Comparator.comparingInt(item -> UtilMap.getInt(item, "numberField_m3s6swzt"))); // 排序
                pList = dataList.stream().map(item -> {
                    Map formData = UtilMap.getMap(item, "formData");

                    Map row = UtilMap.map("title, source, link", UtilMap.getString(formData, "textField_m17kv4aq"), UtilMap.getString(formData, "textField_m17kv4as"), UtilMap.getString(formData, "textField_m17kv4at"));
                    long date = UtilMap.getLong(formData, "dateField_m17kv4ar");
                    if (date > 0L) {
                        row.put("dateTime", UtilDateTime.format(new Date(date), "yyyy-MM-dd HH:mm"));
                    }
                    // 图片免登处理
                    String image = UtilMap.getString(formData, "imageField_m1abjxl0");
                    if (StringUtils.isNotBlank(image)) {
                        List<Map> attas = (List<Map>) JSON.parse(image);
                        row.put("image", convertTemporaryUrl_PN(UtilMap.getString(attas.get(0), "url")));
                        Object image1 = row.get("image");
                        //   System.out.println("image=========" + UtilMap.getString(attas.get(0), "url"));
//                    System.out.println("image1========="+image1);
                    }
                    return row;
                }).collect(Collectors.toList());
                portal_cache.put(type, pList);
            }
        } catch (Exception e) {

        }
        log.info("type: {},list:{}", type, pList);
        return pList;
    }

    @Autowired
    private DDClient ddClient;

    /**
     * 派能
     */
    public String convertTemporaryUrl_PN(String url) {
        String ddapptonken = ddClient.getAccessToken("dingmpxci8bolc3jpima", "Y_k3jpKNHbGvb9S9As2Y61ZaUFNglm7SCqquIkcowLBRoc4ZpH7DG0ZTn8LyHMwI");
        Map param = new HashMap();
        param.put("systemToken", "BN766KC1CS9Q2LJQDAKIN82VVUHT2J07ALF3M7R2");
        param.put("userId", YDConf.PUB_ACCOUNT);
        param.put("fileUrl", url);          // URL在param上时, 需要编码 [UtilHttp已经做了编码] - URLEncoder.encode(url, "UTF-8")
        param.put("timeout", 60000);      // 默认1分钟, 最大24小时 [毫秒]
        // System.out.println("ssss:"+(String) DDR_New.doGet("https://api.dingtalk.com/v1.0/yida/apps/temporaryUrls/APP_G951QZ32AUJNJUE4G127" , ddClient.initTokenHeader_PN(), param).getResult());
        return (String) DDR_New.doGet("https://api.dingtalk.com/v1.0/yida/apps/temporaryUrls/APP_OM7HTYCXYQYCKJ046D9V", DDConf.initTokenHeader(ddapptonken), param).getResult();
    }

    @Autowired
    private DDService ddService;

    @Override
    public Map register(Map<String, String> data) {
        String ddapptonken = ddClient.getAccessToken("dingmpxci8bolc3jpima", "Y_k3jpKNHbGvb9S9As2Y61ZaUFNglm7SCqquIkcowLBRoc4ZpH7DG0ZTn8LyHMwI");
        return ddService.registerJsApi(ddapptonken, data.get("url"), data.get("nonceStr"));
    }
}
