package data_manage_permission

import (
	"eta/eta_mobile/utils"
	"github.com/beego/beego/v2/client/orm"
)

// ModifyDataUserIdByOldUserId
// @Description:  根据旧用户id修改新用户id
// @author: Roc
// @datetime 2024-03-25 17:59:32
// @param oldUserId int
// @param userId int
// @return err error
func ModifyDataUserIdByOldUserId(oldUserIdList []int, userId int, userName string, isMoveManual, isMoveMysteelChemical, isMoveEdb, isMovePredictEdb, isMoveChart, isMoveExcel bool) (err error) {
	num := len(oldUserIdList)
	if num <= 0 {
		return
	}

	if userId <= 0 {
		return
	}

	// 手工指标库
	if isMoveManual {
		edbTo, tmpErr := orm.NewOrmUsingDB("edb").Begin()
		if tmpErr != nil {
			return
		}
		defer func() {
			if err != nil {
				_ = edbTo.Rollback()
			} else {
				_ = edbTo.Commit()
			}
		}()
		sql := `UPDATE edbinfo SET user_id=? WHERE user_id in (` + utils.GetOrmInReplace(num) + `) `
		_, err = edbTo.Raw(sql, userId, oldUserIdList).Exec()
		if err != nil {
			return
		}
	}

	// ETA指标库
	o, err := orm.NewOrmUsingDB("data").Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = o.Rollback()
		} else {
			_ = o.Commit()
		}
	}()

	// 上海钢联数据库
	if isMoveMysteelChemical {
		sql := `UPDATE base_from_mysteel_chemical_index SET sys_user_id=?,sys_user_real_name=? WHERE sys_user_id in (` + utils.GetOrmInReplace(num) + `)  `
		_, err = o.Raw(sql, userId, userName, oldUserIdList).Exec()
		if err != nil {
			return
		}
	}

	// ETA指标库
	if isMoveEdb {
		sql := `UPDATE edb_info SET sys_user_id=?,sys_user_real_name=? WHERE sys_user_id in (` + utils.GetOrmInReplace(num) + `) and edb_info_type = ?`
		_, err = o.Raw(sql, userId, userName, oldUserIdList, 0).Exec()
		if err != nil {
			return
		}
	}
	// 预测指标
	if isMovePredictEdb {
		sql := `UPDATE edb_info SET sys_user_id=?,sys_user_real_name=? WHERE sys_user_id in (` + utils.GetOrmInReplace(num) + `) and edb_info_type = ?`
		_, err = o.Raw(sql, userId, userName, oldUserIdList, 1).Exec()
		if err != nil {
			return
		}
	}

	// ETA表格
	if isMoveChart {
		sql := `UPDATE chart_info SET sys_user_id=?,sys_user_real_name=? WHERE sys_user_id in (` + utils.GetOrmInReplace(num) + `) `
		_, err = o.Raw(sql, userId, userName, oldUserIdList).Exec()
		if err != nil {
			return
		}
	}

	// ETA表格
	if isMoveExcel {
		sql := `UPDATE excel_info SET sys_user_id=?,sys_user_real_name=? WHERE is_delete=0 AND sys_user_id in (` + utils.GetOrmInReplace(num) + `) `
		_, err = o.Raw(sql, userId, userName, oldUserIdList).Exec()
		if err != nil {
			return
		}
	}

	return
}
