package report_approve

import (
	"encoding/json"
	"eta/eta_api/controllers"
	"eta/eta_api/models"
	"eta/eta_api/models/report_approve"
	"eta/eta_api/services"
	"eta/eta_api/utils"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"sort"
	"strconv"
	"strings"
	"time"
)

// ReportApproveController 报告审批
type ReportApproveController struct {
	controllers.BaseAuthController
}

// List
// @Title 审批列表
// @Description 审批列表
// @Param   PageSize			query	int		true	"每页数据条数"
// @Param   CurrentIndex		query	int		true	"当前页页码"
// @Param   ListType			query   int     true	"列表类型：1-待处理；2-已处理；3-我发起的"
// @Param   ReportType			query   int     false	"报告类型：1-中文研报；2-英文研报；3-智能研报"
// @Param   ClassifyIdFirst		query	int		false	"一级分类ID"
// @Param   ClassifyIdSecond	query	int		false	"二级分类ID"
// @Param   Keyword				query	string	false	"搜索关键词"
// @Param   ApproveState		query	int		false	"审批状态：1-待审批；2-已审批；3-已驳回；4-已撤回"
// @Param   TimeType			query	int		false	"时间类型：1-提交时间；2-处理时间；3-审批时间"
// @Param   StartTime			query	string	false	"开始时间"
// @Param   EndTime				query	string	false	"结束时间"
// @Param   SortField			query	int		false	"排序字段：1-提交时间；2-处理时间；3-审批时间"
// @Param   SortRule			query	int		false	"排序方式: 1-正序; 2-倒序(默认)"
// @Success 200 {object} report_approve.ReportApproveListResp
// @router /list [get]
func (this *ReportApproveController) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	params := new(report_approve.ReportApproveListReq)
	if e := this.ParseForm(params); e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "入参解析失败, Err: " + e.Error()
		return
	}
	if params.ListType != 1 && params.ListType != 2 && params.ListType != 3 {
		br.Msg = "列表类型有误"
		return
	}

	// 报告分类
	cnClassifyIdName, enClassifyIdName := make(map[int]string), make(map[int]string)
	cnClassify, e := models.GetAllClassify()
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取中文分类失败, Err: " + e.Error()
		return
	}
	for _, v := range cnClassify {
		cnClassifyIdName[v.Id] = v.ClassifyName
	}
	enClassify, e := models.GetEnglishClassifies()
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取英文分类失败, Err: " + e.Error()
		return
	}
	enRootIdMap := make(map[int]int) // 英文分类的一级分类ID
	for _, v := range enClassify {
		enClassifyIdName[v.Id] = v.ClassifyName
		enRootIdMap[v.Id] = v.RootId
	}

	// 分页
	var startSize int
	if params.PageSize <= 0 {
		params.PageSize = utils.PageSize20
	}
	if params.CurrentIndex <= 0 {
		params.CurrentIndex = 1
	}
	startSize = utils.StartIndex(params.CurrentIndex, params.PageSize)

	resp := new(report_approve.ReportApproveListResp)
	respTotal := 0
	respList := make([]*report_approve.ReportApproveItem, 0)
	timeField := map[int]string{1: fmt.Sprintf("a.%s", report_approve.ReportApproveCols.CreateTime), 2: fmt.Sprintf("a.%s", report_approve.ReportApproveRecordCols.ApproveTime), 3: fmt.Sprintf("b.%s", report_approve.ReportApproveCols.ApproveTime)}
	mineTimeField := map[int]string{1: fmt.Sprintf("%s", report_approve.ReportApproveCols.CreateTime), 3: fmt.Sprintf("%s", report_approve.ReportApproveCols.ApproveTime)}
	orderRules := map[int]string{1: "ASC", 2: "DESC"}
	ormList := make([]*report_approve.ReportApproveItemOrm, 0)

	// 待处理
	if params.ListType == 1 {
		cond := fmt.Sprintf(` AND a.%s = ? AND b.%s = ? AND a.%s = ?`, report_approve.ReportApproveRecordCols.State, report_approve.ReportApproveCols.State, report_approve.ReportApproveRecordCols.ApproveUserId)
		pars := make([]interface{}, 0)
		pars = append(pars, report_approve.ReportApproveStateApproving, report_approve.ReportApproveStateApproving, sysUser.AdminId)
		order := ""

		// 筛选条件
		if params.ReportType > 0 && params.ClassifySecondId > 0 {
			cond += fmt.Sprintf(` AND b.%s = ? AND b.%s = ?`, report_approve.ReportApproveCols.ReportType, report_approve.ReportApproveCols.ClassifySecondId)
			pars = append(pars, params.ReportType, params.ClassifySecondId)
		}
		if params.TimeType <= 0 {
			params.TimeType = 1
		}
		if params.TimeType == 1 && params.StartTime != "" && params.EndTime != "" {
			_, e := time.Parse(utils.FormatDate, params.StartTime)
			if e != nil {
				br.Msg = "开始时间格式有误"
				return
			}
			_, e = time.Parse(utils.FormatDate, params.EndTime)
			if e != nil {
				br.Msg = "结束时间格式有误"
				return
			}
			st := fmt.Sprintf("%s %s", params.StartTime, "00:00:00")
			ed := fmt.Sprintf("%s %s", params.EndTime, "23:59:59")
			cond += fmt.Sprintf(` AND (b.%s BETWEEN ? AND ?)`, report_approve.ReportApproveCols.CreateTime)
			pars = append(pars, st, ed)
		}
		params.Keyword = strings.TrimSpace(params.Keyword)
		if params.Keyword != "" {
			kw := fmt.Sprint("%", params.Keyword, "%")
			cond += fmt.Sprintf(` AND b.%s LIKE ?`, report_approve.ReportApproveCols.ReportTitle)
			pars = append(pars, kw)
		}
		if params.SortField > 0 && params.SortRule > 0 {
			orderField := timeField[params.SortField]
			if orderField == "" {
				br.Msg = "时间排序字段有误"
				return
			}
			orderRule := orderRules[params.SortRule]
			if orderRule == "" {
				br.Msg = "时间排序方式有误"
				return
			}
			order = fmt.Sprintf("%s %s", orderField, orderRule)
		}
		total, e := report_approve.GetApprovingReportApproveCount(cond, pars)
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "GetApprovingReportApproveCount err: " + e.Error()
			return
		}
		respTotal = total
		list, e := report_approve.GetApprovingReportApprovePageList(cond, pars, order, startSize, params.PageSize)
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "GetApprovingReportApprovePageList err: " + e.Error()
			return
		}
		ormList = list
	}

	// 已处理
	if params.ListType == 2 {
		cond := fmt.Sprintf(` AND a.%s = ? AND a.%s IN (%s)`, report_approve.ReportApproveRecordCols.ApproveUserId, report_approve.ReportApproveRecordCols.State, utils.GetOrmInReplace(2))
		pars := make([]interface{}, 0)
		pars = append(pars, sysUser.AdminId, []int{report_approve.ReportApproveStatePass, report_approve.ReportApproveStateRefuse})
		order := ""

		// 筛选条件
		if params.ReportType > 0 && params.ClassifySecondId > 0 {
			cond += fmt.Sprintf(` AND b.%s = ? AND b.%s = ?`, report_approve.ReportApproveCols.ReportType, report_approve.ReportApproveCols.ClassifySecondId)
			pars = append(pars, params.ReportType, params.ClassifySecondId)
		}
		if params.TimeType > 0 && params.StartTime != "" && params.EndTime != "" {
			_, e := time.Parse(utils.FormatDate, params.StartTime)
			if e != nil {
				br.Msg = "开始时间格式有误"
				return
			}
			_, e = time.Parse(utils.FormatDate, params.EndTime)
			if e != nil {
				br.Msg = "结束时间格式有误"
				return
			}
			st := fmt.Sprintf("%s %s", params.StartTime, "00:00:00")
			ed := fmt.Sprintf("%s %s", params.EndTime, "23:59:59")
			cond += fmt.Sprintf(` AND (%s BETWEEN ? AND ?)`, timeField[params.TimeType])
			pars = append(pars, st, ed)
		}
		params.Keyword = strings.TrimSpace(params.Keyword)
		if params.Keyword != "" {
			kw := fmt.Sprint("%", params.Keyword, "%")
			cond += fmt.Sprintf(` AND b.%s LIKE ?`, report_approve.ReportApproveCols.ReportTitle)
			pars = append(pars, kw)
		}
		if params.SortField > 0 && params.SortRule > 0 {
			orderField := timeField[params.SortField]
			if orderField == "" {
				br.Msg = "时间排序字段有误"
				return
			}
			orderRule := orderRules[params.SortRule]
			if orderRule == "" {
				br.Msg = "时间排序方式有误"
				return
			}
			order = fmt.Sprintf("%s %s", orderField, orderRule)
		}
		if params.ApproveState > 0 {
			cond += fmt.Sprintf(` AND a.%s = ?`, report_approve.ReportApproveRecordCols.State)
			pars = append(pars, params.ApproveState)
		}
		total, e := report_approve.GetApprovedReportApproveCount(cond, pars)
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "GetApprovedReportApproveCount err: " + e.Error()
			return
		}
		respTotal = total
		list, e := report_approve.GetApprovedReportApprovePageList(cond, pars, order, startSize, params.PageSize)
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "GetApprovedReportApprovePageList err: " + e.Error()
			return
		}
		ormList = list
	}

	// 我发起的
	if params.ListType == 3 {
		cond := fmt.Sprintf(` AND a.%s = ?`, report_approve.ReportApproveCols.ApplyUserId)
		pars := make([]interface{}, 0)
		pars = append(pars, sysUser.AdminId)
		order := ""

		// 筛选条件
		if params.ReportType > 0 && params.ClassifySecondId > 0 {
			cond += fmt.Sprintf(` AND a.%s = ? AND a.%s = ?`, report_approve.ReportApproveCols.ReportType, report_approve.ReportApproveCols.ClassifySecondId)
			pars = append(pars, params.ReportType, params.ClassifySecondId)
		}
		if params.TimeType > 0 && params.StartTime != "" && params.EndTime != "" {
			_, e := time.Parse(utils.FormatDate, params.StartTime)
			if e != nil {
				br.Msg = "开始时间格式有误"
				return
			}
			_, e = time.Parse(utils.FormatDate, params.EndTime)
			if e != nil {
				br.Msg = "结束时间格式有误"
				return
			}
			st := fmt.Sprintf("%s %s", params.StartTime, "00:00:00")
			ed := fmt.Sprintf("%s %s", params.EndTime, "23:59:59")
			field := mineTimeField[params.TimeType]
			if field == "" {
				br.Msg = "筛选时间有误"
				return
			}
			cond += fmt.Sprintf(` AND (%s BETWEEN ? AND ?)`, field)
			pars = append(pars, st, ed)
		}
		params.Keyword = strings.TrimSpace(params.Keyword)
		if params.Keyword != "" {
			kw := fmt.Sprint("%", params.Keyword, "%")
			cond += fmt.Sprintf(` AND a.%s LIKE ?`, report_approve.ReportApproveCols.ReportTitle)
			pars = append(pars, kw)
		}
		if params.SortField > 0 && params.SortRule > 0 {
			orderField := mineTimeField[params.SortField]
			if orderField == "" {
				br.Msg = "时间排序字段有误"
				return
			}
			orderRule := orderRules[params.SortRule]
			if orderRule == "" {
				br.Msg = "时间排序方式有误"
				return
			}
			order = fmt.Sprintf("%s %s", orderField, orderRule)
		}
		if params.ApproveState > 0 {
			cond += fmt.Sprintf(` AND a.%s = ?`, report_approve.ReportApproveRecordCols.State)
			pars = append(pars, params.ApproveState)
		}
		total, e := report_approve.GetApplyReportApproveCount(cond, pars)
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "GetApplyReportApproveCount err: " + e.Error()
			return
		}
		respTotal = total
		list, e := report_approve.GetApplyReportApprovePageList(cond, pars, order, startSize, params.PageSize)
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "GetApplyReportApprovePageList err: " + e.Error()
			return
		}
		ormList = list
	}

	// 格式化列表
	for _, v := range ormList {
		t := report_approve.FormatReportApproveOrm2Item(v)
		if v.ReportType == report_approve.FlowReportTypeEnglish {
			t.ReportClassify = fmt.Sprintf("%s/%s/%s/%s", report_approve.FlowReportTypeMap[v.ReportType], enClassifyIdName[enRootIdMap[v.ClassifySecondId]], enClassifyIdName[v.ClassifyFirstId], enClassifyIdName[v.ClassifySecondId])
		} else {
			t.ReportClassify = fmt.Sprintf("%s/%s/%s", report_approve.FlowReportTypeMap[v.ReportType], cnClassifyIdName[v.ClassifyFirstId], cnClassifyIdName[v.ClassifySecondId])
		}
		respList = append(respList, t)
	}

	page := paging.GetPaging(params.CurrentIndex, params.PageSize, respTotal)
	resp.Paging = page
	resp.List = respList
	br.Data = resp
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
}

