package org.jeecg.modules.okki.externallink.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.okki.externallink.service.IOkkiExternalLinkService;
import org.jeecg.modules.okki.utils.HttpClientUtils;
import org.jeecg.modules.okki.externallink.entity.OkkiExternalLink;
import org.jeecg.modules.okki.externallink.mapper.OkkiExternalLinkMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * @Description: SEO数据外链
 * @Author: jeecg-boot
 * @Date: 2024-05-09
 * @Version: V1.0
 */
@Slf4j
@Service
public class OkkiExternalLinkServiceImpl extends ServiceImpl<OkkiExternalLinkMapper, OkkiExternalLink> implements IOkkiExternalLinkService {

    @Value("${OKKI.BASE_URL}")
    private String URL;

    @Value("${OKKI.CLIENT_SECRET}")
    private String CLIENT_SECRET;

    @Resource
    private OkkiExternalLinkMapper okkiExternalLinkMapper;

    @Override
    public boolean changeStatus(OkkiExternalLink okkiExternalLink) {
        OkkiExternalLink okkiExternalLink1 = okkiExternalLinkMapper.selectById(okkiExternalLink.getId());
        // 请求okki平台接口
        Map<String, String> query = new TreeMap<>();
        query.put("sign_method", "hmac-md5");
        query.put("timestamp", String.valueOf(System.currentTimeMillis()));
        query.put("site_id", String.valueOf(okkiExternalLink1.getSiteId()));
        query.put("method", "external_link");
        okkiExternalLink.setStatus(1);
        Map<String, Object> postData = new HashMap<>();
        try {
            String queryStr = HttpClientUtils.buildQueryString(query);
            postData.put("id", okkiExternalLink1.getExternalLinkId());
            postData.put("title", okkiExternalLink1.getTitle());
            postData.put("url", okkiExternalLink1.getUrl());
            if (okkiExternalLink1.getUrl() != null) {
                postData.put("pic", okkiExternalLink1.getPic());
            }
            if (okkiExternalLink1.getContent() != null) {
                postData.put("content", okkiExternalLink1.getContent());
            }
            if (okkiExternalLink1.getReportScore() != null) {
                postData.put("report_score", okkiExternalLink1.getReportScore());
            }
            if (okkiExternalLink1.getReportLink() != null) {
                postData.put("report_link", okkiExternalLink1.getReportLink());
            }
            postData.put("enable_flag", okkiExternalLink1.getEnableFlag());
            // 时间转换
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            postData.put("addtime", sdf.format(okkiExternalLink1.getCreateTime()));
            postData.put("edittime", sdf.format(okkiExternalLink1.getUpdateTime()));

            String body = HttpClientUtils.toJsonString(postData);
            String signStr = queryStr + body;
            query.put("signature", HttpClientUtils.generateHmacMD5(signStr, CLIENT_SECRET));
            String okkiUrl = URL + "?" + HttpClientUtils.buildQueryString(query);
            log.info("url:" + okkiUrl + ",body:" + body);
            String res = HttpClientUtils.doPost(okkiUrl, body);
            log.info(res);
            // {"code":0,"msg":"success","now":"2024-05-06 15:34:54","data":[]}
            JSONObject jsonObject = JSONObject.parseObject(res);
            if (jsonObject.get("code").equals(0)) {
                int result = okkiExternalLinkMapper.updateById(okkiExternalLink);
                if (result == 0) {
                    return false;
                } else {
                    return true;
                }
            } else {
                throw new RuntimeException(jsonObject.get("msg").toString());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 发送外链请求
     *
     * @param siteId
     * @return
     */
    @Override
    public boolean sendExternalLinkRequest(String siteId, String title, String url) {
        boolean result = false;
        // 请求okki平台接口
        Map<String, String> query = new TreeMap<>();
        query.put("sign_method", "hmac-md5");
        query.put("timestamp", String.valueOf(System.currentTimeMillis()));
        query.put("site_id", siteId);
        query.put("method", "external_link");
        Map<String, Object> postData = new HashMap<>();
        try {
            DefaultIdentifierGenerator dig = new DefaultIdentifierGenerator();
            long resultId = dig.nextId(new Object());

            String queryStr = HttpClientUtils.buildQueryString(query);
            postData.put("id", resultId);
            postData.put("title", title);
            postData.put("url", url);
            postData.put("enable_flag", 1);

            String body = HttpClientUtils.toJsonString(postData);
            String signStr = queryStr + body;
            query.put("signature", HttpClientUtils.generateHmacMD5(signStr, CLIENT_SECRET));
            String okkiUrl = URL + "?" + HttpClientUtils.buildQueryString(query);
            log.info("url:" + okkiUrl + ",body:" + body);
            String res = HttpClientUtils.doPost(okkiUrl, body);
            log.info(res);
            // {"code":0,"msg":"success","now":"2024-05-06 15:34:54","data":[]}
            JSONObject jsonObject = JSONObject.parseObject(res);
            if (jsonObject.get("code").equals(0)) {
                result = true;
            } else {
                throw new RuntimeException(jsonObject.get("msg").toString());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return result;
    }
}
