/*
 * @description:计量支付接口相关操作
 * @Author: CP
 * @Date: 2020-09-03 16:57:56
 * @FilePath: \construction_management\lib\cld.go
 */
package lib

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"

	"go.mod/web/viewmodels"
)

type Cld struct {
	AuthUrl     string
	CategoryUrl string
	Token       string
}

type Result struct {
	// viewmodels.StaffCld []string
	Code int                  `form:"code" json:"code" `
	Data viewmodels.ResultCld `form:"data" json:"data" `
	Msg  string               `form:"msg" json:"msg" `
}

//创建项目用户service
func NewCld() *Cld {
	return &Cld{
		AuthUrl:     "http://cld.smartcost.com.cn/cm/auth",
		CategoryUrl: "http://cld.com/cm/category",
		// AuthUrl: "http://cld.com/cm/auth",
		Token: "sc@ConS!tru@ct*88",
	}
}

// 验证CLD账号的登陆密码
func (c *Cld) LoginValid(loginData viewmodels.StaffCld) (*Result, error) {
	// TODO 生成令牌和提交时间
	//const [encryptToken, postTime] = this.generateCLDToken();
	client := &http.Client{}
	// 构成数据
	data := url.Values{}
	data.Set("staffName", loginData.StaffName)
	data.Set("password", loginData.Password)
	parameter := strings.NewReader(data.Encode())

	reqest, err := http.NewRequest("POST", c.AuthUrl, parameter)
	if err != nil {
		return nil, errors.New("CLD网络出现问题")
	}
	reqest.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	// 发送请求
	response, err := client.Do(reqest)
	if err != nil {
		return nil, errors.New("CLD网络出现问题")
	}
	if response.StatusCode != 200 {
		return nil, errors.New("请求CLD发送错误")
	}

	body, _ := ioutil.ReadAll(response.Body)
	// fmt.Println(string(body))
	result := Result{}
	err = json.Unmarshal(body, &result)
	if err != nil {
		return nil, errors.New("解析数据错误")
	}

	return &result, nil
}

// 获得cld办事处和员工 列表
func (c *Cld) GetList(categoryId string) (map[string]interface{}, error) {

	data := url.Values{}
	parameter := strings.NewReader(data.Encode())

	url := fmt.Sprintf("%s?categoryId=%s", c.CategoryUrl, categoryId)

	return c.cldRequest("GET", url, parameter)
}

func (c *Cld) cldRequest(Method string, url string, parameter *strings.Reader) (map[string]interface{}, error) {

	client := &http.Client{}
	reqest, err := http.NewRequest(Method, url, parameter)
	if err != nil {
		return nil, errors.New("CLD网络出现问题")
	}
	reqest.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	// 发送请求
	response, err := client.Do(reqest)
	if err != nil {
		return nil, errors.New("CLD网络出现问题")
	}
	if response.StatusCode != 200 {
		return nil, errors.New("请求CLD发送错误")
	}
	body, _ := ioutil.ReadAll(response.Body)

	result := make(map[string]interface{})
	err = json.Unmarshal(body, &result)
	if err != nil {
		return nil, errors.New("解析数据错误")
	}

	return result, nil
}