// Detail
// @Title 审批详情
// @Description 审批详情
// @Param   ReportApproveId  query  int  true  "审批ID"
// @Success 200 {object} report_approve.ReportApproveDetail
// @router /detail [get]
func (this *ReportApproveController) Detail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	approveId, _ := this.GetInt("ReportApproveId")
	if approveId <= 0 {
		br.Msg = "参数有误"
		br.ErrMsg = fmt.Sprintf("参数有误, ReportApproveId: %d", approveId)
		return
	}

	approveOb := new(report_approve.ReportApprove)
	approveItem, e := approveOb.GetItemById(approveId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "审批已被删除, 请刷新页面"
			return
		}
		br.Msg = "获取失败"
		br.ErrMsg = "获取审批失败, Err: " + e.Error()
		return
	}

	// 审批信息
	detail := new(report_approve.ReportApproveDetail)
	detail.Approve = new(report_approve.ReportApproveDetailItem)
	detail.Approve.ReportApproveId = approveItem.ReportApproveId
	detail.Approve.State = approveItem.State
	detail.Approve.FlowId = approveItem.FlowId
	detail.Approve.FlowVersion = approveItem.FlowVersion
	detail.Approve.StartNodeId = approveItem.StartNodeId
	detail.Approve.CurrNodeId = approveItem.CurrNodeId
	detail.Approve.ApplyUserId = approveItem.ApplyUserId
	detail.Approve.ApplyUserName = approveItem.ApplyUserName
	detail.Approve.ApproveTime = utils.TimeTransferString(utils.FormatDateTime, approveItem.ApproveTime)
	detail.Approve.CreateTime = utils.TimeTransferString(utils.FormatDateTime, approveItem.CreateTime)
	detail.Approve.ModifyTime = utils.TimeTransferString(utils.FormatDateTime, approveItem.ModifyTime)

	// 审批流
	//flowOb := new(report_approve.ReportApproveFlow)
	//flowItem, e := flowOb.GetItemById(approveItem.FlowId)
	//if e != nil {
	//	if e.Error() == utils.ErrNoRow() {
	//		br.Msg = "审批流已被删除, 请刷新页面"
	//		return
	//	}
	//	br.Msg = "获取失败"
	//	br.ErrMsg = "获取审批流失败, Err: " + e.Error()
	//	return
	//}
	//detail.ApproveFlow = report_approve.FormatReportApproveFlow2Item(flowItem)

	// 审批节点
	nodeOb := new(report_approve.ReportApproveNode)
	nodeCond := fmt.Sprintf(` AND %s = ? AND %s = ?`, report_approve.ReportApproveNodeCols.ReportApproveFlowId, report_approve.ReportApproveNodeCols.CurrVersion)
	nodePars := make([]interface{}, 0)
	nodePars = append(nodePars, approveItem.FlowId, approveItem.FlowVersion)
	nodeItems, e := nodeOb.GetItemsByCondition(nodeCond, nodePars, []string{}, "")
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取审批节点失败, Err: " + e.Error()
		return
	}

	// 审批记录
	recordOb := new(report_approve.ReportApproveRecord)
	recordCond := fmt.Sprintf(` AND %s = ?`, report_approve.ReportApproveRecordCols.ReportApproveId)
	recordPars := make([]interface{}, 0)
	recordPars = append(recordPars, approveItem.ReportApproveId)
	recordItems, e := recordOb.GetItemsByCondition(recordCond, recordPars, []string{}, fmt.Sprintf("%s DESC", report_approve.ReportApproveRecordCols.ApproveTime))
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取审批记录失败, Err: " + e.Error()
		return
	}
	recordMap := make(map[string]*report_approve.ReportApproveRecord)
	for _, v := range recordItems {
		k := fmt.Sprintf("%d-%d", v.NodeId, v.ApproveUserId)
		recordMap[k] = v
	}

	// 审批流节点详情
	detail.ApproveFlowNodes = make([]*report_approve.ReportApproveDetailNodes, 0)
	for _, v := range nodeItems {
		t := new(report_approve.ReportApproveDetailNodes)
		t.ReportApproveNodeId = v.ReportApproveNodeId
		t.ReportApproveFlowId = v.ReportApproveFlowId
		t.PrevNodeId = v.PrevNodeId
		t.NextNodeId = v.NextNodeId
		t.NodeType = v.NodeType
		t.ApproveType = v.ApproveType
		t.Users = make([]*report_approve.ReportApproveDetailNodeUser, 0)
		us := make([]*report_approve.ReportApproveNodeUserReq, 0)
		if v.Users != "" {
			e = json.Unmarshal([]byte(v.Users), &us)
			if e != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "节点用户解析失败, Err: " + e.Error()
				return
			}
		}
		for _, vu := range us {
			u := new(report_approve.ReportApproveDetailNodeUser)
			u.UserType = vu.UserType
			u.UserId = vu.UserId
			u.UserName = vu.UserName
			u.Sort = vu.Sort
			// 审批记录
			k := fmt.Sprintf("%d-%d", v.ReportApproveNodeId, vu.UserId)
			r := recordMap[k]
			if r != nil {
				u.ApproveRecord = new(report_approve.ReportApproveDetailNodeUserRecord)
				u.ApproveRecord.ReportApproveRecordId = r.ReportApproveRecordId
				u.ApproveRecord.State = r.State
				u.ApproveRecord.ApproveUserId = r.ApproveUserId
				u.ApproveRecord.ApproveUserName = r.ApproveUserName
				u.ApproveRecord.ApproveRemark = r.ApproveRemark
				u.ApproveRecord.ApproveTime = utils.TimeTransferString(utils.FormatDateTime, r.ApproveTime)
			}
			t.Users = append(t.Users, u)
		}
		sort.Slice(t.Users, func(k, j int) bool {
			return t.Users[k].Sort < t.Users[j].Sort
		})
		detail.ApproveFlowNodes = append(detail.ApproveFlowNodes, t)
	}

	// 报告信息
	cnClassifyIdName, enClassifyIdName := make(map[int]string), make(map[int]string)
	cnClassify, e := models.GetAllClassify()
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取中文分类失败, Err: " + e.Error()
		return
	}
	for _, v := range cnClassify {
		cnClassifyIdName[v.Id] = v.ClassifyName
	}
	enClassify, e := models.GetEnglishClassifies()
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取英文分类失败, Err: " + e.Error()
		return
	}
	enRootIdMap := make(map[int]int) // 英文分类的一级分类ID
	for _, v := range enClassify {
		enClassifyIdName[v.Id] = v.ClassifyName
		enRootIdMap[v.Id] = v.RootId
	}
	detail.Report = new(report_approve.ReportApproveDetailReport)
	detail.Report.ReportType = approveItem.ReportType
	detail.Report.ReportId = approveItem.ReportId
	detail.Report.ReportTitle = approveItem.ReportTitle

	// 报告分类路由
	if approveItem.ReportType == report_approve.FlowReportTypeChinese {
		detail.Report.ReportCode = utils.MD5(strconv.Itoa(approveItem.ReportId))
		detail.Report.ReportClassify = fmt.Sprintf("%s/%s/%s", report_approve.FlowReportTypeMap[approveItem.ReportType], cnClassifyIdName[approveItem.ClassifyFirstId], cnClassifyIdName[approveItem.ClassifySecondId])
	}
	if approveItem.ReportType == report_approve.FlowReportTypeEnglish {
		detail.Report.ReportCode = utils.MD5(strconv.Itoa(approveItem.ReportId))
		detail.Report.ReportClassify = fmt.Sprintf("%s/%s/%s/%s", report_approve.FlowReportTypeMap[approveItem.ReportType], enClassifyIdName[enRootIdMap[approveItem.ClassifySecondId]], enClassifyIdName[approveItem.ClassifyFirstId], enClassifyIdName[approveItem.ClassifySecondId])
	}
	if approveItem.ReportType == report_approve.FlowReportTypeSmart {
		detail.Report.ReportCode = 	utils.MD5(fmt.Sprint("smart_", approveItem.ReportId))
		detail.Report.ReportClassify = fmt.Sprintf("%s/%s/%s", report_approve.FlowReportTypeMap[approveItem.ReportType], cnClassifyIdName[approveItem.ClassifyFirstId], cnClassifyIdName[approveItem.ClassifySecondId])
	}

	br.Data = detail
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
}

