package data_manage

import (
	sql2 "database/sql"
	"eta_gn/eta_api/global"
	"eta_gn/eta_api/utils"
	"fmt"
	"time"
)

// ChartInfoShare
// @Description: 指标分享表
type ChartInfoShare struct {
	ChartInfoShareId int       `gorm:"primaryKey" `
	ChartInfoId      int       `description:"图表id"`
	SysUserId        int       `description:"sys_user_id"`
	ShareType        int8      `description:"分享类型,1:仅查看;2:可编辑"`
	CreateTime       time.Time `description:"创建时间"`
}

// TableName
// @Description: 表名
// @author: Roc
// @receiver m
// @datetime 2024-11-27 14:04:14
// @return string
func (m ChartInfoShare) TableName() string {
	return `chart_info_share`
}

// GetListByChartInfoId
// @Description: 根据指标id获取分享用户列表
// @author: Roc
// @receiver m
// @datetime 2024-11-27 15:39:17
// @param chartInfoId int
// @return items []*ChartInfoShare
// @return err error
func (m ChartInfoShare) GetListByChartInfoId(chartInfoId int) (items []*ChartInfoShare, err error) {
	sql := ` SELECT * FROM chart_info_share WHERE chart_info_id = ? ORDER BY chart_info_share_id ASC `
	err = global.DmSQL["data"].Raw(sql, chartInfoId).Find(&items).Error

	return
}

// SaveChartInfoShare
// @Description: 保存配置
// @author: Roc
// @receiver m
// @datetime 2024-11-27 15:54:07
// @param chartInfoIdList []int
// @param userIdList []int
// @param shareType int8
// @return err error
func (m ChartInfoShare) SaveChartInfoShare(chartInfoIdList, userIdList []int, shareType int8) (err error) {
	// TODO 保存之前,得先做关联校验
	addList := make([]*ChartInfoShare, 0)
	for _, chartInfoId := range chartInfoIdList {
		for _, userId := range userIdList {
			addList = append(addList, &ChartInfoShare{
				ChartInfoShareId: 0,
				ChartInfoId:      chartInfoId,
				SysUserId:        userId,
				ShareType:        shareType,
				CreateTime:       time.Now(),
			})
		}
	}

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

	// 先删除原来的配置,新增最新的配置
	sql := fmt.Sprintf("DELETE FROM %s WHERE chart_info_id IN (?) ", m.TableName())
	err = tx.Exec(sql, chartInfoIdList).Error
	if err != nil {
		return
	}

	// 批量添加新的配置
	if len(addList) > 0 {
		err = tx.CreateInBatches(addList, utils.MultiAddNum).Error
		if err != nil {
			return
		}
	}

	return
}

// ShareChartInfoQuery
// @Description: 共享指标
type ShareChartInfoQuery struct {
	ChartInfo
	ShareType string    `gorm:"column:share_type" description:"共享类型"`
	ShareTime time.Time `gorm:"column:share_time" description:"设置共享时间"`
}

// GetAllSharedChartInfoListByFromUserId
// @Description: 获取所有我共享出去的指标列表
// @author: Roc
// @receiver m
// @datetime 2024-12-03 09:56:41
// @param sysUserId int
// @return list []*ShareChartInfoQuery
// @return err error
func (m ChartInfoShare) GetAllSharedChartInfoListByFromUserId(sysUserId int) (list []*ShareChartInfoQuery, err error) {
	sql := `SELECT b."chart_info_id",
       MAX(a.share_type) AS share_type,
MAX(a.create_time) as share_time,
MAX(b."chart_name") "chart_name",
MAX(b."source") "source",
MAX(b."chart_type") "chart_type",
MAX(b."chart_classify_id") "chart_classify_id",
MAX(b."chart_public_classify_id") "chart_public_classify_id",
MAX(b."unique_code") "unique_code",
MAX(b."chart_image") "chart_image",
MAX(b."sys_user_id") "sys_user_id",
MAX(b."sys_user_real_name") "sys_user_real_name",
MAX(b."create_time") "create_time",
MAX(b."modify_time") "modify_time",
MAX(b."sort") AS "sort"
 FROM chart_info_share AS a 
     JOIN chart_info AS b ON a.chart_info_id = b.chart_info_id
	  WHERE 1=1 AND b.sys_user_id = ?
	  GROUP BY b.chart_info_id
ORDER BY share_time DESC`
	err = global.DmSQL["data"].Raw(sql, sysUserId).Scan(&list).Error
	return
}

