package cygx

import (
	"github.com/beego/beego/v2/client/orm"
	"github.com/rdlucklib/rdluck_tools/paging"
	"strconv"
	"strings"
	"time"
)

type CygxProductInterior struct {
	ProductInteriorId   int       `orm:"column(product_interior_id);pk"`
	ColumnName          string    `description:"栏目名称"`
	Title               string    `description:"标题"`
	PublishTime         time.Time `description:"发布日期"`
	CreateTime          time.Time `description:"创建时间"`
	ModifyTime          time.Time `description:"更新时间"`
	Status              int       `description:"0:未发布，1:已发布"`
	Body                string    `description:"内容"`
	IsCancel            int       `description:"是否取消，1是，0否"`
	VisibleRange        int       `description:"设置可见范围1全部，0内部"`
	Abstract            string    `description:"摘要"`
	Department          string    `description:"作者"`
	AdminId             int       `description:"管理员ID"`
	MatchTypeId         int       `description:"匹配类型ID"`
	ChartPermissionId   int       `description:"行业ID"`
	ChartPermissionName string    `description:"行业ID"`
	IsSendWxMsg         int       `description:"是否推送过微信模板消息，1是，0：否"`
}

type AddProductInteriorReq struct {
	ProductInteriorId       int    `description:"ID"`
	DoType                  int    `description:"操作类型 0，保存 、1，发布"`
	ColumnName              string `description:"栏目名称"`
	Title                   string `description:"标题"`
	Abstract                string `description:"摘要"`
	Department              string `description:"作者"`
	Body                    string `description:"内容"`
	PublishTime             string `description:"发布日期"`
	IndustrialManagementIds string `description:"产业id 多个用 , 隔开"`
	IndustrialSubjectIds    string `description:"标的id 多个用 , 隔开"`
	MatchTypeId             int    `description:"匹配类型ID"`
	ChartPermissionId       int    `description:"行业ID"`
}
type ProductInteriorIdReq struct {
	ProductInteriorId int `description:"ID"`
}

// 添加
func AddProductInterior(item *CygxProductInterior, industrialManagementIds, industrialSubjectIds string) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	newId, err := to.Insert(item)
	if err != nil {
		return
	}
	//添加产业与文章的关联
	//new(cygx.CygxProductInteriorIndustrialGroupManagement),
	//	new(cygx.CygxProductInteriorIndustrialGroupSubject),
	industrialManagementIdList := strings.Split(industrialManagementIds, ",")
	for _, v := range industrialManagementIdList {
		itemIndustrialManagementGroup := new(CygxProductInteriorIndustrialGroupManagement)
		newIndustrialId, _ := strconv.Atoi(v)
		itemIndustrialManagementGroup.CreateTime = time.Now()
		itemIndustrialManagementGroup.ProductInteriorId = int(newId)
		itemIndustrialManagementGroup.IndustrialManagementId = newIndustrialId
		_, err = to.Insert(itemIndustrialManagementGroup)
		if err != nil {
			return
		}
	}
	//添加标的与文章的关联
	if industrialSubjectIds != "" {
		industrialSubjectIdList := strings.Split(industrialSubjectIds, ",")
		for _, v := range industrialSubjectIdList {
			itemIndustrialSubjectGroup := new(CygxProductInteriorIndustrialGroupSubject)
			industrialSubjectId, _ := strconv.Atoi(v)
			itemIndustrialSubjectGroup.ProductInteriorId = int(newId)
			itemIndustrialSubjectGroup.IndustrialSubjectId = industrialSubjectId
			itemIndustrialSubjectGroup.CreateTime = time.Now()
			_, err = to.Insert(itemIndustrialSubjectGroup)
			if err != nil {
				return
			}
		}
	}
	return
}

// 修改
func UpdateProductInterior(item *CygxProductInterior, industrialManagementIds, industrialSubjectIds string) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	updateParams := make(map[string]interface{})
	updateParams["PublishTime"] = item.PublishTime
	updateParams["ModifyTime"] = item.ModifyTime
	updateParams["ColumnName"] = item.ColumnName
	updateParams["Title"] = item.Title
	updateParams["Status"] = item.Status
	updateParams["Body"] = item.Body
	updateParams["IsCancel"] = item.IsCancel
	updateParams["VisibleRange"] = item.VisibleRange
	updateParams["Abstract"] = item.Abstract
	updateParams["Department"] = item.Department
	updateParams["MatchTypeId"] = item.MatchTypeId
	updateParams["ChartPermissionId"] = item.ChartPermissionId
	updateParams["ChartPermissionName"] = item.ChartPermissionName
	ptrStructOrTableName := "cygx_product_interior"
	whereParam := map[string]interface{}{"product_interior_id": item.ProductInteriorId}
	qs := to.QueryTable(ptrStructOrTableName)
	for expr, exprV := range whereParam {
		qs = qs.Filter(expr, exprV)
	}
	_, err = qs.Update(updateParams)
	if err != nil {
		return
	}

	//删除文章关联行业 （避免截断表时产生的脏数据，故不用update而是先删除再增加）
	sql := `	DELETE FROM cygx_product_interior_industrial_group_management WHERE product_interior_id = ?`
	_, err = to.Raw(sql, item.ProductInteriorId).Exec()
	if err != nil {
		return
	}
	//删除文章关联标的
	sql = `	DELETE FROM cygx_product_interior_industrial_group_subject WHERE product_interior_id = ?`
	_, err = to.Raw(sql, item.ProductInteriorId).Exec()
	if err != nil {
		return
	}

	industrialManagementIdList := strings.Split(industrialManagementIds, ",")
	for _, v := range industrialManagementIdList {
		itemIndustrialManagementGroup := new(CygxProductInteriorIndustrialGroupManagement)
		newIndustrialId, _ := strconv.Atoi(v)
		itemIndustrialManagementGroup.CreateTime = time.Now()
		itemIndustrialManagementGroup.ProductInteriorId = item.ProductInteriorId
		itemIndustrialManagementGroup.IndustrialManagementId = newIndustrialId
		_, err = to.Insert(itemIndustrialManagementGroup)
		if err != nil {
			return
		}
	}
	//添加标的与文章的关联
	if industrialSubjectIds != "" {
		industrialSubjectIdList := strings.Split(industrialSubjectIds, ",")
		for _, v := range industrialSubjectIdList {
			itemIndustrialSubjectGroup := new(CygxProductInteriorIndustrialGroupSubject)
			industrialSubjectId, _ := strconv.Atoi(v)
			itemIndustrialSubjectGroup.ProductInteriorId = item.ProductInteriorId
			itemIndustrialSubjectGroup.IndustrialSubjectId = industrialSubjectId
			itemIndustrialSubjectGroup.CreateTime = time.Now()
			_, err = to.Insert(itemIndustrialSubjectGroup)
			if err != nil {
				return
			}
		}
	}

	return
}

