package services

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/company_user"
	"hongze/hz_crm_api/models/system"
	"hongze/hz_crm_api/services/alarm_msg"
	"hongze/hz_crm_api/utils"
	"strconv"
	"strings"
	"time"
)

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

	//删除权限
	if count > 0 {
		err = company.DeleteCompanyReportPermission(companyId, productId)
		if err != nil {
			return
		}
	}
	//如果是ficc类型的客户，且权限列表中没有 宏观权限，那么需要默认将宏观加进去
	if productId == utils.COMPANY_PRODUCT_FICC_ID && !utils.InArrayByStr(permissionArr, "1") {
		permissionArr = append(permissionArr, "1")
	}
	for _, pv := range permissionArr {
		permissionId, tmpErr := strconv.Atoi(pv)
		if productId == utils.COMPANY_PRODUCT_RAI_ID && permissionId == 1 {
			continue
		}
		if tmpErr != nil {
			err = tmpErr
			return
		}
		permission := new(company.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()
		permission.Status = "试用"
		err = company.AddCompanyReportPermission(permission)
		if err != nil {
			return
		}
		companyReportPermissionList = append(companyReportPermissionList, permission)

		cpLog := new(company.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 company.AddCompanyPermissionLog(cpLog)
	}
	return
}

func AddCompanyProductLog(companyProduct *company.CompanyProduct, adminId int, logType string) (err error) {
	defer func() {
		if err != nil {
			go alarm_msg.SendAlarmMsg("services:AddCompanyProductLog;Err："+err.Error(), 3)
			//go utils.SendEmail(utils.APPNAME+"失败提醒"+utils.RunMode, "services:AddCompanyProductLog;Err："+err.Error(), utils.EmailSendToUsers)
		}
	}()
	productLog := new(company.CompanyProductLog)
	productLog.CompanyProductId = companyProduct.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 = logType
	productLog.LogCreateTime = time.Now()
	productLog.AdminId = adminId
	err = company.AddCompanyProductLog(productLog)
	//修改公司更新时间
	sql := `UPDATE company SET last_updated_time=NOW() WHERE company_id=? `
	o := orm.NewOrm()
	o.Raw(sql, companyProduct.CompanyId).Exec()
	return
}

func AddCompanyOperationRecord(companyId, sellerId, sysUserId, productId, approveAdminId int, companyName, productName, sysUserRealName, remark, operation, approveContent, approveUserRealName, approveRemark, status string) (err error) {
	defer func() {
		if err != nil {
			go alarm_msg.SendAlarmMsg("services:AddCompanyOperationRecord;Err："+err.Error(), 3)
			//go utils.SendEmail(utils.APPNAME+"失败提醒"+utils.RunMode, "services:AddCompanyOperationRecord;Err："+err.Error(), utils.EmailSendToUsers)
		}
	}()
	record := new(company.CompanyOperationRecord)
	record.CompanyId = companyId
	record.CompanyName = companyName
	record.SellerId = sellerId
	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 = company.AddCompanyOperationRecord(record)
	return
}

// AddCompanyOperationRecordMore 添加操作记录（包含补充信息）
func AddCompanyOperationRecordMore(companyId, sellerId, sysUserId, productId, approveAdminId int, companyName, productName, sysUserRealName, remark, operation, approveContent, approveContentExtra, approveUserRealName, approveRemark, status string) (err error) {
	defer func() {
		if err != nil {
			go alarm_msg.SendAlarmMsg("services:AddCompanyOperationRecordMore;Err："+err.Error(), 3)
			//go utils.SendEmail(utils.APPNAME+"失败提醒"+utils.RunMode, "services:AddCompanyOperationRecord;Err："+err.Error(), utils.EmailSendToUsers)
		}
	}()
	record := new(company.CompanyOperationRecord)
	record.CompanyId = companyId
	record.CompanyName = companyName
	record.SellerId = sellerId
	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.ApproveContentExtra = approveContentExtra
	record.ApproveRemark = approveRemark
	record.Status = status
	_, err = company.AddCompanyOperationRecord(record)
	return
}

func GetProductId(roleTypeCode string) (productId int) {
	if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER ||
		roleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN ||
		roleTypeCode == utils.ROLE_TYPE_CODE_FICC_TEAM ||
		roleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP ||
		roleTypeCode == utils.ROLE_TYPE_CODE_FICC_DEPARTMENT {
		productId = 1
	} else if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER ||
		roleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN ||
		roleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP ||
		roleTypeCode == utils.ROLE_TYPE_CODE_RAI_DEPARTMENT {
		productId = 2
	} else {
		productId = 0
	}
	return
}

// CheckAdminIsSeller 根据用户权限码获取是否属于销售
func CheckAdminIsSeller(roleTypeCode string) (isSeller bool) {
	if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER ||
		roleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP ||
		roleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER ||
		roleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP {
		isSeller = true
	}
	return
}

//func GetCompanyPermissionButton(roleTypeCode, status string, itemGroupId, sysUserGroupId, itemSellerId, sysUserId, authority, productId int) (button company.ButtonPermission) {
//	button.BtnView = true
//	if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN { //超级管理员
//		if !strings.Contains(status, "/") {
//			if status == utils.COMPANY_STATUS_FORMAL { //正式
//				//button.BtnModifySeller = true
//				return
//			} else if status == utils.COMPANY_STATUS_TRY_OUT { //试用
//				button.BtnEdit = true
//				button.BtnDelete = true
//				//button.BtnModifySeller = true
//				return
//			} else if status == utils.COMPANY_STATUS_FREEZE { //冻结
//				//button.BtnModifySeller = true
//				return
//			} else if status == utils.COMPANY_STATUS_LOSE { //流失
//				//button.BtnModifySeller = true
//				button.BtnDelete = true
//				return
//			} else { //永续
//				//button.BtnModifySeller = true
//				button.BtnDelete = true
//				button.BtnEdit = true
//				return
//			}
//		}
//	} else if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN {
//		if productId != 1 {
//			return
//		} else {
//			if !strings.Contains(status, "/") {
//				if status == utils.COMPANY_STATUS_FORMAL { //正式
//					button.BtnModifySeller = true
//					return
//				} else if status == utils.COMPANY_STATUS_TRY_OUT { //试用
//					button.BtnEdit = true
//					button.BtnDelete = true
//					button.BtnModifySeller = true
//					return
//				} else if status == utils.COMPANY_STATUS_FREEZE { //冻结
//					//button.BtnModifySeller = true
//					return
//				} else if status == utils.COMPANY_STATUS_LOSE { //流失
//					//button.BtnModifySeller = true
//					button.BtnDelete = true
//					return
//				} else { //永续
//					return
//				}
//			}
//		}
//	} else if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
//		if !strings.Contains(status, "/") {
//			if status == utils.COMPANY_STATUS_FORMAL { //正式
//				button.BtnModifySeller = true
//				return
//			} else if status == utils.COMPANY_STATUS_TRY_OUT { //试用
//				button.BtnEdit = true
//				button.BtnDelete = true
//				return
//			} else if status == utils.COMPANY_STATUS_FREEZE { //冻结
//				return
//			} else if status == utils.COMPANY_STATUS_LOSE { //流失
//				button.BtnDelete = true
//				return
//			} else { //永续
//				return
//			}
//		}
//	} else if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER {
//		if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER && productId == 2 {
//			return
//		}
//		if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER && productId == 1 {
//			return
//		}
//		//管理权限，0：无，1：部门负责人，2：小组负责人,3:超级管理员
//		if authority == 2 { //组长
//			if !strings.Contains(status, "/") {
//				if sysUserId == itemSellerId { //自己客户
//					if status == utils.COMPANY_STATUS_FORMAL { //正式
//						button.BtnUpdate = true
//						button.BtnModifySeller = true
//						return
//					} else if status == utils.COMPANY_STATUS_TRY_OUT { //试用
//						button.BtnEdit = true
//						button.BtnDelete = true
//						button.BtnSuspend = true
//						button.BtnDelay = true
//						button.BtnTurnPositive = true
//						button.BtnModifySeller = true
//						return
//					} else if status == utils.COMPANY_STATUS_FREEZE { //冻结
//						button.BtnThaw = true
//						return
//					} else if status == utils.COMPANY_STATUS_LOSE { //流失
//						if itemSellerId == sysUserId || itemGroupId == sysUserGroupId {
//							button.BtnApplyReceive = true
//						} else {
//							button.BtnReceive = true
//						}
//						if itemSellerId == sysUserId || (itemGroupId == sysUserGroupId && authority > 0) {
//							button.BtnDelete = true
//						}
//						return
//					} else { //永续
//						button.BtnDelete = true
//						return
//					}
//				} else {
//					if productId == 1 {
//						if status == utils.COMPANY_STATUS_FORMAL { //正式
//							button.BtnModifySeller=true
//							return
//						} else if status == utils.COMPANY_STATUS_TRY_OUT { //试用
//							button.BtnModifySeller=true
//							return
//						} else if status == utils.COMPANY_STATUS_FREEZE { //冻结
//							button.BtnThaw = true
//							return
//						} else if status == utils.COMPANY_STATUS_LOSE { //流失
//							if itemSellerId == sysUserId || itemGroupId == sysUserGroupId {
//								button.BtnApplyReceive = true
//							} else {
//								button.BtnReceive = true
//							}
//							return
//						} else { //永续
//							button.BtnDelete = true
//							return
//						}
//					} else {
//						button.BtnReceive = true
//					}
//				}
//			}
//		} else { //销售
//			if !strings.Contains(status, "/") {
//				if itemSellerId == sysUserId {
//					if status == utils.COMPANY_STATUS_FORMAL { //正式
//						button.BtnUpdate = true
//						return
//					} else if status == utils.COMPANY_STATUS_TRY_OUT { //试用
//						button.BtnEdit = true
//						button.BtnDelete = true
//						button.BtnSuspend = true
//						button.BtnDelay = true
//						button.BtnTurnPositive = true
//						return
//					} else if status == utils.COMPANY_STATUS_FREEZE { //冻结
//						button.BtnThaw = true
//						return
//					} else if status == utils.COMPANY_STATUS_LOSE { //流失
//						if itemSellerId == sysUserId || itemGroupId == sysUserGroupId {
//							button.BtnApplyReceive = true
//						} else {
//							button.BtnReceive = true
//						}
//						if itemSellerId == sysUserId || (itemGroupId == sysUserGroupId && authority > 0) {
//							button.BtnDelete = true
//						}
//						return
//					} else { //永续
//						button.BtnDelete = true
//						return
//					}
//				} else {
//					if productId == 1 {
//						if status == utils.COMPANY_STATUS_FORMAL { //正式
//							return
//						} else if status == utils.COMPANY_STATUS_TRY_OUT { //试用
//							return
//						} else if status == utils.COMPANY_STATUS_FREEZE { //冻结
//							button.BtnThaw = true
//							return
//						} else if status == utils.COMPANY_STATUS_LOSE { //流失
//							if itemSellerId == sysUserId || itemGroupId == sysUserGroupId {
//								button.BtnApplyReceive = true
//							} else {
//								button.BtnReceive = true
//							}
//							return
//						} else { //永续
//							button.BtnDelete = true
//							return
//						}
//					} else {
//						button.BtnReceive = true
//					}
//				}
//			}
//		}
//	} else if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER {
//		if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER && productId == 2 {
//			return
//		}
//		if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER && productId == 1 {
//			return
//		}
//		if !strings.Contains(status, "/") {
//			if authority == 2 { //组长
//				if itemSellerId==sysUserId {
//					if status == utils.COMPANY_STATUS_FORMAL { //正式
//						button.BtnUpdate = true
//						button.BtnModifySeller = true
//						return
//					} else if status == utils.COMPANY_STATUS_TRY_OUT { //试用
//						button.BtnEdit = true
//						button.BtnDelete = true
//						button.BtnSuspend = true
//						button.BtnDelay = true
//						button.BtnTurnPositive = true
//						button.BtnModifySeller = true
//						return
//					} else if status == utils.COMPANY_STATUS_FREEZE { //冻结
//						button.BtnThaw = true
//						return
//					} else if status == utils.COMPANY_STATUS_LOSE { //流失
//						if itemSellerId == sysUserId || itemGroupId == sysUserGroupId {
//							button.BtnApplyReceive = true
//						} else {
//							button.BtnReceive = true
//						}
//						if itemSellerId == sysUserId || (itemGroupId == sysUserGroupId && authority > 0) {
//							button.BtnDelete = true
//						}
//						return
//					} else { //永续
//						button.BtnDelete = true
//						return
//					}
//				}else{
//					if productId==1 {
//						button.BtnReceive=true
//					}else{
//						if status == utils.COMPANY_STATUS_FORMAL { //正式
//							button.BtnModifySeller=true
//							return
//						} else if status == utils.COMPANY_STATUS_TRY_OUT { //试用
//							button.BtnModifySeller=true
//							return
//						} else if status == utils.COMPANY_STATUS_FREEZE { //冻结
//							button.BtnThaw = true
//							return
//						} else if status == utils.COMPANY_STATUS_LOSE { //流失
//							if itemSellerId == sysUserId || itemGroupId == sysUserGroupId {
//								button.BtnApplyReceive = true
//							} else {
//								button.BtnReceive = true
//							}
//							return
//						} else { //永续
//							button.BtnDelete = true
//							return
//						}
//					}
//				}
//			} else {
//				if itemSellerId==sysUserId {
//					if status == utils.COMPANY_STATUS_FORMAL { //正式
//						button.BtnUpdate = true
//						return
//					} else if status == utils.COMPANY_STATUS_TRY_OUT { //试用
//						button.BtnEdit = true
//						button.BtnDelete = true
//						button.BtnSuspend = true
//						button.BtnDelay = true
//						button.BtnTurnPositive = true
//						return
//					} else if status == utils.COMPANY_STATUS_FREEZE { //冻结
//						button.BtnThaw = true
//						return
//					} else if status == utils.COMPANY_STATUS_LOSE { //流失
//						if itemSellerId == sysUserId || itemGroupId == sysUserGroupId {
//							button.BtnApplyReceive = true
//						} else {
//							button.BtnReceive = true
//						}
//						if itemSellerId == sysUserId || (itemGroupId == sysUserGroupId && authority > 0) {
//							button.BtnDelete = true
//						}
//						return
//					} else { //永续
//						button.BtnDelete = true
//						return
//					}
//				}else{
//					if productId==1 {
//						button.BtnReceive=true
//					}else{
//						if status == utils.COMPANY_STATUS_FORMAL { //正式
//							return
//						} else if status == utils.COMPANY_STATUS_TRY_OUT { //试用
//							return
//						} else if status == utils.COMPANY_STATUS_FREEZE { //冻结
//							button.BtnThaw = true
//							return
//						} else if status == utils.COMPANY_STATUS_LOSE { //流失
//							if itemSellerId == sysUserId || itemGroupId == sysUserGroupId {
//								button.BtnApplyReceive = true
//							} else {
//								button.BtnReceive = true
//							}
//							return
//						} else { //永续
//							button.BtnDelete = true
//							return
//						}
//					}
//				}
//			}
//		}
//	}
//	return button
//}

//func GetCompanyPermissionButton(roleTypeCode, status string, itemGroupId, sysUserGroupId, itemSellerId, sysUserId, authority, productId int) (button company.ButtonPermission) {
//	button.BtnView = true
//	if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN { //超级管理员
//		if !strings.Contains(status, "/") {
//			if status == utils.COMPANY_STATUS_FORMAL { //正式
//				button.BtnView = true
//				button.BtnModifySeller = true
//				return
//			} else if status == utils.COMPANY_STATUS_TRY_OUT { //试用
//				button.BtnEdit = true
//				button.BtnDelete = true
//				button.BtnFreeze=true
//				return
//			} else if status == utils.COMPANY_STATUS_FREEZE { //冻结
//				button.BtnModifySeller = true
//				button.BtnView = true
//				return
//			} else if status == utils.COMPANY_STATUS_LOSE { //流失
//				button.BtnDelete = true
//				button.BtnModifySeller = true
//				return
//			} else { //永续
//				button.BtnDelete = true
//				button.BtnEdit = true
//				return
//			}
//		}
//	} else if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN {
//		fmt.Println("itemSellerId:",itemSellerId)
//		fmt.Println("sysUserId:",sysUserId)
//		if !strings.Contains(status, "/") {
//			if itemSellerId == sysUserId {
//				if productId == 1 {
//					if status == utils.COMPANY_STATUS_FORMAL { //正式
//						button.BtnModifySeller = true
//						button.BtnUpdate = true
//						return
//					} else if status == utils.COMPANY_STATUS_TRY_OUT { //试用
//						button.BtnEdit = true
//						button.BtnDelete = true
//						button.BtnModifySeller = true
//						button.BtnSuspend = true
//						button.BtnDelay = true
//						button.BtnTurnPositive = true
//						button.BtnFreeze=true
//						return
//					} else if status == utils.COMPANY_STATUS_FREEZE { //冻结
//						button.BtnModifySeller = true
//						button.BtnView = true
//						return
//					} else if status == utils.COMPANY_STATUS_LOSE { //流失
//						button.BtnModifySeller = true
//						if itemSellerId == sysUserId || (itemGroupId == sysUserGroupId && authority > 0) {
//							button.BtnDelete = true
//						}
//						if itemSellerId == sysUserId || itemGroupId == sysUserGroupId {
//							button.BtnApplyReceive = true
//						} else {
//							button.BtnReceive = true
//						}
//						return
//					} else { //永续
//						button.BtnDelete = true
//						return
//					}
//				} else {
//					//button.BtnReceiveOther=true
//					return
//				}
//			} else {
//				if productId == 1 {
//					if status == utils.COMPANY_STATUS_FORMAL { //正式
//						button.BtnModifySeller = true
//						return
//					} else if status == utils.COMPANY_STATUS_TRY_OUT { //试用
//						button.BtnEdit = true
//						button.BtnDelete = true
//						return
//					} else if status == utils.COMPANY_STATUS_FREEZE { //冻结
//						button.BtnModifySeller = true
//						button.BtnView = true
//						return
//					} else if status == utils.COMPANY_STATUS_LOSE { //流失
//						button.BtnModifySeller = true
//						button.BtnDelete = true
//						button.BtnView = true
//						return
//					} else { //永续
//						return
//					}
//				} else {
//					button.BtnReceiveOther = true
//					return
//				}
//			}
//		}
//	} else if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
//		if !strings.Contains(status, "/") {
//			if itemSellerId == sysUserId {
//				if productId == 2 {
//					if status == utils.COMPANY_STATUS_FORMAL { //正式
//						button.BtnModifySeller = true
//						button.BtnUpdate = true
//						return
//					} else if status == utils.COMPANY_STATUS_TRY_OUT { //试用
//						button.BtnEdit = true
//						button.BtnDelete = true
//						button.BtnModifySeller = true
//						button.BtnSuspend = true
//						button.BtnDelay = true
//						button.BtnTurnPositive = true
//						button.BtnFreeze=true
//						return
//					} else if status == utils.COMPANY_STATUS_FREEZE { //冻结
//						button.BtnModifySeller = true
//						return
//					} else if status == utils.COMPANY_STATUS_LOSE { //流失
//						button.BtnModifySeller = true
//						if itemSellerId == sysUserId || (itemGroupId == sysUserGroupId && authority > 0) {
//							button.BtnDelete = true
//						}
//						if itemSellerId == sysUserId || itemGroupId == sysUserGroupId {
//							button.BtnApplyReceive = true
//						} else {
//							button.BtnReceive = true
//						}
//						return
//					} else { //永续
//						button.BtnDelete = true
//						return
//					}
//				} else {
//					return
//				}
//			} else {
//				if productId == 2 {
//					if status == utils.COMPANY_STATUS_FORMAL { //正式
//						button.BtnModifySeller = true
//						button.BtnView = true
//						return
//					} else if status == utils.COMPANY_STATUS_TRY_OUT { //试用
//						button.BtnEdit = true
//						button.BtnDelete = true
//						return
//					} else if status == utils.COMPANY_STATUS_FREEZE { //冻结
//						button.BtnView = true
//						button.BtnModifySeller = true
//						return
//					} else if status == utils.COMPANY_STATUS_LOSE { //流失
//						button.BtnModifySeller = true
//						button.BtnDelete = true
//						button.BtnView = true
//						return
//					} else { //永续
//						return
//					}
//				} else {
//					//button.BtnReceive = true
//					return
//				}
//			}
//		}
//	} else if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER {
//		if !strings.Contains(status, "/") {
//			if itemSellerId == sysUserId {
//				if productId == 1 {
//					if status == utils.COMPANY_STATUS_FORMAL { //正式
//						button.BtnUpdate = true
//						return
//					} else if status == utils.COMPANY_STATUS_TRY_OUT { //试用
//						button.BtnDelete = true
//						button.BtnEdit = true
//						button.BtnSuspend = true
//						button.BtnDelay = true
//						button.BtnTurnPositive = true
//						button.BtnFreeze=true
//						return
//					} else if status == utils.COMPANY_STATUS_FREEZE { //冻结
//						button.BtnThaw = true
//						return
//					} else if status == utils.COMPANY_STATUS_LOSE { //流失
//						if itemSellerId == sysUserId || itemGroupId == sysUserGroupId {
//							button.BtnApplyReceive = true
//						} else {
//							button.BtnReceive = true
//						}
//						if itemSellerId == sysUserId || (sysUserGroupId == itemGroupId && authority == 2) {
//							button.BtnDelete = true
//						}
//						return
//					} else { //永续
//						button.BtnDelete = true
//						return
//					}
//				} else {
//					button.BtnReceiveOther = true
//					return
//				}
//			} else {
//				if productId == 1 {
//					if status == utils.COMPANY_STATUS_FORMAL { //正式
//						return
//					} else if status == utils.COMPANY_STATUS_TRY_OUT { //试用
//						return
//					} else if status == utils.COMPANY_STATUS_FREEZE { //冻结
//						button.BtnApplyReceive = true
//						button.BtnView = false
//						return
//					} else if status == utils.COMPANY_STATUS_LOSE { //流失
//						if itemGroupId == sysUserGroupId {
//							button.BtnApplyReceive = true
//						} else {
//							button.BtnReceive = true
//						}
//						button.BtnView = false
//						return
//					} else { //永续
//						button.BtnDelete = true
//						return
//					}
//				} else {
//					button.BtnReceiveOther = true
//					button.BtnView = false
//					return
//				}
//			}
//		}
//	} else if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER {
//		if !strings.Contains(status, "/") {
//			if itemSellerId == sysUserId {
//				if productId == 2 {
//					if status == utils.COMPANY_STATUS_FORMAL { //正式
//						button.BtnUpdate = true
//						return
//					} else if status == utils.COMPANY_STATUS_TRY_OUT { //试用
//						button.BtnDelete = true
//						button.BtnEdit = true
//						button.BtnSuspend = true
//						button.BtnDelay = true
//						button.BtnTurnPositive = true
//						button.BtnFreeze=true
//						return
//					} else if status == utils.COMPANY_STATUS_FREEZE { //冻结
//						button.BtnThaw = true
//						return
//					} else if status == utils.COMPANY_STATUS_LOSE { //流失
//						if itemGroupId == sysUserGroupId {
//							button.BtnApplyReceive = true
//						} else {
//							button.BtnReceive = true
//						}
//						if sysUserGroupId == itemGroupId && authority == 2 {
//							button.BtnDelete = true
//						}
//						return
//					} else { //永续
//						button.BtnDelete = true
//						return
//					}
//				} else {
//					button.BtnReceiveOther = true
//					return
//				}
//			} else {
//				if productId == 2 {
//					if status == utils.COMPANY_STATUS_FORMAL { //正式
//						return
//					} else if status == utils.COMPANY_STATUS_TRY_OUT { //试用
//						return
//					} else if status == utils.COMPANY_STATUS_FREEZE { //冻结
//						button.BtnApplyReceive = true
//						button.BtnView = false
//						return
//					} else if status == utils.COMPANY_STATUS_LOSE { //流失
//						if itemGroupId == sysUserGroupId {
//							button.BtnApplyReceive = true
//						} else {
//							button.BtnReceive = true
//						}
//						button.BtnView = false
//						return
//					} else { //永续
//						button.BtnDelete = true
//						return
//					}
//				} else {
//					button.BtnReceiveOther = true
//					button.BtnView = false
//					return
//				}
//			}
//		}
//	}
//	return button
//}
//

func GetCompanyPermissionButton(roleTypeCode, status, itemSellerIds, itemGroupIdS string, itemGroupId, sysUserGroupId, itemSellerId, sysUserId, authority, productId, shareSellerId int, shareSellerIds string) (button company.ButtonPermission) {
	//产品状态map
	productStatusMap := make(map[int]string)
	if productId == 1 {
		productStatusMap[1] = status
	} else if productId == 2 {
		productStatusMap[2] = status
	}
	if strings.Contains(status, "/") {
		statusSlice := strings.Split(status, "/")
		productStatusMap[1] = statusSlice[0]
		productStatusMap[2] = statusSlice[1]
	}

	//所属销售map
	sellerIdMap := make(map[int]int)
	if productId == 1 {
		sellerIdMap[1] = itemSellerId
	} else if productId == 2 {
		sellerIdMap[2] = itemSellerId
	}
	if strings.Contains(itemSellerIds, "/") {
		sellerIdSlice := strings.Split(itemSellerIds, "/")
		sellerIdMap[1], _ = strconv.Atoi(sellerIdSlice[0])
		sellerIdMap[2], _ = strconv.Atoi(sellerIdSlice[1])
	}

	//分组map
	groupIdMap := make(map[int]int)
	if productId == 1 {
		groupIdMap[1] = itemGroupId
	} else if productId == 2 {
		groupIdMap[2] = itemGroupId
	}
	if strings.Contains(itemGroupIdS, "/") {
		groupIdSlice := strings.Split(itemGroupIdS, "/")
		groupIdMap[1], _ = strconv.Atoi(groupIdSlice[0])
		groupIdMap[2], _ = strconv.Atoi(groupIdSlice[1])
	}

	shareSellerIdArr := strings.Split(shareSellerIds, ",")

	if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN { //超级管理员
		button.BtnView = true //查看详情权限
		if !strings.Contains(status, "/") {
			if status == utils.COMPANY_STATUS_FORMAL { //正式
				//button.BtnModifySeller = true
				if productId == utils.COMPANY_PRODUCT_RAI_ID {
					button.BtnRemarkViewHistory = true
				} else {
					button.BtnRemarkView = true
				}
				return
			} else if status == utils.COMPANY_STATUS_TRY_OUT { //试用
				button.BtnEdit = true
				button.BtnDelete = true
				if productId == utils.COMPANY_PRODUCT_RAI_ID {
					button.BtnRemarkViewHistory = true
				} else {
					button.BtnRemarkView = true
				}
				//button.BtnModifySeller = true
				button.BtnFreeze = false
				if productId == utils.COMPANY_PRODUCT_FICC_ID {
					button.BtnClose = true // 超管/FICC管理员可关闭试用客户
				}
				return
			} else if status == utils.COMPANY_STATUS_FREEZE { //冻结
				//button.BtnModifySeller = true
				if productId == utils.COMPANY_PRODUCT_RAI_ID {
					button.BtnRemarkViewHistory = true
				} else {
					button.BtnRemarkView = true
				}
				return
			} else if status == utils.COMPANY_STATUS_LOSE { //流失
				//button.BtnModifySeller = true
				button.BtnDelete = true
				if productId == utils.COMPANY_PRODUCT_RAI_ID {
					button.BtnRemarkViewHistory = true
				}
				return
			} else if status == utils.COMPANY_STATUS_CLOSE { // 关闭
				//button.BtnModifySeller = true
				button.BtnDelete = true
				if productId == utils.COMPANY_PRODUCT_FICC_ID {
					button.BtnLoss = true // 超管/FICC管理员可关闭转流失
				}
				return
			} else { //永续
				//button.BtnModifySeller = true
				button.BtnDelete = true
				button.BtnEdit = true
				if productId == utils.COMPANY_PRODUCT_RAI_ID {
					button.BtnRemarkViewHistory = true
				}
				return
			}
		}
	} else if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN {
		//查看详情权限
		productStatus, hasProduct := productStatusMap[1]
		if hasProduct {
			button.BtnView = true
			if productStatus == utils.COMPANY_STATUS_FORMAL { //正式
				button.BtnModifySeller = true
				button.BtnShare = true
				return
			} else if productStatus == utils.COMPANY_STATUS_TRY_OUT { //试用
				button.BtnEdit = true
				//button.BtnDelete = true
				button.BtnModifySeller = true
				button.BtnFreeze = false
				button.BtnClose = true // 超管/FICC管理员可关闭试用客户
				return
			} else if productStatus == utils.COMPANY_STATUS_FREEZE { //冻结
				button.BtnModifySeller = true
				return
			} else if productStatus == utils.COMPANY_STATUS_LOSE { //流失
				//button.BtnModifySeller = true
				//button.BtnDelete = true
				return
			} else if productStatus == utils.COMPANY_STATUS_CLOSE { // 关闭
				button.BtnLoss = true // 超管/FICC管理员可关闭转流失
				return
			} else { //永续
				return
			}
		} else {
			productStatus2, hasProduct2 := productStatusMap[2]
			//如果没有权限的话，那么允许领取其他部门客户按钮权限
			if hasProduct2 {
				//其他产品的流失客户可以有查看权限
				if productStatus2 == utils.COMPANY_STATUS_LOSE {
					button.BtnView = true //查看权限
				}
			}
		}
		return
	} else if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
		//查看详情权限
		productStatus, hasProduct := productStatusMap[2]
		if hasProduct {
			button.BtnView = true
			if productStatus == utils.COMPANY_STATUS_FORMAL { //正式
				button.BtnModifySeller = true
				button.BtnShare = true
				button.BtnRemarkViewHistory = true
			} else if productStatus == utils.COMPANY_STATUS_TRY_OUT { //试用
				button.BtnEdit = true
				//button.BtnDelete = true
				button.BtnModifySeller = true
				button.BtnFreeze = false
				// CRM14.7.2 权益管理员可以设置试用客户为共享
				button.BtnShare = true
				button.BtnRemarkViewHistory = true
			} else if productStatus == utils.COMPANY_STATUS_FREEZE { //冻结
				button.BtnModifySeller = true
				button.BtnRemarkViewHistory = true
			} else if productStatus == utils.COMPANY_STATUS_LOSE { //流失
				//button.BtnDelete = true
				button.BtnRemarkViewHistory = true
			} else { //永续
				button.BtnModifySeller = true
				button.BtnShare = true
				button.BtnRemarkViewHistory = true
			}
		} else {
			productStatus2, hasProduct2 := productStatusMap[1]
			//如果没有权限的话，那么允许领取其他部门客户按钮权限
			if hasProduct2 {
				//其他产品的流失客户可以有查看权限
				if productStatus2 == utils.COMPANY_STATUS_LOSE {
					button.BtnView = true //查看权限
				}
			}
		}
		return
	} else if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER || roleTypeCode == utils.ROLE_TYPE_CODE_FICC_TEAM || roleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP {
		//判断该客户是否有ficc权限
		productStatus, hasProduct := productStatusMap[1]
		if hasProduct {
			//如果有权限的话：

			//获取当前ficc的销售id
			sellerId, hasSellerId := sellerIdMap[1]
			//获取当前ficc的销售分组id
			groupId, hasGroupId := groupIdMap[1]

			//如果是自己客户，那么拥有查看权限
			if hasSellerId {
				if sellerId == sysUserId || utils.InArrayByStr(shareSellerIdArr, strconv.Itoa(sysUserId)) || shareSellerId == sysUserId {
					button.BtnView = true                             //显示权限、详情
					if productStatus == utils.COMPANY_STATUS_FORMAL { //正式
						button.BtnUpdate = true       //服务更新
						button.BtnAddAgreement = true //补充协议
						button.BtnTryOut = true
						button.BtnModifySeller = true
						button.BtnShare = true
						button.BtnRemarkEdit = true
						button.BtnRemarkView = true
						if sellerId != sysUserId {
							button.BtnModifySeller = false
						}
					} else if productStatus == utils.COMPANY_STATUS_TRY_OUT { //试用
						button.BtnEdit = true
						button.BtnDelete = true
						button.BtnSuspend = true
						button.BtnDelay = true
						button.BtnTurnPositive = true
						button.BtnFreeze = true
						button.BtnModifySeller = true
						button.BtnRemarkEdit = true
						button.BtnRemarkView = true
						if sellerId != sysUserId {
							button.BtnModifySeller = false
						}
					} else if productStatus == utils.COMPANY_STATUS_FREEZE { //冻结
						button.BtnThaw = true
						button.BtnModifySeller = true
						button.BtnRemarkEdit = true
						button.BtnRemarkView = true
						if sellerId != sysUserId {
							button.BtnModifySeller = false
						}
					} else if productStatus == utils.COMPANY_STATUS_LOSE { //流失
						button.BtnApplyReceive = true
					} else { //永续
						//button.BtnDelete = true
					}
				} else {
					if productStatus == utils.COMPANY_STATUS_LOSE { //流失
						button.BtnView = true //显示权限、详情
						//如果不是自己客户，那么判断是否是本小组的，如果是本小组，那么还是申请领取，非本小组的话，那就是领取
						if groupId == sysUserGroupId {
							button.BtnApplyReceive = true
						} else {
							button.BtnReceive = true
						}
					}
				}

			}
			//如果是组长，且该客户属于本组客户
			if authority == 4 && hasGroupId && groupId == sysUserGroupId && roleTypeCode == utils.ROLE_TYPE_CODE_FICC_TEAM {
				button.BtnView = true                             //查看详情权限
				if productStatus == utils.COMPANY_STATUS_FORMAL { //正式
					button.BtnModifySeller = true
					button.BtnShare = true
					button.BtnRemarkView = true
				} else if productStatus == utils.COMPANY_STATUS_TRY_OUT { //试用
					button.BtnModifySeller = true
					button.BtnRemarkView = true
				} else if productStatus == utils.COMPANY_STATUS_FREEZE { //冻结
					button.BtnModifySeller = true
					button.BtnRemarkView = true
					//button.BtnThaw = false
				} else if productStatus == utils.COMPANY_STATUS_LOSE { //流失
					if sellerId == sysUserId || groupId == sysUserGroupId || utils.InArrayByStr(shareSellerIdArr, strconv.Itoa(sysUserId)) || shareSellerId == sysUserId {
						button.BtnApplyReceive = true
					} else {
						button.BtnReceive = true
					}
				} else { //永续
					//button.BtnDelete = true
				}
			}

			//如果是ficc销售主管，且该客户属于本组客户

			//获取父级groupId
			groupIdpid, err := company.GetParentIdFromGroup(groupId)
			if err != nil {
				fmt.Println(err.Error())
			}
			sysUserGroupIdpid, err := company.GetParentIdFromGroup(sysUserGroupId)
			if err != nil {
				fmt.Println(err.Error())
			}
			var pidBool bool
			//处理主管和销售在不同的二三级分组下的情况
			if groupIdpid != nil && sysUserGroupIdpid != nil {
				pidBool = *groupIdpid == *sysUserGroupIdpid || *groupIdpid == sysUserGroupId || groupId == sysUserGroupId || groupId == *sysUserGroupIdpid
			}
			if authority == 2 && hasGroupId && pidBool && roleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP {
				button.BtnView = true                             //查看详情权限
				if productStatus == utils.COMPANY_STATUS_FORMAL { //正式
					button.BtnModifySeller = true
					button.BtnShare = true
					button.BtnRemarkView = true
				} else if productStatus == utils.COMPANY_STATUS_TRY_OUT { //试用
					button.BtnModifySeller = true
					button.BtnRemarkView = true
				} else if productStatus == utils.COMPANY_STATUS_FREEZE { //冻结
					button.BtnModifySeller = true
					button.BtnRemarkView = true
					//button.BtnThaw = false
				} else if productStatus == utils.COMPANY_STATUS_LOSE { //流失
					if sellerId == sysUserId || groupId == sysUserGroupId || utils.InArrayByStr(shareSellerIdArr, strconv.Itoa(sysUserId)) || shareSellerId == sysUserId {
						button.BtnApplyReceive = true
					} else {
						button.BtnReceive = true
					}
				} else { //永续
					//button.BtnDelete = true
				}
			}

			//ficc同一个大组当作一个小组来处理领取按钮
			var ids []*string
			if groupIdpid != nil && *groupIdpid != 0 {
				ids, err = company.GetGroupIdsByParentId(*groupIdpid)
				if err != nil {
					fmt.Println(err.Error())
				}
			}
			var idSlice []string
			var sid string
			for _, id := range ids {
				idSlice = append(idSlice, *id)
			}
			sid = strings.Join(idSlice, ",")
			if strings.Contains(sid, strconv.Itoa(itemGroupId)) {
				if productStatus == utils.COMPANY_STATUS_LOSE { //流失
					button.BtnApplyReceive = true
					button.BtnReceive = false
				}
			}

		} else {
			productStatus2, hasProduct2 := productStatusMap[2]
			//如果没有权限的话，那么允许领取其他部门客户按钮权限
			if hasProduct2 {
				//如果客户ficc权限是永续，那么也没有其他部门客户的按钮权限
				if productStatus2 != utils.COMPANY_STATUS_FOREVER {
					button.BtnReceiveOther = true //领取其他部门客户按钮权限
				}
				//其他产品的流失客户可以有查看权限
				if productStatus2 == utils.COMPANY_STATUS_LOSE {
					button.BtnView = true //查看权限
				}
			}

		}
		return
	} else if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER || roleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP {
		//判断该客户是否有权益权限
		productStatus, hasProduct := productStatusMap[2]
		if hasProduct {
			//如果有权限的话：

			//获取当前 权益 的销售id
			sellerId, hasSellerId := sellerIdMap[2]
			//获取当前 权益 的销售分组id
			groupId, hasGroupId := groupIdMap[2]

			//如果是自己客户，那么拥有查看权限
			if hasSellerId {
				if sellerId == sysUserId || utils.InArrayByStr(shareSellerIdArr, strconv.Itoa(sysUserId)) || shareSellerId == sysUserId {
					button.BtnView = true                             //显示权限、详情
					if productStatus == utils.COMPANY_STATUS_FORMAL { //正式
						button.BtnUpdate = true
						button.BtnTryOut = true
						button.BtnModifySeller = true
						//button.BtnShare = true
						button.BtnRemarkEdit = true
						//button.BtnRemarkView = true //权益销售隐藏
						button.BtnRemarkViewHistory = true
					} else if productStatus == utils.COMPANY_STATUS_TRY_OUT { //试用
						button.BtnEdit = true
						button.BtnDelete = true
						button.BtnSuspend = true
						button.BtnDelay = true
						button.BtnTurnPositive = true
						button.BtnModifySeller = true
						button.BtnFreeze = true
						button.BtnRemarkEdit = true
						//button.BtnRemarkView = true //权益销售隐藏
						button.BtnRemarkViewHistory = true
						//button.BtnShare = true
					} else if productStatus == utils.COMPANY_STATUS_FREEZE { //冻结
						button.BtnThaw = true
						button.BtnModifySeller = true
						button.BtnRemarkEdit = true
						button.BtnRemarkView = true
					} else if productStatus == utils.COMPANY_STATUS_LOSE { //流失
						button.BtnApplyReceive = true
						button.BtnRemarkViewHistory = true
					} else if productStatus == utils.COMPANY_STATUS_FOREVER { //永续
						button.BtnTurnPositive = true
						button.BtnRemarkViewHistory = true
					}
				} else {
					if productStatus == utils.COMPANY_STATUS_LOSE { //流失
						button.BtnView = true //显示权限、详情
						button.BtnRemarkViewHistory = true
						//如果不是自己客户，那么判断是否是本小组的，如果是本小组，那么还是申请领取，非本小组的话，那就是领取
						if groupId == sysUserGroupId {
							button.BtnApplyReceive = true
						} else {
							button.BtnReceive = true
						}
					}
				}

			}
			//如果是组长，且该客户属于本组客户
			if authority == 2 && hasGroupId && groupId == sysUserGroupId {
				button.BtnView = true                             //查看详情权限
				button.BtnRemarkViewHistory = true                //历史备注
				if productStatus == utils.COMPANY_STATUS_FORMAL { //正式
					button.BtnModifySeller = true
					//button.BtnShare = true
					//button.BtnRemarkView = true //权益销售隐藏
					//button.BtnRemarkViewHistory = true
				} else if productStatus == utils.COMPANY_STATUS_TRY_OUT { //试用
					button.BtnModifySeller = true
					//button.BtnRemarkView = true //权益销售隐藏
					//button.BtnRemarkViewHistory = true
					//button.BtnShare = true
				} else if productStatus == utils.COMPANY_STATUS_FREEZE { //冻结
					button.BtnModifySeller = true
					//button.BtnRemarkView = true //权益销售隐藏
					//button.BtnRemarkViewHistory = true
				} else if productStatus == utils.COMPANY_STATUS_LOSE { //流失
					if sellerId == sysUserId || groupId == sysUserGroupId || utils.InArrayByStr(shareSellerIdArr, strconv.Itoa(sysUserId)) || shareSellerId == sysUserId {
						button.BtnApplyReceive = true
					} else {
						button.BtnReceive = true
					}
					//button.BtnRemarkViewHistory = true
				} else { //永续
					//button.BtnDelete = true
					//button.BtnRemarkViewHistory = true
				}
			}

		} else {
			productStatus2, hasProduct2 := productStatusMap[1]
			//如果没有权限的话，那么允许领取其他部门客户按钮权限
			if hasProduct2 {
				//如果客户 权益 权限是永续，那么也没有其他部门客户的按钮权限
				if productStatus2 != utils.COMPANY_STATUS_FOREVER {
					button.BtnReceiveOther = true //领取其他部门客户按钮权限
				}
				//其他产品的流失客户可以有查看权限
				if productStatus2 == utils.COMPANY_STATUS_LOSE {
					button.BtnView = true //查看权限
				}
			}
		}
		return
	}
	return button
}

