package report_approve

import (
	"eta_gn/eta_api/global"
	"eta_gn/eta_api/utils"
	"fmt"
	"strings"
	"time"

	"github.com/rdlucklib/rdluck_tools/paging"
)

type ReportApprove struct {
	ReportApproveId  int       `gorm:"primaryKey;column:report_approve_id;type:int(10) unsigned;not null"`                      // 审批ID
	ReportType       int       `gorm:"column:report_type;type:tinyint(4) unsigned;not null;default:0"`                          // 报告类型:1-中文研报;2-英文研报;3-智能研报
	ReportId         int       `gorm:"index:idx_report_id;column:report_id;type:int(10) unsigned;not null;default:0"`           // 报告Id
	ReportTitle      string    `gorm:"column:report_title;type:varchar(255);not null;default:''"`                               // 报告标题
	ClassifyFirstId  int       `gorm:"column:classify_first_id;type:int(10) unsigned;not null;default:0"`                       // 一级分类Id
	ClassifySecondId int       `gorm:"column:classify_second_id;type:int(10) unsigned;not null;default:0"`                      // 二级分类Id
	State            int       `gorm:"column:state;type:tinyint(4) unsigned;not null;default:0"`                                // 审批状态:1-待审批;2-已审批;3-已驳回;4-已撤回
	FlowId           int       `gorm:"column:flow_id;type:int(10) unsigned;not null;default:0"`                                 // 审批流Id
	FlowVersion      int       `gorm:"column:flow_version;type:int(10) unsigned;not null;default:0"`                            // 审批流版本
	StartNodeId      int       `gorm:"column:start_node_id;type:int(10) unsigned;not null;default:0"`                           // 开始节点Id
	CurrNodeId       int       `gorm:"column:curr_node_id;type:int(10) unsigned;not null;default:0"`                            // 当前节点Id
	ApplyUserId      int       `gorm:"index:idx_approve_user_id;column:apply_user_id;type:int(10) unsigned;not null;default:0"` // 申请人Id
	ApplyUserName    string    `gorm:"column:apply_user_name;type:varchar(128);not null;default:''"`                            // 申请人姓名
	ApproveRemark    string    `gorm:"column:approve_remark;type:varchar(255);not null;default:''"`                             // 审批备注
	ApproveTime      time.Time `gorm:"column:approve_time;type:datetime"`                                                       // 审批时间
	CreateTime       time.Time `gorm:"column:create_time;type:datetime"`                                                        // 创建时间
	ModifyTime       time.Time `gorm:"column:modify_time;type:datetime"`                                                        // 更新时间
	ClassifyThirdId  int       `gorm:"column:classify_third_id;type:int(10) unsigned;default:0"`                                // 三级分类Id
}

var ReportApproveCols = struct {
	ReportApproveId  string
	ReportType       string
	ReportId         string
	ReportTitle      string `description:"报告标题"`
	ClassifyFirstId  string `description:"一级分类ID"`
	ClassifySecondId string `description:"二级分类ID"`
	ClassifyThirdId  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",
	ClassifyThirdId:  "classify_third_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) {
	err = global.DmSQL["rddp"].Create(m).Error
	return
}

func (m *ReportApprove) CreateMulti(items []*ReportApprove) (err error) {
	if len(items) == 0 {
		return
	}
	err = global.DmSQL["rddp"].CreateInBatches(items, utils.MultiAddNum).Error
	return
}

func (m *ReportApprove) Update(cols []string) (err error) {
	err = global.DmSQL["rddp"].Select(cols).Updates(m).Error
	return
}

func (m *ReportApprove) Del() (err error) {
	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), m.PrimaryId())
	err = global.DmSQL["rddp"].Exec(sql, m.ReportApproveId).Error
	return
}

func (m *ReportApprove) MultiDel(menuIds []int) (err error) {
	if len(menuIds) == 0 {
		return
	}
	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s IN (%s)`, m.TableName(), m.PrimaryId(), utils.GetOrmInReplace(len(menuIds)))
	err = global.DmSQL["rddp"].Exec(sql, menuIds).Error
	return
}

func (m *ReportApprove) GetItemById(id int) (item *ReportApprove, err error) {
	sql := fmt.Sprintf(`SELECT * FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), m.PrimaryId())
	err = global.DmSQL["rddp"].Raw(sql, id).First(&item).Error
	return
}

func (m *ReportApprove) GetItemByCondition(condition string, pars []interface{}, orderRule string) (item *ReportApprove, err error) {
	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 = global.DmSQL["rddp"].Raw(sql, pars).First(&item).Error
	return
}

func (m *ReportApprove) GetCountByCondition(condition string, pars []interface{}) (count int, err error) {
	sql := fmt.Sprintf(`SELECT COUNT(1) FROM %s WHERE 1=1 %s`, m.TableName(), condition)
	err = global.DmSQL["rddp"].Raw(sql, pars...).Scan(&count).Error
	return
}

