package user

import (
	"errors"
	userReq "hongze/hongze_yb/models/request/user"
	admin2 "hongze/hongze_yb/models/tables/admin"
	"hongze/hongze_yb/models/tables/chart_permission"
	"hongze/hongze_yb/models/tables/company"
	"hongze/hongze_yb/models/tables/company_product"
	"hongze/hongze_yb/models/tables/rddp/msg_code"
	"hongze/hongze_yb/models/tables/wx_user"
	"hongze/hongze_yb/models/tables/yb_apply_record"
	"hongze/hongze_yb/services"
	companyService "hongze/hongze_yb/services/company"
	"hongze/hongze_yb/services/user"
	"hongze/hongze_yb/utils"
	"strings"
	"time"
)

// SendSmsCode 发送手机短信
func SendSmsCode(openid, mobile, areaNum string) (err error, errMsg string) {
	if mobile == "" {
		err = errors.New("请输入手机号")
		return
	}
	msgCode := utils.GetRandDigit(4)
	var result bool
	if areaNum == "86" || areaNum == "" || areaNum == "0" {
		//国内的短信
		result = services.SendSmsCode(mobile, msgCode)
	} else {
		//国际短信
		result = services.SendSmsCodeGj(mobile, msgCode, areaNum)
	}
	//发送成功
	if result {
		item := &msg_code.MsgCode{
			OpenID:          openid,
			Mobile:          mobile,
			Code:            msgCode,
			ExpiredIn:       time.Now().Add(15 * time.Minute).Unix(),
			Enabled:         1,
			CreatedTime:     time.Time{},
			LastUpdatedTime: time.Time{},
		}
		err = item.Create()
	} else {
		err = errors.New("短信发送失败")
	}
	return
}

// SendEmailCode 发送邮件
func SendEmailCode(openid, email string) (err error, errMsg string) {
	if email == "" {
		err = errors.New("请输入邮箱地址")
		return
	}
	if !utils.ValidateEmailFormatat(email) {
		err = errors.New("邮箱格式错误，请重新输入")
		return
	}
	msgCode := utils.GetRandDigit(4)
	content := "尊敬的用户：</br>您好，感谢您使用弘则研究，您正在进行邮箱验证，本次请求的验证码为：" + msgCode + "（为了保障您账号的安全性，请在15分钟内完成验证。）</br>弘则研究团队 </br>" + time.Now().Format(utils.FormatDateCN)
	title := "弘则研究登陆验证"
	//发送邮件
	result, err := services.SendEmailByHz(title, content, email)

	if result {
		item := &msg_code.MsgCode{
			OpenID:          openid,
			Mobile:          email,
			Code:            msgCode,
			ExpiredIn:       time.Now().Add(15 * time.Minute).Unix(),
			Enabled:         1,
			CreatedTime:     time.Time{},
			LastUpdatedTime: time.Time{},
		}
		err = item.Create()
	} else {
		err = errors.New("发送失败，Err:" + err.Error())
	}

	return
}

type CompanyPermission struct {
	Name           string           `json:"name" description:"分类名称"`
	PermissionList []PermissionList `json:"permission_list" description:"权限列表"`
}

type PermissionList struct {
	Name      string    `json:"name" description:"权限名称"`
	StartDate time.Time `json:"start_date" description:"开始日期"`
	EndDate   time.Time `json:"end_date" description:"结束日期"`
	Status    string    `json:"status" description:"状态"`
}

type Detail struct {
	CompanyName    string              `json:"company_name" description:"客户名称（公司名称）"`
	Status         string              `json:"status" description:"客户状态"`
	IsSuspend      int8                `json:"is_suspend" description:"启用与否字段：1:暂停,0:启用"`
	RealName       string              `json:"real_name" description:"用户名称"`
	Mobile         string              `json:"mobile" description:"手机号"`
	Email          string              `json:"email" description:"邮箱"`
	SellerName     string              `json:"seal_name" description:"所属销售名称"`
	SellerMobile   string              `json:"seal_mobile" description:"所属销售手机号"`
	PermissionList []CompanyPermission `json:"permission_list" description:"权限列表"`
	IsInner		   int				   `json:"is_inner" description:"是否为内部员工"`
	AdminInfo      *admin2.Admin	   `json:"admin_info" description:"系统管理员信息"`
}