// GetCompanyPermissionButtonByReceiveEnabled 查询当前销售 "添加客户" 权限来判断按钮权限
func GetCompanyPermissionButtonByReceiveEnabled(btnItem *company.ButtonPermission, receiveEnabled bool) (buttonNew *company.ButtonPermission) {
	//查询当前销售 "添加客户" 权限是否为禁用
	if !receiveEnabled {
		//申请领取、领取客户、领取其他部门客户按钮权限按钮显示时
		if btnItem.BtnApplyReceive || btnItem.BtnReceive || btnItem.BtnReceiveOther {
			btnItem.BtnApplyReceive = false
			btnItem.BtnReceive = false
			btnItem.BtnReceiveOther = false
		}
		if btnItem.BtnThaw {
			btnItem.BtnThaw = false
		}
	}
	buttonNew = btnItem
	return buttonNew
}

//func GetCompanyPermissionButtonOld(roleTypeCode, status string, itemGroupId, sysUserGroupId, itemSellerId, sysUserId, authority, productId int) (button company.ButtonPermission) {
//	button.BtnView = true
//	if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN { //超级管理员
//		if !strings.Contains(status, "/") {
//			if status == utils.COMPANY_STATUS_FORMAL { //正式
//				//button.BtnModifySeller = true
//				return
//			} else if status == utils.COMPANY_STATUS_TRY_OUT { //试用
//				button.BtnEdit = true
//				button.BtnDelete = true
//				//button.BtnModifySeller = true
//				button.BtnFreeze = false
//				return
//			} else if status == utils.COMPANY_STATUS_FREEZE { //冻结
//				//button.BtnModifySeller = true
//				return
//			} else if status == utils.COMPANY_STATUS_LOSE { //流失
//				//button.BtnModifySeller = true
//				button.BtnDelete = true
//				return
//			} else { //永续
//				//button.BtnModifySeller = true
//				button.BtnDelete = true
//				button.BtnEdit = true
//				return
//			}
//		}
//	} else if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN {
//		if productId != 1 {
//			return
//		} else {
//			if !strings.Contains(status, "/") {
//				if status == utils.COMPANY_STATUS_FORMAL { //正式
//					button.BtnModifySeller = true
//					return
//				} else if status == utils.COMPANY_STATUS_TRY_OUT { //试用
//					//button.BtnEdit = true
//					//button.BtnDelete = true
//					button.BtnModifySeller = true
//					button.BtnFreeze = false
//					return
//				} else if status == utils.COMPANY_STATUS_FREEZE { //冻结
//					//button.BtnModifySeller = true
//					return
//				} else if status == utils.COMPANY_STATUS_LOSE { //流失
//					//button.BtnModifySeller = true
//					//button.BtnDelete = true
//					return
//				} else { //永续
//					return
//				}
//			}
//		}
//	} else if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
//		if !strings.Contains(status, "/") {
//			if status == utils.COMPANY_STATUS_FORMAL { //正式
//				button.BtnModifySeller = true
//				return
//			} else if status == utils.COMPANY_STATUS_TRY_OUT { //试用
//				//button.BtnEdit = true
//				//button.BtnDelete = true
//				button.BtnModifySeller = true
//				button.BtnFreeze = false
//				return
//			} else if status == utils.COMPANY_STATUS_FREEZE { //冻结
//				return
//			} else if status == utils.COMPANY_STATUS_LOSE { //流失
//				//button.BtnDelete = true
//				return
//			} else { //永续
//				return
//			}
//		}
//	} else if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER {
//		if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER && productId == 2 {
//			if !strings.Contains(status, "/") {
//				button.BtnReceiveOther = true //领取其他部门客户按钮权限
//			} else {
//				//共享客户，需要取出当前销售对应的 产品 权限（目前是ficc销售，所以是ficc的权限，也就是第1个）
//				statusSlice := strings.Split(status, "/")
//				ficcStatus := statusSlice[0]
//				if ficcStatus == utils.COMPANY_STATUS_LOSE { //流失
//					if itemSellerId == sysUserId || itemGroupId == sysUserGroupId {
//						button.BtnApplyReceive = true //申请领取按钮权限
//					} else {
//						button.BtnReceive = true //领取客户按钮权限
//					}
//					return
//				}
//			}
//			return
//		}
//		if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER && productId == 1 {
//			return
//		}
//		//管理权限，0：无，1：部门负责人，2：小组负责人,3:超级管理员
//		if authority == 2 { //组长
//			if !strings.Contains(status, "/") {
//				if sysUserId == itemSellerId { //自己客户
//					if status == utils.COMPANY_STATUS_FORMAL { //正式
//						button.BtnUpdate = true
//						button.BtnModifySeller = true
//						button.BtnTryOut = true
//						return
//					} else if status == utils.COMPANY_STATUS_TRY_OUT { //试用
//						button.BtnEdit = true
//						button.BtnDelete = true
//						button.BtnSuspend = true
//						button.BtnDelay = true
//						button.BtnTurnPositive = true
//						button.BtnModifySeller = true
//						button.BtnFreeze = true
//						return
//					} else if status == utils.COMPANY_STATUS_FREEZE { //冻结
//						button.BtnThaw = true
//						return
//					} else if status == utils.COMPANY_STATUS_LOSE { //流失
//						if itemSellerId == sysUserId || itemGroupId == sysUserGroupId {
//							button.BtnApplyReceive = true
//						} else {
//							button.BtnReceive = true
//						}
//						if itemSellerId == sysUserId || (itemGroupId == sysUserGroupId && authority > 0) {
//							//button.BtnDelete = true
//						}
//						return
//					} else { //永续
//						button.BtnDelete = true
//						return
//					}
//				} else {
//					if productId == 1 {
//						if status == utils.COMPANY_STATUS_FORMAL { //正式
//							button.BtnModifySeller = true
//							return
//						} else if status == utils.COMPANY_STATUS_TRY_OUT { //试用
//							button.BtnModifySeller = true
//							return
//						} else if status == utils.COMPANY_STATUS_FREEZE { //冻结
//							button.BtnThaw = false
//							return
//						} else if status == utils.COMPANY_STATUS_LOSE { //流失
//							if itemSellerId == sysUserId || itemGroupId == sysUserGroupId {
//								button.BtnApplyReceive = true
//							} else {
//								button.BtnReceive = true
//							}
//							return
//						} else { //永续
//							button.BtnDelete = true
//							return
//						}
//					} else {
//						//button.BtnReceive = true
//					}
//				}
//			}
//		} else { //销售
//			if !strings.Contains(status, "/") {
//				if itemSellerId == sysUserId {
//					if status == utils.COMPANY_STATUS_FORMAL { //正式
//						button.BtnUpdate = true
//						button.BtnTryOut = true
//						return
//					} else if status == utils.COMPANY_STATUS_TRY_OUT { //试用
//						button.BtnEdit = true
//						button.BtnDelete = true
//						button.BtnSuspend = true
//						button.BtnDelay = true
//						button.BtnTurnPositive = true
//						button.BtnFreeze = true
//						return
//					} else if status == utils.COMPANY_STATUS_FREEZE { //冻结
//						button.BtnThaw = true
//						return
//					} else if status == utils.COMPANY_STATUS_LOSE { //流失
//						if itemSellerId == sysUserId || itemGroupId == sysUserGroupId {
//							button.BtnApplyReceive = true
//						} else {
//							button.BtnReceive = true
//						}
//						if itemSellerId == sysUserId || (itemGroupId == sysUserGroupId && authority > 0) {
//							//button.BtnDelete = true
//						}
//						return
//					} else { //永续
//						button.BtnDelete = true
//						return
//					}
//				} else {
//					if productId == 1 {
//						if status == utils.COMPANY_STATUS_FORMAL { //正式
//							return
//						} else if status == utils.COMPANY_STATUS_TRY_OUT { //试用
//							return
//						} else if status == utils.COMPANY_STATUS_FREEZE { //冻结
//							button.BtnThaw = false
//							return
//						} else if status == utils.COMPANY_STATUS_LOSE { //流失
//							if itemSellerId == sysUserId || itemGroupId == sysUserGroupId {
//								button.BtnApplyReceive = true
//							} else {
//								button.BtnReceive = true
//							}
//							return
//						} else { //永续
//							button.BtnDelete = true
//							return
//						}
//					} else {
//						//button.BtnReceive = true
//					}
//				}
//			} else {
//				//共享客户，需要取出当前销售对应的 产品 权限（目前是ficc销售，所以是ficc的权限，也就是第1个）
//				statusSlice := strings.Split(status, "/")
//				ficcStatus := statusSlice[0]
//				if ficcStatus == utils.COMPANY_STATUS_LOSE { //流失
//					if itemSellerId == sysUserId || itemGroupId == sysUserGroupId {
//						button.BtnApplyReceive = true //申请领取按钮权限
//					} else {
//						button.BtnReceive = true //领取客户按钮权限
//					}
//					return
//				}
//			}
//		}
//	} else if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER {
//		if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER && productId == 2 {
//			return
//		}
//		if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER && productId == 1 {
//			if !strings.Contains(status, "/") {
//				button.BtnReceiveOther = true //领取其他部门客户按钮权限
//			} else {
//				//共享客户，需要取出当前销售对应的 产品 权限（目前是权益销售，所以是权益的权限，也就是第2个）
//				statusSlice := strings.Split(status, "/")
//				raiStatus := statusSlice[1]
//				if raiStatus == utils.COMPANY_STATUS_LOSE { //流失
//					if itemSellerId == sysUserId || itemGroupId == sysUserGroupId {
//						button.BtnApplyReceive = true //申请领取按钮权限
//					} else {
//						button.BtnReceive = true //领取客户按钮权限
//					}
//					return
//				}
//			}
//			return
//		}
//		if !strings.Contains(status, "/") {
//			if authority == 2 { //组长
//				if itemSellerId == sysUserId {
//					if status == utils.COMPANY_STATUS_FORMAL { //正式
//						button.BtnUpdate = true
//						button.BtnModifySeller = true
//						button.BtnTryOut = true
//						return
//					} else if status == utils.COMPANY_STATUS_TRY_OUT { //试用
//						button.BtnEdit = true
//						button.BtnDelete = true
//						button.BtnSuspend = true
//						button.BtnDelay = true
//						button.BtnTurnPositive = true
//						button.BtnModifySeller = true
//						button.BtnFreeze = true
//						return
//					} else if status == utils.COMPANY_STATUS_FREEZE { //冻结
//						button.BtnThaw = true
//						return
//					} else if status == utils.COMPANY_STATUS_LOSE { //流失
//						if itemSellerId == sysUserId || itemGroupId == sysUserGroupId {
//							button.BtnApplyReceive = true
//						} else {
//							button.BtnReceive = true
//						}
//						if itemSellerId == sysUserId || (itemGroupId == sysUserGroupId && authority > 0) {
//							//button.BtnDelete = true
//						}
//						return
//					} else { //永续
//						button.BtnDelete = true
//						return
//					}
//				} else {
//					if productId == 1 {
//						//button.BtnReceive = true
//					} else {
//						if status == utils.COMPANY_STATUS_FORMAL { //正式
//							button.BtnModifySeller = true
//							return
//						} else if status == utils.COMPANY_STATUS_TRY_OUT { //试用
//							button.BtnModifySeller = true
//							return
//						} else if status == utils.COMPANY_STATUS_FREEZE { //冻结
//							button.BtnThaw = false
//							return
//						} else if status == utils.COMPANY_STATUS_LOSE { //流失
//							if itemSellerId == sysUserId || itemGroupId == sysUserGroupId {
//								button.BtnApplyReceive = true
//							} else {
//								button.BtnReceive = true
//							}
//							return
//						} else { //永续
//							button.BtnDelete = true
//							return
//						}
//					}
//				}
//			} else {
//				if itemSellerId == sysUserId {
//					if status == utils.COMPANY_STATUS_FORMAL { //正式
//						button.BtnUpdate = true
//						button.BtnTryOut = true
//						return
//					} else if status == utils.COMPANY_STATUS_TRY_OUT { //试用
//						button.BtnEdit = true
//						button.BtnDelete = true
//						button.BtnSuspend = true
//						button.BtnDelay = true
//						button.BtnTurnPositive = true
//						button.BtnFreeze = true
//						return
//					} else if status == utils.COMPANY_STATUS_FREEZE { //冻结
//						button.BtnThaw = true
//						return
//					} else if status == utils.COMPANY_STATUS_LOSE { //流失
//						if itemSellerId == sysUserId || itemGroupId == sysUserGroupId {
//							button.BtnApplyReceive = true //申请领取按钮权限
//						} else {
//							button.BtnReceive = true //领取客户按钮权限
//						}
//						if itemSellerId == sysUserId || (itemGroupId == sysUserGroupId && authority > 0) {
//							//button.BtnDelete = true
//						}
//						return
//					} else { //永续
//						button.BtnDelete = true
//						return
//					}
//				} else {
//					if productId == 1 {
//						//button.BtnReceive = true
//					} else {
//						if status == utils.COMPANY_STATUS_FORMAL { //正式
//							return
//						} else if status == utils.COMPANY_STATUS_TRY_OUT { //试用
//							return
//						} else if status == utils.COMPANY_STATUS_FREEZE { //冻结
//							button.BtnThaw = false
//							return
//						} else if status == utils.COMPANY_STATUS_LOSE { //流失
//							if itemSellerId == sysUserId || itemGroupId == sysUserGroupId {
//								button.BtnApplyReceive = true //申请领取按钮权限
//							} else {
//								button.BtnReceive = true //领取客户按钮权限
//							}
//							return
//						} else { //永续
//							button.BtnDelete = true
//							return
//						}
//					}
//				}
//			}
//		} else {
//			//共享客户，需要取出当前销售对应的 产品 权限（目前是权益销售，所以是权益的权限，也就是第2个）
//			statusSlice := strings.Split(status, "/")
//			raiStatus := statusSlice[1]
//			if raiStatus == utils.COMPANY_STATUS_LOSE { //流失
//				if itemSellerId == sysUserId || itemGroupId == sysUserGroupId {
//					button.BtnApplyReceive = true //申请领取按钮权限
//				} else {
//					button.BtnReceive = true //领取客户按钮权限
//				}
//				return
//			}
//		}
//	}
//	return button
//}

