package report_approve

import (
	"eta/eta_api/utils"
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"github.com/rdlucklib/rdluck_tools/paging"
	"strings"
	"time"
)

// ReportApprove 报告审批表
type ReportApprove struct {
	ReportApproveId  int       `orm:"column(report_approve_id);pk" description:"审批ID"`
	ReportType       int       `description:"报告类型：1-中文研报；2-英文研报；3-智能研报"`
	ReportId         int       `description:"报告ID"`
	ReportTitle      string    `description:"报告标题"`
	ClassifyFirstId  int       `description:"一级分类ID"`
	ClassifySecondId int       `description:"二级分类ID"`
	State            int       `description:"审批状态：1-待审批；2-已审批；3-已驳回；4-已撤回"`
	FlowId           int       `description:"审批流ID"`
	FlowVersion      int       `description:"审批流版本"`
	StartNodeId      int       `description:"开始节点ID"`
	CurrNodeId       int       `description:"当前节点ID"`
	ApplyUserId      int       `description:"申请人ID"`
	ApplyUserName    string    `description:"申请人姓名"`
	ApproveRemark    string    `description:"审批备注"`
	ApproveTime      time.Time `description:"审批时间"`
	CreateTime       time.Time `description:"创建时间"`
	ModifyTime       time.Time `description:"修改时间"`
}

var ReportApproveCols = struct {
	ReportApproveId  string
	ReportType       string
	ReportId         string
	ReportTitle      string `description:"报告标题"`
	ClassifyFirstId  string `description:"一级分类ID"`
	ClassifySecondId string `description:"二级分类ID"`
	State            string
	FlowId           string
	FlowVersion      string
	StartNodeId      string
	CurrNodeId       string
	ApplyUserId      string `description:"申请人ID"`
	ApplyUserName    string `description:"申请人姓名"`
	ApproveRemark    string `description:"审批备注"`
	ApproveTime      string `description:"审批时间"`
	CreateTime       string
	ModifyTime       string
}{
	ReportApproveId:  "report_approve_id",
	ReportType:       "report_type",
	ReportId:         "report_id",
	ReportTitle:      "report_title",
	ClassifyFirstId:  "classify_first_id",
	ClassifySecondId: "classify_second_id",
	State:            "state",
	FlowId:           "flow_id",
	FlowVersion:      "flow_version",
	StartNodeId:      "start_node_id",
	CurrNodeId:       "curr_node_id",
	ApplyUserId:      "apply_user_id",
	ApplyUserName:    "apply_user_name",
	ApproveRemark:    "approve_remark",
	ApproveTime:      "approve_time",
	CreateTime:       "create_time",
	ModifyTime:       "modify_time",
}

func (m *ReportApprove) TableName() string {
	return "report_approve"
}

func (m *ReportApprove) PrimaryId() string {
	return ReportApproveCols.ReportApproveId
}

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

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

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

func (m *ReportApprove) 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.ReportApproveId).Exec()
	return
}

