package controller

import (
	"cold-delivery/app/admin/model"
	"cold-delivery/app/admin/service"
	"cold-delivery/app/admin/service/dto"
	"cold-delivery/common/actions"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"gogs.baozhida.cn/zoie/OAuth-core/api"
	"gogs.baozhida.cn/zoie/OAuth-core/pkg/jwtauth/user"
	_ "gogs.baozhida.cn/zoie/OAuth-core/pkg/response"
	"time"
)

type IceRaftController struct {
	api.Api
}

// GetPage 获取冰排列表
// @Summary 获取冰排列表
// @Description 获取冰排列表
// @Tags 冰排
// @Param name query string false "冰排名称"
// @Param pageSize query int false "页条数"
// @Param page query int false "页码"
// @Success 200 {object} response.Response{data=response.Page{list=[]model.IceRaft}} "{"code": 200, "data": [...]}"
// @Router /api/ice-raft [get]
// @Security Bearer
func (e IceRaftController) GetPage(c *gin.Context) {
	s := service.IceRaft{}
	req := dto.IceRaftGetPageReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.Query).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	//数据权限检查
	p := actions.GetPermissionFromContext(c)

	list := make([]model.IceRaft, 0)
	var count int64

	err = s.GetPage(&req, &list, &count, p)
	if err != nil {
		e.Error(500, err, err.Error())
		return
	}
	e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}
func (e IceRaftController) GetPageByCoolerBoxId(c *gin.Context) {
	s := service.IceRaft{}
	req := dto.GetPageByCoolerBoxIdReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.Query).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	//数据权限检查
	p := actions.GetPermissionFromContext(c)

	list := make([]string, 0)

	err = s.GetPageByCoolerBoxId(req.CoolerBoxId, &list, p)
	if err != nil {
		e.Error(500, err, err.Error())
		return
	}
	e.OK(list, "查询成功")
}

// GetNewestRecordPage 获取冰排记录列表
// @Summary 获取冰排列表
// @Description 获取冰排列表
// @Tags 冰排
// @Param name query string false "冰排名称"
// @Param pageSize query int false "页条数"
// @Param page query int false "页码"
// @Success 200 {object} response.Response{data=response.Page{list=[]model.IceRaft}} "{"code": 200, "data": [...]}"
// @Router /api/ice-raft [get]
// @Security Bearer
func (e IceRaftController) GetNewestRecordPage(c *gin.Context) {
	s := service.IceRaft{}
	req := dto.IceRaftGetNewestRecordPageReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.Query).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	//数据权限检查
	p := actions.GetPermissionFromContext(c)

	list := make([]model.IceRaft, 0)
	var count int64

	err = s.GetRecordPage(&req, &list, &count, p)
	if err != nil {
		e.Error(500, err, err.Error())
		return
	}
	e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}
func (e IceRaftController) GetNewestRecordPageSSE(c *gin.Context) {
	s := service.IceRaft{}
	req := dto.IceRaftGetNewestRecordPageReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.Query).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	//数据权限检查
	p := actions.GetPermissionFromContext(c)

	list := make([]model.IceRaft, 0)
	var count int64

	// Set the response header to indicate SSE content type
	c.Header("Content-Type", "text/event-stream")
	c.Header("Cache-Control", "no-cache")
	c.Header("Connection", "keep-alive")
	// Create a channel to send events to the client
	println("Client connected")
	// Listen for client close and remove the client from the list
	notify := c.Writer.CloseNotify()
	go func() {
		<-notify
		fmt.Println("Client disconnected")
	}()
	type Page struct {
		Count    int         `json:"count"`    //总数
		Page     int         `json:"page"`     //页码
		PageSize int         `json:"pageSize"` //页条数
		List     interface{} `json:"list"`
	}
	type Response struct {
		RequestId string `protobuf:"bytes,1,opt,name=requestId,proto3" json:"requestId,omitempty"`
		Code      int32  `protobuf:"varint,2,opt,name=code,proto3" json:"code,omitempty"`
		Msg       string `protobuf:"bytes,3,opt,name=msg,proto3" json:"msg,omitempty"`
		Status    string `protobuf:"bytes,4,opt,name=status,proto3" json:"status,omitempty"`
		Data      Page   `json:"data"`
	}
	// Continuously send data to the client
	for {
		err = s.GetRecordPage(&req, &list, &count, p)
		if err != nil {
			e.Error(500, err, err.Error())
			return
		}

		var response Response
		var page Page
		response.Code = 200
		response.Msg = "查询成功"
		response.Msg = "查询成功"
		page.Count = int(count)
		page.Page = req.GetPageIndex()
		page.PageSize = req.GetPageSize()
		page.List = list
		response.Data = page
		//data := <-eventChan
		res, _ := json.Marshal(&response)
		fmt.Fprintf(c.Writer, "data: %s\n\n", string(res))
		c.Writer.Flush()
		time.Sleep(10 * time.Second)
	}
}


