package report

import (
	"github.com/beego/beego/v2/client/orm"
	"hongze/hongze_open_api/models/tables/company_report_permission"
	"hongze/hongze_open_api/utils"
	"time"
)

type ReportList struct {
	ResearchReportId   int    `json:"research_report_id" orm:"column(research_report_id)" description:"报告Id"`
	ResearchReportName string `json:"research_report_name" orm:"column(research_report_name)" description:"标题"`
	Periods            int    `json:"periods" description:"期数"`
	ResearchReportDate string `json:"research_report_date" description:"发布时间"`
	HttpUrl            string `json:"http_url" description:"报告详情"`
}

type ReportListResp struct {
	List   []*ReportList     `description:"列表"  json:"list"`
	Paging *utils.PagingItem `description:"分页数据" json:"paging"`
}

type ResearchReportInfo struct {
	ResearchReportInfo            *ResearchReport                                        `json:"research_report_info"`
	ResearchReportTypeList        []*company_report_permission.ResearchReportTypeList    `json:"research_report_type_list"`
	HasMenu                       int                                                    `json:"has_menu"`
	ResearchReportTypeContentList []*company_report_permission.ResearchReportTypeContent `description:"报告详情"`
}

//
//// ResearchReport 研究报告表
//type ResearchReport struct {
//	//ResearchReportID    uint64    `gorm:"primaryKey;column:research_report_id;type:bigint(20) unsigned;not null" json:"-"`                       // 研究报告id
//	ResearchReportID    uint64    `orm:"column(research_report_id)"json:"research_report_id";description:"报告Id"`                                                        // 研究报告id
//	ResearchReportName  string    `gorm:"index:research_report_name;column:research_report_name;type:varchar(128)" json:"research_report_name";description:"研究报告名称"`    // 研究报告名称
//	ResearchReportTitle string    `gorm:"index:research_report_title;column:research_report_title;type:varchar(128)" json:"research_report_title";description:"研究报告标题"` // 研究报告标题
//	ResearchReportImg   string    `gorm:"column:research_report_img;type:varchar(128)" json:"research_report_img";description:"报告缩略图URL"`                               // 报告缩略图URL
//	ResearchReportDate  time.Time `gorm:"column:research_report_date;type:date;not null" description:"报告日期"`                                                            // 报告日期
//	Type                string    `gorm:"column:type;type:varchar(32);default:day" json:"type";description:"day 晨报  week 周报 twoweek双周报 month 月报"`                       // day 晨报  week 周报 twoweek双周报 month 月报
//	Author              string    `gorm:"column:author;type:varchar(100)" json:"author";description:"报告作者"`                                                             // 报告作者
//	ReportVariety       string    `gorm:"column:report_variety;type:varchar(30)" json:"report_variety";description:"研究报告的品种，双周报和月报有标识"`                                 // 研究报告的品种，双周报和月报有标识
//	IsHasMenu           int8      `gorm:"column:is_has_menu;type:tinyint(1);default:0" json:"is_has_menu";description:"报告Id"`                                           // 报告是否含有目录
//	IsSendedMsg         int8      `gorm:"column:is_sended_msg;type:tinyint(1);default:0" json:"is_sended_msg";description:"报告是否含有目录"`                                   // 是否发送过模板消息
//	Periods             int       `gorm:"column:periods;type:int(8)" json:"periods";description:"期数"`                                                                   // 期数
//	Status              string    `gorm:"column:status;type:varchar(20);not null" json:"status";description:"状态，draft：草稿"`                                              // 状态，draft：草稿，
//	Enabled             int8      `gorm:"index:enabled;column:enabled;type:tinyint(1);default:1" json:"enabled";description:"报告状态"`                                     // 报告状态
//	CreatedTime         time.Time `gorm:"index:created_time;column:created_time;type:datetime;default:CURRENT_TIMESTAMP" json:"created_time";description:"创建时间"`        // 创建时间
//	LastUpdatedTime     time.Time `gorm:"index:last_updated_time;column:last_updated_time;type:timestamp;not null;default:CURRENT_TIMESTAMP" json:"last_updated_time";description:"修改时间"`
//	Viewers             int       `gorm:"column:viewers;type:int(8);default:0" json:"viewers";description:"H5观看用户数"` // H5观看用户数
//}