type GetCygxProductInteriorResp struct {
	Paging *paging.PagingItem `description:"分页数据"`
	List   []*CygxProductInteriorResp
}

type CygxProductInteriorResp struct {
	ProductInteriorId   int    `description:"ID"`
	PublishTime         string `description:"发布日期"`
	CreateTime          string `description:"创建时间"`
	ModifyTime          string `description:"更新时间"`
	Status              int    `description:"0:未发布，1:已发布，3：已下线"`
	Title               string `description:"标题"`
	ColumnName          string `description:"栏目名称"`
	Body                string `description:"内容"`
	IsCancel            int    `description:"是否取消，1是，0否"`
	VisibleRange        int    `description:"设置可见范围1全部，0内部"`
	Abstract            string `description:"摘要"`
	Department          string `description:"作者"`
	Pv                  int    `description:"PV"`
	Uv                  int    `description:"Uv"`
	CommentNum          int    `description:"留言总数"`
	MatchTypeId         int    `description:"匹配类型ID"`
	MatchTypeName       string `description:"匹配类型名称"`
	ChartPermissionId   int    `description:"行业ID"`
	ChartPermissionName string `description:"行业名称"`
	Label               string `description:"标签"`
	IsSendWxMsg         int    `description:"是否推送过微信模板消息，1是，0：否"`
	ListIndustrial      []*IndustrialActivityGroupManagementRep
	ListSubject         []*SubjectActivityGroupManagementRep
}

// 获取数量
func GetCygxProductInteriorCount(condition string, pars []interface{}) (count int, err error) {
	sqlCount := ` SELECT COUNT(1) AS count  FROM cygx_product_interior as art WHERE 1= 1  `
	if condition != "" {
		sqlCount += condition
	}
	o := orm.NewOrmUsingDB("hz_cygx")
	err = o.Raw(sqlCount, pars).QueryRow(&count)
	return
}

// 列表
func GetCygxProductInteriorList(condition string, pars []interface{}, startSize, pageSize int) (items []*CygxProductInteriorResp, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_product_interior as art WHERE 1= 1 `
	if condition != "" {
		sql += condition
	}
	sql += ` LIMIT ?,?  `
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

type GetCygxProductInteriorDetailResp struct {
	Detail *CygxProductInteriorResp
}

// 通过ID获取详情
func GetCygxProductInteriorDetail(productInteriorId int) (item *CygxProductInteriorResp, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_product_interior  WHERE product_interior_id=? `
	err = o.Raw(sql, productInteriorId).QueryRow(&item)
	return
}

// 删除数据
func DeleteProductInterior(productInteriorId int) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := ` DELETE FROM cygx_product_interior WHERE product_interior_id = ?`
	_, err = o.Raw(sql, productInteriorId).Exec()
	return
}

// 修改是否展示
func EditProductInteriorStatus(status, isCancel, productInteriorId int) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `UPDATE cygx_product_interior SET status=?,is_cancel = ? ,visible_range=0, modify_time=NOW()   WHERE product_interior_id=? `
	_, err = o.Raw(sql, status, isCancel, productInteriorId).Exec()
	return
}

// 修改可见范围
func ProductInteriorVisibleRange(visibleRange, productInteriorId int) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `UPDATE cygx_product_interior SET visible_range=?, modify_time=NOW()   WHERE product_interior_id=?  `
	_, err = o.Raw(sql, visibleRange, productInteriorId).Exec()
	return
}

// 修改是否推送过模板消息的状态
func UpdateProductInteriorIsSendWxMsg(productInteriorId, isSendWxMsg int) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `UPDATE cygx_product_interior SET is_send_wx_msg=?  WHERE product_interior_id =?`
	_, err = o.Raw(sql, isSendWxMsg, productInteriorId).Exec()
	return
}