// Get 通过id获取冰排
// @Summary 通过id获取冰排
// @Description 通过id获取冰排
// @Tags 冰排
// @Param id path string true "冰排id"
// @Success 200 {object} response.Response{data=model.IceRaft} "{"code": 200, "data": [...]}"
// @Router /api/ice-raft/{id} [get]
// @Security Bearer
func (e IceRaftController) Get(c *gin.Context) {
	s := service.IceRaft{}
	req := dto.IceRaftGetReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, nil).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	var object model.IceRaft
	p := actions.GetPermissionFromContext(c)

	//数据权限检查
	err = s.Get(&req, &object, p)
	if err != nil {
		e.Error(500, err, err.Error())
		return
	}

	e.OK(object, "查询成功")
}

// Insert 添加冰排
// @Summary 添加冰排
// @Description 添加冰排
// @Tags 冰排
// @Accept  application/json
// @Product application/json
// @Param data body dto.IceRaftInsertReq true "data"
// @Success 200 {string} string	"{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string	"{"code": -1, "message": "添加失败"}"
// @Router /api/ice-raft [post]
// @Security Bearer
func (e IceRaftController) Insert(c *gin.Context) {
	s := service.IceRaft{}
	req := dto.IceRaftInsertReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	p := actions.GetPermissionFromContext(c)
	// 设置创建人
	req.SetCreateBy(user.GetUserId(c))
	req.SetDeptId(p.DeptId)
	err = s.Insert(&req)
	if err != nil {
		e.Error(500, err, err.Error())
		return
	}
	e.OK(req.GetId(), "创建成功")
}

// Update 修改冰排
// @Summary 修改冰排
// @Description 修改冰排
// @Tags 冰排
// @Accept  application/json
// @Product application/json
// @Param data body dto.IceRaftUpdateReq true "body"
// @Success 200 {string} string	"{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string	"{"code": -1, "message": "添加失败"}"
// @Router /api/ice-raft [put]
// @Security Bearer
func (e IceRaftController) Update(c *gin.Context) {
	s := service.IceRaft{}
	req := dto.IceRaftUpdateReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	p := actions.GetPermissionFromContext(c)

	req.SetUpdateBy(user.GetUserId(c))
	err = s.Update(&req, p)
	if err != nil {
		e.Error(500, err, err.Error())
		return
	}
	e.OK(req.GetId(), "更新成功")
}

// Delete 删除冰排
// @Summary 删除冰排
// @Description 删除冰排
// @Tags 冰排
// @Accept  application/json
// @Product application/json
// @Param data body dto.IceRaftDeleteReq true "body"
// @Success 200 {string} string	"{"code": 200, "message": "删除成功"}"
// @Success 200 {string} string	"{"code": -1, "message": "删除失败"}"
// @Router /api/ice-raft [delete]
// @Security Bearer
func (e IceRaftController) Delete(c *gin.Context) {
	s := service.IceRaft{}
	req := dto.IceRaftDeleteReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON, nil).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	//数据权限检查
	p := actions.GetPermissionFromContext(c)
	err = s.Remove(&req, p)
	if err != nil {
		e.Error(500, err, err.Error())
		return
	}
	e.OK(req.GetId(), "删除成功")
}

