package httpclient

import (
	"bytes"
	"crm-api/pkg/lfshook"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"time"

	"gopkg.in/ini.v1"
)

func Get(url string) *http.Response {
	if url == "" {
		lfshook.NewLogger().Errorf("http get url is empty")
		return nil
	}
	// 若认证存在，添加到 get url
	// if configs.ConfigGlobal.Key != "" {
	// 	url = fmt.Sprintf("%s&key=%s", url, configs.ConfigGlobal.Key)
	// }

	lfshook.NewLogger().Infof("get %s", url)
	client := http.Client{
		Timeout: 10 * time.Second,
	}
	resp, err := client.Get(url)
	if err != nil {
		lfshook.NewLogger().Errorf("Error: unable to connect to - %s\n", err.Error())
	} else if resp.Status != "200 OK" {
		lfshook.NewLogger().Errorf("Error: non 200 status from - %s\n", resp.Status)
	}
	return resp
}

func BasicAuthGet(url string) *http.Response {
	if url == "" {
		lfshook.NewLogger().Errorf("http get url is empty")
		return nil
	}

	lfshook.NewLogger().Infof("get %s", url)
	client := http.Client{
		Timeout: 10 * time.Second,
	}
	// resp, err := client.Get(url)
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil
	}

	// 读取vtiger配置文件中的用户密码
	// confPath := "/etc/asterisk/vtiger_api.conf"
	confPath := "/etc/asterisk/crm_api.conf"
	cfg, err := ini.Load(confPath)
	if err != nil {
		lfshook.NewLogger().Error(err)
		return nil
	}
	BasicAuthUser := cfg.Section("general").Key("vtigerBasicAuthUser").String()
	BasicAuthPWD := cfg.Section("general").Key("vtigerBasicAuthPWD").String()
	if BasicAuthUser == "" || BasicAuthPWD == "" {
		lfshook.NewLogger().Error("/etc/asterisk/crm_api.conf not set BasicAuthUser or BasicAuthPWD")
		return nil
	}
	// 认证
	// res.SetBasicAuth("juncheng.du@zycoo.com", "8DJ3O28MCZ4sPAk5")
	// req.SetBasicAuth(configs.ConfigGlobal.BasicAuthUser, configs.ConfigGlobal.BasicAuthPWD)
	req.SetBasicAuth(BasicAuthUser, BasicAuthPWD)

	resp, err := client.Do(req)
	if err != nil {
		lfshook.NewLogger().Errorf("Error: unable to connect to - %s\n", err.Error())
	} else if resp.Status != "200 OK" {
		lfshook.NewLogger().Errorf("Error: non 200 status from - %s\n", resp.Status)
	}

	return resp
}

func ApiKeyGet(url string) *http.Response {
	if url == "" {
		lfshook.NewLogger().Errorf("http get url is empty")
		return nil
	}

	lfshook.NewLogger().Infof("get %s", url)
	client := http.Client{
		Timeout: 10 * time.Second,
	}
	// resp, err := client.Get(url)
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil
	}

	// 读取vtiger配置文件中的用户密码
	// confPath := "/etc/asterisk/vtiger_api.conf"
	confPath := "/etc/asterisk/crm_api.conf"
	cfg, err := ini.Load(confPath)
	if err != nil {
		lfshook.NewLogger().Error(err)
		return nil
	}
	ApiKey := cfg.Section("general").Key("vtigerApiKey").String()
	ApiKeyValue := cfg.Section("general").Key("vtigerApiKeyValue").String()
	if ApiKey == "" || ApiKeyValue == "" {
		lfshook.NewLogger().Error("/etc/asterisk/crm_api.conf not set ApiKey or ApiKeyValue")
		return nil
	}
	// 认证
	// req.Header.Set(configs.ConfigGlobal.ApiKey, configs.ConfigGlobal.ApiKeyValue)
	req.Header.Set(ApiKey, ApiKeyValue)

	resp, err := client.Do(req)
	if err != nil {
		lfshook.NewLogger().Errorf("Error: unable to connect to - %s\n", err.Error())
	} else if resp.Status != "200 OK" {
		lfshook.NewLogger().Errorf("Error: non 200 status from - %s\n", resp.Status)
	} else if resp.Status == "200 OK" {
		lfshook.NewLogger().Errorf("Error: 200 ok status from - %s\n", resp.Status)
	}

	// 读取请求后的响应
	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("读取请求后的响应时发生错误:", err)
		return nil
	}
	// 打印请求后的响应
	fmt.Printf("data = %+v\n", string(data))

	return resp
}

func ZohoGet(url string) *http.Response {
	if url == "" {
		lfshook.NewLogger().Errorf("http get url is empty")
		return nil
	}

	client := http.Client{
		Timeout: 10 * time.Second,
	}
	// resp, err := client.Get(url)
	req, err := http.NewRequest("POST", url, nil)
	if err != nil {
		return nil
	}

	// 读取vtiger配置文件中的用户密码
	// confPath := "/etc/asterisk/vtiger_api.conf"
	confPath := "/etc/asterisk/crm_api.conf"
	cfg, err := ini.Load(confPath)
	if err != nil {
		lfshook.NewLogger().Error(err)
		return nil
	}
	AccessToken := cfg.Section("general").Key("zohoAccessToken").String()
	if AccessToken == "" {
		lfshook.NewLogger().Error("/etc/asterisk/crm_api.conf not set zohoAccessToken")
		return nil
	}
	// 认证
	req.Header.Set("Authorization", "Bearer "+AccessToken)
	lfshook.NewLogger().Errorf("11111111111111%s", AccessToken)
	lfshook.NewLogger().Errorf("22222222222222%s", req.Header)
	lfshook.NewLogger().Infof("request %+v", req)
	resp, err := client.Do(req)
	if err != nil {
		lfshook.NewLogger().Errorf("Error: unable to connect to - %s\n", err.Error())
	} else if resp.Status != "200 OK" {
		lfshook.NewLogger().Errorf("Error: non 200 status from - %s\n", resp.Status)
	} else if resp.Status == "200 OK" {
		lfshook.NewLogger().Infof(" 200 ok status from - %s\n", resp.Status)
	}
	// if resp.Body != nil {
	// 	// 读取请求后的响应
	// 	data, err := ioutil.ReadAll(resp.Body)
	// 	if err != nil {
	// 		fmt.Println("读取请求后的响应时发生错误:", err)
	// 		return nil
	// 	}
	// 	// 打印请求后的响应
	// 	fmt.Printf("data = %+v\n", string(data))

	// } else {
	// 	fmt.Println("指针为空")
	// 	lfshook.NewLogger().Error("Error: resp.Body is nil")
	// }
	return resp
}

func Post(event interface{}, url string) *http.Response {
	eventByte, err := json.Marshal(event)
	if err != nil {
		lfshook.NewLogger().Errorf("event marshall error %+v", err)
		return nil
	}
	data := bytes.NewBuffer([]byte(eventByte))
	client := http.Client{
		Timeout: 20 * time.Second,
	}
	resp, err := client.Post(url, "application/json", data)
	if err != nil {
		lfshook.NewLogger().Errorf("Error: unable to connect to - %s\n", err.Error())
	} else if resp.Status != "200 OK" {
		lfshook.NewLogger().Errorf("Error: non 200 status from - %s\n, event: %+v", resp.Status, event)
	}
	return resp
}
