package org.jeecg.modules.stm.wb.manage.service.impl;

import org.jeecg.modules.stm.wb.manage.entity.WbCompanyInfo;
import org.jeecg.modules.stm.wb.manage.mapper.WbCompanyInfoMapper;
import org.jeecg.modules.stm.wb.manage.service.IWbCompanyInfoService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

/**
 * @Description: wb_company_info
 * @Author: jeecg-boot
 * @Date:   2024-03-09
 * @Version: V1.0
 */
@Service
public class WbCompanyInfoServiceImpl extends ServiceImpl<WbCompanyInfoMapper, WbCompanyInfo> implements IWbCompanyInfoService {

    public Boolean checkCMMI(WbCompanyInfo wbCompanyInfo) {
        String strUrl = "https://www.cmmiinstitute.com/pars?StateId=033eec20-8497-4ff0-bf7b-c48fdcd3d67d&PageNumber=1&Handler=ApplyFilters";

        try {
            URL url = new URL(strUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            setURLConnProperty(connection,"POST");
            String cookies = getCookie(url,"UTF8");
            String requestBody ="Filters.OrganizationSearch=&Filters.AppraisalSearch=60510&Filters.ModelViewOrDomain=" +
                    "&Filters.CountryIsoCode=&Filters.AchievedLevel=&Filters.AppraisalYear=" +
                    "&__RequestVerificationToken="+cookies;
            connection.setDoOutput(true);
            connection.setDoInput(true);
            //connection.setRequestProperty("Cookie",cookies);
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(requestBody.getBytes());
            outputStream.flush();
            outputStream.close();
            int statusCode = connection.getResponseCode();

            InputStream inputStream = statusCode == 200 ? connection.getInputStream() : connection.getErrorStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            inputStream.close();
            connection.disconnect();
            System.out.println(response.toString());

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //conn.disconnect();
        }
        //System.out.println(document.html());
        return null;
    }

    public String getCookie(URL url,String charset) {
        try {
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setInstanceFollowRedirects(false);
            conn.setRequestMethod("GET");
            conn.connect();
            String cookie= "";
            Map<String, List<String>> respone_headers=conn.getHeaderFields();
            for (String key : respone_headers.keySet()) {
                if(key!=null &&key.equals("Set-Cookie")) {
                    System.err.println(respone_headers.get(key));
                    List<String> string = respone_headers.get(key);
                    StringBuilder builder = new StringBuilder();
                    for (String str : string) {
                        if(str.startsWith(".AspNetCore.Session")){
                            int s1 = str.indexOf("=");
                            int s2 = str.indexOf(";");
                            cookie = str.substring(s1+1,s2);
                            break;
                        }
                    }
                    //cookie=builder.toString();
                    break;
                }
            }
            conn.disconnect();
            return cookie;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private  void setURLConnProperty(HttpURLConnection conn,String method) throws Exception{
        try {
            conn.setRequestMethod(method);
            conn.setConnectTimeout(50000);
            conn.setReadTimeout(100000);
            conn.setRequestProperty("Referer", "https://www.cmmiinstitute.com/pars?StateId=033eec20-8497-4ff0-bf7b-c48fdcd3d67d&PageNumber=1&Handler=ApplyFilters");
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36");
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
}