package model

import (
	"app.yhyue.com/moapp/jybase/common"
	"app.yhyue.com/moapp/jybase/date"
	"encoding/json"
	IC "jyBXSubscribe/rpc/init"
	"strings"
)

type User struct {
	Id        int
	Name      string //员工姓名
	Mail      string //邮箱
	Phone     string //手机号
	Dept_id   int    //部门id
	Dept_name string //部门名称
	//Role      string //角色
	Power int //权限
}

type CurrentUser struct {
	Role_admin_department bool        //是否是部门管理员
	Role_admin_system     bool        //是否是系统管理员
	Dept                  *Department //部门信息
	BondPhone             string      //手机号
	NickName              string      //昵称
	HeadImageUrl          string      //头像
	PersonalAuth          int         //个人认证
	PersonalAuthReason    string      //个人认证不通过原因
	User_power            int         //是否分配权限
	User_name             string      //用户姓名
}

type Department struct {
	Id         int
	Name       string //部门名
	Pid        int    //上级部门id
	Pname      string //上级部门名称
	Nodiff     int    //全员无差别接收 0：关闭 1：打开
	Subdis     int    //订阅分发 0：关闭 1：打开
	Aid        int    //管理员id
	Aname      string //管理员姓名
	Rname      string //角色名
	User_count int    //该部门下员工的总数
	Dept_count int    //该部门下子部门总数
	Ent_id     int    //公司id
}

type namePower struct {
	entUserId string
	power     int //1 超级订阅权益 2大会员权益
}

const (
	//角色
	Role_admin_system     = 1 //系统管理员
	Role_admin_department = 2 //部门管理员
)

// 当前登录用户的信息
func EntInfo(entId, entUserId int) *CurrentUser {
	currentUser := &CurrentUser{
		Dept: &Department{},
	}
	user := IC.MainMysql.SelectBySql(`SELECT a.name as user_name from entniche_user a INNER JOIN entniche_user_role b on (a.id=b.user_id) where a.id=? and b.role_id=? limit 1`, entUserId, Role_admin_system)
	if user != nil && len(*user) > 0 {
		currentUser.Role_admin_system = true
		currentUser.User_name, _ = (*user)[0]["user_name"].(string)
		currentUser.User_power = 1
		r := IC.MainMysql.SelectBySql(`SELECT id,name,subdis,nodiff from entniche_department where ent_id=? and pid=0 limit 1`, entId)
		if r != nil && len(*r) == 1 {
			department := JsonUnmarshal((*r)[0], &Department{}).(*Department)
			if department != nil {
				department.Pid = department.Id
				currentUser.Dept = department
			}
		}
	} else {
		//角色、权限
		r := IC.MainMysql.SelectBySql(`SELECT a.name as user_name,a.power as user_power,b.role_id,d.id as dept_id,d.name as dept_name,d.subdis as dept_subdis,d.nodiff as dept_nodiff,e.id as dept_pid from entniche_user a 
			LEFT JOIN entniche_user_role b on (b.user_id=?) 
			INNER JOIN entniche_department_user c on (a.id=? and a.id=c.user_id) 
			INNER JOIN entniche_department d on (c.dept_id=d.id) 
			INNER JOIN entniche_department e on (e.ent_id=? and e.pid=0) 
			order by a.id desc limit 1`, entUserId, entUserId, entId)
		if r != nil && len(*r) == 1 {
			currentUser.User_name, _ = (*r)[0]["user_name"].(string)
			currentUser.User_power = common.IntAll((*r)[0]["user_power"])
			if common.IntAll((*r)[0]["role_id"]) == Role_admin_department {
				currentUser.Role_admin_department = true
			}
			currentUser.Dept.Id = common.IntAll((*r)[0]["dept_id"])
			currentUser.Dept.Pid = common.IntAll((*r)[0]["dept_pid"])
			currentUser.Dept.Name = common.ObjToString((*r)[0]["dept_name"])
			currentUser.Dept.Subdis = common.IntAll((*r)[0]["dept_subdis"])
			currentUser.Dept.Nodiff = common.IntAll((*r)[0]["dept_nodiff"])
		}
	}
	return currentUser
}

// map转结构体
func JsonUnmarshal(m interface{}, s interface{}) interface{} {
	var b []byte
	if v, ok := m.(string); ok {
		b = []byte(v)
	} else if v, ok := m.([]byte); ok {
		b = v
	} else {
		b, _ = json.Marshal(m)
	}
	json.Unmarshal(b, &s)
	return s
}

// 获取部门下可以进行分发的人员(不包含部门名称和部门id)
func GetDisUsers(entId, deptId int) *[]*User {
	r := IC.MainMysql.SelectBySql(`select DISTINCT c.id,c.name,c.phone,c.power,b.dept_id from entniche_department_parent a 
		INNER JOIN entniche_department_user b on (b.dept_id=? or (a.pid=? and a.id=b.dept_id)) 
		INNER JOIN entniche_user c on (c.ent_id=? and b.user_id=c.id) 
		order by convert(c.name using gbk) COLLATE gbk_chinese_ci asc`, deptId, deptId, entId)
	users, _ := JsonUnmarshal(r, &[]*User{}).(*[]*User)
	if users == nil {
		return &[]*User{}
	}
	return users
}

// 获取企业下所有的员工(不包含部门名称和部门id)
func GetEntUsers(entId int) *[]*User {
	r := IC.MainMysql.SelectBySql(`select a.id,a.name,a.phone,a.power,b.dept_id from entniche_user a  LEFT JOIN entniche_department_user b on  (a.id=b.user_id )  where ent_id=?
		order by convert(name using gbk) COLLATE gbk_chinese_ci asc`, entId)
	users, _ := JsonUnmarshal(*r, &[]*User{}).(*[]*User)
	if users == nil {
		return &[]*User{}
	}
	return users
}

// 获取企业下分配权益的用户
func GetEntPowerUsers(entId int) map[namePower]int {
	nowFormat := date.NowFormat(date.Date_Short_Layout)
	r := IC.MainMysql.SelectBySql(`select a.ent_user_id,b.product_type from entniche_power a  LEFT JOIN entniche_wait_empower b ON (a.wait_empower_id = b.id) where a.ent_id=? and a.status = 1 and b.start_time <=? and b.end_time>=? `, entId, nowFormat, nowFormat)
	if r == nil {
		return nil
	}
	data := make(map[namePower]int)
	for _, v := range *r {
		if strings.Contains(common.InterfaceToStr(v["product_type"]), "VIP") {
			var _n namePower
			_n.entUserId = common.InterfaceToStr(v["ent_user_id"])
			_n.power = 1
			data[_n] = 1
		} else if strings.Contains(common.InterfaceToStr(v["product_type"]), "大会员") {
			var _n namePower
			_n.entUserId = common.InterfaceToStr(v["ent_user_id"])
			_n.power = 2
			data[_n] = 2
		}
	}
	return data
}

func GetIsEnt(entId int) bool {
	return IC.MainMysql.CountBySql(`select count(*) from entniche_info where id=? and status = 1`, entId) > 0
}