type ResearchReport struct {
	//ResearchReportID    uint64    `gorm:"primaryKey;column:research_report_id;type:bigint(20) unsigned;not null" json:"-"`                       // 研究报告id
	ResearchReportID    uint64    `orm:"column(research_report_id)"json:"research_report_id";description:"报告Id"`                                                      // 研究报告id
	ResearchReportName  string    `gorm:"index:research_report_name;column:research_report_name;type:varchar(128)" json:"researchReportName";description:"研究报告名称"`    // 研究报告名称
	ResearchReportTitle string    `gorm:"index:research_report_title;column:research_report_title;type:varchar(128)" json:"researchReportTitle";description:"研究报告标题"` // 研究报告标题
	ResearchReportImg   string    `gorm:"column:research_report_img;type:varchar(128)" json:"researchReportImg";description:"报告缩略图URL"`                               // 报告缩略图URL
	ResearchReportDate  time.Time `gorm:"column:research_report_date;type:date;not null"  json:"researchReportDate";description:"报告日期"`                               // 报告日期
	Type                string    `gorm:"column:type;type:varchar(32);default:day" json:"type";description:"day 晨报  week 周报 twoweek双周报 month 月报"`                     // day 晨报  week 周报 twoweek双周报 month 月报
	Author              string    `gorm:"column:author;type:varchar(100)" json:"author";description:"报告作者"`                                                           // 报告作者
	ReportVariety       string    `gorm:"column:report_variety;type:varchar(30)" json:"reportVariety";description:"研究报告的品种，双周报和月报有标识"`                                // 研究报告的品种，双周报和月报有标识
	IsHasMenu           int8      `gorm:"column:is_has_menu;type:tinyint(1);default:0" json:"isHasMenu";description:"报告Id"`                                           // 报告是否含有目录
	IsSendedMsg         int8      `gorm:"column:is_sended_msg;type:tinyint(1);default:0" json:"isSendedMsg";description:"报告是否含有目录"`                                   // 是否发送过模板消息
	Periods             int       `gorm:"column:periods;type:int(8)" json:"periods";description:"期数"`                                                                 // 期数
	Status              string    `gorm:"column:status;type:varchar(20);not null" json:"status";description:"状态，draft：草稿"`                                            // 状态，draft：草稿，
	Enabled             int8      `gorm:"index:enabled;column:enabled;type:tinyint(1);default:1" json:"enabled";description:"报告状态"`                                   // 报告状态
	CreatedTime         time.Time `gorm:"index:created_time;column:created_time;type:datetime;default:CURRENT_TIMESTAMP" json:"createdTime";description:"创建时间"`       // 创建时间
	LastUpdatedTime     time.Time `gorm:"index:last_updated_time;column:last_updated_time;type:timestamp;not null;default:CURRENT_TIMESTAMP" json:"lastUpdatedTime";description:"修改时间"`
	Viewers             int       `gorm:"column:viewers;type:int(8);default:0" json:"viewers";description:"H5观看用户数"` // H5观看用户数
}

type ResearchReportTypeContent struct {
	ResearchReportTypeTitle     string
	ResearchReportTypeContentId int       `json:"research_report_type_content_id" description:"研究报告内容id"`
	ResearchReportTypeId        int       `json:"research_report_id" description:"报告id"`
	Sort                        int       `json:"sort" description:"排序"`
	ContentType                 string    `json:"content_type" description:"内容分类类型"`
	Content                     string    `json:"content" description:"内容"`
	ImgUrl                      string    `json:"img_url" description:"图片路径"`
	CreatedTime                 time.Time `json:"created_time" description:"创建时间"`
	LastUpdatedTime             time.Time `json:"last_updated_time" description:"最近一次更新时间"`
}

func GetReportListCount(condition string, pars []interface{}) (count int, err error) {
	o := orm.NewOrm()

	sql := `SELECT COUNT(1) AS count  FROM research_report WHERE 1=1 `
	if condition != "" {
		sql += condition
	}
	err = o.Raw(sql, pars).QueryRow(&count)
	return
}

