package services

import (
	"fmt"
	"hongze/hongze_cygx/models"
	"hongze/hongze_cygx/utils"
	"strconv"
	"strings"
	"time"
)

func CheckHtgj(companyCodeHt, companyNameHt, email, sign string) (errMsg string, errHt error, user *models.WxUser, companyName string) {
	errMsg = CheckSign(companyCodeHt+companyNameHt+email, sign)
	if errMsg != "" {
		if errMsg == "机构下账号个数已达上限" {
			return
		}
		errMsg = "签名方式错误！"
		return
	}
	var wxuUserName, tripartiteCompanyCode string
	var startDate, endDate string
	var companyId int64

	companyName = companyCodeHt[0:4] + "_" + companyNameHt
	tripartiteCompanyCode = companyCodeHt + "_" + companyNameHt
	wxUser := new(models.WxUser)
	productId := 2
	productName := "权益"
	itemCompany := new(models.Company)
	sellerInfo, err := models.GetSellerByName(utils.HtgjDefaultSaleName)
	if err != nil {
		errHt = err
		return
	}
	wxuUserName = email
	countCompay, err := models.GetCompanyCountByThirdName(tripartiteCompanyCode)
	if err != nil {
		errHt = err
		return
	}
	if countCompay == 0 {
		defaultPermissionIds, err := models.GetCompanyPermissionIdWithHtgj()
		if err != nil {
			errHt = err
			return
		}
		companySourceInfo, err := models.GetCompanySourceByName(utils.HtgjName)
		if err != nil {
			errHt = err
			return
		}

		companyCode, err := models.GetCompanyCode()
		if err != nil {
			errHt = err
			return
		}
		startDate = time.Now().Format(utils.FormatDate)
		endDate = time.Now().AddDate(0, 2, 0).Format(utils.FormatDate)
		itemCompany.TripartiteCompanyCode = tripartiteCompanyCode
		itemCompany.CompanyName = companyName
		itemCompany.CreditCode = "HZ" + strconv.FormatInt(time.Now().UnixNano()/1e6, 10)
		itemCompany.CompanyCode = companyCode
		itemCompany.StartDate = startDate
		itemCompany.EndDate = endDate
		itemCompany.CreatedTime = time.Now()
		itemCompany.LastUpdatedTime = time.Now()
		itemCompany.Enabled = 1
		itemCompany.CompanyType = 2
		itemCompany.RegionType = "海外"
		companyId, err = models.AddCompany(itemCompany)
		if err != nil {
			errHt = err
			return
		}
		//更新三方Code
		itemCompany.OpenCompanyCode = GenerateOpenCompanyCode(int(companyId))
		itemCompany.CompanyId = int(companyId)
		itemCompany.Update([]string{"OpenCompanyCode"})

		companyProduct := new(models.CompanyProduct)
		companyProduct.CompanyId = int(companyId)
		companyProduct.ProductId = productId
		companyProduct.ProductName = productName
		companyProduct.CompanyName = companyName
		companyProduct.Source = companySourceInfo.SourceName
		companyProduct.Reasons = ""
		companyProduct.Status = "试用"
		companyProduct.StartDate = startDate
		companyProduct.EndDate = endDate
		companyProduct.IndustryId = 11 //11是海通国际的ID
		companyProduct.IndustryName = "其他类型"
		companyProduct.SellerId = sellerInfo.AdminId
		companyProduct.SellerName = sellerInfo.RealName
		companyProduct.GroupId = sellerInfo.GroupId
		companyProduct.DepartmentId = sellerInfo.DepartmentId
		companyProduct.IsSuspend = 0
		companyProduct.CreateTime = time.Now()
		companyProduct.ModifyTime = time.Now()
		companyProduct.CompanyType = "权益"
		companyProduct.OpenCode = GenerateOpenCompanyProductCode(int(companyId), productId)
		companyProductId, err := models.AddCompanyProduct(companyProduct)
		if err != nil {
			errHt = err
			return
		}
		err = AddCompanyPermission(int(companyId), sellerInfo.AdminId, productId, productName, sellerInfo.RealName, defaultPermissionIds, startDate, endDate)
		if err != nil {
			errHt = err
			return
		}

		{
			record := new(models.CompanyOperationRecord)
			record.CompanyId = int(companyId)
			record.CompanyName = companyName
			record.SellerId = sellerInfo.AdminId
			record.SysUserId = sellerInfo.AdminId
			record.SysRealName = sellerInfo.RealName
			record.Remark = "新增客户"
			record.Operation = "add"
			record.CreateTime = time.Now()
			record.ProductId = productId
			record.ProductName = productName
			record.Status = "试用"
			_, err = models.AddCompanyOperationRecord(record)
			if err != nil {
				errHt = err
				go utils.SendEmail(utils.APPNAME+"失败提醒"+utils.RunMode, "海通国际添加客户失败"+err.Error(), utils.EmailSendToUsers)
			}
		}
		//新增客户日志
		{
			companyLog := new(models.CompanyLog)
			companyLog.CompanyId = int(companyId)
			companyLog.CompanyName = companyName
			companyLog.CreditCode = ""
			companyLog.CompanyCode = companyCode
			companyLog.Sort = itemCompany.Sort
			companyLog.IsFeeCustomer = itemCompany.IsFeeCustomer
			companyLog.Country = itemCompany.Country
			companyLog.Address = itemCompany.Address
			companyLog.City = itemCompany.City
			companyLog.Province = itemCompany.Province
			companyLog.Enabled = itemCompany.Enabled
			companyLog.CreatedTime = itemCompany.CreatedTime
			companyLog.LastUpdatedTime = itemCompany.LastUpdatedTime
			companyLog.Seller = itemCompany.Seller
			companyLog.SellsId = itemCompany.SellsId
			companyLog.CompanyBelong = itemCompany.CompanyBelong
			companyLog.StartDate = itemCompany.StartDate
			companyLog.EndDate = itemCompany.EndDate
			companyLog.FirstStartDate = itemCompany.FirstStartDate
			companyLog.FirstEndDate = itemCompany.FirstEndDate
			companyLog.DateType = itemCompany.DateType
			companyLog.AdminId = sellerInfo.AdminId
			companyLog.LogType = "add"
			companyLog.LogCreateTime = time.Now()
			go models.AddCompanyLog(companyLog)
		}

		//新增客户产品日志
		{
			productLog := new(models.CompanyProductLog)
			productLog.CompanyProductId = int(companyProductId)
			productLog.CompanyId = companyProduct.CompanyId
			productLog.ProductId = companyProduct.ProductId
			productLog.ProductName = companyProduct.ProductName
			productLog.CompanyName = companyProduct.CompanyName
			productLog.CompanyName = companyProduct.CompanyName
			productLog.Source = companyProduct.Source
			productLog.Reasons = companyProduct.Reasons
			productLog.Status = companyProduct.Status
			productLog.IndustryId = companyProduct.IndustryId
			productLog.IndustryName = companyProduct.IndustryName
			productLog.SellerId = companyProduct.SellerId
			productLog.SellerName = companyProduct.SellerName
			productLog.GroupId = companyProduct.GroupId
			productLog.DepartmentId = companyProduct.DepartmentId
			productLog.IsSuspend = companyProduct.IsSuspend
			productLog.SuspendTime = companyProduct.SuspendTime
			productLog.ApproveStatus = companyProduct.ApproveStatus
			productLog.FreezeTime = companyProduct.FreezeTime
			productLog.Remark = companyProduct.Remark
			productLog.StartDate = companyProduct.StartDate
			productLog.EndDate = companyProduct.EndDate
			productLog.CreateTime = companyProduct.CreateTime
			productLog.ModifyTime = companyProduct.ModifyTime
			productLog.LoseReason = companyProduct.LoseReason
			productLog.LossTime = companyProduct.LossTime
			productLog.LogType = "add"
			productLog.LogCreateTime = time.Now()
			productLog.AdminId = sellerInfo.AdminId
			go models.AddCompanyProductLog(productLog)
		}

	} else {
		companyInfo, err := models.GetCompanyByThirdName(tripartiteCompanyCode)
		if err != nil {
			errHt = err
			return
		}
		companyId = int64(companyInfo.CompanyId)
	}
	countUser, err := models.GetUserCountByThirdName(int(companyId), wxuUserName)
	if countUser == 0 {

		countCompanyUser, err := models.GetUserCountByCompanyId(int(companyId))
		if err != nil {
			errHt = err
			return
		}
		if countCompanyUser >= 15 {
			errMsg = "机构下账号个数已达上限"
			return
		}
		wxUser.CompanyId = int(companyId)
		wxUser.RealName = wxuUserName
		wxUser.Email = wxuUserName
		wxUser.TripartiteCode = wxuUserName
		wxUser.Source = 7
		wxUser.CreatedTime = time.Now()
		newUserId, err := models.AddWxUser(wxUser)
		if err != nil {
			errHt = err
			return
		}
		md5Mobile := utils.Get16MD5Encode(strconv.Itoa(int(newUserId)))
		wxUser.Mobile = md5Mobile
		wxUser.UserId = int(newUserId)
		err = models.UpdateUserMobile(int(newUserId), md5Mobile)
		if err != nil {
			errHt = err
			return
		}
		models.AddUserSellerRelation(newUserId, int(companyId), sellerInfo.AdminId, productId, sellerInfo.RealName, wxUser.Mobile, wxuUserName)
	} else {
		wxUser, err = models.GetUserByThirdName(int(companyId), wxuUserName)
		if err != nil {
			errHt = err
			return
		}
	}
	user = wxUser
	return
}