// InStorage 冰排入库
// @Summary 冰排入库
// @Description 冰排入库
// @Tags 冰排
// @Accept  application/json
// @Product application/json
// @Param data body dto.IceRaftInStorageReq true "body"
// @Success 200 {string} string	"{"code": 200, "message": "删除成功"}"
// @Success 200 {string} string	"{"code": -1, "message": "删除失败"}"
// @Router /api/ice-raft [delete]
// @Security Bearer
func (e IceRaftController) InStorage(c *gin.Context) {
	s := service.IceRaft{}
	req := dto.IceRaftInStorageReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON, nil).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	//数据权限检查
	p := actions.GetPermissionFromContext(c)
	err = s.InStorage(&req, p)
	if err != nil {
		e.Error(500, err, err.Error())
		return
	}
	e.OK(nil, "入库成功")
}

// OutStorage 冰排出库
// @Summary 冰排出库
// @Description 冰排出库
// @Tags 冰排
// @Accept  application/json
// @Product application/json
// @Param data body dto.IceRaftOutStorageReq true "body"
// @Success 200 {string} string	"{"code": 200, "message": "删除成功"}"
// @Success 200 {string} string	"{"code": -1, "message": "删除失败"}"
// @Router /api/ice-raft [delete]
// @Security Bearer
func (e IceRaftController) OutStorage(c *gin.Context) {
	s := service.IceRaft{}
	req := dto.IceRaftOutStorageReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON, nil).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	//数据权限检查
	p := actions.GetPermissionFromContext(c)
	err = s.OutStorage(&req, p)
	if err != nil {
		e.Error(500, err, err.Error())
		return
	}
	e.OK(nil, "出库成功")
}

type IceRaftRecordController struct {
	api.Api
}

// GetPage 获取冰排历史记记录列表
// @Summary 获取冰排列表
// @Description 获取冰排列表
// @Tags 冰排
// @Param name query string false "冰排名称"
// @Param pageSize query int false "页条数"
// @Param page query int false "页码"
// @Success 200 {object} response.Response{data=response.Page{list=[]model.IceRaft}} "{"code": 200, "data": [...]}"
// @Router /api/ice-raft [get]
// @Security Bearer
func (e IceRaftRecordController) GetPage(c *gin.Context) {
	s := service.IceRaftRecord{}
	req := dto.IceRaftRecordGetPageReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.Query).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	//数据权限检查
	p := actions.GetPermissionFromContext(c)

	list := make([]model.IceRaftRecord, 0)
	var count int64

	err = s.GetPage(&req, &list, &count, p)
	if err != nil {
		e.Error(500, err, err.Error())
		return
	}
	e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}

// Update 修改冰排出入库历史记录
// @Summary 修改冰排出入库历史记录
// @Description 修改冰排出入库历史记录
// @Tags 冰排
// @Accept  application/json
// @Product application/json
// @Param data body dto.IceRaftUpdateReq true "body"
// @Success 200 {string} string	"{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string	"{"code": -1, "message": "添加失败"}"
// @Router /api/ice-raft [put]
// @Security Bearer
func (e IceRaftRecordController) Update(c *gin.Context) {
	s := service.IceRaftRecord{}
	req := dto.IceRaftRecordUpdateReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	p := actions.GetPermissionFromContext(c)

	req.SetUpdateBy(user.GetUserId(c))
	err = s.Update(&req, p)
	if err != nil {
		e.Error(500, err, err.Error())
		return
	}
	e.OK(req.GetId(), "更新成功")
}

// Delete 删除冰排出入库历史记录
// @Summary 删除冰排出入库历史记录
// @Description 删除冰排出入库历史记录
// @Tags 冰排
// @Accept  application/json
// @Product application/json
// @Param data body dto.IceRaftDeleteReq true "body"
// @Success 200 {string} string	"{"code": 200, "message": "删除成功"}"
// @Success 200 {string} string	"{"code": -1, "message": "删除失败"}"
// @Router /api/ice-raft [delete]
// @Security Bearer
func (e IceRaftRecordController) Delete(c *gin.Context) {
	s := service.IceRaftRecord{}
	req := dto.IceRaftRecordDeleteReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON, nil).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	//数据权限检查
	p := actions.GetPermissionFromContext(c)
	err = s.Remove(&req, p)
	if err != nil {
		e.Error(500, err, err.Error())
		return
	}
	e.OK(req.GetId(), "删除成功")
}