func GetReportList(condition string, pars []interface{}, startSize, pageSize int) (items []*ReportList, err error) {
	o := orm.NewOrm()
	//产品权限

	sql := `SELECT * FROM research_report WHERE 1=1`
	if condition != "" {
		sql += condition
	}
	sql += `ORDER BY  periods DESC LIMIT ?,?`
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

//GetResearchReportInfo 获取报告详情
func GetResearchReportInfo(researchReportId, userId int) (result ResearchReportInfo, hasPermission bool, err error) {
	//获取报告详情
	reportInfo, err := GetByResearchReportId(researchReportId)
	if err != nil {
		return
	}
	reportType := reportInfo.Type
	//这些个报告需要做权限校验

	if utils.InArray(reportInfo.Type, []string{"month", "two_week", "other"}) {
		list, tmpErr := company_report_permission.GetReportVarietyList(userId, reportType)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		for _, v := range list {
			if reportInfo.ResearchReportID == v.ReportChapterTypeId {
				hasPermission = true
				break
			}
		}
		if !hasPermission {
			return
		}
	} else {
		hasPermission = true
	}
	researchReportTypeList := make([]*company_report_permission.ResearchReportTypeList, 0)
	tmpResearchReportTypeList, err := company_report_permission.GetResearchReportType(reportInfo.ResearchReportID, userId, reportInfo.Type)
	if err != nil {
		return
	}
	reportDate := reportInfo.ResearchReportDate
	for _, v := range tmpResearchReportTypeList {
		if reportDate.Before(v.PauseStartTime) || reportDate.After(v.PauseEndTime) {
			researchReportTypeList = append(researchReportTypeList, v)
		}
	}
	result = ResearchReportInfo{
		ResearchReportInfo:     reportInfo,
		ResearchReportTypeList: researchReportTypeList,
		HasMenu:                1,
	}
	if len(researchReportTypeList) <= 0 {

	} else if len(researchReportTypeList) == 1 {
		//只有一个章节，即没有目录的时候，需要直接返回章节详情
		result.HasMenu = 0
		researchReportTypeContent, tmpErr := company_report_permission.GetResearchReportTypeContentList(researchReportTypeList[0].ResearchReportTypeId)
		if tmpErr != nil {
			return
		}
		result.ResearchReportTypeContentList = researchReportTypeContent
	}
	return
}

// GetPermissionNameByReportId
func GetByResearchReportId(researchReportid int) (item *ResearchReport, err error) {
	sql := `SELECT * FROM research_report WHERE research_report_id = ?`
	o := orm.NewOrm()
	err = o.Raw(sql, researchReportid).QueryRow(&item)
	return
}

type ResearchReportTypeContentInfo struct {
	ResearchReportTypeInfo        *company_report_permission.ResearchReportTypeInfo      `json:"research_report_type_info"`
	Add                           int                                                    `json:"add"`
	ResearchReportTypeContentList []*company_report_permission.ResearchReportTypeContent `description:"报告详情" json:"research_report_type_content_list"`
	ResearchReportTypeList        []*company_report_permission.ResearchReportTypeList    `json:"research_report_type_list"`
}

// GetResearchReportTypeContentInfo 获取报告章节详情
func GetResearchReportTypeContentInfo(researchReportTypeId, userId uint64) (result ResearchReportTypeContentInfo, hasPermission bool, err error) {
	//获取章节详情
	researchReportTypeContentList, err := company_report_permission.GetResearchReportTypeContentList(researchReportTypeId)
	if err != nil {
		return
	}
	researchReportTypeInfo, err := company_report_permission.GetResearchReportTypeInfo(researchReportTypeId)
	if err != nil {
		return
	}
	//获取报告详情
	reportInfo, err := GetByResearchReportId(int(researchReportTypeInfo.ResearchReportID))
	if err != nil {
		return
	}
	reportType := reportInfo.Type
	researchReportTypeInfo.Type = reportInfo.Type
	//这些个报告需要做权限校验
	if utils.InArray(reportInfo.Type, []string{"week", "month", "two_week", "other"}) {
		list, tmpErr := company_report_permission.GetReportVarietyList(int(userId), reportType)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		if reportInfo.Type == "week" {
			//周报校验章节是否在权限内
			for _, v := range list {
				if researchReportTypeInfo.ReportChapterTypeId == v.ReportChapterTypeId {
					hasPermission = true
					break
				}
			}
		} else {
			//双周报和月报校验 类型是否在权限内
			for _, v := range list {
				if reportInfo.ResearchReportID == v.ReportChapterTypeId {
					hasPermission = true
					break
				}
			}
		}
		if !hasPermission {
			return
		}
	} else {
		hasPermission = true
	}
	add := 1
	if len(researchReportTypeContentList) > 0 {
		add = 0
	}
	result = ResearchReportTypeContentInfo{
		ResearchReportTypeContentList: researchReportTypeContentList,
		ResearchReportTypeInfo:        researchReportTypeInfo,
		Add:                           add,
	}
	return
}
