package supply_analysis

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

// Variety variety 品种表
type Variety struct {
	VarietyId                 int       `orm:"column(variety_id);pk"`
	VarietyName               string    `description:"品种名称"`
	LastUpdateSysUserId       int       `description:"最后更新人id"`
	LastUpdateSysUserRealName string    `description:"最后更新人名称"`
	ProductionDay             int       `description:"生产天数"`
	SysUserId                 int       `description:"创建人id"`
	SysUserRealName           string    `description:"创建人姓名"`
	ModifyTime                time.Time `description:"修改时间"`
	CreateTime                time.Time `description:"创建时间"`
}

// GetVarietyById 根据品种id获取品种详情
func GetVarietyById(id int) (item *Variety, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM variety WHERE variety_id = ?`
	err = o.Raw(sql, id).QueryRow(&item)
	return
}

// GetVarietyByName 根据品种名称获取品种详情
func GetVarietyByName(name string) (item *Variety, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM variety WHERE variety_name = ?`
	err = o.Raw(sql, name).QueryRow(&item)
	return
}

// AddVariety 添加品种
func AddVariety(item *Variety) (lastId int64, err error) {
	o := orm.NewOrm()
	lastId, err = o.Insert(item)
	return
}

// CreateVariety 添加品种
func CreateVariety(item *Variety, adminIdList []int) (err error) {
	to, err := orm.NewOrm().Begin()
	if err != nil {
		return
	}

	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	lastId, err := to.Insert(item)
	if err != nil {
		return
	}

	item.VarietyId = int(lastId)

	varietyAdminPermissionList := make([]*VarietyAdminPermission, 0)
	for _, adminId := range adminIdList {
		varietyAdminPermissionList = append(varietyAdminPermissionList, &VarietyAdminPermission{
			//Id:              0,
			VarietyId:  item.VarietyId,
			SysUserId:  adminId,
			CreateTime: time.Now(),
		})
	}
	if len(varietyAdminPermissionList) > 0 {
		_, err = to.InsertMulti(len(varietyAdminPermissionList), varietyAdminPermissionList)
	}

	return
}

// EditVariety 编辑品种
func EditVariety(item *Variety, adminIdList []int) (err error) {
	to, err := orm.NewOrm().Begin()
	if err != nil {
		return
	}

	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()

	_, err = to.Update(item, "VarietyName", "LastUpdateSysUserId", "LastUpdateSysUserRealName", "ModifyTime")
	if err != nil {
		return
	}

	// 删除历史的权限配置
	sql := `DELETE FROM variety_admin_permission where variety_id = ? `
	_, err = to.Raw(sql, item.VarietyId).Exec()
	if err != nil {
		return
	}

	// 添加新的权限配置
	varietyAdminPermissionList := make([]*VarietyAdminPermission, 0)
	for _, adminId := range adminIdList {
		varietyAdminPermissionList = append(varietyAdminPermissionList, &VarietyAdminPermission{
			//Id:              0,
			VarietyId:  item.VarietyId,
			SysUserId:  adminId,
			CreateTime: time.Now(),
		})
	}
	if len(varietyAdminPermissionList) > 0 {
		_, err = to.InsertMulti(len(varietyAdminPermissionList), varietyAdminPermissionList)
	}

	return
}

// VarietyItem 列表页返回的数据结构
type VarietyItem struct {
	VarietyId                 int           `orm:"column(variety_id);pk"`
	VarietyName               string        `description:"品种名称"`
	LastUpdateSysUserId       int           `description:"最后更新人id"`
	LastUpdateSysUserRealName string        `description:"最后更新人名称"`
	PermissionUserId          string        `description:"有操作权限的用户id" json:"-"`
	ModifyTime                string        `description:"修改时间"`
	CreateTime                string        `description:"创建时间"`
	Button                    VarietyButton `description:"操作按钮权限"`
}

type VarietyButton struct {
	Edit    bool `description:"操作权限"`
	Delete  bool `description:"删除权限"`
	Analyse bool `description:"分析权限"`
}

// GetListBySuperAdminPage 不区分是否有分析权限的获取分页数据
func (item Variety) GetListBySuperAdminPage(condition string, pars []interface{}, startSize, pageSize int) (total int, items []*VarietyItem, err error) {
	o := orm.NewOrm()
	baseSql := ` FROM ( SELECT a.*, GROUP_CONCAT(DISTINCT b.sys_user_id ORDER BY b.sys_user_id ASC SEPARATOR ',') AS permission_user_id FROM variety a 
				LEFT JOIN variety_admin_permission b on a.variety_id=b.variety_id 
				LEFT JOIN variety_edb_info c on a.variety_id=c.variety_id WHERE 1=1 `
	if condition != "" {
		baseSql += condition
	}
	baseSql += ` GROUP BY a.variety_id ) d `
	// 数据总数
	totalSql := `SELECT COUNT(1) total ` + baseSql
	err = o.Raw(totalSql, pars).QueryRow(&total)
	if err != nil {
		return
	}

	// 列表页数据
	listSql := `SELECT * ` + baseSql + ` ORDER BY modify_time DESC,variety_id DESC LIMIT ?,?`
	_, err = o.Raw(listSql, pars, startSize, pageSize).QueryRows(&items)
	return
}

// GetListByPage 获取分页数据
func (item Variety) GetListByPage(condition string, pars []interface{}, startSize, pageSize int) (total int, items []*VarietyItem, err error) {
	o := orm.NewOrm()
	baseSql := ` FROM ( SELECT a.*, GROUP_CONCAT(DISTINCT b.sys_user_id ORDER BY b.sys_user_id ASC SEPARATOR ',') AS permission_user_id FROM variety a 
				JOIN variety_admin_permission b on a.variety_id=b.variety_id 
				JOIN variety_edb_info c on a.variety_id=c.variety_id WHERE 1=1 `
	if condition != "" {
		baseSql += condition
	}
	baseSql += ` GROUP BY a.variety_id ) d `
	// 数据总数
	totalSql := `SELECT COUNT(1) total ` + baseSql
	err = o.Raw(totalSql, pars).QueryRow(&total)
	if err != nil {
		return
	}

	// 列表页数据
	listSql := `SELECT * ` + baseSql + ` ORDER BY modify_time DESC,variety_id DESC LIMIT ?,?`
	_, err = o.Raw(listSql, pars, startSize, pageSize).QueryRows(&items)
	return
}

// Update 更基础信息
func (variety *Variety) Update(cols []string) (err error) {
	o := orm.NewOrm()
	_, err = o.Update(variety, cols...)
	return
}

// GetVarietyMaxSort 获取图表分类下最大的排序数
func GetVarietyMaxSort(parentId int) (sort int, err error) {
	o := orm.NewOrm()
	sql := `SELECT Max(sort) AS sort FROM future_good_chart_classify WHERE parent_id=? AND is_delete=0 `
	err = o.Raw(sql, parentId).QueryRow(&sort)
	return
}

type VarietyView struct {
	VarietyId   int    `orm:"column(future_good_chart_classify_id);pk"`
	VarietyName string `description:"分类名称"`
	ParentId    int    `description:"父级id"`
}

func GetVarietyViewById(classifyId int) (item *VarietyView, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM future_good_chart_classify WHERE future_good_chart_classify_id=? AND is_delete=0 `
	err = o.Raw(sql, classifyId).QueryRow(&item)
	return
}