func (m *ReportApprove) GetItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string) (items []*ReportApprove, err error) {
	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 = global.DmSQL["rddp"].Raw(sql, pars...).Find(&items).Error
	return
}

func (m *ReportApprove) GetPageItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string, startSize, pageSize int) (items []*ReportApprove, err error) {
	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 = global.DmSQL["rddp"].Raw(sql, pars...).Find(&items).Error
	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"`
	ClassifyThirdId       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:"修改时间"`
	DetailImgUrl          string `description:"报告详情长图地址"`
	DetailPdfUrl          string `description:"报告详情PDF地址"`
}

// 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.ClassifyThirdId = origin.ClassifyThirdId
	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"`
	ClassifyThirdId  int    `form:"ClassifyThirdId" 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"`
	ClassifyThirdId       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:"修改时间"`
	NodeState             int       `description:"当前节点审批状态:1-待审批;2-已审批;3-已驳回;4-已撤回" json:"-"`
	NodeApproveTime       time.Time `description:"当前节点审批时间" json:"-"`
}

// GetApprovingReportApproveCount 获取待处理的审批分页列表总数
func GetApprovingReportApproveCount(cond string, pars []interface{}) (count int, err error) {
	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 = global.DmSQL["rddp"].Raw(sql, pars...).Scan(&count).Error
	return
}

// GetApprovingReportApprovePageList 获取待处理的审批列表-分页
func GetApprovingReportApprovePageList(cond string, pars []interface{}, orderRule string, startSize, pageSize int) (items []*ReportApproveItemOrm, err error) {
	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)
	pars = append(pars, startSize, pageSize)
	err = global.DmSQL["rddp"].Raw(sql, pars...).Find(&items).Error
	return
}

// GetApprovedReportApproveCount 获取已处理的审批分页列表总数
func GetApprovedReportApproveCount(cond string, pars []interface{}) (count int, err error) {
	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 = global.DmSQL["rddp"].Raw(sql, pars...).Scan(&count).Error
	return
}

// GetApprovedReportApprovePageList 获取已处理的审批列表-分页
func GetApprovedReportApprovePageList(cond string, pars []interface{}, orderRule string, startSize, pageSize int) (items []*ReportApproveItemOrm, err error) {
	order := `ORDER BY a.create_time DESC`
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT a.report_approve_record_id, a.node_state AS record_state,a.node_state,a.node_approve_time, a.node_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)
	pars = append(pars, startSize, pageSize)
	err = global.DmSQL["rddp"].Raw(sql, pars...).Find(&items).Error
	return
}

// GetApplyReportApproveCount 获取我发起的审批分页列表总数
func GetApplyReportApproveCount(cond string, pars []interface{}) (count int, err error) {
	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 = global.DmSQL["rddp"].Raw(sql, pars...).Scan(&count).Error
	return
}

// GetApplyReportApprovePageList 获取我发起的审批列表-分页
func GetApplyReportApprovePageList(cond string, pars []interface{}, orderRule string, startSize, pageSize int) (items []*ReportApproveItemOrm, err error) {
	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)
	pars = append(pars, startSize)
	pars = append(pars, pageSize)
	err = global.DmSQL["rddp"].Raw(sql, pars...).Find(&items).Error
	return
}

// ReportApproveDetail 审批详情信息
type ReportApproveDetail struct {
	Report           *ReportApproveDetailReport  `description:"报告信息"`
	Approve          *ReportApproveDetailItem    `description:"审批信息"`
	ApproveFlowNodes []*ReportApproveDetailNodes `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:"报告分类"`
	ReportLayout   int8   `description:"报告布局,1:常规布局,2:智能布局。默认:1"`
}

// CreateApproveAndRecord 新增审批和记录
func (m *ReportApprove) CreateApproveAndRecord(approveItem *ReportApprove, recordItems []*ReportApproveRecord) (err error) {
	if approveItem == nil {
		err = fmt.Errorf("approve is nil")
		return
	}

	tx := global.DmSQL["data"].Begin()
	defer func() {
		if err != nil {
			_ = tx.Rollback()
			return
		}
		_ = tx.Commit()
	}()

	e := tx.Create(approveItem).Error
	if e != nil {
		err = fmt.Errorf("insert approve err: %v", e)
		return
	}

	if len(recordItems) > 0 {
		for _, v := range recordItems {
			v.ReportApproveId = approveItem.ReportApproveId
		}
		e = tx.CreateInBatches(recordItems, utils.MultiAddNum).Error
		if e != nil {
			err = fmt.Errorf("insert records err: %v", e)
			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"`
	ClassifyThirdId  int `description:"三级分类ID"`
}