// Approve
// @Title 通过审批
// @Description 通过审批
// @Param	request	body report_approve.ReportApprovePassReq true "type json string"
// @Success 200 string "操作成功"
// @router /approve [post]
func (this *ReportApproveController) Approve() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req report_approve.ReportApprovePassReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数有误"
		br.ErrMsg = "参数解析失败, Err: " + e.Error()
		return
	}
	if req.ReportApproveId <= 0 {
		br.Msg = "参数有误"
		br.ErrMsg = fmt.Sprintf("参数有误, ReportApproveId: %d", req.ReportApproveId)
		return
	}

	approveOb := new(report_approve.ReportApprove)
	approveItem, e := approveOb.GetItemById(req.ReportApproveId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "审批不存在, 请刷新页面"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "获取审批信息失败, Err: " + e.Error()
		return
	}
	if approveItem.State != report_approve.ReportApproveStateApproving {
		br.Msg = "审批状态有误, 请刷新页面"
		br.ErrMsg = fmt.Sprintf("审批状态有误, State: %d", approveItem.State)
		return
	}

	// 校验审批记录和审批
	recordOb := new(report_approve.ReportApproveRecord)
	recordCond := fmt.Sprintf(` AND %s = ? AND %s = ? AND %s = ?`, report_approve.ReportApproveRecordCols.ReportApproveId, report_approve.ReportApproveRecordCols.ApproveUserId, report_approve.ReportApproveRecordCols.State)
	recordPars := make([]interface{}, 0)
	recordPars = append(recordPars, approveItem.ReportApproveId, sysUser.AdminId, report_approve.ReportApproveStateApproving)
	recordItem, e := recordOb.GetItemByCondition(recordCond, recordPars, "")
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "无权审批"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "获取审批记录失败, Err: " + e.Error()
		return
	}

	// 通过审批
	tips, e := services.PassReportApprove(approveItem, recordItem, sysUser.AdminId, req.ReportUrl)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "通过审批失败, Err: " + e.Error()
		return
	}
	if tips != "" {
		br.Msg = tips
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// Refuse
// @Title 驳回审批
// @Description 驳回审批
// @Param	request	body report_approve.ReportApproveRefuseReq true "type json string"
// @Success 200 string "操作成功"
// @router /refuse [post]
func (this *ReportApproveController) Refuse() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req report_approve.ReportApproveRefuseReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数有误"
		br.ErrMsg = "参数解析失败, Err: " + e.Error()
		return
	}
	if req.ReportApproveId <= 0 {
		br.Msg = "参数有误"
		br.ErrMsg = fmt.Sprintf("参数有误, ReportApproveId: %d", req.ReportApproveId)
		return
	}

	approveOb := new(report_approve.ReportApprove)
	approveItem, e := approveOb.GetItemById(req.ReportApproveId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "审批不存在, 请刷新页面"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "获取审批信息失败, Err: " + e.Error()
		return
	}
	if approveItem.State != report_approve.ReportApproveStateApproving {
		br.Msg = "审批状态有误, 请刷新页面"
		br.ErrMsg = fmt.Sprintf("审批状态有误, State: %d", approveItem.State)
		return
	}

	// 校验审批记录和审批
	recordOb := new(report_approve.ReportApproveRecord)
	recordCond := fmt.Sprintf(` AND %s = ? AND %s = ? AND %s = ?`, report_approve.ReportApproveRecordCols.ReportApproveId, report_approve.ReportApproveRecordCols.ApproveUserId, report_approve.ReportApproveRecordCols.State)
	recordPars := make([]interface{}, 0)
	recordPars = append(recordPars, approveItem.ReportApproveId, sysUser.AdminId, report_approve.ReportApproveStateApproving)
	recordItem, e := recordOb.GetItemByCondition(recordCond, recordPars, "")
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "无权审批"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "获取审批记录失败, Err: " + e.Error()
		return
	}

	// 驳回审批
	if e = services.RefuseReportApprove(approveItem, recordItem, req.ApproveRemark, sysUser.AdminId); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "驳回审批失败, Err: " + e.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// Cancel