// GetAllSharedChartInfoListByReceivedUserId
// @Description: 获取所有我收到的共享的指标列表
// @author: Roc
// @receiver m
// @datetime 2024-12-03 09:56:41
// @param sysUserId int
// @return list []*ShareChartInfoQuery
// @return err error
func (m ChartInfoShare) GetAllSharedChartInfoListByReceivedUserId(sysUserId int) (list []*ShareChartInfoQuery, err error) {
	sql := `SELECT b."chart_info_id",
       MAX(a.share_type) AS share_type,
MAX(a.create_time) as share_time,
MAX(b."chart_name") "chart_name",
MAX(b."source") "source",
MAX(b."chart_type") "chart_type",
MAX(b."chart_classify_id") "chart_classify_id",
MAX(b."chart_public_classify_id") "chart_public_classify_id",
MAX(b."unique_code") "unique_code",
MAX(b."chart_image") "chart_image",
MAX(b."sys_user_id") "sys_user_id",
MAX(b."sys_user_real_name") "sys_user_real_name",
MAX(b."create_time") "create_time",
MAX(b."modify_time") "modify_time",
MAX(b."sort") AS "sort"
 FROM chart_info_share AS a 
     JOIN chart_info AS b ON a.chart_info_id = b.chart_info_id
	  WHERE 1=1 AND a.sys_user_id = ? AND b.sys_user_id != ?
	  GROUP BY b.chart_info_id
ORDER BY share_time DESC`
	err = global.DmSQL["data"].Raw(sql, sysUserId, sysUserId).Scan(&list).Error
	return
}

// GetShareChartInfoListPageList
// @Description: 获取分享的指标列表(分页)
// @author: Roc
// @receiver m
// @datetime 2024-12-03 14:42:12
// @param condition string
// @param pars []interface{}
// @param startSize int
// @param pageSize int
// @return total int32
// @return list []*ChartInfoList
// @return err error
func (m ChartInfoShare) GetShareChartInfoListPageList(condition string, pars []interface{}, startSize, pageSize int) (total int32, list []*ChartInfoView, err error) {
	baseSql := `SELECT b."chart_info_id",
       MAX(a.share_type) AS share_type,
MAX(a.create_time) as share_time,
MAX(b."chart_name") "chart_name",
MAX(b."source") "source",
MAX(b."chart_type") "chart_type",
MAX(b."chart_classify_id") "chart_classify_id",
MAX(b."chart_public_classify_id") "chart_public_classify_id",
MAX(b."unique_code") "unique_code",
MAX(b."chart_image") "chart_image",
MAX(b."sys_user_id") "sys_user_id",
MAX(b."sys_user_real_name") "sys_user_real_name",
MAX(b."create_time") "create_time",
MAX(b."modify_time") "modify_time",
MAX(b."sort") AS "sort"
  FROM chart_info_share AS a 
     JOIN chart_info AS b ON a.chart_info_id = b.chart_info_id
	  WHERE 1=1 `

	baseSql += condition
	baseSql += ` GROUP BY b.chart_info_id `

	totalSql := `SELECT COUNT(1) AS total FROM (` + baseSql + `) AS d`
	var totalNull sql2.NullInt32
	err = global.DmSQL["data"].Raw(totalSql, pars...).Scan(&totalNull).Error
	if err != nil {
		return
	}
	total = totalNull.Int32

	sql := baseSql + ` ORDER BY share_time DESC LIMIT ?,? `
	pars = append(pars, startSize, pageSize)
	err = global.DmSQL["data"].Raw(sql, pars...).Scan(&list).Error
	return
}