package report_approve

import (
	"encoding/json"
	"eta/eta_api/utils"
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"strings"
	"time"
)

// ReportApproveNode 报告审批节点表
type ReportApproveNode struct {
	ReportApproveNodeId int       `orm:"column(report_approve_node_id);pk" description:"报告审批节点ID"`
	ReportApproveFlowId int       `description:"报告审批流ID"`
	PrevNodeId          int       `description:"上一个节点ID（0为开始节点）"`
	NextNodeId          int       `description:"下一个节点ID（0为结束节点）"`
	NodeType            int       `description:"节点类型：0-审批；1-抄送"`
	ApproveType         int       `description:"审批类型：1-依次审批；2-会签；3-或签"`
	Users               string    `description:"审批人信息-JSON，user_type：user-用户；role-角色，user_id：用户/角色ID"`
	CurrVersion         int       `description:"当前版本号"`
	CreateTime          time.Time `description:"创建时间"`
}

var ReportApproveNodeCols = struct {
	ReportApproveNodeId string
	ReportApproveFlowId string
	PrevNodeId          string
	NextNodeId          string
	NodeType            string
	ApproveType         string
	Users               string
	CurrVersion         string
	CreateTime          string
}{
	ReportApproveNodeId: "report_approve_node_id",
	ReportApproveFlowId: "report_approve_flow_id",
	PrevNodeId:          "prev_node_id",
	NextNodeId:          "next_node_id",
	NodeType:            "node_type",
	ApproveType:         "approve_type",
	Users:               "users",
	CurrVersion:         "curr_version",
	CreateTime:          "create_time",
}

func (m *ReportApproveNode) TableName() string {
	return "report_approve_node"
}

func (m *ReportApproveNode) PrimaryId() string {
	return "report_approve_node_id"
}

func (m *ReportApproveNode) Create() (err error) {
	o := orm.NewOrmUsingDB("rddp")
	id, err := o.Insert(m)
	if err != nil {
		return
	}
	m.ReportApproveNodeId = int(id)
	return
}

func (m *ReportApproveNode) CreateMulti(items []*ReportApproveNode) (err error) {
	if len(items) == 0 {
		return
	}
	o := orm.NewOrmUsingDB("rddp")
	_, err = o.InsertMulti(len(items), items)
	return
}

func (m *ReportApproveNode) Update(cols []string) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	_, err = o.Update(m, cols...)
	return
}

func (m *ReportApproveNode) Del() (err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), m.PrimaryId())
	_, err = o.Raw(sql, m.ReportApproveNodeId).Exec()
	return
}

func (m *ReportApproveNode) MultiDel(menuIds []int) (err error) {
	if len(menuIds) == 0 {
		return
	}
	o := orm.NewOrmUsingDB("rddp")
	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s IN (%s)`, m.TableName(), m.PrimaryId(), utils.GetOrmInReplace(len(menuIds)))
	_, err = o.Raw(sql, menuIds).Exec()
	return
}

func (m *ReportApproveNode) GetItemById(id int) (item *ReportApproveNode, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := fmt.Sprintf(`SELECT * FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), m.PrimaryId())
	err = o.Raw(sql, id).QueryRow(&item)
	return
}

func (m *ReportApproveNode) GetItemByCondition(condition string, pars []interface{}, orderRule string) (item *ReportApproveNode, err error) {
	o := orm.NewOrmUsingDB("rddp")
	order := ``
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT * FROM %s WHERE 1=1 %s %s LIMIT 1`, m.TableName(), condition, order)
	err = o.Raw(sql, pars).QueryRow(&item)
	return
}

func (m *ReportApproveNode) GetCountByCondition(condition string, pars []interface{}) (count int, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := fmt.Sprintf(`SELECT COUNT(1) FROM %s WHERE 1=1 %s`, m.TableName(), condition)
	err = o.Raw(sql, pars).QueryRow(&count)
	return
}

func (m *ReportApproveNode) GetItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string) (items []*ReportApproveNode, err error) {
	o := orm.NewOrmUsingDB("rddp")
	fields := strings.Join(fieldArr, ",")
	if len(fieldArr) == 0 {
		fields = `*`
	}
	order := `ORDER BY create_time DESC, report_approve_node_id ASC`
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT %s FROM %s WHERE 1=1 %s %s`, fields, m.TableName(), condition, order)
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