// 校验当前操作员是否具有联系人权限是否有操作权限
func CheckCompanyUserButton(roleTypeCode string, itemSellerId, sysUserId, productId, shareSellerId int, status string) (ok bool) {
	if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
		ok = true
		return
	}
	if sysUserId == itemSellerId || shareSellerId == sysUserId {
		ok = true
		//如果客户状态是流失，那么就无法操作
		if status == utils.COMPANY_STATUS_LOSE || status == utils.COMPANY_STATUS_CLOSE {
			ok = false
			return
		}
		return
	} else {
		if productId == 1 && roleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN {
			//如果是ficc类型，同时当前账户是ficc管理员
			ok = true
		} else if productId == 2 && roleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
			//如果是权益类型，同时当前账户是 权益管理员
			ok = true
		}
	}
	return
}

// 校验当前操作员是否具给联系人开通个人研选的权限
func CheckCompanyUserYanXuanButton(roleTypeCode string, adminMobile string) (ok bool, err error) {
	if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN || roleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER || roleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP {
		ok = true
		return
	}
	crmConfig, err := company.GetConfigDetailByCode("rai_wx_user_yanxuan_button")
	if err != nil {
		return
	}

	sliceMobile := strings.Split(crmConfig.ConfigValue, ",")
	for _, v := range sliceMobile {
		if v == adminMobile {
			ok = true
			return
		}
	}
	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
}

