package services

import (
	"fmt"
	"hongze/hongze_task/models"
	"hongze/hongze_task/utils"
	"strconv"
	"time"
)

//客户自动冻结->试用两个月结束后，进入冻结
func CompanyFreeze() (err error) {
	defer func() {
		if err != nil {
			go utils.SendEmail(utils.APPNAME+"【"+utils.RunMode+"】"+"失败提醒", "试用两个月结束后，进入冻结 ErrMsg:"+err.Error(), utils.EmailSendToUsers)
		}
	}()
	endDate := time.Now().AddDate(0,0,-1).Format(utils.FormatDate)
	items, err := models.GetCompanyNeedFreeze(endDate)
	if err != nil {
		fmt.Println("GetCompanyNeedFreeze Err:" + err.Error())
		utils.FileLog.Info("GetCompanyNeedFreeze Err:%s" + err.Error())
		return
	}
	for k, v := range items {
		fmt.Println(k, v.CompanyId)
		count, err := models.GetCompanyApprovalCount(v.CompanyId,v.ProductId)
		if err != nil {
			return err
		}
		if count > 0 {
			continue
		}
		err = models.CompanyFreeze(v.CompanyId, v.ProductId)
		if err != nil {
			utils.FileLog.Info("CompanyFreeze Err:%s" + err.Error())
			return err
		}
		//新增操作记录
		{
			remark := "试用转冻结"
			operation := "freeze"
			approveContent := "冻结"
			AddCompanyOperationRecord(v.CompanyId, utils.AdminId, v.ProductId, utils.AdminId, v.CompanyName,
				v.ProductName, utils.RealName, remark, operation, approveContent, approveContent, "", v.Status)
		}
	}
	return
}

//客户自动流失->冻结超3个月未处理
func CompanyLoss() (err error) {
	defer func() {
		if err != nil {
			go utils.SendEmail(utils.APPNAME+"【"+utils.RunMode+"】"+"失败提醒", "自动流失->冻结超3个月未处理 ErrMsg:"+err.Error(), utils.EmailSendToUsers)
		}
	}()
	endDate := time.Now().AddDate(0,0,-1).Format(utils.FormatDate)
	items, err := models.GetCompanyNeedLoss(endDate)
	if err != nil {
		fmt.Println("GetCompanyNeedLoss Err:" + err.Error())
		utils.FileLog.Info("GetCompanyNeedLoss Err:%s" + err.Error())
		return
	}
	for k, v := range items {
		fmt.Println(k, v.CompanyId)
		count, err := models.GetCompanyApprovalCount(v.CompanyId,v.ProductId)
		if err != nil {
			return err
		}
		if count > 0 {
			continue
		}
		err = models.CompanyLoss(v.CompanyId, v.ProductId)
		if err != nil {
			utils.FileLog.Info("CompanyLoss Err:%s" + err.Error())
			return err
		}
		//新增操作记录
		{
			remark := "冻结转流失"
			operation := "loss"
			approveContent := "流失"
			AddCompanyOperationRecord(v.CompanyId, utils.AdminId, v.ProductId, utils.AdminId, v.CompanyName,
				v.ProductName, utils.RealName, remark, operation, approveContent, approveContent, "", v.Status)
		}
	}
	return
}

//正式客户自动试用->合同到期未续约转试用
func CompanyTryOut() (err error) {
	defer func() {
		if err != nil {
			go utils.SendEmail(utils.APPNAME+"【"+utils.RunMode+"】"+"失败提醒", "正式客户自动试用->合同到期未续约转试用 ErrMsg:"+err.Error(), utils.EmailSendToUsers)
		}
	}()
	endDate := time.Now().AddDate(0,0,-1).Format(utils.FormatDate)
	items, err := models.GetCompanyNeedTryOut(endDate)
	if err != nil {
		fmt.Println("GetCompanyNeedTryOut Err:" + err.Error())
		utils.FileLog.Info("GetCompanyNeedTryOut Err:%s" + err.Error())
		return
	}
	for k, v := range items {
		count, err := models.GetCompanyApprovalCount(v.CompanyId,v.ProductId)
		if err != nil {
			return err
		}
		if count > 0 {
			continue
		}
		fmt.Println(k, v.CompanyId)
		err = models.CompanyTryOut(v.CompanyId, v.ProductId)
		if err != nil {
			utils.FileLog.Info("CompanyLoss Err:%s" + err.Error())
			return err
		}
		//新增操作记录
		{
			remark := "正式转试用"
			operation := "try_out"
			approveContent := "试用"
			AddCompanyOperationRecord(v.CompanyId, utils.AdminId, v.ProductId, utils.AdminId, v.CompanyName,
				v.ProductName, utils.RealName, remark, operation, approveContent, approveContent, "", v.Status)
		}
	}
	return
}