func (m *ReportApprove) 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 *ReportApprove) GetItemById(id int) (item *ReportApprove, 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 *ReportApprove) GetItemByCondition(condition string, pars []interface{}, orderRule string) (item *ReportApprove, 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 *ReportApprove) 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 *ReportApprove) GetItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string) (items []*ReportApprove, 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`, fields, m.TableName(), condition, order)
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

func (m *ReportApprove) GetPageItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string, startSize, pageSize int) (items []*ReportApprove, 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
}

// ReportApproveItem 报告审批信息
type ReportApproveItem struct {
	ReportApproveId       int    `description:"审批ID"`
	ReportApproveRecordId int    `description:"审批记录ID"`
	ReportType            int    `description:"报告类型：1-中文研报；2-英文研报；3-智能研报"`
	ReportId              int    `description:"报告ID"`
	ReportTitle           string `description:"报告标题"`
	ReportClassify        string `description:"报告分类"`
	ClassifyFirstId       int    `description:"一级分类ID"`
	ClassifySecondId      int    `description:"二级分类ID"`
	State                 int    `description:"审批状态：1-待审批；2-已审批；3-已驳回；4-已撤回"`
	RecordState           int    `description:"审批记录状态：1-待审批；2-已通过；3-已驳回"`
	FlowId                int    `description:"审批流ID"`
	FlowVersion           int    `description:"审批流版本"`
	StartNodeId           int    `description:"开始节点ID"`
	CurrNodeId            int    `description:"当前节点ID"`
	ApplyUserId           int    `description:"申请人ID"`
	ApplyUserName         string `description:"申请人姓名"`
	ApproveRemark         string `description:"审批备注"`
	ApproveTime           string `description:"审批时间"`
	HandleTime            string `description:"处理时间"`
	CreateTime            string `description:"创建时间"`
	ModifyTime            string `description:"修改时间"`
}

// FormatReportApproveOrm2Item 格式化报告审批
func FormatReportApproveOrm2Item(origin *ReportApproveItemOrm) (item *ReportApproveItem) {
	item = new(ReportApproveItem)
	if origin == nil {
		return
	}
	item.ReportApproveId = origin.ReportApproveId
	item.ReportApproveRecordId = origin.ReportApproveRecordId
	item.ReportType = origin.ReportType
	item.ReportId = origin.ReportId
	item.ReportTitle = origin.ReportTitle
	item.ClassifyFirstId = origin.ClassifyFirstId
	item.ClassifySecondId = origin.ClassifySecondId
	item.State = origin.State
	item.RecordState = origin.RecordState
	item.FlowId = origin.FlowId
	item.FlowVersion = origin.FlowVersion
	item.StartNodeId = origin.StartNodeId
	item.CurrNodeId = origin.CurrNodeId
	item.ApplyUserId = origin.ApplyUserId
	item.ApplyUserName = origin.ApplyUserName
	item.ApproveRemark = origin.ApproveRemark
	item.ApproveTime = utils.TimeTransferString(utils.FormatDateTime, origin.ApproveTime)
	item.HandleTime = utils.TimeTransferString(utils.FormatDateTime, origin.HandleTime)
	item.CreateTime = utils.TimeTransferString(utils.FormatDateTime, origin.CreateTime)
	item.ModifyTime = utils.TimeTransferString(utils.FormatDateTime, origin.ModifyTime)
	return
}

// ReportApproveListReq 审批列表请求体
type ReportApproveListReq struct {
	PageSize         int    `form:"PageSize"`
	CurrentIndex     int    `form:"CurrentIndex"`
	ListType         int    `form:"ListType" description:"列表类型：1-待处理；2-已处理；3-我发起的"`
	ReportType       int    `form:"ReportType" description:"报告类型：1-中文研报；2-英文研报；3-智能研报"`
	ClassifyFirstId  int    `form:"ClassifyFirstId" description:"一级分类ID"`
	ClassifySecondId int    `form:"ClassifySecondId" description:"二级分类ID"`
	Keyword          string `form:"Keyword" description:"关键词：报告标题"`
	ApproveState     int    `form:"ApproveState" description:"审批状态：1-待审批；2-已审批；3-已驳回；4-已撤回"`
	TimeType         int    `form:"TimeType" description:"时间类型：1-提交时间；2-处理时间；3-审批时间"`
	StartTime        string `form:"StartTime" description:"开始时间"`
	EndTime          string `form:"EndTime" description:"结束时间"`
	SortField        int    `form:"SortField" description:"排序字段：1-提交时间；2-处理时间；3-审批时间"`
	SortRule         int    `form:"SortRule" description:"排序方式: 1-正序; 2-倒序(默认)"`
}

// ReportApproveListResp 审批列表响应体
type ReportApproveListResp struct {
	List   []*ReportApproveItem
	Paging *paging.PagingItem `description:"分页数据"`
}

type ReportApproveItemOrm struct {
	ReportApproveId       int       `description:"审批ID"`
	ReportApproveRecordId int       `description:"审批记录ID"`
	ReportType            int       `description:"报告类型：1-中文研报；2-英文研报；3-智能研报"`
	ReportId              int       `description:"报告ID"`
	ReportTitle           string    `description:"报告标题"`
	ClassifyFirstId       int       `description:"一级分类ID"`
	ClassifySecondId      int       `description:"二级分类ID"`
	State                 int       `description:"审批状态：1-待审批；2-已审批；3-已驳回；4-已撤回"`
	RecordState           int       `description:"审批记录状态：1-待审批；2-已通过；3-已驳回"`
	FlowId                int       `description:"审批流ID"`
	FlowVersion           int       `description:"审批流版本"`
	StartNodeId           int       `description:"开始节点ID"`
	CurrNodeId            int       `description:"当前节点ID"`
	ApplyUserId           int       `description:"申请人ID"`
	ApplyUserName         string    `description:"申请人姓名"`
	ApproveRemark         string    `description:"审批备注"`
	ApproveTime           time.Time `description:"审批时间"`
	HandleTime            time.Time `description:"处理时间"`
	CreateTime            time.Time `description:"创建时间"`
	ModifyTime            time.Time `description:"修改时间"`
}

// GetApprovingReportApproveCount 获取待处理的审批分页列表总数
func GetApprovingReportApproveCount(cond string, pars []interface{}) (count int, err error) {
	o := orm.NewOrmUsingDB("rddp")
	base := fmt.Sprintf(`SELECT a.report_approve_record_id
		FROM report_approve_record AS a
		JOIN report_approve AS b ON a.report_approve_id = b.report_approve_id AND a.node_id = b.curr_node_id
		WHERE 1 = 1 %s`, cond)
	sql := fmt.Sprintf(`SELECT COUNT(1) FROM (%s) t`, base)
	err = o.Raw(sql, pars).QueryRow(&count)
	return
}

// GetApprovingReportApprovePageList 获取待处理的审批列表-分页
func GetApprovingReportApprovePageList(cond string, pars []interface{}, orderRule string, startSize, pageSize int) (items []*ReportApproveItemOrm, err error) {
	o := orm.NewOrmUsingDB("rddp")
	order := `ORDER BY a.create_time DESC`
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT a.report_approve_record_id, a.state AS record_state, b.*
		FROM report_approve_record AS a
		JOIN report_approve AS b ON a.report_approve_id = b.report_approve_id AND a.node_id = b.curr_node_id
		WHERE 1 = 1 %s %s
		LIMIT ?,?`, cond, order)
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