// GetApplyTurnContractType
// 获取客户申请合同类型
func GetApplyTurnContractType(companyId, productId int) (contractType string, err error) {
	//合同类型
	contractType = "新签合同"
	companyProduct, err := company.GetCompanyProductByCompanyIdAndProductId(companyId, productId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			err = nil
			return
		}
		err = errors.New("获取客户信息失败,Err:" + err.Error())
		return
	}

	// 当前客户产品状态为试用，那么是续约合同
	if companyProduct.Status == "正式" {
		contractType = "续约合同"
	}
	var condition string
	var pars []interface{}
	condition += " AND product_id = ?"
	pars = append(pars, productId)
	condition += " AND status = ?"
	pars = append(pars, 1)
	list, err := company.GetCompanyContractListByCompanyId(companyId, condition, pars)
	if err != nil {
		err = errors.New("获取合同信息失败,Err:" + err.Error())
		return
	}
	if len(list) > 0 {
		contractType = "续约合同"
	}
	//查询是否存在正式转试用的记录，如果存在，那么合同类型是续约合同
	total, err := company.GetCompanyProductOperationRecordCount(companyProduct.CompanyId, companyProduct.ProductId)
	if err != nil {
		err = errors.New("查询用户变更记录异常,Err:" + err.Error())
		return
	}
	if total > 0 {
		contractType = "续约合同"
	}
	return
}

