package business

/**
 * @Author: yk
 * @Date:   2024/01/30 15:04
 * @Desc: 外部接口实现，关于人员的接口
 */

import (
	"bytes"
	"digimetastaffsync/common"
	"digimetastaffsync/mydatabase"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"mime/multipart"
	"net/http"
	"sort"
	"strconv"
	"strings"
	"time"
)

var timeStep int

func init() {
	common.LoadConfig()
	//初始化时间步长时间步长
	timeStep = common.ConfigData.Timer
}

type FeatureResp struct {
	Status  int           `json:"status"`
	Message string        `json:"message"`
	Result  []interface{} `json:"result"`
}

type Staff struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	NickName string `json:"nickName"`
	Phone    string `json:"phone"`
	Type     int    `json:"type"`
	Url      string `json:"Url"`
	Image    string `json:"image"`
}

type Req struct {
	Code           string `json:"code"`
	StaffName      string `json:"staffName"`
	StaffType      int    `json:"staffType"`
	Gender         int    `json:"gender"`
	DevId          string `json:"devId"`
	FaceFeature    string `json:"faceFeature"`
	HireDate       string `json:"hireDate"`
	Birthday       string `json:"birthDate"`
	Phone          string `json:"phone"`
	StaffBase64Img string `json:"staffBase64Img"`
	DelFlag        int    `json:"status"`
	Modified       string `json:"modified"`
}

func RegStaff(param Req) (*common.Response, error) {
	url := common.ConfigData.PushDataUrl
	common.Info(common.GenLogLine()+"reg staff url:%s\n", url)
	method := "POST"

	param.DevId = common.ConfigData.DevId
	if len(param.StaffBase64Img) < 20000 {
		param.StaffBase64Img = ""
	}
	fmt.Printf("code:%s, staffName:%s, staffType:%d, gender:%d, devId:%s, faceFeature:%s, hireDate:%s, birthday:%s, phone:%s, DelFlag:%d, modified:%s\n",
		param.Code, param.StaffName, param.StaffType, param.Gender, param.DevId, param.FaceFeature, param.HireDate, param.Birthday, param.Phone, param.DelFlag, param.Modified)
	common.Info(common.GenLogLine()+"exec reg code:%s, staffName:%s, staffType:%d, gender:%d, devId:%s, faceFeature:%s, hireDate:%s, birthday:%s, phone:%s, DelFlag:%d, modified:%s\n",
		param.Code, param.StaffName, param.StaffType, param.Gender, param.DevId, param.FaceFeature, param.HireDate, param.Birthday, param.Phone, param.DelFlag, param.Modified)
	fmt.Println()
	jsonData, err := json.Marshal(param)
	if err != nil {
		fmt.Println("Error marshaling JSON:", err)
	}

	req, err := http.NewRequest(method, url, bytes.NewBuffer(jsonData))

	if err != nil {
		fmt.Errorf(common.GenLogLine()+"%s", err)
		common.Error(common.GenLogLine()+"%s", err)
		return nil, err
	}
	req.Header.Add("Content-Type", "application/json")

	client := &http.Client{}
	res, err := client.Do(req)
	if err != nil {
		fmt.Errorf(common.GenLogLine()+"%s", err)
		common.Error(common.GenLogLine()+"%s", err)
		return nil, err
	}
	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		fmt.Errorf(common.GenLogLine()+"%s", err)
		common.Error(common.GenLogLine()+"%s", err)
		return nil, err
	}
	var response *common.Response
	err = json.Unmarshal([]byte(string(body)), &response)
	if err != nil {
		fmt.Println("Error:", err)
		return nil, err
	}
	common.Error(common.GenLogLine()+"reg result %s", string(body))
	return response, nil
}

func RegOnlineStaff(param Req) error {
	url := common.ConfigData.PushDataUrl
	fmt.Printf("url:%s\n", url)
	method := "POST"

	param.DevId = common.ConfigData.DevId
	fmt.Printf("====param:%v\n", param)
	jsonData, err := json.Marshal(param)
	if err != nil {
		fmt.Println("Error marshaling JSON:", err)
	}

	req, err := http.NewRequest(method, url, bytes.NewBuffer(jsonData))

	if err != nil {
		fmt.Errorf(common.GenLogLine()+"%s", err)
		common.Error(common.GenLogLine()+"%s", err)
		return err
	}
	req.Header.Add("Content-Type", "application/json")

	client := &http.Client{}
	res, err := client.Do(req)
	if err != nil {
		fmt.Errorf(common.GenLogLine()+"%s", err)
		common.Error(common.GenLogLine()+"%s", err)
		return err
	}
	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		fmt.Errorf(common.GenLogLine()+"%s", err)
		common.Error(common.GenLogLine()+"%s", err)
		return err
	}
	fmt.Println(string(body))
	return nil
}