// GetApprovedReportApproveCount 获取已处理的审批分页列表总数
func GetApprovedReportApproveCount(cond string, pars []interface{}) (count int, err error) {
	o := orm.NewOrmUsingDB("rddp")
	base := fmt.Sprintf(`SELECT a.report_approve_record_id
		FROM report_approve_record AS a
		JOIN report_approve AS b ON a.report_approve_id = b.report_approve_id
		WHERE 1 = 1 %s`, cond)
	sql := fmt.Sprintf(`SELECT COUNT(1) FROM (%s) t`, base)
	err = o.Raw(sql, pars).QueryRow(&count)
	return
}

// GetApprovedReportApprovePageList 获取已处理的审批列表-分页
func GetApprovedReportApprovePageList(cond string, pars []interface{}, orderRule string, startSize, pageSize int) (items []*ReportApproveItemOrm, err error) {
	o := orm.NewOrmUsingDB("rddp")
	order := `ORDER BY a.create_time DESC`
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT a.report_approve_record_id, a.state AS record_state, a.approve_time AS handle_time, b.*
		FROM report_approve_record AS a
		JOIN report_approve AS b ON a.report_approve_id = b.report_approve_id
		WHERE 1 = 1 %s %s
		LIMIT ?,?`, cond, order)
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

// GetApplyReportApproveCount 获取我发起的审批分页列表总数
func GetApplyReportApproveCount(cond string, pars []interface{}) (count int, err error) {
	o := orm.NewOrmUsingDB("rddp")
	base := fmt.Sprintf(`SELECT a.* FROM report_approve AS a WHERE 1 = 1 %s`, cond)
	sql := fmt.Sprintf(`SELECT COUNT(1) FROM (%s) t`, base)
	err = o.Raw(sql, pars).QueryRow(&count)
	return
}

// GetApplyReportApprovePageList 获取我发起的审批列表-分页
func GetApplyReportApprovePageList(cond string, pars []interface{}, orderRule string, startSize, pageSize int) (items []*ReportApproveItemOrm, err error) {
	o := orm.NewOrmUsingDB("rddp")
	order := `ORDER BY a.create_time DESC`
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT a.* FROM report_approve AS a WHERE 1 = 1 %s %s LIMIT ?,?`, cond, order)
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