// GetUserInfo 获取用户我的页面详情数据
func GetUserInfo(userInfo user.UserInfo) (userDetail Detail, err error, errMsg string) {
	list := make([]CompanyPermission, 0)
	companyName := userInfo.Note
	status := ``
	var isSuspend int8
	sellerName := ``
	sellerMobile := ``
	if userInfo.CompanyID > 1 {
		companyInfo, tmpErr := company.GetByCompanyId(userInfo.CompanyID)
		if tmpErr != nil {
			err = tmpErr
			if tmpErr == utils.ErrNoRow {
				err = errors.New("找不到该客户")
				errMsg = "找不到该客户"
				return
			}
			errMsg = "系统异常"
			return
		}
		companyName = companyInfo.CompanyName

		companyProduct, tmpErr := company_product.GetByCompany2ProductId(userInfo.CompanyID, 1)

		//如果有ficc权限，那么就去查询相关权限
		if tmpErr == nil {
			status = companyProduct.Status //产品状态
			isSuspend = companyProduct.IsSuspend

			//销售信息
			sellerName = companyProduct.SellerName
			adminInfo, tmpErr := admin2.GetByAdminId(companyProduct.SellerID)
			if tmpErr == nil {
				sellerMobile = adminInfo.Mobile
			}
			//获取所有的权限分类列表
			allPermissionList, tmpErr := companyService.GetPermissionListByProductId(1)
			if tmpErr != nil {
				err = tmpErr
				return
			}
			permissionClassMap := make(map[int]*chart_permission.ChartPermission)

			for _, chartPermission := range allPermissionList {
				permissionClassMap[int(chartPermission.ChartPermissionID)] = chartPermission
			}

			// 获取权限列表
			permissionList, tmpErr := companyService.GetValidPermissionByCompany2ProductId(userInfo.CompanyID, 1)
			if tmpErr != nil {
				err = tmpErr
				return
			}

			permissionMap := make(map[string][]PermissionList)
			for _, permission := range permissionList {
				chartPermission, ok := permissionClassMap[permission.ChartPermissionID]
				if ok {
					tmpPermission := PermissionList{
						Name:      chartPermission.PermissionName,
						StartDate: permission.StartDate,
						EndDate:   permission.EndDate,
						Status:    permission.Status,
					}
					if tmpPermissionList, ok2 := permissionMap[chartPermission.ClassifyName]; ok2 {
						permissionMap[chartPermission.ClassifyName] = append(tmpPermissionList, tmpPermission)
					} else {
						tmpPermissionList := make([]PermissionList, 0)
						permissionMap[chartPermission.ClassifyName] = append(tmpPermissionList, tmpPermission)
					}
				}
			}

			for name, tmpPermissionList := range permissionMap {
				list = append(list, CompanyPermission{
					Name:           name,
					PermissionList: tmpPermissionList,
				})
			}
		}

	}
	// 是否为内部员工
	isInner := 0
	ok, adminInfo, err := user.GetAdminByUserInfo(userInfo)
	if err != nil {
		err = errors.New("获取用户系统管理员信息失败")
		errMsg = "系统异常"
		return
	}
	if ok == true {
		isInner = 1
	}

	userDetail = Detail{
		CompanyName:    companyName, 		//客户名称（公司名称）
		Status:         status,      		//产品状态
		IsSuspend:      isSuspend,   		//是否启用
		RealName:       userInfo.RealName,
		Mobile:         userInfo.Mobile,
		Email:          userInfo.Email,
		SellerName:     sellerName,
		SellerMobile:   sellerMobile,
		PermissionList: list,				//权限列表
		IsInner: 		isInner,			// 是否为内部员工
		AdminInfo: 		adminInfo,			// 系统管理员信息
	}

	return
}

type Record struct {
	BusinessCardURL string `json:"business_card_url" description:"名片"`
	RealName        string `json:"real_name" description:"姓名"`
	CompanyName     string `json:"company_name" description:"客户备注的公司名称"`
	Mobile          string `json:"mobile" description:"手机号"`
}