func HandleStaff(emp Req) error {
	if emp.StaffBase64Img != "" {
		//feature = FetchStaffFaceFeature(emp.StaffBase64Img)
		//emp.FaceFeature = LocalFetchStaffFaceFeature(emp.StaffBase64Img)
	}
	var sType int
	if emp.StaffType > 70 {
		sType = 4
	} else {
		sType = 5
	}
	emp.StaffType = sType
	var sDels = []int{5, 6, 7, 8}
	if common.AryContainInt(sDels, emp.DelFlag) {
		emp.DelFlag = 1
	} else {
		emp.DelFlag = 0
	}

	RegStaff(emp)
	return nil
}

// Fetch2 获取员工信息,模拟获取saas的人员数据
func Fetch2() []Staff {
	_token, err := common.GetToken()
	if err != nil {
		fmt.Errorf(common.GenLogLine()+"%s", err)
		common.Error(common.GenLogLine()+"%s", err)
		return nil
	}
	url := common.ConfigData.FetchDataUrl
	method := "GET"

	payload := strings.NewReader(``)

	client := &http.Client{}
	req, err := http.NewRequest(method, url, payload)

	if err != nil {
		fmt.Errorf(common.GenLogLine()+"%s", err)
		common.Error(common.GenLogLine()+"%s", err)
		return nil
	}
	token := fmt.Sprintf(`Bearer %s`, _token)
	req.Header.Add("Authorization", token)

	res, err := client.Do(req)
	if err != nil {
		fmt.Errorf(common.GenLogLine()+"%s", err)
		common.Error(common.GenLogLine()+"%s", err)
		return nil
	}
	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		fmt.Errorf(common.GenLogLine()+"%s", err)
		common.Error(common.GenLogLine()+"%s", err)
		return nil
	}

	var response *common.Response
	err = json.Unmarshal([]byte(string(body)), &response)
	if err != nil {
		fmt.Println("Error:", err)
	}

	var result []Staff

	switch v := response.Data["items"].(type) {
	case []interface{}:
		for _, item := range v {
			var s Staff
			//fmt.Println(item)
			if item.(map[string]interface{})["id"] != nil {
				s.ID = (item.(map[string]interface{})["id"]).(string)
			}
			if item.(map[string]interface{})["name"] != nil {
				s.Name = (item.(map[string]interface{})["name"]).(string)
			}
			if item.(map[string]interface{})["nickName"] != nil {
				s.NickName = (item.(map[string]interface{})["nickName"]).(string)
			}
			if item.(map[string]interface{})["phone"] != nil {
				s.Phone = (item.(map[string]interface{})["phone"]).(string)
			}
			if item.(map[string]interface{})["type"] != nil {
				s.Type = (item.(map[string]interface{})["type"]).(int)
			}
			if item.(map[string]interface{})["resource"] != nil {
				if item.(map[string]interface{})["resource"].(map[string]interface{})["url"] != nil {
					s.Url = (item.(map[string]interface{})["resource"].(map[string]interface{})["url"]).(string)
				}
			}
			result = append(result, s)
		}
	default:
		fmt.Println("无法解析的类型")
	}
	return result
}

// AbleSendCode 发送验证码
func AbleSendCode(phone string) string {

	url := common.ConfigData.CheckSendCodeUrl + "/" + phone
	method := "GET"

	payload := strings.NewReader("")

	client := &http.Client{}
	req, err := http.NewRequest(method, url, payload)

	if err != nil {
		fmt.Errorf(common.GenLogLine()+"%s", err)
		common.Error(common.GenLogLine()+"%s", err)
		return err.Error()
	}

	res, err := client.Do(req)
	if err != nil {
		fmt.Errorf(common.GenLogLine()+"%s", err)
		common.Error(common.GenLogLine()+"%s", err)
		return err.Error()
	}
	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		fmt.Errorf(common.GenLogLine()+"%s", err)
		common.Error(common.GenLogLine()+"%s", err)
		return err.Error()
	}
	fmt.Println("response Body:", string(body))

	return string(body)
}