// GetLastContractPermissionList
// 获取客户的最近合同的权限期限
func GetLastContractPermissionList(companyId, productId int) (permissionMap map[int]company.PermissionLookItem, err error) {
	permissionMap = map[int]company.PermissionLookItem{}

	contractList, err := company.GetCompanyWillContractList(companyId, productId)
	if err != nil {
		err = errors.New("获取合同信息失败,Err:" + err.Error())
		return
	}
	for _, contractInfo := range contractList {
		permissionList, permissionErr := company.GetCompanyContractPermissionListByContractIds(strconv.Itoa(contractInfo.CompanyContractId))
		if permissionErr != nil {
			err = errors.New("获取合同信息失败,Err:" + permissionErr.Error())
			return
		}
		for _, v := range permissionList {
			if permission, ok := permissionMap[v.ChartPermissionId]; ok {
				nowEndDateTime, tmpErr := time.Parse(utils.FormatDate, v.EndDate)
				if tmpErr != nil {
					err = errors.New("获取合同信息失败，合同结束日期格式化失败,Err:" + tmpErr.Error())
					return
				}
				perEndDateTime, tmpErr := time.Parse(utils.FormatDate, permission.EndDate)
				if err != nil {
					err = errors.New("获取合同信息失败，合同结束日期格式化失败2,Err:" + tmpErr.Error())
					return
				}
				//如果当前合同的权限期限晚于已经记录的权限期限，那么重新赋值
				if nowEndDateTime.After(perEndDateTime) {
					permissionMap[v.ChartPermissionId] = company.PermissionLookItem{
						ChartPermissionId: v.ChartPermissionId,
						PermissionName:    v.ChartPermissionName,
						StartDate:         v.StartDate,
						EndDate:           v.EndDate,
						//Status            string `description:"'正式','试用','关闭'"`
						//ExpireDay         string `description:"到期天数"`
						ClassifyName: v.ClassifyName,
					}
				}
			} else {
				permissionMap[v.ChartPermissionId] = company.PermissionLookItem{
					ChartPermissionId: v.ChartPermissionId,
					PermissionName:    v.ChartPermissionName,
					StartDate:         v.StartDate,
					EndDate:           v.EndDate,
					//Status            string `description:"'正式','试用','关闭'"`
					//ExpireDay         string `description:"到期天数"`
					ClassifyName: v.ClassifyName,
				}
			}
		}
	}

	//获取权限
	permissionList, permissionErr := company.GetCompanyReportPermissionListByProductId(companyId, productId)
	if permissionErr != nil {
		err = errors.New("获取权限失败,Err:" + permissionErr.Error())
		return
	}
	for _, v := range permissionList {
		if permission, ok := permissionMap[v.ChartPermissionId]; ok {
			nowEndDateTime, tmpErr := time.Parse(utils.FormatDate, v.EndDate)
			if tmpErr != nil {
				err = errors.New("获取合同信息失败，合同结束日期格式化失败,Err:" + tmpErr.Error())
				return
			}
			perEndDateTime, tmpErr := time.Parse(utils.FormatDate, permission.EndDate)
			if err != nil {
				err = errors.New("获取合同信息失败，合同结束日期格式化失败2,Err:" + tmpErr.Error())
				return
			}
			//如果当前合同的权限期限晚于已经记录的权限期限，那么重新赋值
			if nowEndDateTime.After(perEndDateTime) {
				permissionMap[v.ChartPermissionId] = company.PermissionLookItem{
					ChartPermissionId: v.ChartPermissionId,
					PermissionName:    v.PermissionName,
					StartDate:         v.StartDate,
					EndDate:           v.EndDate,
					//Status            string `description:"'正式','试用','关闭'"`
					//ExpireDay         string `description:"到期天数"`
					ClassifyName: v.ClassifyName,
				}
			}
		} else {
			permissionMap[v.ChartPermissionId] = company.PermissionLookItem{
				ChartPermissionId: v.ChartPermissionId,
				PermissionName:    v.PermissionName,
				StartDate:         v.StartDate,
				EndDate:           v.EndDate,
				//Status            string `description:"'正式','试用','关闭'"`
				//ExpireDay         string `description:"到期天数"`
				ClassifyName: v.ClassifyName,
			}
		}
	}
	return
}

