package cygx

import (
	"github.com/beego/beego/v2/client/orm"
	"time"
)

// 首页资源表与产业的关系
type CygxResourceDataIndustrialGroupManagement struct {
	Id                     int       `orm:"column(id);pk" description:"主键ID"`
	ResourceDataId         int       `description:"cygx_resource_data 主键ID"`
	SourceId               int       `description:"资源ID"`
	Source                 string    `description:"资源类型 报告 ：article 、图表 ：newchart、微路演 ：roadshow、活动 ：activity、活动视频：activityvideo、活动音频：activityvoice、专项调研活动：activityspecial"`
	IndustrialManagementId int       `description:"cygx_industrial_management表的主键ID"`
	CreateTime             time.Time `description:"创建时间"`
}

// 首页资源表与产业的关系
type CygxResourceDataIndustrialGroupSubject struct {
	Id                  int       `orm:"column(id);pk" description:"主键ID"`
	ResourceDataId      int       `description:"cygx_resource_data 主键ID"`
	SourceId            int       `description:"资源ID"`
	Source              string    `description:"资源类型 报告 ：article 、图表 ：newchart、微路演 ：roadshow、活动 ：activity、活动视频：activityvideo、活动音频：activityvoice、专项调研活动：activityspecial"`
	IndustrialSubjectId int       `description:"cygx_industrial_subject表的主键ID"`
	CreateTime          time.Time `description:"创建时间"`
}

// 添加
func AddCygxResourceDataGroup(sourceId int, source string, industrialItems []*CygxResourceDataIndustrialGroupManagement, subjectItems []*CygxResourceDataIndustrialGroupSubject) (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()
		}
	}()
	//删除关联产业
	sql := `	DELETE FROM cygx_resource_data_industrial_group_management WHERE source_id = ? AND source =? `
	_, err = to.Raw(sql, sourceId, source).Exec()
	if err != nil {
		return
	}
	//删除关联标的
	sql = `	DELETE FROM cygx_resource_data_industrial_group_subject WHERE source_id = ? AND source =? `
	_, err = to.Raw(sql, sourceId, source).Exec()
	if err != nil {
		return
	}

	//批量插入关联产业
	if len(industrialItems) > 0 {
		_, err = to.InsertMulti(len(industrialItems), industrialItems)
		if err != nil {
			return
		}
	}

	//批量插入关联标的
	if len(subjectItems) > 0 {
		_, err = to.InsertMulti(len(subjectItems), subjectItems)
		if err != nil {
			return
		}
	}

	return
}

// 删除
func DeleteCygxResourceDataGroup(sourceId int, source 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()
		}
	}()
	//删除关联产业
	sql := `	DELETE FROM cygx_resource_data_industrial_group_management WHERE source_id = ? AND source =? `
	_, err = to.Raw(sql, sourceId, source).Exec()
	if err != nil {
		return
	}
	//删除关联标的
	sql = `	DELETE FROM cygx_resource_data_industrial_group_subject WHERE source_id = ? AND source =? `
	_, err = to.Raw(sql, sourceId, source).Exec()
	if err != nil {
		return
	}

	return
}