func SendCode(phone string) string {

	ableSend := AbleSendCode(phone)
	fmt.Println("ableSend:", ableSend)
	url := common.ConfigData.SendCodeUrl
	method := "POST"

	payload := strings.NewReader(`{
    "phone":"` + phone + `"}`)

	client := &http.Client{}
	req, err := http.NewRequest(method, url, payload)

	if err != nil {
		fmt.Errorf(common.GenLogLine()+"%s", err)
		common.Error(common.GenLogLine()+"%s", err)
		return err.Error()
	}
	req.Header.Add("Content-Type", "application/json")

	res, err := client.Do(req)
	if err != nil {
		fmt.Errorf(common.GenLogLine()+"%s", err)
		common.Error(common.GenLogLine()+"%s", err)
		return err.Error()
	}
	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		fmt.Errorf(common.GenLogLine()+"%s", err)
		common.Error(common.GenLogLine()+"%s", err)
		return err.Error()
	}
	fmt.Println("response Body:", string(body))
	var result map[string]interface{}
	err = json.Unmarshal([]byte(string(body)), &result)
	if err != nil {
		fmt.Println("解析JSON出错：", err)
		return err.Error()
	}

	return string(body)
}

func ValidCode(phone string, code string) (string, error) {
	ableSend := AbleSendCode(phone)
	fmt.Println("ableSend:", ableSend)
	url := common.ConfigData.ValidCodeUrl + phone + "/" + code
	method := "GET"

	payload := strings.NewReader(``)

	client := &http.Client{}
	req, err := http.NewRequest(method, url, payload)

	res, err := client.Do(req)
	if err != nil {
		fmt.Errorf(common.GenLogLine()+"%s", err)
		common.Error(common.GenLogLine()+"%s", err)
		return "", err
	}
	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		fmt.Errorf(common.GenLogLine()+"%s", err)
		common.Error(common.GenLogLine()+"%s", err)
		return "", err
	}
	fmt.Println("response Body:", string(body))

	common.Error(common.GenLogLine()+"reg result %s", string(body))
	return string(body), nil
}

func StaffInfo(staffId string) (map[string]interface{}, error) {
	fmt.Println("staffId:", staffId)
	url := common.ConfigData.StaffInfoUrl
	method := "GET"
	token, err := common.GetToken()
	if err != nil {
		return nil, err
	}
	payload := &bytes.Buffer{}
	writer := multipart.NewWriter(payload)
	_ = writer.WriteField("id", staffId)
	err = writer.Close()
	if err != nil {
		fmt.Println(err)
		return nil, err
	}

	client := &http.Client{}
	req, err := http.NewRequest(method, url, payload)

	if err != nil {
		fmt.Println(err)
		return nil, err
	}
	req.Header.Add("Authorization", "Bearer "+token)

	req.Header.Set("Content-Type", writer.FormDataContentType())
	res, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return nil, err
	}
	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		fmt.Println(err)
		return nil, err
	}
	fmt.Println(string(body))
	var result map[string]interface{}
	err = json.Unmarshal([]byte(string(body)), &result)
	if err != nil {
		fmt.Println("解析JSON出错：", err)
		return nil, err
	}
	items, ok := result["data"].(map[string]interface{})["items"].([]interface{})
	if !ok {
		fmt.Println("无法获取items字段")
		return nil, err
	}

	if len(items) == 0 {
		return nil, errors.New("未找到员工信息")
	}
	firstItem := items[0].(map[string]interface{})

	common.Error(common.GenLogLine()+"info result %v", firstItem)
	return firstItem, nil
}

func MgrLogin(userName string, password string) string {
	url := common.ConfigData.MgrLoginUrl
	fmt.Println("url:", url)
	enterpriseName := common.ConfigData.EnterpriseName
	method := "POST"

	payload := strings.NewReader(`{
    "enterpriseName":"` + enterpriseName + `",
	"userName":"` + userName + `",
	"password":"` + password + `"}`)

	client := &http.Client{}
	req, err := http.NewRequest(method, url, payload)

	if err != nil {
		fmt.Errorf(common.GenLogLine()+"%s", err)
		common.Error(common.GenLogLine()+"%s", err)
		return err.Error()
	}
	req.Header.Add("Content-Type", "application/json")

	res, err := client.Do(req)
	if err != nil {
		fmt.Errorf(common.GenLogLine()+"%s", err)
		common.Error(common.GenLogLine()+"%s", err)
		return err.Error()
	}
	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		fmt.Errorf(common.GenLogLine()+"%s", err)
		common.Error(common.GenLogLine()+"%s", err)
		return err.Error()
	}
	fmt.Println("response Body:", string(body))

	return string(body)
}

