package main

import (
	"digimetastaffsync/business"
	"digimetastaffsync/common"
	"digimetastaffsync/mydatabase"
	"fmt"
	"github.com/gin-gonic/gin"
	"io"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"strings"
)

func init() {
	setupLogger()
	common.SetFlags(log.Ldate | log.Ltime)
	common.LoadConfig()

}

func setupLogger() {
	logsDir := "logs"
	logFileName := "web.log"
	logFilePath := filepath.Join(logsDir, logFileName)

	// 检查日志文件是否存在
	if _, err := os.Stat(logFilePath); os.IsNotExist(err) {
		// 不存在则创建新文件
		err := os.MkdirAll(logsDir, 0755)
		if err != nil {
			log.Fatalf("Error creating logs directory: %v", err)
		}

		// 创建日志文件
		file, err := os.Create(logFilePath)
		if err != nil {
			log.Fatalf("Error creating log file: %v", err)
		}
		defer file.Close()

		// 设置 Gin 默认的写入器
		gin.DefaultWriter = io.MultiWriter(file)
	} else {
		// 存在则打开已有文件
		file, err := os.OpenFile(logFilePath, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
		if err != nil {
			log.Fatalf("Error opening log file: %v", err)
		}
		defer file.Close()

		// 设置 Gin 默认的写入器
		gin.DefaultWriter = io.MultiWriter(file)
	}

	// 设置 Gin 的日志输出
	gin.SetMode(gin.ReleaseMode)
}

type Config struct {
	Port  string `json:"port"`
	Phone string `json:"phone"`
	Mode  string `json:"mode"`
	DevId string `json:"devId"`
}

func main() {

	router := gin.Default()
	router.LoadHTMLGlob("templates/*")
	router.GET("/", HomeHandler)
	router.GET("/reg", RegPageHandler)
	router.GET("/config", ConfigPageHandler)
	router.GET("/info", InfoPageHandler)
	router.POST("/send_validation_code", SendCodeHandler)
	router.POST("/valid_code", ValidCodeHandler)
	router.POST("/phone_login", PhoneLoginHandler)
	router.POST("/mgr_login", MgrLoginHandler)
	router.GET("/mgr", MgrPageHandler)
	router.GET("/test", TestHandler)
	router.GET("/register", RegisterPageHandler)
	router.POST("/register", RegisterHandler)
	router.POST("/pass", PassHandler)
	router.POST("/updateConfig", UpdateConfigHandler)

	common.Info(common.GenLogLine()+"file content:%s", common.ReadFile("di.txt"))

	defer mydatabase.GetDb().Close()
	port := common.ConfigData.Port
	if port == "" {
		port = "18080"
		log.Printf("Defaulting to port %s", port)
	}

	// 启动定时任务，用于同步人脸操作
	go business.TimerHandle()

	log.Printf("Listening on port %s", port)
	log.Printf("Open http://localhost:%s in the browser", port)
	router.Static("/static", "./static")
	router.Run(fmt.Sprintf(":%s", port))

}

// UpdateConfigHandler 更新配置
func UpdateConfigHandler(c *gin.Context) {
	var updateValues map[string]interface{}
	if err := c.BindJSON(&updateValues); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	str := common.UpdateConfig(updateValues)
	if str != "" {
		c.JSON(http.StatusInternalServerError, gin.H{"message": str})
		return
	}
	//更新配置文件变量configData
	common.LoadConfig()

	c.JSON(http.StatusOK, gin.H{"message": "配置更新成功"})
}

func HomeHandler(c *gin.Context) {
	t := c.Query("type")
	c.HTML(http.StatusOK, "login.html", gin.H{
		"type": t,
	})
}

func RegPageHandler(c *gin.Context) {
	c.HTML(http.StatusOK, "reg.html", nil)
}

func ConfigPageHandler(c *gin.Context) {

	c.HTML(http.StatusOK, "conf.html", gin.H{
		"config": common.ConfigData,
	})
}

func InfoPageHandler(c *gin.Context) {
	staffId := c.Query("staffId")
	res, err := business.StaffInfo(staffId)
	if err != nil {
		c.HTML(http.StatusOK, "info.html", gin.H{
			"err": err.Error(),
		})
	}
	fmt.Printf("res:%v", res)
	c.HTML(http.StatusOK, "info.html", gin.H{
		"info": res,
	})
}

func PhoneLoginHandler(c *gin.Context) {
	phone := c.PostForm("phone")
	res, err := business.PhoneLogin(phone)
	if err != nil {
		c.JSON(http.StatusInternalServerError, err.Error())
	}
	c.JSON(http.StatusOK, res)
}

func MgrLoginHandler(c *gin.Context) {
	phone := c.PostForm("userName")
	pwd := c.PostForm("password")
	str := business.MgrLogin(phone, pwd)
	c.JSON(http.StatusOK, str)
}

func SendCodeHandler(c *gin.Context) {
	phone := c.PostForm("phone")
	str := business.SendCode(phone)
	c.JSON(http.StatusOK, str)
}

func ValidCodeHandler(c *gin.Context) {
	phone := c.PostForm("phone")
	code := c.PostForm("code")
	str, err := business.ValidCode(phone, code)
	if err != nil {
		c.JSON(http.StatusInternalServerError, err.Error())
	}
	c.JSON(http.StatusOK, str)
}

// RegisterPageHandler 处理注册页面请求
func RegisterPageHandler(c *gin.Context) {

	c.HTML(http.StatusOK, "register.html", map[string]interface{}{"Message": ""})
}

// MgrPageHandler  处理管理页面请求
func MgrPageHandler(c *gin.Context) {
	key := c.Query("key")
	users, err := mydatabase.Select(key)
	if err != nil {
		log.Fatal(err)
	}

	if err != nil {
		common.Error("Error marshaling JSON:%s", err)
		return
	}
	c.HTML(http.StatusOK, "mgr.html", gin.H{
		"users": users,
		"key":   key,
	})
}

func TestHandler(c *gin.Context) {
	fmt.Printf("timer:   ====%d\n", common.ConfigData.Timer)
	c.JSON(http.StatusOK, "request successfully")
}

// RegisterHandler 处理注册页面请求
func RegisterHandler(c *gin.Context) {
	// 从表单中获取用户输入
	username := c.PostForm("staffName")
	phone := c.PostForm("staffPhone")
	avatar := c.PostForm("avatar")

	emp, _ := mydatabase.SelectOneByPhone(phone)
	fmt.Println("====phone：" + phone)
	fmt.Println(emp)
	if emp.ID > 0 {
		c.JSON(http.StatusInternalServerError, map[string]interface{}{"Message": "已存在该手机号对应的员工，请查验后重试！"})
		return
	}

	// 在实际应用中，你可能会将用户信息保存到数据库中
	avatar = strings.ReplaceAll(avatar, "data:image/jpeg;base64,", "")

	features, imgName, err := business.LocalFetchStaffFaceFeature(avatar)
	if err != nil {
		c.JSON(http.StatusInternalServerError, map[string]interface{}{"Message": err.Error()})
		return
	}
	mydatabase.Insert(username, 0, phone, imgName, features, 1)
	// 将注册成功的消息渲染到页面
	message := fmt.Sprintf("Registration successful! %s %s  %s %s!", username, phone, imgName, features)
	fmt.Println(message)
	c.JSON(http.StatusOK, map[string]interface{}{"Message": "注册成功，请等待审核！"})
}

// PassHandler 审核通过或拒绝的处理函数
func PassHandler(c *gin.Context) {
	// 从表单中获取用户输入
	id := c.PostForm("id")
	handleType := c.PostForm("handle")
	handleTypeInt, _ := strconv.Atoi(handleType)

	if handleTypeInt != 1 && handleTypeInt != 2 && handleTypeInt != 4 {
		c.JSON(http.StatusInternalServerError, map[string]interface{}{"Message": "handleType参数错误！"})
		return
	}

	idInt, _ := strconv.Atoi(id)
	emp, err := mydatabase.SelectOne(idInt)

	if err != nil || !(emp.ID > 0) {
		c.JSON(http.StatusInternalServerError, map[string]interface{}{"Message": "指定id未查询到记录"})
		return
	}

	if handleTypeInt == 1 {
		emp.Avatar = strings.ReplaceAll(emp.Avatar, "data:image/jpeg;base64,", "")
		//将员工信息提交到后台
		resp, err := business.RegStaff(business.EmpToReq(emp))
		if err != nil {
			c.JSON(http.StatusOK, map[string]interface{}{"Message": err.Error()})
			return
		}
		if resp != nil && resp.Code != 0 {
			c.JSON(http.StatusOK, map[string]interface{}{"Message": resp.Msg})
			return
		}
		//更新sqllite里面数据状态
		mydatabase.Update(emp.ID, emp.Name, emp.Phone, emp.Avatar, 1, 1)

		c.JSON(http.StatusOK, map[string]interface{}{"Message": "操作成功，注册流程结束！"})
	} else if handleTypeInt == 2 {
		//更新sqllite里面数据状态
		mydatabase.SoftDelete(emp.ID)
		c.JSON(http.StatusOK, map[string]interface{}{"Message": "操作成功"})
	} else if handleTypeInt == 4 {
		//删除数据
		mydatabase.Delete(emp.ID)
		//删除指定路径图片
		if emp.Avatar != "" {
			os.Remove(emp.Avatar)
		}
		c.JSON(http.StatusOK, map[string]interface{}{"Message": "操作成功"})
	}
}
