package cms

import (
	"git.rosy.net.cn/jx-callback/business/auth2"
	"git.rosy.net.cn/jx-callback/business/auth2/authprovider/weixin"
	"git.rosy.net.cn/jx-callback/business/authz/autils"
	"git.rosy.net.cn/jx-callback/business/model"
	"git.rosy.net.cn/jx-callback/business/model/dao"
	"git.rosy.net.cn/jx-callback/business/model/legacymodel"
	"git.rosy.net.cn/jx-callback/globals"
	"git.rosy.net.cn/jx-callback/globals/api2"
)

// todo 是否需要将Store.MarketManPhone与OperatorPhone成角色？

func TransferLegacyWeixins(mobile string) (err error) {
	if !globals.EnableWXAuth2 || globals.DisableWXAuth1 {
		return nil
	}
	remark4Transfer := "transfer"
	// DELETE t1
	// FROM auth_bind t1
	// WHERE t1.remark = 'transfer';

	// DELETE t1
	// FROM user t1
	// WHERE t1.remark = 'transfer';

	// TRUNCATE TABLE casbin_rule;

	sql := `
	SELECT t1.*
	FROM weixins t1
	LEFT JOIN user t2 ON t2.mobile = t1.tel
	LEFT JOIN auth_bind t3 ON t3.auth_id = t1.openid AND t3.type = 'weixinsns'
	LEFT JOIN auth_bind t4 ON t4.auth_id = t1.openid_mini AND t4.type = 'weixinmini'
	WHERE`
	sqlParams := []interface{}{}
	if mobile != "" {
		remark4Transfer = "transfer2"
		sql += " t1.tel = ?"
		sqlParams = append(sqlParams, mobile)
	} else {
		sql += " t2.id IS NULL OR (t1.openid <> '' AND t3.id IS NULL) OR (t1.openid_mini <> '' AND t4.id IS NULL)"
	}
	sql += " ORDER BY t1.parentid;"
	var weixinList []*legacymodel.WeiXins
	db := dao.GetDB()
	err = dao.GetRows(db, &weixinList, sql, sqlParams...)
	if err != nil {
		return err
	}
	parentMap := make(map[int]*legacymodel.WeiXins)
	for _, v := range weixinList {
		if v.ParentID == -1 {
			parentMap[v.ID] = v
		} else {
			if parentMap[v.ParentID] != nil {
				v.JxStoreID = parentMap[v.ParentID].JxStoreID
			}
		}
		if v.Tel != "" {
			user := &model.User{
				UserID2: v.Tel,
				Name:    v.NickName,
				Mobile:  &v.Tel,
				Type:    model.UserTypeStoreBoss,
				Remark:  remark4Transfer,
			}
			if user.Name == "" {
				user.Name = user.GetMobile()
			}
			userList, _, err2 := dao.GetUsers(db, 0, "", nil, nil, []string{v.Tel}, 0, -1)
			if err = err2; err != nil {
				return err
			}
			if len(userList) == 0 {
				err = CreateUser(user, v.LastOperator)
			} else {
				user = userList[0]
			}
			if err != nil {
				return err
			}
			if v.OpenID != "" {
				auth2.AddAuthBind(user, &auth2.AuthInfo{
					AuthBindInfo: &auth2.AuthBindEx{
						AuthBind: model.AuthBind{
							Type:    weixin.AuthTypeMP,
							AuthID:  v.OpenID,
							AuthID2: v.OpenIDUnion,
							Remark:  remark4Transfer,
						},
					},
				})
			}
			if v.OpenIDMini != "" {
				auth2.AddAuthBind(user, &auth2.AuthInfo{
					AuthBindInfo: &auth2.AuthBindEx{
						AuthBind: model.AuthBind{
							Type:    weixin.AuthTypeMini,
							AuthID:  v.OpenIDMini,
							AuthID2: v.OpenIDUnion,
							Remark:  remark4Transfer,
						},
					},
				})
			}
			if v.JxStoreID > 0 { // 运营就不加到门店老板组里了
				if user.Type&model.UserTypeOperator == 0 {
					api2.RoleMan.AddRole4User(user.GetID(), autils.NewStoreBossRole(v.JxStoreID))
				}
			} else {
				if mobile != "" {
					rList, err2 := api2.RoleMan.GetUserRoleList(user.GetID())
					if err = err2; err == nil {
						for _, role := range rList {
							if role.StoreID > 0 {
								api2.RoleMan.DeleteRole4User(user.GetID(), autils.NewStoreBossRole(role.StoreID))
							}
						}
					}
				}
			}
		}
	}
	return err
}