func PhoneLogin(phone string) (map[string]interface{}, error) {
	url := common.ConfigData.PhoneLoginUrl
	method := "POST"

	payload := strings.NewReader(`{
    "phone":"` + phone + `"}`)

	client := &http.Client{}
	req, _ := http.NewRequest(method, url, payload)

	req.Header.Add("Content-Type", "application/json")

	res, err := client.Do(req)
	if err != nil {
		fmt.Errorf(common.GenLogLine()+"%s", err)
		common.Error(common.GenLogLine()+"%s", err)
		return nil, err
	}
	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		fmt.Errorf(common.GenLogLine()+"%s", err)
		common.Error(common.GenLogLine()+"%s", err)
		return nil, err
	}
	fmt.Println("response Body:", string(body))
	var result map[string]interface{}
	err = json.Unmarshal([]byte(string(body)), &result)
	if err != nil {
		fmt.Println("解析JSON出错：", err)
		return nil, err
	}

	return result, nil
}

func Fetch() []Req {
	url := common.ConfigData.FetchData2Url
	method := "POST"

	payload := strings.NewReader("appId=dfwycustomer2u8&ygbh")

	client := &http.Client{}
	req, err := http.NewRequest(method, url, payload)

	if err != nil {
		fmt.Errorf(common.GenLogLine()+"%s", err)
		common.Error(common.GenLogLine()+"%s", err)
		return nil
	}
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

	res, err := client.Do(req)
	if err != nil {
		fmt.Errorf(common.GenLogLine()+"%s", err)
		common.Error(common.GenLogLine()+"%s", err)
		return nil
	}
	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		fmt.Errorf(common.GenLogLine()+"%s", err)
		common.Error(common.GenLogLine()+"%s", err)
		return nil
	}

	var response *common.Resp
	err = json.Unmarshal([]byte(string(body)), &response)
	if err != nil {
		fmt.Println("Error:", err)
	}

	var result []Req
	fmt.Printf("====%#v====datassss\n", response)

	for _, item := range response.Data {
		var s Req
		//fmt.Println(item)
		if item.(map[string]interface{})["workcode"] != nil {
			s.Code = (item.(map[string]interface{})["workcode"]).(string)
		}
		if item.(map[string]interface{})["name"] != nil {
			s.StaffName = (item.(map[string]interface{})["name"]).(string)
		}
		if item.(map[string]interface{})["mobile"] != nil {
			s.Phone = (item.(map[string]interface{})["mobile"]).(string)
		}
		if item.(map[string]interface{})["level"] != nil {
			s.StaffType, _ = strconv.Atoi((item.(map[string]interface{})["level"]).(string))
		}
		if item.(map[string]interface{})["birthday"] != nil {
			s.Birthday = (item.(map[string]interface{})["birthday"]).(string)
		}
		if item.(map[string]interface{})["companystartdate"] != nil {
			s.HireDate = (item.(map[string]interface{})["companystartdate"]).(string)
		}
		if item.(map[string]interface{})["status"] != nil {
			s.DelFlag, _ = strconv.Atoi((item.(map[string]interface{})["status"]).(string))
		}
		if item.(map[string]interface{})["image"] != nil {
			s.StaffBase64Img = (item.(map[string]interface{})["image"]).(string)
		}
		if item.(map[string]interface{})["modified"] != nil {
			s.Modified = (item.(map[string]interface{})["modified"]).(string)
		}

		result = append(result, s)
	}

	if len(result) > 0 {
		sort.Slice(result, func(i, j int) bool {
			a, err := time.Parse("2006-01-02 15:04:05", result[i].Modified)
			if err != nil {
				common.Error(common.GenLogLine() + err.Error())
			}
			b, err2 := time.Parse("2006-01-02 15:04:05", result[j].Modified)
			if err2 != nil {
				common.Error(common.GenLogLine() + err2.Error())
			}
			return b.Before(a)
		})

	}

	return result
}

func FetchStaffImage(ygbh string) string {

	url := common.ConfigData.FetchData2Url
	method := "POST"

	payload := strings.NewReader("appId=dfwycustomer2u8&ygbh=" + fmt.Sprintf("%s", ygbh))

	client := &http.Client{}
	req, err := http.NewRequest(method, url, payload)

	if err != nil {
		fmt.Errorf(common.GenLogLine()+"%s", err)
		common.Error(common.GenLogLine()+"%s", err)
		return ""
	}
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	res, _ := client.Do(req)

	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		fmt.Errorf(common.GenLogLine()+"%s", err)
		common.Error(common.GenLogLine()+"%s", err)
		return ""
	}

	var response *common.Resp
	err = json.Unmarshal([]byte(string(body)), &response)
	if err != nil {
		fmt.Println("Error:", err)
	}

	var result string = ""

	for _, item := range response.Data {
		var s string
		//fmt.Println(item)
		if item.(map[string]interface{})["image"] != nil {
			s = (item.(map[string]interface{})["image"]).(string)
		}
		result = s
	}
	return strings.Replace(result, "\n", "", -1)
}

