package enterprise_session

import (
	"errors"
	"fmt"
	enterprise "git.rosy.net.cn/baseapi/platformapi/enterprise_wechat"
	"git.rosy.net.cn/jx-callback/business/auth2"
	"git.rosy.net.cn/jx-callback/business/authz"
	"git.rosy.net.cn/jx-callback/business/authz/autils"
	"git.rosy.net.cn/jx-callback/business/jxstore/cms"
	"git.rosy.net.cn/jx-callback/business/model"
	"git.rosy.net.cn/jx-callback/business/model/dao"
	"git.rosy.net.cn/jx-callback/globals/api"
	"strconv"
	"strings"
)

type CreateSession struct {
}

// 创建老板的业务群
func (c *CreateSession) CreateBossToStaffAndCreateSession(token string, storeId int) (map[string]interface{}, error) {
	// 获取老本的电话和门店信息
	authInfo, err := auth2.GetTokenInfo(token)
	if err != nil {
		return nil, err
	}

	store, err := dao.GetStoreDetail2(dao.GetDB(), storeId, "", 0)
	if err != nil {
		return nil, err
	}
	if store.Tel1 != authInfo.Mobile || store.Tel1 == "" {
		return nil, errors.New("不是门店老板,不创建群聊")
	}

	// 检测用户是否存在
	if _, err := CheckUserExist(store); err != nil {
		return nil, err
	}

	// 获取创建群聊所需基础人员id
	enterpriseIdList, err := CheckBoosGroupChat(store)
	if err != nil {
		return nil, err
	}

	result := make(map[string]interface{}, 0)
	result["enterpriseIdList"] = enterpriseIdList
	result["chatName"] = "京西菜市" + store.Name + "群"
	return result, nil
}

// 检测用户是否存在
func CheckUserExist(store *dao.StoreDetail2) (string, error) {
	enterpriseUserId, err := api.EnterpriseChatHeadApi.GetUserIdByMobile(store.Tel1)
	if strings.Contains(fmt.Sprintf("%v", err), "user no exist") || strings.Contains(fmt.Sprintf("%v", err), "46004") {
		boss := &enterprise.CreateBoos2JXStaffReq{
			Userid:           store.Tel1 + "_" + strconv.Itoa(store.ID),
			Name:             store.LicenceOwnerName,
			Alias:            "",
			Mobile:           store.Tel1,
			Department:       nil, // 四川省
			Order:            nil,
			Gender:           "1",
			Email:            "",
			IsLeaderInDept:   nil,
			Enable:           0,
			AvatarMediaid:    "",
			Telephone:        "",
			Address:          store.Address,
			Extattr:          enterprise.Extattr{},
			MainDepartment:   0,
			ToInvite:         true,
			ExternalPosition: "",
			ExternalProfile:  enterprise.ExternalProfile{},
		}
		if boss.Name == "" {
			boss.Name = store.Name + "(老板名称不存在)"
		}

		// 查询本门店所属省code
		parentCityName := ""
		if store.CityCode == 0 {
			return "", errors.New("门店位置不能为空")
		}
		parentCityName, err = GetCityCode(store.CityCode)
		if err != nil {
			return "", err
		}
		// 查询企业微信所有省份部门分类
		departmentList, err := api.EnterpriseChatHeadApi.GetAllDepartmentList()
		if err != nil {
			return "", err
		}
		for _, v := range departmentList {
			if !strings.Contains(v.Name, parentCityName[:6]) {
				continue
			}
			boss.Department = []int{v.ID}
			break
		}

		// 创建老板为京西员工,并存放在对应的省份里面
		if err := api.EnterpriseChatHeadApi.CreateBoss2JxStaff(boss); err != nil {
			return "", err
		}
		enterpriseUserId = boss.Userid
	}

	return enterpriseUserId, err
}

func GetCityCode(cityCode int) (string, error) {
	for i := 0; i < 4; i++ {
		place, err := dao.GetPlaceByCode(dao.GetDB(), cityCode)
		if err != nil {
			return "", err
		}
		if place.Level == model.YES && place.ParentCode == 0 {
			return place.Name, nil
		}
		cityCode = place.ParentCode
	}
	return "", errors.New("未查询到目标城市")
}

// 获取当前门店企业内部人员信息
func CheckBoosGroupChat(store *dao.StoreDetail2) ([]string, error) {
	// 获取门店角色
	roleNames := []string{"StoreBoss"}
	storeIDs := []int{store.ID}
	var roleList []*authz.RoleInfo
	for _, roleName := range roleNames {
		if roleName == authz.StoreRoleBoss {
			for _, storeID := range storeIDs {
				roleList = append(roleList, autils.NewRole(roleName, storeID))
			}
		} else {
			roleList = append(roleList, autils.NewRole(roleName, 0))
		}
	}
	retVal, err := cms.GetRolesUserList(nil, roleList)
	if err != nil {
		return nil, err
	}

	// 获取角色系统userId
	systemUserId := make([]string, 0, 0)
	for _, v := range retVal {
		if len(v) == 0 {
			return nil, errors.New("门店负责人为空,数据异常.联系管理员")
		}
		systemUserId = append(systemUserId, v...)
	}

	// 根据userId获取系统用户电话号码
	userList, _, err := dao.GetUsers(dao.GetDB(), 0, "", systemUserId, nil, nil, 0, 50)
	if err != nil {
		return nil, err
	}

	enterpriseList := make([]string, 0, 0)
	// 获取用户企业微信用户id
	for _, v := range userList {
		enterpriseId, err := api.EnterpriseChatHeadApi.GetUserIdByMobile(*v.Mobile)
		if err != nil {
			continue
		}
		enterpriseList = append(enterpriseList, enterpriseId)
	}
	return enterpriseList, nil
}

// 获取企业微信token
func GetEnterpriseTokenInfo() (string, string) {
	api.EnterpriseChatMin.CheckAccessTokenExpiresIn()
	api.EnterpriseChatHeadApi.CheckAccessTokenExpiresIn()
	return api.EnterpriseChatMin.ReturnToken(), api.EnterpriseChatHeadApi.ReturnToken()
	// 企业微信api
	//return api.EnterpriseChatHeadApi.ReturnToken()
}