func AddCompanyOperationRecord(companyId, sysUserId, productId, approveAdminId int, companyName, productName, sysUserRealName, remark, operation, approveContent, approveUserRealName, approveRemark, status string) (err error) {
	defer func() {
		if err != nil {
			go utils.SendEmail(utils.APPNAME+"失败提醒"+utils.RunMode, "services:AddCompanyOperationRecord;Err"+err.Error(), utils.EmailSendToUsers)
		}
	}()
	record := new(models.CompanyOperationRecord)
	record.CompanyId = companyId
	record.CompanyName = companyName
	record.SysUserId = sysUserId
	record.SysRealName = sysUserRealName
	record.Remark = remark
	record.Operation = operation
	record.CreateTime = time.Now()
	record.ProductId = productId
	record.ProductName = productName
	record.ApproveUserId = approveAdminId
	record.ApproveRealName = approveUserRealName
	record.ApproveContent = approveContent
	record.ApproveRemark = approveRemark
	record.Status = status
	_, err = models.AddCompanyOperationRecord(record)
	return
}

//客户老数据同步
func CompanyOldDataSync() {
	companyItems, err := models.GetCompanyOldDataSync()
	if err != nil {
		fmt.Println("GetCompanyOldDataSync Err:" + err.Error())
		return
	}
	productId := 1
	productName := "ficc"
	for k, v := range companyItems {
		fmt.Println(k, v.CompanyName, v.CompanyId)
		productItem := new(models.CompanyProduct)
		productItem.CompanyId = v.CompanyId
		productItem.ProductId = productId
		productItem.ProductName = productName
		productItem.CompanyName = v.CompanyName
		//客户标签,1：付费客户，2：试用客户，3：流失客户，4：潜在客户,5:永续
		//'试用','永续','冻结','流失','正式','潜在'
		status := ""
		if v.CompanyType == 1 {
			status = "正式"
		} else if v.CompanyType == 2 {
			status = "试用"
		} else if v.CompanyType == 3 {
			status = "流失"
		} else if v.CompanyType == 4 {
			status = "潜在"
		} else if v.CompanyType == 5 {
			status = "永续"
		} else {
			fmt.Println("无效的客户状态："+status, v.CompanyType)
			return
		}
		if status == "" {
			fmt.Println("无效的客户状态："+status, v.CompanyType)
			return
		}
		productItem.Status = status
		//获取销售
		seller, err := models.GetAdminByAdminId(v.SellsId)
		if err != nil && err.Error() != utils.ErrNoRow() {
			fmt.Println("获取销售失败，Err:"+err.Error(), v.SellsId)
			return
		}
		var adminId, groupId, departmentId int
		var sellerRealName string
		if seller == nil {
			fmt.Println("销售不存在:", v.SellsId)
			//return
		} else {
			adminId = seller.AdminId
			sellerRealName = seller.RealName
			groupId = seller.GroupId
			departmentId = seller.DepartmentId
		}
		productItem.SellerId = adminId
		productItem.SellerName = sellerRealName
		productItem.GroupId = groupId
		productItem.DepartmentId = departmentId
		productItem.CreateTime = time.Now()
		productItem.ModifyTime = time.Now()
		productItem.StartDate = v.StartDate
		productItem.EndDate = v.EndDate
		productItem.LoseReason = v.LoseReason
		productItem.LossTime = v.LossTime
		_, err = models.AddCompanyProduct(productItem)
		if err != nil {
			fmt.Println("新增客户产品失败,Err:" + err.Error())
			return
		}
		//权限处理
		err = models.ModifyCompanyOldPermission(v.StartDate, v.EndDate, productName, v.CompanyId, productId)
		if err != nil {
			fmt.Println("客户权限处理失败,Err:" + err.Error())
			return
		}
		if k > 500 {
			return
		}
	}
}

