package handlers

import (
	"net/http"

	"easydo-echo_win7/middleware"
	"easydo-echo_win7/models"
	"easydo-echo_win7/services"
	"easydo-echo_win7/utils"

	"github.com/jmoiron/sqlx"
	"github.com/labstack/echo-contrib/session"
	"github.com/labstack/echo/v4"
)

func Add_quality_inspect_program_to_routes(e *echo.Echo) {
	group := e.Group("/qualityInspectProgram")
	group.Use(middleware.AuthMiddleware)
	group.POST("/getPage", qualityInspectProgramGetPage)
	group.POST("/getList", qualityInspectProgramGetList)
	group.POST("/save", qualityInspectProgramSave)
	group.POST("/update", qualityInspectProgramUpdate)
	group.POST("/remove", qualityInspectProgramRemove)

}

func qualityInspectProgramGetPage(c echo.Context) error {
	var paramMap map[string]interface{}
	if err := c.Bind(&paramMap); err != nil {
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("参数解析失败", err.Error()))
	}
	result, _ := services.JdbcClient.GetJdbcPage(paramMap, models.QualityInspectProgram{})
	list := utils.ConvertInterface[[]models.QualityInspectProgram](result.Records)
	if len(list) == 0 {
		list = []models.QualityInspectProgram{}
	}
	for i := range list {
		model := list[i]
		minioList, err := services.JdbcClient.GetMinioFile(model)
		if err != nil {
			utils.PrintSearchFileErr(err)
		}
		model.FileList = &minioList

		inspect_user := new(models.SysUser)
		inspect_user.ID = model.InspectUserId
		services.JdbcClient.GetJdbcModelById(inspect_user)
		model.InspectUserName = inspect_user.NickName

		review_user := new(models.SysUser)
		review_user.ID = model.ReviewUserId
		services.JdbcClient.GetJdbcModelById(review_user)
		model.ReviewUserName = review_user.NickName

		list[i] = model
	}

	result.Records = list
	return c.JSON(http.StatusOK, result)

}

func qualityInspectProgramGetList(c echo.Context) error {
	var paramMap map[string]interface{}
	if err := c.Bind(&paramMap); err != nil {
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("参数解析失败", err.Error()))
	}
	result, _ := services.JdbcClient.GetJdbcList(paramMap, models.QualityInspectProgram{})
	list := utils.ConvertInterface[[]models.QualityInspectProgram](result)
	if len(list) == 0 {
		return c.JSON(http.StatusOK, []string{})
	}
	return c.JSON(http.StatusOK, list)
}

func qualityInspectProgramSave(c echo.Context) error {
	tx, _ := services.MYSQL_DB.Beginx()

	program := new(models.QualityInspectProgram)
	if err := c.Bind(program); err != nil {
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("参数解析失败", err.Error()))
	}
	sess, _ := session.Get("auth_session", c)
	err_msg := qualityInspectProgram_generateCode(program, tx)
	if err_msg != "" {
		tx.Rollback()
		return c.JSON(http.StatusBadRequest, utils.ErrorResponse(err_msg, ""))
	}
	user_id, ok := sess.Values["user_id"].(int64)
	if !ok {
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("用户请先登录", ""))
	}
	program.CreateId = &user_id
	err := services.JdbcClient.JdbcInsert(program, tx)
	if err != nil {
		utils.PrintSqlErr(err)
		tx.Rollback()
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}

	if program.FileList == nil {
		tx.Commit()
		return c.JSON(http.StatusOK, program)
	}
	fileList := *program.FileList
	for _, file := range fileList {
		file.RefId = program.ID
		refType := models.File_Ref_Type_Quality_Inspect_Program
		file.RefType = &refType

		err := services.JdbcClient.JdbcInsert(&file, tx)
		if err != nil {
			utils.PrintSqlErr(err)
			tx.Rollback()
			return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
		}
	}
	tx.Commit()
	return c.JSON(http.StatusOK, program)
}

func qualityInspectProgramUpdate(c echo.Context) error {
	tx, _ := services.MYSQL_DB.Beginx()

	program := new(models.QualityInspectProgram)
	if err := c.Bind(program); err != nil {
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("参数解析失败", err.Error()))
	}
	sess, _ := session.Get("auth_session", c)
	user_id, ok := sess.Values["user_id"].(int64)
	if !ok {
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("用户请先登录", ""))
	}
	program.UpdateId = &user_id
	err := services.JdbcClient.JdbcUpdateById(program, tx)
	if err != nil {
		utils.PrintSqlErr(err)
		tx.Rollback()
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}

	if program.FileList == nil {
		tx.Commit()
		return c.JSON(http.StatusOK, program)
	}

	fileList := *program.FileList
	for _, file := range fileList {
		file.RefId = program.ID
		refType := models.File_Ref_Type_Quality_Inspect_Program
		file.RefType = &refType

		err := services.JdbcClient.JdbcInsert(&file, tx)
		if err != nil {
			utils.PrintSqlErr(err)
			tx.Rollback()
			return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
		}
	}
	tx.Commit()
	return c.JSON(http.StatusOK, program)
}

func qualityInspectProgramRemove(c echo.Context) error {
	tx, _ := services.MYSQL_DB.Beginx()

	program := new(models.QualityInspectProgram)
	if err := c.Bind(program); err != nil {
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("参数解析失败", err.Error()))
	}

	err := services.JdbcClient.JdbcRemoveById(program, tx)
	if err != nil {
		utils.PrintSqlErr(err)
		tx.Rollback()
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}

	minio_file := new(models.MinioFile)
	minio_file.RefId = program.ID
	refType := models.File_Ref_Type_Quality_Inspect_Program
	minio_file.RefType = &refType
	err = services.JdbcClient.JdbcRemove(minio_file, tx)
	if err != nil {
		utils.PrintSqlErr(err)
		tx.Rollback()
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}
	tx.Commit()
	return c.JSON(http.StatusOK, program)
}

func qualityInspectProgram_generateCode(model *models.QualityInspectProgram, tx *sqlx.Tx) string {
	sync := new(models.Synchronized)
	sync.Sync.Lock()
	defer sync.Sync.Unlock()

	if model.Code != nil && len(*model.Code) > 0 {
		modelParam := new(models.QualityInspectProgram)
		modelParam.Code = model.Code
		modelParam.TenantId = model.TenantId
		count, err := services.JdbcClient.GetJdbcCount(modelParam, tx)
		if err != nil {
			utils.PrintSqlErr(err)
			return "SQL执行失败"
		}
		if count > 0 {
			return "编号已存在，请重新填写"
		}
	} else {
		for {
			code, err := services.GetFlowNo(models.Flow_No_Type_Quality_Inspect_Program, *model.TenantId, tx)
			if err != nil {
				return "自动生成编码失败"
			}
			modelParam := new(models.QualityInspectProgram)
			modelParam.Code = &code
			modelParam.TenantId = model.TenantId
			count, err := services.JdbcClient.GetJdbcCount(modelParam, tx)
			if err != nil {
				utils.PrintSqlErr(err)
				return "SQL执行失败"
			}
			if count == 0 {
				model.Code = &code
				break
			}
		}

	}
	return ""
}