// GetFiccLastUserViewHistoryByCompanyIds 根据客户id集合map获取ficc最后一次阅读时间
func GetFiccLastUserViewHistoryByCompanyIds(companyIdStr string, mobileList, emailList []string, mobileCompanyIdMap, emailCompanyIdMap map[string]int) (companyViewTime map[int]time.Time, err error) {
	//user_view_record mobile
	companyViewTime = make(map[int]time.Time)
	userViewList, err := models.GetLastUserViewHistoryByCompanyIdsMobile(companyIdStr)
	if err != nil {
		return
	}
	for _, userView := range userViewList {
		companyViewTime[userView.CompanyId] = userView.ViewTime
	}

	//user_view_record email
	userViewList, err = models.GetLastUserViewHistoryByCompanyIdsEmail(companyIdStr)
	if err != nil {
		return
	}
	checkLastTime(companyViewTime, userViewList)

	//AdvisoryArticleViewRecord mobile
	userViewList, err = models.GetLastAdvisoryArticleViewRecordByCompanyIdsMobile(companyIdStr)
	if err != nil {
		return
	}
	checkLastTime(companyViewTime, userViewList)

	//AdvisoryArticleViewRecord email
	userViewList, err = models.GetLastAdvisoryArticleViewRecordByCompanyIdsEmail(companyIdStr)
	if err != nil {
		return
	}
	checkLastTime(companyViewTime, userViewList)

	//ReportViewRecord mobile
	mobileOrEmailViewList, err := models.GetLastReportViewRecordByMobileList(mobileList)
	if err != nil {
		return
	}
	checkMobileOrEmailLastTime(companyViewTime, mobileOrEmailViewList, mobileCompanyIdMap)

	//ReportViewRecord email
	mobileOrEmailViewList, err = models.GetLastReportViewRecordByEmailList(emailList)
	if err != nil {
		return
	}
	checkMobileOrEmailLastTime(companyViewTime, mobileOrEmailViewList, emailCompanyIdMap)

	//UserViewStatistics mobile
	userViewList, err = models.GetLastUserViewStatisticsByCompanyIdsMobile(companyIdStr)
	if err != nil {
		return
	}
	checkLastTime(companyViewTime, userViewList)

	//UserViewStatistics email
	userViewList, err = models.GetLastUserViewStatisticsByCompanyIdsEmail(companyIdStr)
	if err != nil {
		return
	}
	checkLastTime(companyViewTime, userViewList)

	return
}

// GetRaiLastUserViewHistoryByCompanyIds 根据客户id集合map获取权益最后一次阅读时间
func GetRaiLastUserViewHistoryByCompanyIds(companyIdStr string) (companyViewTime map[int]time.Time, err error) {
	//CygxArticleViewRecord mobile
	companyViewTime = make(map[int]time.Time)
	userViewList, err := models.GetLastCygxArticleViewRecordByCompanyIdsMobile(companyIdStr)
	if err != nil {
		return
	}
	for _, userView := range userViewList {
		companyViewTime[userView.CompanyId] = userView.ViewTime
	}

	//CygxArticleViewRecord email
	userViewList, err = models.GetLastCygxArticleViewRecordByCompanyIdsEmail(companyIdStr)
	if err != nil {
		return
	}
	checkLastTime(companyViewTime, userViewList)
	return
}

// checkLastTime 检测最后的时间并重新赋值
func checkLastTime(companyViewTime map[int]time.Time, userViewList []*models.CompanyLastViewSlice) {
	for _, userView := range userViewList {
		if viewTime, ok := companyViewTime[userView.CompanyId]; ok {
			if userView.ViewTime.After(viewTime) { //如果当前时间晚于 map中的时间，那么重新赋值
				companyViewTime[userView.CompanyId] = userView.ViewTime
			}
		} else { //如果没有数据，那么直接赋值
			companyViewTime[userView.CompanyId] = userView.ViewTime
		}
	}
	return
}

// checkMobileOrEmailLastTime 根据用户信息检测最后的时间并重新赋值
func checkMobileOrEmailLastTime(companyViewTime map[int]time.Time, userViewList []*models.MobileOrEmailLastViewSlice, companyMap map[string]int) {
	for _, userView := range userViewList {
		// 先找到客户id
		companyId, ok := companyMap[userView.Mobile]
		if !ok {
			continue
		}

		// 相同客户id的数据进行比较

		if viewTime, ok := companyViewTime[companyId]; ok {
			if userView.ViewTime.After(viewTime) { //如果当前时间晚于 map中的时间，那么重新赋值
				companyViewTime[companyId] = userView.ViewTime
			}
		} else { //如果没有数据，那么直接赋值
			companyViewTime[companyId] = userView.ViewTime
		}
	}
	return
}