//正式/试用客户--到期提醒
func CompanyRemind()(err error) {
	defer func() {
		if err != nil {
			go utils.SendEmail(utils.APPNAME+"失败提醒"+utils.RunMode, "到期提醒失败：CompanyRemind;Err"+err.Error(), utils.EmailSendToUsers)
		}
	}()
	//获取销售
	sellers, err := models.GetSellers()
	for k, v := range sellers {
		fmt.Println(k, v.AdminId, v.Mobile)
		CompanyRemind30Day(v)
		time.Sleep(5*time.Second)
		CompanyRemind15Day(v)
		time.Sleep(5*time.Second)
		CompanyRemind7Day(v)
		time.Sleep(5*time.Second)
		CompanyRemind1Day(v)
		time.Sleep(5*time.Second)
	}
	return
}

//30天后到期客户
func CompanyRemind30Day(seller *models.Sellers) {
	var err error
	defer func() {
		if err != nil {
			go utils.SendEmail(utils.APPNAME+"失败提醒"+utils.RunMode, "到期提醒失败：CompanyRemind;Err"+err.Error(), utils.EmailSendToUsers)
		}
	}()
	remindEndDate := "2020-12-31" //time.Now().AddDate(0, 0, 30).Format(utils.FormatDate)
	companyItems, err := models.GetRemindCompany(seller.AdminId, remindEndDate)
	if err != nil {
		return
	}
	emailContents := "<div><p>您有【" + strconv.Itoa(len(companyItems)) + "】 客户将于30天后到期，请注意查看</p>"
	emailContents += "<table border='1'><tr><td width='200'>30天后到期客户名称</td><td width='200'>到期日期</td><td width='200'>销售人员</td><td>客户类型</td></tr>"
	var isSend bool
	msgContent := ``
	for _, v := range companyItems {
		emailContents += `<tr><td>` + v.CompanyName + `</td><td>` + v.EndDate + `</td><td>` + seller.RealName + `</td><td>` + v.Status + `</td></tr>`
		msgContent += `客户：` + v.CompanyName + "；状态：" + v.Status + "\n"
		isSend = true
	}
	emailContents += "</table></br>"

	if isSend {
		if seller.Email != "" {
			utils.SendEmailByHongze("到期前30天提醒", emailContents, seller.Email, "", "")
		}

		if seller.OpenId != "" {
			first := "您有【" + strconv.Itoa(len(companyItems)) + "】 客户将于30天后到期，请注意查看"
			keyword1 := "到期前30天提醒"
			keyword2 := remindEndDate
			remark := msgContent

			openIdList := make([]*models.OpenIdList, 0)
			openIdItem := new(models.OpenIdList)
			openIdItem.OpenId = seller.OpenId
			openIdList = append(openIdList, openIdItem)
			SendWxMsgWithCompanyRemind(first, keyword1, keyword2, remark, openIdList)
		}
	}
}

//15天后到期客户
func CompanyRemind15Day(seller *models.Sellers) {
	var err error
	defer func() {
		if err != nil {
			go utils.SendEmail(utils.APPNAME+"失败提醒"+utils.RunMode, "到期提醒失败：CompanyRemind;Err"+err.Error(), utils.EmailSendToUsers)
		}
	}()
	remindEndDate := time.Now().AddDate(0, 0, 15).Format(utils.FormatDate)
	companyItems, err := models.GetRemindCompany(seller.AdminId, remindEndDate)
	if err != nil {
		return
	}
	var isSend bool
	msgContent := ``
	emailContents := "<div><p>您有【" + strconv.Itoa(len(companyItems)) + "】 客户将于15天后到期，请注意查看</p>"
	emailContents += "<table border='1'><tr><td width='200'>15天后到期客户名称</td><td width='200'>到期日期</td><td width='200'>销售人员</td><td>客户类型</td></tr>"
	for _, v := range companyItems {
		emailContents += `<tr><td>` + v.CompanyName + `</td><td>` + v.EndDate + `</td><td>` + seller.RealName + `</td><td>` + v.Status + `</td></tr>`
		msgContent += `客户：` + v.CompanyName + "；状态：" + v.Status + "\n"
		isSend = true
	}
	emailContents += "</table></br>"

	if isSend {
		if seller.Email != "" {
			utils.SendEmailByHongze("到期前15天提醒", emailContents, seller.Email, "", "")
		}

		if seller.OpenId != "" {
			first := "您有【" + strconv.Itoa(len(companyItems)) + "】 客户将于15天后到期，请注意查看"
			keyword1 := "到期前15天提醒"
			keyword2 := remindEndDate
			remark := msgContent

			openIdList := make([]*models.OpenIdList, 0)
			openIdItem := new(models.OpenIdList)
			openIdItem.OpenId = seller.OpenId
			openIdList = append(openIdList, openIdItem)
			SendWxMsgWithCompanyRemind(first, keyword1, keyword2, remark, openIdList)
		}
	}
}

