package com.ruoyi.project.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.IpUtils;
import com.ruoyi.project.domain.TrsResultsLog;
import com.ruoyi.project.domain.TrsWordResults;
import com.ruoyi.project.mapper.TrsResultsLogMapper;
import com.ruoyi.project.mapper.TrsWordResultsMapper;
import com.ruoyi.project.service.ITrsWordResultsService;
import okhttp3.*;
import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

import static com.ruoyi.common.utils.ShiroUtils.getSysUser;


/**
 * 字典工具类
 * 
 * @author ruoyi
 */
@Component
public class TrsUtils
{
    @Autowired
    private TrsResultsLogMapper trsResultsLogMapper;

    @Autowired
    private TrsWordResultsMapper trsWordResultsMapper;


    @Autowired
    private OkHttpClient okHttpClient;

//    private static final String TEXT_URL = "http://xiaosi.trs.cn/ckm-open/api/open/JsonBody/ckm-collate/proxy/collate/text";
    private static final String TEXT_URL = "http://10.14.252.29:7001/ckm-open/api/open/JsonBody/ckm-collate/proxy/collate/text";
//    private static final String LOGIN_URL = "http://xiaosi.trs.cn/ckm-open/api/login";
    private static final String LOGIN_URL = "http://10.14.252.29:7001/ckm-open/api/login";
    private static final String USERNAME = "nmg.zzqzf";
    private static final String CODE = "$2a$10$JEojjudeVgp967LbbROBCu2dpTFZJN/mNmkjkaYWCuRsUX6s2qSUK";

    public TrsResultsLog getJiaodui(String content, String title, String type, HttpServletRequest request){

        content = Jsoup.parse(content).text();
        Long logId = null;
        //审校日志
        TrsResultsLog trsResultsLog = new TrsResultsLog();
        trsResultsLog.setContent(content);
        trsResultsLog.setTitle(title);
        trsResultsLog.setTime(new Date());
        trsResultsLog.setOperuser(getSysUser().getLoginName());
        trsResultsLog.setIp(IpUtils.getIpAddr(request));
        trsResultsLog.setDeptId(getSysUser().getDeptId());
        trsResultsLog.setUserId(getSysUser().getUserId());
        trsResultsLog.setStatus("无结果");
        trsResultsLogMapper.insertTrsResultsLog(trsResultsLog);
        logId =trsResultsLog.getId();

        getText(content, logId);

        return trsResultsLogMapper.selectTrsResultsLogById(logId);
    }


    /**
     * 执行登录操作
     * @return 登录成功返回token，失败返回null
     */
    public String login() {
        // 构建JSON请求体
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("username", USERNAME);
        jsonBody.put("code", CODE);
        // 创建请求体
        RequestBody requestBody = RequestBody.create(
                MediaType.parse("application/json"),
                jsonBody.toString()
        );
        // 构建请求
        Request request = new Request.Builder()
                .url(LOGIN_URL)
                .post(requestBody)
                .build();
        try (Response response = okHttpClient.newCall(request).execute()) {
            int responseCode = response.code();
            if (responseCode == 200) {
                // 登录成功，获取响应数据
                String responseData = response.body().string();
                // 解析响应数据，获取token
                JSONObject jsonResponse = JSONObject.parseObject(responseData);
                return jsonResponse.getString("token");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public void getText(String content, Long logId) {
        // 构建JSON请求体
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("mode", "0");
        jsonBody.put("text", content);
        // 创建请求体
        RequestBody requestBody = RequestBody.create(
                MediaType.parse("application/json"),
                jsonBody.toString()
        );
        // 构建请求
        Request request = new Request.Builder()
                .url(TEXT_URL)
                .post(requestBody)
                .addHeader("authorization", "Bearer " + login())
//                .addHeader("authorization", "Bearer eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjRmYjU2MzFhOWFiNDkyN2NmNTE0ZWE4MTYxM2MzMTVhIn0.S54dcxwhUdPOKrQDGDEiDN4ywTuJg0hA-FKtXcQBeJlG4-D3nWE9V3UpJMmGmNRMGU53ZvPE7m6Y63ViNIo6Qg")
                .build();
        try (Response response = okHttpClient.newCall(request).execute()) {
            int responseCode = response.code();
            if (responseCode == 200) {
                // 登录成功，获取响应数据
                String responseData = response.body().string();
                // 解析响应数据，获取token
                JSONArray jsonResponse = JSONObject.parseObject(responseData).getJSONArray("data");
                boolean flag = true;
                for (int i = 0; i < jsonResponse.size(); i++) {
                    JSONObject errorMap = jsonResponse.getJSONObject(i);
                    TrsWordResults r = new TrsWordResults();
                    r.setLogId(logId);
                    r.setWrongWord(errorMap.getString("errorWord"));
                    r.setCorrectWord(errorMap.getString("collateWord"));
                    r.setSitename("common");
                    r.setTime(new Date());
                    r.setErrorType(errorMap.getString("errorTypeInfo"));
                    r.setSource(errorMap.getString("reference"));
                    r.setContent(errorMap.getString("sentence"));
                    r.setStartpos(errorMap.getInteger("startPos"));
                    r.setEndpos(errorMap.getInteger("endPos"));
                    trsWordResultsMapper.insertTrsWordResults(r);
                    if(flag){
                        //审校日志
                        TrsResultsLog trsResultsLog = new TrsResultsLog();
                        trsResultsLog.setId(logId);
                        trsResultsLog.setStatus("有结果");
                        trsResultsLog.setErrortype(errorMap.getString("errorTypeInfo"));
                        trsResultsLogMapper.updateTrsResultsLog(trsResultsLog);
                        if(null!=errorMap.getString("errorTypeInfo")&&!"".equals(errorMap.getString("errorTypeInfo"))){
                            flag = false;
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