// GetFiccCountUserViewHistoryByCompanyIds 根据客户id集合map获取ficc的阅读次数
func GetFiccCountUserViewHistoryByCompanyIds(companyIdStr string, mobileList, emailList []string, mobileCompanyIdMap, emailCompanyIdMap map[string]int) (companyViewTotal map[int]int, err error) {
	//user_view_record mobile
	companyViewTotal = make(map[int]int)
	userViewList, err := models.GetCountUserViewHistoryByCompanyIdsMobile(companyIdStr)
	if err != nil {
		return
	}
	for _, userView := range userViewList {
		companyViewTotal[userView.CompanyId] = userView.ViewTotal
	}
	userViewList, err = models.GetCountUserViewHistoryByCompanyIdsEmail(companyIdStr)
	if err != nil {
		return
	}
	checkCount(companyViewTotal, userViewList)

	//AdvisoryArticleViewRecord mobile
	userViewList, err = models.GetCountAdvisoryArticleViewRecordByCompanyIdsMobile(companyIdStr)
	if err != nil {
		return
	}
	checkCount(companyViewTotal, userViewList)

	//AdvisoryArticleViewRecord email
	userViewList, err = models.GetCountAdvisoryArticleViewRecordByCompanyIdsEmail(companyIdStr)
	if err != nil {
		return
	}
	checkCount(companyViewTotal, userViewList)

	//ReportViewRecord mobile
	mobileOrEmailViewList, err := models.GetCountReportViewRecordByMobileList(mobileList)
	if err != nil {
		return
	}
	checkMobileOrEmailCount(companyViewTotal, mobileOrEmailViewList, mobileCompanyIdMap)

	//ReportViewRecord email
	mobileOrEmailViewList, err = models.GetCountReportViewRecordByEmailList(emailList)
	if err != nil {
		return
	}
	checkMobileOrEmailCount(companyViewTotal, mobileOrEmailViewList, emailCompanyIdMap)

	//UserViewStatistics mobile
	userViewList, err = models.GetUserViewStatisticsByCompanyIdsMobile(companyIdStr)
	if err != nil {
		return
	}
	checkCount(companyViewTotal, userViewList)

	//UserViewStatistics email
	userViewList, err = models.GetUserViewStatisticsByCompanyIdsEmail(companyIdStr)
	if err != nil {
		return
	}
	checkCount(companyViewTotal, userViewList)
	return
}

// GetRaiCountUserViewHistoryByCompanyIds 根据客户id集合map获取权益的阅读次数
func GetRaiCountUserViewHistoryByCompanyIds(companyIdStr string) (companyViewTotal map[int]int, err error) {
	//CygxArticleViewRecord mobile
	companyViewTotal = make(map[int]int)
	userViewList, err := models.GetCountCygxArticleViewRecordByCompanyIdsMobile(companyIdStr)
	if err != nil {
		return
	}
	for _, userView := range userViewList {
		companyViewTotal[userView.CompanyId] = userView.ViewTotal
	}

	//CygxArticleViewRecord email
	userViewList, err = models.GetCountCygxArticleViewRecordByCompanyIdsEmail(companyIdStr)
	if err != nil {
		return
	}
	checkCount(companyViewTotal, userViewList)
	return
}

// GetAllCountUserViewHistoryByCompanyIds 根据客户id集合map获取所有的阅读次数
//func GetAllCountUserViewHistoryByCompanyIds(companyIdStr string) (companyViewTotal map[int]int, err error) {
//	companyViewTotal = make(map[int]int)
//	companyFiccViewTotal, err := GetFiccCountUserViewHistoryByCompanyIds(companyIdStr)
//	if err != nil {
//		return
//	}
//
//	companyRaiViewTotal, err := GetRaiCountUserViewHistoryByCompanyIds(companyIdStr)
//	if err != nil {
//		return
//	}
//
//	companyIdList := strings.Split(companyIdStr, ",")
//
//	for _, companyIdStr := range companyIdList {
//		companyId, _ := strconv.Atoi(companyIdStr)
//		ficcTotal, ok := companyFiccViewTotal[companyId]
//		if !ok {
//			ficcTotal = 0
//		}
//		raiTotal, ok := companyRaiViewTotal[companyId]
//		if !ok {
//			raiTotal = 0
//		}
//		companyViewTotal[companyId] = ficcTotal + raiTotal
//	}
//	return
//}

func checkCount(companyViewTotal map[int]int, userViewList []*models.CompanyViewTotalSlice) {
	for _, userView := range userViewList {
		if viewTotal, ok := companyViewTotal[userView.CompanyId]; ok {
			companyViewTotal[userView.CompanyId] = viewTotal + userView.ViewTotal
		} else { //如果没有数据，那么直接赋值
			companyViewTotal[userView.CompanyId] = userView.ViewTotal
		}
	}
	return
}

// checkMobileOrEmailCount 根据手机号或者邮箱进行数据比较
func checkMobileOrEmailCount(companyViewTotal map[int]int, mobileOrEmailViewList []*models.MobileOrEmailViewTotalSlice, companyMap map[string]int) {
	for _, userView := range mobileOrEmailViewList {
		// 先找到客户id
		companyId, ok := companyMap[userView.Mobile]
		if !ok {
			continue
		}

		// 相同客户id的数据进行比较
		if viewTotal, ok := companyViewTotal[companyId]; ok {
			companyViewTotal[companyId] = viewTotal + userView.ViewTotal
		} else { //如果没有数据，那么直接赋值
			companyViewTotal[companyId] = userView.ViewTotal
		}
	}
	return
}

// ModifyCompanyProductLastViewData 修改客户产品的总共阅读次数以及最近阅读时间
func ModifyCompanyProductLastViewData(companyIdList []int) (err error) {
	defer func() {
		if err != nil {
			go alarm_msg.SendAlarmMsg("修改客户产品的总共阅读次数以及最近阅读时间失败，"+fmt.Sprint("companyIdList:", companyIdList, ";err：", err), 3)
			//go utils.SendEmail("修改客户产品的总共阅读次数以及最近阅读时间失败", fmt.Sprint("companyIdList:", companyIdList, ";err:", err), utils.EmailSendToUsers)
		}
	}()

	wxUserList, err := models.GetWxUserByCompanyIds(companyIdList)
	if err != nil {
		return
	}
	mobileList := make([]string, 0)
	mobileCompanyIdMap := make(map[string]int, 0)
	emailList := make([]string, 0)
	emailCompanyIdMap := make(map[string]int, 0)

	for _, v := range wxUserList {
		if v.Mobile != `` {
			mobileList = append(mobileList, v.Mobile)
			mobileCompanyIdMap[v.Mobile] = v.CompanyId
		}
		if v.Email != `` {
			emailList = append(emailList, v.Email)
			emailCompanyIdMap[v.Email] = v.CompanyId
		}
	}

	// 根据companyId列表获取客户公司的阅读情况
	companyViewRecordList, err := models.GetUserViewHistoryByCompanyIdList(companyIdList)
	if err != nil {
		return
	}
	companyViewRecordMap := make(map[int]*models.CompanyViewRecord)
	for _, v := range companyViewRecordList {
		companyViewRecordMap[v.CompanyId] = v
	}

	for _, companyId := range companyIdList {
		companyViewRecord, ok := companyViewRecordMap[companyId]
		//ficc
		var companyFiccViewTotal, companyRaiViewTotal int
		var companyFiccLastView, companyRaiLastView time.Time
		var companyFiccLastViewStr, companyRaiLastViewStr string

		if ok && companyViewRecord != nil {
			companyFiccViewTotal = companyViewRecord.FiccViewTotal
			companyFiccLastView = companyViewRecord.FiccLastViewTime
			companyRaiViewTotal = companyViewRecord.RaiViewTotal
			companyRaiLastView = companyViewRecord.RaiLastViewTime
		}

		if companyFiccLastView.IsZero() {
			companyFiccLastViewStr = "0000-00-00 00:00:00"
		} else {
			companyFiccLastViewStr = companyFiccLastView.Format(utils.FormatDateTime)
		}
		company.ModifyCompanyProductLastViewData(companyId, 1, companyFiccViewTotal, companyFiccLastViewStr)

		//权益
		if companyRaiLastView.IsZero() {
			companyRaiLastViewStr = "0000-00-00 00:00:00"
		} else {
			companyRaiLastViewStr = companyRaiLastView.Format(utils.FormatDateTime)
		}

		company.ModifyCompanyProductLastViewData(companyId, 2, companyRaiViewTotal, companyRaiLastViewStr)
	}

	return
}

// CompanyDeleteBakInfo 删除客户时的备份信息
type CompanyDeleteBakInfo struct {
	CompanyId                  int                                     `description:"客户id"`
	CompanyName                string                                  `description:"客户名称"`
	CompanyInfo                *company.Company                        `description:"客户主表信息"`
	CompanyProductInfo         []*company.CompanyProduct               `description:"客户产品信息"`
	CompanyPermissionInfo      []*company.CompanyReportPermission      `description:"客户产品权限信息"`
	UserSellerRelationInfo     []*models.UserSellerRelation            `description:"联系人与销售关系信息"`
	UserRecordInfo             []*models.UserRecord                    `description:"联系人关系信息"`
	UserInfo                   []*models.WxUser                        `description:"联系人信息"`
	CompanyChartPermissionInfo []*company_user.ChartClassifyPermission `description:"客户图表权限信息"`
	CompanyContract            []*company.CompanyContract              `description:"客户合同信息"`
	CompanyContractPermission  []*company.CompanyContractPermission    `description:"客户合同权限信息"`
	OpUserId                   int                                     `description:"操作人id"`
	OpUserName                 string                                  `description:"操作人名称"`
}

// GetBeforeDeleteCompanyInfo 获取删除客户之前的信息
func GetBeforeDeleteCompanyInfo(companyId int) (companyProductLists []*company.CompanyProduct, companyReportPermissions []*company.CompanyReportPermission, wxUsers []*models.WxUser, userSellerRelations []*models.UserSellerRelation, companyContracts []*company.CompanyContract, companyContractPermissions []*company.CompanyContractPermission, companyInfo *company.Company, err error) {
	o := orm.NewOrm()

	//删除客户产品
	bakSql := `SELECT * FROM company_product WHERE company_id=? `
	_, err = o.Raw(bakSql, companyId).QueryRows(&companyProductLists)
	if err != nil {
		return
	}

	//删除客户权限
	bakSql = `SELECT *  FROM company_report_permission WHERE company_id=? `
	_, err = o.Raw(bakSql, companyId).QueryRows(&companyReportPermissions)
	if err != nil {
		return
	}

	//联系人表
	bakSql = `SELECT * FROM wx_user WHERE company_id=? `
	_, err = o.Raw(bakSql, companyId).QueryRows(&wxUsers)
	if err != nil {
		return
	}

	//联系人 与 销售 关系表
	bakSql = `SELECT *  FROM user_seller_relation WHERE company_id=? `
	_, err = o.Raw(bakSql, companyId).QueryRows(&userSellerRelations)
	if err != nil {
		return
	}

	// 合同
	bakSql = `SELECT *  FROM company_contract WHERE company_id=? `
	_, err = o.Raw(bakSql, companyId).QueryRows(&companyContracts)
	if err != nil {
		return
	}

	// 合同权限
	bakSql = `SELECT *  FROM company_contract_permission WHERE company_id=? `
	_, err = o.Raw(bakSql, companyId).QueryRows(&companyContractPermissions)
	if err != nil {
		return
	}
	// 客户
	bakSql = `SELECT *  FROM company WHERE company_id=? `
	err = o.Raw(bakSql, companyId).QueryRow(&companyInfo)
	if err != nil {
		return
	}
	return
}