//7天后到期客户名称
func CompanyRemind7Day(seller *models.Sellers) {
	var err error
	defer func() {
		if err != nil {
			go utils.SendEmail(utils.APPNAME+"失败提醒"+utils.RunMode, "到期提醒失败：CompanyRemind;Err"+err.Error(), utils.EmailSendToUsers)
		}
	}()
	remindEndDate := time.Now().AddDate(0, 0, 7).Format(utils.FormatDate)
	companyItems, err := models.GetRemindCompany(seller.AdminId, remindEndDate)
	if err != nil {
		return
	}
	var isSend bool
	msgContent := ``
	emailContents := "<div><p>您有【" + strconv.Itoa(len(companyItems)) + "】 客户将于7天后到期，请注意查看</p>"
	emailContents += "<table border='1'><tr><td width='200'>7天后到期客户名称</td><td width='200'>到期日期</td><td width='200'>销售人员</td><td>客户类型</td></tr>"
	for _, v := range companyItems {
		emailContents += `<tr><td>` + v.CompanyName + `</td><td>` + v.EndDate + `</td><td>` + seller.RealName + `</td><td>` + v.Status + `</td></tr>`
		msgContent += `客户：` + v.CompanyName + "；状态：" + v.Status + "\n"
		isSend = true
	}
	emailContents += "</table></br>"

	if isSend {
		if seller.Email != "" {
			utils.SendEmailByHongze("到期前7天提醒", emailContents, seller.Email, "", "")
		}

		if seller.OpenId != "" {
			first := "您有【" + strconv.Itoa(len(companyItems)) + "】 客户将于7天后到期，请注意查看"
			keyword1 := "到期前7天提醒"
			keyword2 := remindEndDate
			remark := msgContent

			openIdList := make([]*models.OpenIdList, 0)
			openIdItem := new(models.OpenIdList)
			openIdItem.OpenId = seller.OpenId
			openIdList = append(openIdList, openIdItem)
			SendWxMsgWithCompanyRemind(first, keyword1, keyword2, remark, openIdList)
		}
	}
}

//到期当天提醒
func CompanyRemind1Day(seller *models.Sellers) {
	var err error
	defer func() {
		if err != nil {
			go utils.SendEmail(utils.APPNAME+"失败提醒"+utils.RunMode, "到期提醒失败：CompanyRemind;Err"+err.Error(), utils.EmailSendToUsers)
		}
	}()
	remindEndDate := time.Now().AddDate(0, 0, 0).Format(utils.FormatDate)
	companyItems, err := models.GetRemindCompany(seller.AdminId, remindEndDate)
	if err != nil {
		return
	}
	var isSend bool
	msgContent := ``
	emailContents := "<div><p>您有【" + strconv.Itoa(len(companyItems)) + "】 客户将于今天后到期，请注意查看</p>"
	emailContents += "<table border='1'><tr><td width='200'>1天后到期客户名称</td><td width='200'>到期日期</td><td width='200'>销售人员</td><td>客户类型</td></tr>"
	for _, v := range companyItems {
		emailContents += `<tr><td>` + v.CompanyName + `</td><td>` + v.EndDate + `</td><td>` + seller.RealName + `</td><td>` + v.Status + `</td></tr>`
		msgContent += `客户：` + v.CompanyName + "；状态：" + v.Status + "\n"
		isSend = true
	}
	emailContents += "</table></br>"

	if isSend {
		if seller.Email != "" {
			utils.SendEmailByHongze("到期前1天提醒", emailContents, seller.Email, "", "")
		}

		if seller.OpenId != "" {
			first := "您有【" + strconv.Itoa(len(companyItems)) + "】 客户将于1天后到期，请注意查看"
			keyword1 := "到期前1天提醒"
			keyword2 := remindEndDate
			remark := msgContent

			openIdList := make([]*models.OpenIdList, 0)
			openIdItem := new(models.OpenIdList)
			openIdItem.OpenId = seller.OpenId
			openIdList = append(openIdList, openIdItem)
			SendWxMsgWithCompanyRemind(first, keyword1, keyword2, remark, openIdList)
		}
	}
}