func FetchStaffFaceFeature(base64 string) string {
	url := "http://39.105.51.226:5000/cv/feature-extraction-service/1.7"
	method := "POST"

	err := common.SaveBase64ImageToFile(base64, "images/"+fmt.Sprintf("%d", time.Now().Unix())+"test.jpg")
	fmt.Printf("%v\n", err)

	payload := strings.NewReader(`{
    "detect":true,
    "base64Data":"` + base64 + `"}`)

	client := &http.Client{}
	req, err := http.NewRequest(method, url, payload)

	if err != nil {
		fmt.Errorf(common.GenLogLine()+"%s", err)
		common.Error(common.GenLogLine()+"%s", err)
		return ""
	}
	req.Header.Add("Authorization", "Bearer ")
	req.Header.Add("Content-Type", "application/json")

	res, err := client.Do(req)
	if err != nil {
		fmt.Errorf(common.GenLogLine()+"%s", err)
		common.Error(common.GenLogLine()+"%s", err)
		return ""
	}
	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		fmt.Errorf(common.GenLogLine()+"%s", err)
		common.Error(common.GenLogLine()+"%s", err)
		return ""
	}
	fmt.Println(string(body))

	var response *FeatureResp
	err = json.Unmarshal([]byte(string(body)), &response)
	if err != nil {
		fmt.Println("Error:", err)
	}

	var result string
	result, err = extractFeature(response.Result[0])
	fmt.Printf(" success data : %+v\n", result)
	return result
}

func extractFeature(data interface{}) (string, error) {
	// 将 interface{} 类型转换为 map[string]interface{}
	resultMap, ok := data.(map[string]interface{})
	if !ok {
		return "", fmt.Errorf("Invalid data format")
	}
	// 取出 "faces" 字段
	faces, ok := resultMap["faces"].([]interface{})
	if !ok || len(faces) == 0 {
		return "", fmt.Errorf("No faces found")
	}

	// 取出 "feature" 字段
	feature, ok := faces[0].(map[string]interface{})["feature"].([]interface{})
	if !ok || len(feature) == 0 {
		return "", fmt.Errorf("No feature found")
	}

	// 转换 feature 字段为 []float64 类型
	var featureValues []float64
	for _, value := range feature {
		if floatValue, ok := value.(float64); ok {
			featureValues = append(featureValues, floatValue)
		} else {
			return "", fmt.Errorf("Invalid feature value type")
		}
	}
	str := common.FloatSliceToString(featureValues)
	return str, nil
}

func LocalFetchStaffFaceFeature(base64 string) (string, string, error) {
	url := "http://" + common.ConfigData.DevIp + common.ConfigData.LocalDetectUrl
	method := "POST"

	imgName := "static/faces/" + fmt.Sprintf("%d", time.Now().Unix()) + "test.jpg"
	err := common.SaveBase64ImageToFile(base64, imgName)

	payload := strings.NewReader(`{
    "imgbase64":"` + base64 + `"}`)

	client := &http.Client{}
	req, _ := http.NewRequest(method, url, payload)

	//req.Header.Add("Authorization", "Bearer ")
	req.Header.Add("Content-Type", "application/json")

	res, err := client.Do(req)
	if err != nil {
		fmt.Errorf(common.GenLogLine()+"%s", err)
		common.Error(common.GenLogLine()+"%s", err)
		return "", imgName, err
	}
	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		fmt.Errorf(common.GenLogLine()+"%s", err)
		common.Error(common.GenLogLine()+"%s", err)
		return "", imgName, err
	}
	fmt.Println(string(body))

	var response map[string]interface{}
	err = json.Unmarshal([]byte(string(body)), &response)
	if err != nil {
		fmt.Println("Error:", err)
		return "", imgName, err
	}

	faces, ok := response["data"].(map[string]interface{})
	if !ok {
		fmt.Errorf("No faces found")
	}

	feature, ok1 := faces["faceData"].(map[string]interface{})["theFeature"].([]interface{})
	if !ok1 || len(feature) == 0 {
		return "", imgName, err
	}

	// 转换 feature 字段为 []float64 类型
	var featureValues []float64
	for _, value := range feature {
		if floatValue, ok := value.(float64); ok {
			featureValues = append(featureValues, floatValue)
		} else {
			return "", imgName, err
		}
	}
	str := common.FloatSliceToString(featureValues)
	return str, imgName, nil
}

