package handlers

import (
	"fmt"
	"net/http"

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

	"easydo-echo_win7/middleware"

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

func Add_sale_plan_to_routes(e *echo.Echo) {
	group := e.Group("/salePlan")
	group.Use(middleware.AuthMiddleware)
	group.POST("/getPage", salePlanGetPage)
	group.POST("/getList", salePlanGetList)
	group.POST("/save", salePlanSave)
	group.POST("/update", salePlanUpdate)
	group.POST("/remove", salePlanRemove)
}

func salePlanGetPage(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, err := services.JdbcClient.GetJdbcPage(paramMap, models.SalePlan{})
	if err != nil {
		utils.PrintSqlErr(err)
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}
	list := utils.ConvertInterface[[]models.SalePlan](result.Records)
	if len(list) == 0 {
		list = []models.SalePlan{}
	}
	for i := range list {
		model := list[i]

		sqlStr := fmt.Sprintf("SELECT sum(actual_price) as actual_price FROM sale_order where order_date > '%s' and order_date < '%s' and status = '%s'",
			*model.BeginDate, *model.EndDate, models.Sale_Order_Status_Complete)
		row := services.MYSQL_DB.QueryRowx(sqlStr)
		sale_order := new(models.SaleOrder)
		err = services.JdbcClient.ScanRowToModel(row, sale_order)
		if err != nil {
			utils.PrintSqlErr(err)
			return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
		}
		if sale_order.ActualPrice == nil {
			totalActualPrice := models.Common_Value_Zere_Float
			model.TotalActualPrice = &totalActualPrice
		} else {
			model.TotalActualPrice = sale_order.ActualPrice
		}

		list[i] = model
	}

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

}

func salePlanGetList(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, err := services.JdbcClient.GetJdbcList(paramMap, models.SalePlan{})
	if err != nil {
		utils.PrintSqlErr(err)
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}
	list := utils.ConvertInterface[[]models.SalePlan](result)
	if len(list) == 0 {
		return c.JSON(http.StatusOK, []models.SalePlan{})
	}
	for i := range list {
		model := list[i]

		sqlStr := fmt.Sprintf("SELECT sum(actual_price) as actual_price FROM sale_order where order_date > '%s' and order_date < '%s' and status = '%s'",
			*model.BeginDate, *model.EndDate, models.Sale_Order_Status_Complete)
		row := services.MYSQL_DB.QueryRowx(sqlStr)
		sale_order := new(models.SaleOrder)
		err = services.JdbcClient.ScanRowToModel(row, sale_order)
		if err != nil {
			utils.PrintSqlErr(err)
			return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
		}
		if sale_order.ActualPrice == nil {
			totalActualPrice := models.Common_Value_Zere_Float
			model.TotalActualPrice = &totalActualPrice
		} else {
			model.TotalActualPrice = sale_order.ActualPrice
		}

		list[i] = model
	}
	return c.JSON(http.StatusOK, list)
}

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

	plan := new(models.SalePlan)
	if err := c.Bind(plan); err != nil {
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("参数解析失败", err.Error()))
	}
	essit_plan := new(models.SalePlan)
	essit_plan.BeginDate = plan.BeginDate
	essit_plan.EndDate = plan.EndDate
	essit_plan.Type = plan.Type
	count, err := services.JdbcClient.GetJdbcCount(essit_plan, tx)
	if err != nil {
		utils.PrintSqlErr(err)
		tx.Rollback()
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}
	if count > 0 {
		return c.JSON(http.StatusBadRequest, utils.ErrorResponse("该计划已存在，请勿重复添加", ""))
	}
	sess, _ := session.Get("auth_session", c)
	err_msg := salePlan_generateCode(plan, 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("用户请先登录", ""))
	}
	plan.CreateId = &user_id
	err = services.JdbcClient.JdbcInsert(plan, tx)
	if err != nil {
		utils.PrintSqlErr(err)
		tx.Rollback()
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}
	tx.Commit()
	return c.JSON(http.StatusOK, plan)
}

func salePlanUpdate(c echo.Context) error {
	sale_plan := new(models.SalePlan)
	if err := c.Bind(sale_plan); 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("用户请先登录", ""))
	}
	sale_plan.UpdateId = &user_id
	err := services.JdbcClient.JdbcUpdateById(sale_plan)
	if err != nil {
		utils.PrintSqlErr(err)
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}
	return c.JSON(http.StatusOK, sale_plan)
}

func salePlanRemove(c echo.Context) error {

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

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

func salePlan_generateCode(model *models.SalePlan, 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.SalePlan)
		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_Sale_Plan, *model.TenantId, tx)
			if err != nil {
				return "自动生成编码失败"
			}
			modelParam := new(models.SalePlan)
			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 ""
}
