package com.xxl.job.executor.service.impl;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxl.job.executor.entity.LeaderMsg;
import com.xxl.job.executor.mapper.LeaderMsgMapper;
import com.xxl.job.executor.service.LeaderMsgService;
import com.xxl.job.executor.util.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class LeaderMsgServiceImpl extends ServiceImpl<LeaderMsgMapper, LeaderMsg> implements LeaderMsgService {

    @Value("${rmw.app.code:PC42ce3bfa4980a9}")
    private String appCode;

    public List<LeaderMsg> getLeaderMsgInfo(String fid,int typeId,String lastItem){
        String msgs = getLeaderMsgs(fid,typeId,lastItem);
        JSONObject result=JSONObject.parseObject(msgs);
        List<LeaderMsg> leaderMsgs = JSONObject.parseArray(result.getJSONObject("resultData").getString("data"), LeaderMsg.class);
        return leaderMsgs;
    }



    public String  getLeaderMsgs(String fid, int typeId, String lastItem){
        String domain="http://liuyan.people.com.cn";
        String url="/v1/threads/list/df";
//        String param="{\"fid\":"+fid+"}";
        String param="{\"fid\":\""+fid+"\",\"showUnAnswer\":1,\"typeId\":"+typeId+",\"lastItem\":\""+lastItem+"\",\"position\":\"0\",\"rows\":10,\"orderType\":2}";

        HashMap<String,Object> bodymap=new HashMap<>();
        bodymap.put("appCode",appCode);
        bodymap.put("param",param);
        bodymap.put("signature",getSignature(url,param));
        bodymap.put("token","");
        String bodydata= JSONObject.toJSONString(bodymap);
        String result = HttpUtil.createPost(domain+url).body(bodydata).execute().body();
        return result;
    }

    /**
     * 获取 Signature
     * @param url
     * @param param
     * @return
     */
    private String getSignature(String url,String param){
        return SecureUtil.md5(url+param+SecureUtil.md5(appCode).substring(0,16));
    }
}