// GenerateOpenCompanyCode 生成第三方code编号
func GenerateOpenCompanyCode(companyId int) (openCode string) {
	openCode = utils.MD5(fmt.Sprint(companyId, "hzyj20210902"))
	return
}

// GenerateOpenCompanyProductCode 生成客户产品第三方code编号
func GenerateOpenCompanyProductCode(companyId, productId int) (openCode string) {
	openCode = utils.MD5(fmt.Sprint(companyId, "_", productId, "hzyj20210902"))
	return
}

//新增客户权限
func AddCompanyPermission(companyId, sysUserId, productId int, productName, sysUserName, permissionStr, startDate, endDate string) (err error) {
	if permissionStr == "" {
		return
	}
	permissionArr := strings.Split(permissionStr, ",")
	count, _ := models.GetCompanyReportPermissionCount(companyId, productId)

	//删除权限
	if count > 0 {
		err = models.DeleteCompanyReportPermission(companyId, productId)
		if err != nil {
			return
		}
	}
	for _, pv := range permissionArr {
		permissionId, err := strconv.Atoi(pv)
		if err != nil {
			return err
		}
		permission := new(models.CompanyReportPermission)
		permission.CompanyId = companyId
		permission.ReportPermissionId = permissionId
		permission.CreatedTime = time.Now()
		permission.LastUpdatedTime = time.Now()
		permission.ChartPermissionId = permissionId
		permission.StartDate = startDate
		permission.EndDate = endDate
		permission.ProductId = productId
		permission.ProductName = productName
		permission.ModifyTime = time.Now().Format(utils.FormatDateTime)
		permission.Status = "试用"
		err = models.AddCompanyReportPermission(permission)
		if err != nil {
			return err
		}

		cpLog := new(models.CompanyPermissionLog)
		cpLog.CompanyId = companyId
		cpLog.ChartPermissionId = permissionId
		cpLog.CreateTime = time.Now()
		cpLog.SysUserId = sysUserId
		cpLog.SysUserName = sysUserName
		cpLog.StartDate = startDate
		cpLog.EndDate = endDate
		cpLog.ProductId = productId
		cpLog.ProductName = productName
		go models.AddCompanyPermissionLog(cpLog)
	}
	return
}

func CheckSign(userName, sign string) (errMsg string) {
	var pwdSign string
	pwdSign = userName + utils.HtgjSalt
	fmt.Println("pwdSign", pwdSign)
	pwdSign = strings.ToUpper(utils.MD5(pwdSign))
	fmt.Println(pwdSign)
	if sign != pwdSign {
		errMsg = "签名错误"
	}
	return
}
