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

import cn.hutool.core.lang.Assert;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxl.job.executor.entity.json.LeaderInfoJson;
import com.xxl.job.executor.mapper.LeaderInfoJsonMapper;
import com.xxl.job.executor.service.LeaderInfoJsonService;
import com.xxl.job.executor.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

@Service
@Slf4j
public class LeaderInfoJsonServiceImpl extends ServiceImpl<LeaderInfoJsonMapper, LeaderInfoJson> implements LeaderInfoJsonService {

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

    @Autowired
    private LeaderInfoJsonMapper leaderInfoJsonMapper;

    @Override
    public Result getAllLeaderInfo(Integer fid) {
        try {
            getLeaderTreeInfo(fid);
            return Result.OK("同步成功");
        }catch (Exception e){
            log.error("递归获取领导人信息树发生异常：{}",e.getMessage());
            e.printStackTrace();
            return Result.ERROR("递归获取领导人信息树发生异常");
        }
    }
    /**
     * 递归获取领导人信息树
     * @param fid
     * @return
     */
    private void getLeaderTreeInfo(Integer fid){

        String result=sendLeaderTreeGet(fid);
        JSONObject jsonObject = JSONObject.parseObject(result);
        Assert.notNull(jsonObject,"获取领导人信息树接口返回值解析为NULL");
        int code=jsonObject.getInteger("code");
        if (code==0){
            List<LeaderInfoJson> infoJsons = JSONObject.parseArray(jsonObject.getString("data"), LeaderInfoJson.class);
            for (LeaderInfoJson info:infoJsons
            ) {
                if (leaderInfoJsonMapper.selectById(info.getFid())==null){
                    leaderInfoJsonMapper.insert(info);
                }
                //查看是否有子集
                if (info.getHasChild()==1){
                    getLeaderTreeInfo(info.getFid());
                }
            }
        }


    }

    /**
     * 发送POST请求获取树
     * @param fid
     * @return
     */
    private String sendLeaderTreeGet(Integer fid){
        //根据fid查询当前地区的领导人列表，18代表内蒙古自治区
        String domain="http://liuyan.people.com.cn";
        String url="/v1/forum/getChildForums";

        String param="{\"fid\":"+fid+"}";
        HashMap<String,Object> bodymap=new HashMap<>();
        bodymap.put("appCode",appCode);
        bodymap.put("token","");
        bodymap.put("signature",getSignature(url,param,appCode));
        bodymap.put("param",param);
        String bodydata= JSONObject.toJSONString(bodymap);
        //String result = HttpUtil.createPost(domain+url).body(bodydata).execute().body();
//        String result = HttpUtil.get(domain+url);
        String result = HttpUtil.get(domain+url,bodymap);
        Assert.notNull(result,"获取领导人信息树接口失败，返回NULL");
        return result;
    }

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