// ReportApproveDetail 审批详情信息
type ReportApproveDetail struct {
	Report           *ReportApproveDetailReport  `description:"报告信息"`
	Approve          *ReportApproveDetailItem    `description:"审批信息"`
	ApproveFlowNodes []*ReportApproveDetailNodes `description:"审批节点信息"`
	//ApproveFlow      *ReportApproveFlowItem      `description:"审批流信息"`
}

// ReportApproveDetailItem 审批详情-审批信息
type ReportApproveDetailItem struct {
	ReportApproveId int    `description:"审批ID"`
	State           int    `description:"审批状态：1-待审批；2-已审批；3-已驳回；4-已撤回"`
	FlowId          int    `description:"审批流ID"`
	FlowVersion     int    `description:"审批流版本"`
	StartNodeId     int    `description:"开始节点ID"`
	CurrNodeId      int    `description:"当前节点ID"`
	ApplyUserId     int    `description:"申请人ID"`
	ApplyUserName   string `description:"申请人姓名"`
	ApproveTime     string `description:"审批时间"`
	CreateTime      string `description:"创建时间"`
	ModifyTime      string `description:"修改时间"`
}

// ReportApproveDetailReport 审批详情-报告信息
type ReportApproveDetailReport struct {
	ReportType     int    `description:"报告类型：1-中文研报；2-英文研报；3-智能研报"`
	ReportId       int    `description:"报告ID"`
	ReportTitle    string `description:"报告标题"`
	ReportCode     string `description:"报告code"`
	ReportClassify string `description:"报告分类"`
	//ClassifyFirstId  int    `description:"一级分类ID"`
	//ClassifySecondId int    `description:"二级分类ID"`
	//Content          string `description:"报告内容"`
}

// CreateApproveAndRecord 新增审批和记录
func (m *ReportApprove) CreateApproveAndRecord(approveItem *ReportApprove, recordItems []*ReportApproveRecord) (err error) {
	if approveItem == nil {
		err = fmt.Errorf("approve is nil")
		return
	}
	o := orm.NewOrmUsingDB("rddp")
	tx, e := o.Begin()
	if e != nil {
		err = fmt.Errorf("orm begin err: %s", e.Error())
		return
	}
	defer func() {
		if err != nil {
			_ = tx.Rollback()
			return
		}
		_ = tx.Commit()
	}()

	lastId, e := tx.Insert(approveItem)
	if e != nil {
		err = fmt.Errorf("insert approve err: %s", e.Error())
		return
	}
	approveItem.ReportApproveId = int(lastId)

	if len(recordItems) > 0 {
		for _, v := range recordItems {
			v.ReportApproveId = approveItem.ReportApproveId
		}
		_, e = tx.InsertMulti(len(recordItems), recordItems)
		if e != nil {
			err = fmt.Errorf("insert records err: %s", e.Error())
			return
		}
	}
	return
}

// ReportApprovePassReq 审批通过请求体
type ReportApprovePassReq struct {
	ReportApproveId int    `description:"审批ID"`
	ReportUrl       string `description:"报告URL"`
}

// ReportApproveRefuseReq 审批驳回请求体
type ReportApproveRefuseReq struct {
	ReportApproveId int    `description:"审批ID"`
	ApproveRemark   string `description:"驳回理由"`
}

// ReportApproveCancelReq 撤销审批请求体
type ReportApproveCancelReq struct {
	ReportApproveId int `description:"审批ID"`
}

// ReportApproveCheckApproveOpenReq 校验分类是否打开审批请求体
type ReportApproveCheckApproveOpenReq struct {
	ReportType       int `description:"报告类型：1-中文研报；2-英文研报；3-智能研报"`
	ClassifyFirstId  int `description:"一级分类ID"`
	ClassifySecondId int `description:"二级分类ID"`
}