// CheckCompanyReceiveButton 查询领取客户按钮的权限
func CheckCompanyReceiveButton(adminId int) (receiveEnabled bool, err error) {
	receiveEnabled = true
	receivePermissionInfo, err := company.GetSellerCompanyPermissionByAdminIdType(adminId, 1)
	if err != nil {
		if err.Error() != utils.ErrNoRow() {
			err = errors.New("获取账号权限失败，Err:" + err.Error())
			return
		}
	} else {
		if receivePermissionInfo != nil && receivePermissionInfo.Enabled == 0 {
			receiveEnabled = false
		}
	}
	return
}

// AddWxUserOpLog 记录新增用户的日志
func AddWxUserOpLog(wxUserOpLog company.WxUserOpLog) {
	userSellerRelationList, err := models.GetUserSellerRelationList(wxUserOpLog.UserId)
	if err != nil {
		return
	}

	userSellerRelationInfo, _ := json.Marshal(userSellerRelationList)
	wxUserOpLog.UserSellerInfo = string(userSellerRelationInfo)
	company.AddWxUserOpLog(&wxUserOpLog)
}

// FilterReadAndContractAuth 根据已购品种和阅读权限获取筛选条件
func FilterReadAndContractAuth(chartPermissions, contractPermissions, condition string) (cond string, empty bool, err error) {
	cond = condition
	var queryChart, queryContract bool
	if chartPermissions != "" && chartPermissions != "1" {
		queryChart = true
	}
	if contractPermissions != "" && contractPermissions != "1" {
		queryContract = true
	}
	if !queryChart && !queryContract {
		return
	}

	readIds := make([]int, 0)
	buyIds := make([]int, 0)
	// 阅读权限
	if queryChart {
		{
			// 处理权益的主观客观的筛选条件搜索
			ids := make([]int, 0)
			strIdArr := strings.Split(chartPermissions, ",")
			for _, s := range strIdArr {
				v, _ := strconv.Atoi(s)
				ids = append(ids, v)
			}
			if len(ids) == 0 {
				err = fmt.Errorf("权限ID有误")
				return
			}
			names, e := company.GetPermissionNameByPermissionIds(ids)
			if e != nil {
				err = fmt.Errorf("根据权限ID获取名称失败, Err: %s", e.Error())
				return
			}
			permissionIds, e := company.GetPermissionIdsByPermissionNames(names)
			if e != nil {
				err = fmt.Errorf("根据权限名称获取ID失败, Err: %s", e.Error())
				return
			}
			companyIds, e := company.GetCompanyIdsStrByReportPermissionIds(permissionIds)
			if e != nil {
				err = fmt.Errorf("根据合同权限获取公司ID失败, Err: %s", e.Error())
				return
			}
			readIds = companyIds
		}
	}

	// 已购合同权限
	if queryContract {
		{
			// 处理权益的主观客观的筛选条件搜索
			ids := make([]int, 0)
			strIdArr := strings.Split(contractPermissions, ",")
			for _, s := range strIdArr {
				v, _ := strconv.Atoi(s)
				ids = append(ids, v)
			}
			if len(ids) == 0 {
				err = fmt.Errorf("权限ID有误")
				return
			}
			names, e := company.GetPermissionNameByPermissionIds(ids)
			if e != nil {
				err = fmt.Errorf("根据权限ID获取名称失败, Err: %s", e.Error())
				return
			}
			permissionIds, e := company.GetPermissionIdsByPermissionNames(names)
			if e != nil {
				err = fmt.Errorf("根据权限名称获取ID失败, Err: %s", e.Error())
				return
			}
			companyIds, e := company.GetCompanyIdsStrByContractPermissionIds(permissionIds)
			if e != nil {
				err = fmt.Errorf("根据合同权限获取公司ID失败, Err: %s", e.Error())
				return
			}
			buyIds = companyIds

			// 勾选了已购品种的, 仅筛选正式客户
			cond += ` AND b.status = '正式'`
		}
	}

	queryIds := make([]int, 0)
	queryIdArr := make([]string, 0)
	// 阅读权限和已购品种同时筛选取两者的companyIds交集
	if queryChart && queryContract {
		queryIds = utils.IntersectInt(readIds, buyIds)
	} else if queryChart && !queryContract {
		queryIds = readIds
	} else if !queryChart && queryContract {
		queryIds = buyIds
	}
	if len(queryIds) == 0 {
		empty = true
		return
	}
	for _, q := range queryIds {
		queryIdArr = append(queryIdArr, strconv.Itoa(q))
	}
	cond += ` AND a.company_id IN (` + strings.Join(queryIdArr, ",") + `) `
	return
}

// GetShareCompanyPermissionButton 正式客户共享-权限按钮
func GetShareCompanyPermissionButton(roleTypeCode, statuses string, productId int, item *company.CompanyItem, sysUser *system.Admin) (button *company.ButtonPermission) {
	statuses = strings.Replace(statuses, "(共享)", "", -1)
	statusMap := make(map[int]string)
	statusMap[productId] = statuses
	if strings.Contains(statuses, "/") {
		statusArr := strings.Split(statuses, "/")
		statusMap[1] = statusArr[0]
		statusMap[2] = statusArr[1]
	}
	//roleTypeCode, itemStatus, item.SellerIds, item.GroupIds, item.GroupId, sysUser.GroupId, item.SellerId, sysUser.AdminId, sysUser.Authority, item.ProductId, item.ShareSellerId

	//所属销售map
	sellerIdMap := make(map[int]string)
	sellerIdMap[productId] = item.SellerIds
	if strings.Contains(item.SellerIds, "/") {
		sellerIdSlice := strings.Split(item.SellerIds, "/")
		sellerIdMap[1] = sellerIdSlice[0]
		sellerIdMap[2] = sellerIdSlice[1]
	}

	//分组map
	groupIdMap := make(map[int]string)
	groupIdMap[productId] = item.GroupIds

	if strings.Contains(item.GroupIds, "/") {
		groupIdSlice := strings.Split(item.GroupIds, "/")
		groupIdMap[1] = groupIdSlice[0]
		groupIdMap[2] = groupIdSlice[1]
	}

	// 查看权限均有
	button = new(company.ButtonPermission)
	button.BtnView = true

	// 超管, FICC管理员
	if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN || roleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN || roleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
		button.BtnModifySeller = true
		button.BtnRemarkView = true
		button.BtnServiceRecord = true
	}

	//梁春悦、罗礼智的单独展示
	if sysUser.RoleName == "权益服务组长" || sysUser.RoleName == "权益销售组长（外部）" {
		button.BtnModifySeller = true
	}
	if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
		button.BtnModifySeller = false
	}
	status, _ := statusMap[1]
	//if !ok {
	//	return
	//}
	// 客户非关闭状态可见沟通记录按钮
	if status != utils.COMPANY_STATUS_CLOSE {
		button.BtnServiceRecord = true
	}

	// 销售
	sellerArr := []string{
		utils.ROLE_TYPE_CODE_FICC_GROUP, utils.ROLE_TYPE_CODE_FICC_TEAM, utils.ROLE_TYPE_CODE_FICC_SELLER,
		utils.ROLE_TYPE_CODE_RAI_GROUP, utils.ROLE_TYPE_CODE_RAI_SELLER, utils.ROLE_TYPE_CODE_RAI_ADMIN,
	}
	if !utils.InArrayByStr(sellerArr, roleTypeCode) {
		return
	}
	if status == utils.COMPANY_STATUS_TRY_OUT {
		button.BtnTurnPositive = true
		button.BtnRemarkEdit = true
		button.BtnRemarkView = true
		button.BtnServiceRecord = true
	}
	if status == utils.COMPANY_STATUS_FORMAL {
		button.BtnUpdate = true
		button.BtnAddAgreement = true
		button.BtnTryOut = true
		button.BtnRemarkEdit = true
		button.BtnRemarkView = true
		button.BtnServiceRecord = true
	}
	companyButton := GetCompanyPermissionButton(roleTypeCode, statuses, item.SellerIds, item.GroupIds, item.GroupId, sysUser.GroupId, item.SellerId, sysUser.AdminId, sysUser.Authority, item.ProductId, -1, item.ShareSellerIds)
	if companyButton.BtnShare == true {
		button.BtnShare = true
	}
	//备注与历史备注修改 CRM15.9.1
	button.BtnRemarkView = companyButton.BtnRemarkView

	if productId == 2 {
		button.BtnRemarkView = false
		button.BtnRemarkViewHistory = true
	}

	if utils.InArrayByStr([]string{utils.ROLE_TYPE_CODE_RAI_ADMIN, utils.ROLE_TYPE_CODE_RAI_SELLER, utils.ROLE_TYPE_CODE_RAI_GROUP}, roleTypeCode) {
		button.BtnServiceRecord = false //王芳，权益销售，权益销售组长，这三种身份看不到这个按钮
	}
	return
}

// 处理客户列表签约未签约状态回显
func GetLsitCompanyStatusButton(companyType, status, signingStatus string) (button *company.CompanyStatusButton) {
	var ficcStatus string
	var raiStatus string
	var ficcSigningStatus string
	var raiSigningStatus string
	if strings.Contains(status, "/") {
		//signingStatus 1；已签约，0：未签约 ，如果是 0的时候，表示两个都是未签约，手动改为 0/0 ,如果两个都是1 的时候展示 1 手动改为 1/1
		tmpStatusArr := strings.Split(status, "/")
		ficcStatus = tmpStatusArr[0]
		raiStatus = tmpStatusArr[1]
		if signingStatus == "0" {
			signingStatus = "0/0"
		} else if signingStatus == "1" {
			signingStatus = "1/1"
		}
		if strings.Contains(status, "/") {
			tmpSigningStatusArr := strings.Split(signingStatus, "/")
			ficcSigningStatus = tmpSigningStatusArr[0]
			raiSigningStatus = tmpSigningStatusArr[1]
		}
	} else {
		if strings.Contains(companyType, "ficc") {
			ficcStatus = status
			ficcSigningStatus = signingStatus
		} else {
			raiStatus = status
			raiSigningStatus = signingStatus
		}
	}

	if ficcStatus == utils.COMPANY_STATUS_LOSE {
		if ficcSigningStatus == "0" {
			ficcSigningStatus = "未签约过"
		} else if ficcSigningStatus == "1" {
			ficcSigningStatus = "已签约过"
		}
	} else {
		ficcSigningStatus = ""
	}

	if raiStatus == utils.COMPANY_STATUS_LOSE {
		if raiSigningStatus == "0" {
			raiSigningStatus = "未签约过"
		} else if raiSigningStatus == "1" {
			raiSigningStatus = "已签约过"
		}
	} else {
		raiSigningStatus = ""
	}

	button = new(company.CompanyStatusButton)
	button.FiccStatus = ficcStatus
	button.RaiStatus = raiStatus
	button.FiccSigningStatus = ficcSigningStatus
	button.RaiSigningStatus = raiSigningStatus
	return
}