// GetLastApplyInfo 获取最近的一套申请记录
func GetLastApplyInfo(userId, source int) (record Record, err error) {
	recordInfo, err := yb_apply_record.GetLastNotOpRecordByUserId(userId, source)
	if err != nil {
		if err == utils.ErrNoRow {
			err = nil
		}
		return
	}
	record = Record{
		BusinessCardURL: recordInfo.BusinessCardURL,
		RealName:        recordInfo.RealName,
		CompanyName:     recordInfo.CompanyName,
		Mobile:          recordInfo.Mobile,
	}
	return
}

// Apply 客户申请
func Apply(userId int, companyId int64, mobile, email string, applyInfo userReq.ApplyReq) (ybApplyRecord *yb_apply_record.YbApplyRecord, err error) {
	sellerName := ``
	status := `潜在用户`
	companyName := applyInfo.CompanyName

	tmpmYbApplyRecord, err := yb_apply_record.GetLastNotOpRecordByUserId(userId, applyInfo.Source)
	if err == nil {
		ybApplyRecord = tmpmYbApplyRecord	// 申请来源每一种只存在一条数据
		return
	} else {
		if err != utils.ErrNoRow {
			return
		}
	}

	// 联系人信息
	wxUserInfo, err := wx_user.GetByUserId(userId)
	if err != nil {
		return
	}

	if companyId > 1 {
		//客户信息
		companyInfo, tmpErr := company.GetByCompanyId(companyId)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		companyName = companyInfo.CompanyName

		//客户产品权限
		companyProductList, tmpErr := company_product.GetListByCompanyId(companyId)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		sellerNameList := make([]string, 0)
		statusList := make([]string, 0)
		for _, companyProductInfo := range companyProductList {
			if companyProductInfo.ProductID == 2 && status == "潜在用户" {
				status = "权益用户"
			}
			if companyProductInfo.ProductID == 1 {
				sellerName = companyProductInfo.SellerName
				status = companyProductInfo.Status
				if companyProductInfo.IsSuspend == 1 {
					status = `试用暂停`
				}
			}
		}
		if len(sellerNameList) > 0 && len(statusList) > 0 {
			sellerName = strings.Join(sellerNameList, ",")
			status = strings.Join(statusList, ",")
		}
	}
	ybApplyRecord = &yb_apply_record.YbApplyRecord{
		UserID:          userId,
		BusinessCardURL: applyInfo.BusinessCardUrl,
		RealName:        applyInfo.RealName,
		CompanyName:     applyInfo.CompanyName,
		Mobile:          mobile,
		Email:           email,
		Permission:      applyInfo.Permission,
		SellerName:      sellerName,
		Status:          status,
		CompanyIDPay:    int(companyId),
		CompanyNamePay:  companyName,
		CreateTime:      time.Now(),
		Source: 		 applyInfo.Source,
	}
	err = ybApplyRecord.Create()
	if err != nil {
		return
	}

	// 修改客户信息
	wxUserInfo.RealName = applyInfo.RealName
	wxUserInfo.Note = applyInfo.CompanyName
	wxUserInfo.IsNote = 1

	applyMethod := wxUserInfo.ApplyMethod //0:未申请，1:已付费客户申请试用，2:非客户申请试用
	applyMethod = 2
	if sellerName != "" {
		applyMethod = 1
	}
	wxUserInfo.ApplyMethod = applyMethod

	_ = wxUserInfo.Update([]string{"RealName", "Note", "IsNote", "ApplyMethod"})
	return
}

// GetUserTabBar 获取用户小程序TabBar
func GetUserTabBar(userInfo user.UserInfo) (list []string, err error) {
	//buy,report,chart,activity,user
	list = []string{"activity", "user", "chart"}

	//companyProduct, err := company_product.GetByCompany2ProductId(userInfo.CompanyID, 1)
	//if err != nil {
	//	if err == utils.ErrNoRow {
	//		err = nil
	//	}
	//	return
	//}
	//if strings.Contains("永续,正式,试用", companyProduct.Status) {
	//	list = append(list, "report", "chart")
	//}
	//if strings.Contains("永续,正式", companyProduct.Status) {
	//	list = append(list, "buy")
	//}

	return
}