// @Title 撤销审批
// @Description 撤销审批
// @Param	request	body report_approve.ReportApproveCancelReq true "type json string"
// @Success 200 string "操作成功"
// @router /cancel [post]
func (this *ReportApproveController) Cancel() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req report_approve.ReportApproveCancelReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数有误"
		br.ErrMsg = "参数解析失败, Err: " + e.Error()
		return
	}
	if req.ReportApproveId <= 0 {
		br.Msg = "参数有误"
		br.ErrMsg = fmt.Sprintf("参数有误, ReportApproveId: %d", req.ReportApproveId)
		return
	}

	approveOb := new(report_approve.ReportApprove)
	approveItem, e := approveOb.GetItemById(req.ReportApproveId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "审批已被删除, 请刷新页面"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "获取审批失败, Err: " + e.Error()
		return
	}
	if approveItem.ApplyUserId != sysUser.AdminId {
		br.Msg = "非申请人不可撤销"
		return
	}

	// 撤销审批
	e = services.CancelReportApprove(approveItem.ReportType, approveItem.ReportId, approveItem.ReportApproveId, sysUser.AdminId, sysUser.RealName)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "撤销审批失败, Err: " + e.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// MessageList
// @Title 审批消息列表
// @Description 审批消息列表
// @Param   PageSize			query	int		true	"每页数据条数"
// @Param   CurrentIndex		query	int		true	"当前页页码"
// @Success 200 {object} report_approve.ReportApproveMessageListResp
// @router /message/list [get]
func (this *ReportApproveController) MessageList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	params := new(report_approve.ReportApproveListReq)
	if e := this.ParseForm(params); e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "入参解析失败, Err: " + e.Error()
		return
	}

	// 分页
	var startSize int
	if params.PageSize <= 0 {
		params.PageSize = utils.PageSize20
	}
	if params.CurrentIndex <= 0 {
		params.CurrentIndex = 1
	}
	startSize = utils.StartIndex(params.CurrentIndex, params.PageSize)

	resp := new(report_approve.ReportApproveMessageListResp)
	resp.List = make([]*report_approve.ReportApproveMessageItem, 0)
	cond := fmt.Sprintf(` AND %s = ?`, report_approve.ReportApproveMessageCols.ReceiveUserId)
	pars := make([]interface{}, 0)
	pars = append(pars, sysUser.AdminId)
	order := fmt.Sprintf(`%s ASC, %s DESC`, report_approve.ReportApproveMessageCols.IsRead, report_approve.ReportApproveMessageCols.CreateTime)

	messageOb := new(report_approve.ReportApproveMessage)
	total, e := messageOb.GetCountByCondition(cond, pars)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取审批消息列表总数失败, Err: " + e.Error()
		return
	}
	list, e := messageOb.GetPageItemsByCondition(cond, pars, []string{}, order, startSize, params.PageSize)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取审批消息列表失败, Err: " + e.Error()
		return
	}
	for _, v := range list {
		t := report_approve.FormatReportApproveMessage2Item(v)
		resp.List = append(resp.List, t)
	}

	// 未读消息数
	cond += fmt.Sprintf(` AND %s = ?`, report_approve.ReportApproveMessageCols.IsRead)
	pars = append(pars, 0)
	unreadTotal, e := messageOb.GetCountByCondition(cond, pars)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取审批消息列表总数失败, Err: " + e.Error()
		return
	}
	resp.UnreadTotal = unreadTotal

	page := paging.GetPaging(params.CurrentIndex, params.PageSize, total)
	resp.Paging = page
	br.Data = resp
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
}