func GetMaxId(dataList []Staff) string {
	maxID := dataList[0].ID
	common.Info(common.GenLogLine()+"maxID:", maxID)
	for _, data := range dataList {
		if data.ID > maxID {
			maxID = data.ID
			common.Info(common.GenLogLine()+"maxID:%s", maxID)
		}
	}
	return maxID
}

func GetNewestModified(dataList []Req) string {
	if len(dataList) == 0 {
		return ""
	}
	maxID := dataList[0].Modified
	return maxID
}

func TimerHandle() {

	fmt.Printf("TimerHandle start %d\n", timeStep)
	ticker := time.NewTicker(time.Second * time.Duration(timeStep))

	defer ticker.Stop()
	for range ticker.C { //十秒执行一次
		common.Info(common.GenLogLine() + "=====执行timerHandle开始=====")
		now := time.Now()
		// 将时间设置为23点59分59秒
		t := time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 55, 0, now.Location())
		duration := t.Sub(now)
		isWithin10Seconds := duration > 0*time.Second && duration <= time.Duration(timeStep)*time.Second

		common.Info(common.GenLogLine() + "--1,执行日志分割判断 是否开始切割：--" + strconv.FormatBool(isWithin10Seconds))
		if isWithin10Seconds {
			common.Info(common.GenLogLine() + "--1.1执行RenameLogFile--")
			common.RenameLogFile()
		}
		common.Info(common.GenLogLine() + "--1,执行日志分割判断 END--")

		if common.ConfigData.Sync == 1 {
			common.Info(common.GenLogLine() + "--2,数据同步 START--")

			//获取接口数据
			staffs := Fetch()
			cachedTime := common.GetCache("maxTime")

			if len(staffs) == 0 {
				common.Info(common.GenLogLine() + "数据为空")
			} else {
				//获取最新更新时间
				maxTime := GetNewestModified(staffs)
				var t1 time.Time
				var t2 time.Time
				var t3 time.Time
				if cachedTime == "" {
					cachedTime = common.ReadFile("di.txt")
					common.SetCacheWithExpire("maxTime", cachedTime, 0)
				}
				t1, _ = time.Parse("2006-01-02 15:04:05", cachedTime)
				t2, _ = time.Parse("2006-01-02 15:04:05", maxTime)
				if !t2.After(t1) {
					common.Info(common.GenLogLine() + "--2.1, 数据已被同步")
				} else {
					common.SetCacheWithExpire("maxTime", maxTime, 0)

					for _, staff := range staffs {
						time.Sleep(1 * time.Second) // 暂停1秒
						t3, _ = time.Parse("2006-01-02 15:04:05", staff.Modified)
						if t3.After(t1) {
							staff.StaffBase64Img = FetchStaffImage(staff.Code)
							common.Info(common.GenLogLine()+"----%v", "" == staff.StaffBase64Img)
							str := HandleStaff(staff)
							common.Info(common.GenLogLine()+"--2.2注册人员  姓名:%s 编号:%s 更新时间:%s--\n", staff.StaffName, staff.Code, staff.Modified)
							//str := RegOnlineStaff(staff)
							ss := ""
							if str == nil {
								ss = "保存成功"
							} else {
								ss = str.Error()
							}
							fmt.Printf("注册人员:%v\n", ss)
							common.Info(common.GenLogLine()+"--2.3注册人员:%v--\n", ss)
						} else {
							break
						}
					}
					common.WriteFile("di.txt", maxTime)
					common.Info(common.GenLogLine()+"--2.4,数据同步，缓存数据maxID-- :%s", common.GetCache("maxTime"))
				}
			}
			common.Info(common.GenLogLine() + "--2,数据同步 END--")
		}

		common.Info(common.GenLogLine() + "=====执行timerHandle结束=====")
	}
}

func EmpToReq(emp mydatabase.Emp) Req {
	var req Req
	req.StaffName = emp.Name
	req.StaffType = 5 //普通员工
	req.Phone = emp.Phone
	req.StaffBase64Img = emp.Avatar
	req.FaceFeature = emp.Features
	return req
}