func (m *ReportApproveNode) GetPageItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string, startSize, pageSize int) (items []*ReportApproveNode, err error) {
	o := orm.NewOrmUsingDB("rddp")
	fields := strings.Join(fieldArr, ",")
	if len(fieldArr) == 0 {
		fields = `*`
	}
	order := `ORDER BY create_time DESC`
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT %s FROM %s WHERE 1=1 %s %s LIMIT ?,?`, fields, m.TableName(), condition, order)
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

// ReportApproveNodeSaveReq 报告审批节点保存请求体
type ReportApproveNodeSaveReq struct {
	ApproveType int                        `description:"审批类型：1-依次审批；2-会签；3-或签"`
	Users       []ReportApproveNodeUserReq `description:"审批人信息"`
}

// ReportApproveNodeUserReq 报告审批节点用户请求体
type ReportApproveNodeUserReq struct {
	UserType string `description:"审批人类型: user-用户; role-角色"`
	UserId   int    `description:"用户/角色ID"`
	UserName string `description:"用户/角色姓名"`
	Sort     int    `description:"排序"`
}

// ReportApproveNodeItem 报告审批节点详情信息
type ReportApproveNodeItem struct {
	ReportApproveNodeId int                         `description:"报告审批节点ID"`
	ReportApproveFlowId int                         `description:"报告审批流ID"`
	PrevNodeId          int                         `description:"上一个节点ID（0为开始节点）"`
	NextNodeId          int                         `description:"下一个节点ID（0为结束节点）"`
	NodeType            int                         `description:"节点类型：0-审批；1-抄送"`
	ApproveType         int                         `description:"审批类型：1-依次审批；2-会签；3-或签"`
	Users               []*ReportApproveNodeUserReq `description:"审批人信息"`
}

// ReportApproveDetailNodes 审批详情-节点信息
type ReportApproveDetailNodes struct {
	ReportApproveNodeId int                            `description:"报告审批节点ID"`
	ReportApproveFlowId int                            `description:"报告审批流ID"`
	PrevNodeId          int                            `description:"上一个节点ID（0为开始节点）"`
	NextNodeId          int                            `description:"下一个节点ID（0为结束节点）"`
	NodeType            int                            `description:"节点类型：0-审批；1-抄送"`
	ApproveType         int                            `description:"审批类型：1-依次审批；2-会签；3-或签"`
	Users               []*ReportApproveDetailNodeUser `description:"审批人信息"`
}

// ReportApproveDetailNodeUser 审批详情-节点用户信息
type ReportApproveDetailNodeUser struct {
	ReportApproveNodeUserReq
	ApproveRecord *ReportApproveDetailNodeUserRecord `description:"用户审批记录"`
}

// FormatReportApproveNode2Item 格式化报告审批节点信息
func FormatReportApproveNode2Item(origin *ReportApproveNode) (item *ReportApproveNodeItem, err error) {
	if origin == nil {
		return
	}
	item = new(ReportApproveNodeItem)
	item.ReportApproveNodeId = origin.ReportApproveNodeId
	item.ReportApproveFlowId = origin.ReportApproveFlowId
	item.PrevNodeId = origin.PrevNodeId
	item.NextNodeId = origin.NextNodeId
	item.NodeType = origin.NodeType
	item.ApproveType = origin.ApproveType
	item.Users = make([]*ReportApproveNodeUserReq, 0)
	if origin.Users != "" {
		e := json.Unmarshal([]byte(origin.Users), &item.Users)
		if e != nil {
			err = fmt.Errorf("node users unmarshal err: %s", e.Error())
			return
		}
	}
	return
}