// MessageRead
// @Title 消息已读
// @Description 消息已读
// @Param	request	body report_approve.ReportApproveMessageReadReq true "type json string"
// @Success 200 string "操作成功"
// @router /message/read [post]
func (this *ReportApproveController) MessageRead() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req report_approve.ReportApproveMessageReadReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数有误"
		br.ErrMsg = "参数解析失败, Err: " + e.Error()
		return
	}
	if req.MessageId <= 0 {
		br.Msg = "参数有误"
		br.ErrMsg = fmt.Sprintf("参数有误, MessageId: %d", req.MessageId)
		return
	}

	messageOb := new(report_approve.ReportApproveMessage)
	messageItem, e := messageOb.GetItemById(req.MessageId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "消息不存在, 请刷新页面"
			return
		}
		br.Msg = "获取失败"
		br.ErrMsg = "获取审批消息失败, Err: " + e.Error()
		return
	}
	messageItem.IsRead = 1
	messageItem.ModifyTime = time.Now().Local()
	cols := []string{"IsRead", "ModifyTime"}
	if e = messageItem.Update(cols); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "更新审批消息已读失败, Err: " + e.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// CheckApproveOpen
// @Title 校验分类是否开启审批
// @Description 校验分类是否开启审批
// @Param	request	body report_approve.ReportApproveCheckApproveOpenReq true "type json string"
// @Success 200 string "操作成功"
// @router /classify/check_open [post]
func (this *ReportApproveController) CheckApproveOpen() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req report_approve.ReportApproveCheckApproveOpenReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数有误"
		br.ErrMsg = "参数解析失败, Err: " + e.Error()
		return
	}

	// 校验是否开启了审批流
	opening, e := services.CheckReportOpenApprove(req.ReportType, req.ClassifyFirstId, req.ClassifySecondId)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "校验报告是否开启审批流失败, Err: " + e.Error()
		return
	}

	br.Data = opening
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}
