package controllers

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"github.com/tealeg/xlsx"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/advisory"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/company_user"
	"hongze/hz_crm_api/models/company_user/request"
	"hongze/hz_crm_api/models/company_user/response"
	"hongze/hz_crm_api/models/cygx"
	"hongze/hz_crm_api/models/system"
	"hongze/hz_crm_api/models/yb"
	"hongze/hz_crm_api/services"
	"hongze/hz_crm_api/services/alarm_msg"
	cygxService "hongze/hz_crm_api/services/cygx"
	"hongze/hz_crm_api/services/elastic"
	"hongze/hz_crm_api/utils"
	"os"
	"path"
	"path/filepath"
	"strconv"
	"strings"
	"time"
	"unicode/utf8"
)

// 客户联系人管理
type CompanyUserController struct {
	BaseAuthController
}

// @Title 新增客户联系人
// @Description 新增客户联系人接口
// @Param	request	body company.AddUserReq true "type json string"
// @router /user/add [post]
func (this *CompanyUserController) AddUser() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req company.AddUserReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.RealName == "" {
		br.Msg = "请填写姓名"
		br.IsSendEmail = false
		return
	}

	//空格移除
	req.MobileOne = utils.TrimStr(req.MobileOne)
	req.MobileTwo = utils.TrimStr(req.MobileTwo)
	req.Email = utils.TrimStr(req.Email)
	req.RealName = utils.TrimStr(req.RealName)
	//判断该手机号、邮箱是否已经添加，如果已经添加，那么就不再添加
	var key string
	if req.MobileOne != "" {
		key = "wx_user:mobile:" + req.MobileOne
	} else {
		key = "wx_user:email:" + req.Email
	}
	isHas := utils.Rc.IsExist(key)
	if isHas == true {
		br.Msg = "重复添加"
		return
	} else {
		//设置3分钟缓存，不允许重复添加
		utils.Rc.SetNX(key, 1, time.Second*300)

		//添加完成删除对应的缓存
		defer utils.Rc.Delete(key)
	}

	source := req.Source
	if source == "" {
		br.Msg = "没有来源"
		return
	}
	regionType := req.RegionType //区域来源
	productId := services.GetProductId(sysUser.RoleTypeCode)

	//操作员的产品权限
	companyProductList := make([]*company.CompanyProduct, 0)

	var companyInfo *company.Company
	var e error
	if req.CompanyId > 0 {
		companyInfo, e = company.GetCompanyById(req.CompanyId)
		if e != nil {
			br.Msg = "客户信息有误"
			br.ErrMsg = "获取客户信息失败, Err: " + e.Error()
			return
		}
	}

	//权益类客户，邮箱必填（2021-03-22 13:32:59修改）
	if productId == 1 || regionType == "国内" { //ficc类客户
		if req.MobileOne == "" && req.Email == "" {
			br.Msg = "请输入手机号或邮箱"
			br.IsSendEmail = false
			return
		}
	} else if productId == 2 { //权益类客户
		if req.MobileOne == "" {
			br.Msg = "请输入手机号"
			br.ErrMsg = "请输入手机号"
			br.IsSendEmail = false
			return
		}
		if req.Email == "" {
			br.Msg = "请输入邮箱"
			br.ErrMsg = "请输入邮箱"
			br.IsSendEmail = false
			return
		}
	} else {
		//如果是管理员账户，那么需要从企业信息里面去获取所属类型客户了
		//获取企业客户信息
		if req.Source == "add_custom" {
			//添加客户时新增联系人
		} else if req.Source == "pick_custom" {
			//领取客户时添加联系人
			br.ErrMsg = "管理员账户不允许领取客户"
			br.Msg = "来源异常"
			return
		} else if req.Source == "add_user" {
			//普通类型添加客户
			//companyInfo, err := company.GetCompanyById(req.CompanyId)
			//if err != nil {
			//	br.ErrMsg = "获取客户信息失败，Err:" + err.Error()
			//	br.Msg = "获取客户信息失败"
			//	return
			//}

			//手机号、邮箱校验（必填一个）
			if req.MobileOne == "" && req.Email == "" {
				br.Msg = "请输入手机号或邮箱"
				br.IsSendEmail = false
				return
			}
			//shareSellerId = companyInfo.ShareSellerId
			//获取当前操作员产品权限
			tmpCompanyProductList, productErr := getSysCompanyProductList(productId, req.CompanyId)
			if productErr != nil {
				br.Msg = "新增失败"
				br.ErrMsg = "新增失败，获取当前操作员产品权限异常,Err:" + productErr.Error()
				return
			}
			if tmpCompanyProductList == nil {
				br.Msg = "新增失败"
				br.ErrMsg = "新增失败，获取当前操作员找不到产品权限"
				return
			}
			for _, v := range tmpCompanyProductList {
				//权益（海外）客户，需要有提示
				if v.ProductId == 2 && companyInfo.RegionType == "海外" {
					if req.MobileOne == "" {
						br.Msg = "请输入手机号"
					}
					if req.Email == "" {
						br.Msg = "请输入邮箱"
						br.ErrMsg = "请输入邮箱"
						return
					}
				}
			}
			companyProductList = tmpCompanyProductList
		} else {
			br.ErrMsg = "来源异常"
			br.Msg = "来源异常"
			return
		}
	}

	if productId != 0 {
		if req.Source == "add_custom" {
			//添加客户时新增联系人
		} else if req.Source == "pick_custom" {
			//领取客户时添加联系人
			tmpCompanyProduct := &company.CompanyProduct{
				CompanyId:    req.CompanyId,
				ProductId:    productId,
				ProductName:  sysUser.RoleName,
				SellerId:     sysUser.AdminId,
				SellerName:   sysUser.RealName,
				GroupId:      sysUser.GroupId,
				DepartmentId: sysUser.DepartmentId,
			}
			companyProductList = append(companyProductList, tmpCompanyProduct)
		} else if req.Source == "add_user" {
			shareSellerId := 0
			if req.CompanyId > 0 {
				item, e := company.GetCompanyProductByCompanyIdAndProductId(req.CompanyId, productId)
				if e != nil {
					br.Msg = "客户信息有误"
					br.ErrMsg = "获取客户信息失败, Err: " + e.Error()
					return
				}
				shareSellerId = item.ShareSellerId
			}
			//获取当前操作员产品权限
			tmpCompanyProductList, productErr := getSysCompanyProductList(productId, req.CompanyId)
			if productErr != nil {
				br.Msg = "新增失败"
				br.ErrMsg = "新增失败，获取当前操作员产品权限异常,Err:" + productErr.Error()
				return
			}
			if tmpCompanyProductList == nil {
				br.Msg = "新增失败"
				br.ErrMsg = "新增失败，获取当前操作员找不到产品权限"
				return
			}
			companyProductList = tmpCompanyProductList

			//操作权限校验
			for _, v := range tmpCompanyProductList {
				companyUserStatus := services.CheckCompanyUserButton(sysUser.RoleTypeCode, v.SellerId, sysUser.AdminId, v.ProductId, shareSellerId, v.Status)
				if companyUserStatus == false {
					br.Msg = "没有操作权限"
					br.ErrMsg = "没有操作权限"
					br.IsSendEmail = false
					return
				}
			}
		}
	} else {
		//超管
		if req.Source != "add_custom" {
			//不是添加客户的时候添加的联系人
			tmpCompanyProductList, productErr := getSysCompanyProductList(productId, req.CompanyId)
			if productErr != nil {
				br.Msg = "新增失败"
				br.ErrMsg = "新增失败，获取当前操作员产品权限异常,Err:" + productErr.Error()
				return
			}
			if tmpCompanyProductList == nil {
				br.Msg = "新增失败"
				br.ErrMsg = "新增失败，获取当前操作员找不到产品权限"
				return
			}
			companyProductList = tmpCompanyProductList
		}
	}

	userCount, err := company.GetCompanyUserCount(req.CompanyId)
	if err != nil {
		br.Msg = "新增失败"
		br.ErrMsg = "判断联系人数量失败,Err:" + err.Error()
		return
	}

	if userCount == 0 {
		if req.BusinessCardUrl == "" {
			br.Msg = "请上传名片"
			br.IsSendEmail = false
			return
		}
	}

	//systemUser models.Company.CompanyUser
	//var sysemUser company.CompanyUser
	//校验主手机号
	if req.MobileOne != "" {
		mobileOneItem, err := company.GetUserCountByMobile(req.MobileOne)
		if err != nil && err.Error() == utils.ErrNoRow() {
			mobileOneItem, err = company.CheckCompanyUserCountByMobileTwo(req.MobileOne)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "新增失败"
				br.ErrMsg = "判断手机号1是否存在,Err:" + err.Error()
				return
			}
		}

		if mobileOneItem != nil {
			if mobileOneItem.UserId > 0 {
				//如果有传入客户编号，且客户编号与该查出来的用户编号一致的情况下
				if req.CompanyId > 0 {
					//获取联系人分组信息
					userSellerGroupInfo, err := models.GetUserGroupSellerByUserId(int(mobileOneItem.UserId))
					if err != nil && err.Error() != utils.ErrNoRow() {
						br.Msg = "查询信息异常"
						br.Success = true
						br.Data = mobileOneItem
						br.IsSendEmail = false
						br.Ret = 600
						return
					}

					if req.CompanyId == mobileOneItem.CompanyId {
						//如果是该客户下的用户，那么判断该用户与当前账号是否存在关系，如果没有关系，那么直接添加关系后直接返回
						if len(companyProductList) > 0 {
							isHas := checkUserSellerRelation(companyProductList, mobileOneItem, &req, br)
							if isHas == false {
								return
							}
						}

						//修改返回给前端用户的信息
						if userSellerGroupInfo != nil {
							mobileOneItem.SellerRealName = userSellerGroupInfo.SellerRealName
							mobileOneItem.Status = userSellerGroupInfo.Status
						}

						br.Msg = "手机号1已存在"
						br.Success = true
						br.Data = mobileOneItem
						br.IsSendEmail = false
						br.Ret = 600
						return
					} else {
						hasMove := true //是否可移动

						//如果是大于 1 的客户，那么就是非潜在客户，需要去查询对应的销售
						if mobileOneItem.CompanyId > 1 {
							//获取联系人分组信息
							userSellerGroupInfoList, err := models.GetUserGroupSellersByUserId(int(mobileOneItem.UserId))

							//根据分组校验
							if err == nil && len(userSellerGroupInfoList) > 0 {
								sellerMap := make(map[int]string)    //销售信息map
								sellerNameSlice := make([]string, 0) //销售姓名切片
								statusNameSlice := make([]string, 0) //客户状态姓名切片
								for _, v := range userSellerGroupInfoList {
									if v.Status != utils.COMPANY_STATUS_LOSE && v.Status != utils.COMPANY_STATUS_FOREVER && hasMove == true {
										hasMove = false
									}
									statusNameSlice = append(statusNameSlice, v.Status)
									if _, ok := sellerMap[v.SellerId]; ok {
										continue
									}
									sellerMap[v.SellerId] = v.SellerRealName
									sellerNameSlice = append(sellerNameSlice, v.SellerRealName)
								}
								mobileOneItem.SellerRealName = strings.Join(sellerNameSlice, "/")
								mobileOneItem.Status = strings.Join(statusNameSlice, "/")
							}
						}

						//是否可移动
						mobileOneItem.HasMove = hasMove

						br.Msg = "手机号1已存在"
						br.Success = true
						br.Data = mobileOneItem
						br.IsSendEmail = false
						br.Ret = 600
						return
					}
				} else {
					if strings.Contains(mobileOneItem.Status, "/") {
						if strings.Contains(mobileOneItem.Status, "正式") || strings.Contains(mobileOneItem.Status, "试用") {
							mobileOneItem.HasMove = false
						} else {
							mobileOneItem.HasMove = true
						}
					} else {
						if mobileOneItem.Status == utils.COMPANY_STATUS_FREEZE || //冻结
							mobileOneItem.Status == utils.COMPANY_STATUS_LOSE || //流失
							mobileOneItem.Status == utils.COMPANY_STATUS_POTENTIAL || //潜在
							mobileOneItem.Status == utils.COMPANY_STATUS_FOREVER { //永续
							mobileOneItem.HasMove = true
						}
					}
					br.Msg = "手机号1已存在"
					br.Success = true
					br.Data = mobileOneItem
					br.IsSendEmail = false
					br.Ret = 600
					return
				}
			}
		}
	}

	if req.Email != "" {
		emailItem, err := company.CheckCompanyUserCountByEmail(req.Email)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "新增失败"
			br.ErrMsg = "新增失败,Err:" + err.Error()
			return
		}

		if emailItem != nil {
			if emailItem.UserId > 0 {
				if req.CompanyId > 0 {
					//获取联系人分组信息
					userSellerGroupInfo, err := models.GetUserGroupSellerByUserId(int(emailItem.UserId))
					if err != nil && err.Error() != utils.ErrNoRow() {
						br.Msg = "查询信息异常"
						br.Success = true
						br.Data = emailItem
						br.IsSendEmail = false
						br.Ret = 600
						return
					}
					if req.CompanyId == emailItem.CompanyId {
						//如果是该客户下的用户，那么判断该用户与当前账号是否存在关系，如果没有关系，那么直接添加关系后直接返回
						if len(companyProductList) > 0 {
							isHas := checkUserSellerRelation(companyProductList, emailItem, &req, br)
							if isHas == false {
								return
							}
						}

						//修改返回给前端用户的信息
						if userSellerGroupInfo != nil {
							emailItem.SellerRealName = userSellerGroupInfo.SellerRealName
							emailItem.Status = userSellerGroupInfo.Status
						}

						br.Msg = "邮箱已存在"
						br.Success = true
						br.Data = emailItem
						br.IsSendEmail = false
						br.Ret = 600
						return
					} else {
						hasMove := true //是否可移动

						//如果是大于 1 的客户，那么就是非潜在客户，需要去查询对应的销售
						if emailItem.CompanyId > 1 {
							//获取联系人分组信息
							userSellerGroupInfoList, err := models.GetUserGroupSellersByUserId(int(emailItem.UserId))

							//根据分组校验
							if err == nil && len(userSellerGroupInfoList) > 0 {
								sellerMap := make(map[int]string)    //销售信息map
								sellerNameSlice := make([]string, 0) //销售姓名切片
								statusNameSlice := make([]string, 0) //客户状态姓名切片
								for _, v := range userSellerGroupInfoList {
									if v.Status != utils.COMPANY_STATUS_LOSE && v.Status != utils.COMPANY_STATUS_FOREVER && hasMove == true {
										hasMove = false
									}
									statusNameSlice = append(statusNameSlice, v.Status)
									if _, ok := sellerMap[v.SellerId]; ok {
										continue
									}
									sellerMap[v.SellerId] = v.SellerRealName
									sellerNameSlice = append(sellerNameSlice, v.SellerRealName)
								}
								emailItem.SellerRealName = strings.Join(sellerNameSlice, "/")
								emailItem.Status = strings.Join(statusNameSlice, "/")
							}
						}
						//是否可移动
						emailItem.HasMove = hasMove

						br.Msg = "邮箱已存在"
						br.Success = true
						br.Data = emailItem
						br.IsSendEmail = false
						br.Ret = 600
						return
					}
				} else {
					if strings.Contains(emailItem.Status, "/") {
						if strings.Contains(emailItem.Status, "正式") || strings.Contains(emailItem.Status, "试用") {
							emailItem.HasMove = false
						} else {
							emailItem.HasMove = true
						}
					} else {
						if emailItem.Status == utils.COMPANY_STATUS_FREEZE || //冻结
							emailItem.Status == utils.COMPANY_STATUS_LOSE || //流失
							emailItem.Status == utils.COMPANY_STATUS_POTENTIAL || //潜在
							emailItem.Status == utils.COMPANY_STATUS_FOREVER { //永续
							emailItem.HasMove = true
						}
					}
					br.Msg = "邮箱已存在"
					br.Success = true
					br.Data = emailItem
					br.IsSendEmail = false
					br.Ret = 600
					return
				}
			}
		}
	}

	//if req.BusinessCardUrl != "" && utils.RunMode == "release" {
	if req.BusinessCardUrl != "" {
		// 获取图片识别客户名称的配置
		crmConfig, err := company.GetConfigDetailByCode("card_recognition_company_name")
		if err != nil {
			br.Msg = "获取配置失败"
			br.ErrMsg = "获取配置失败"
			br.IsSendEmail = false
			return
		}
		// 获取图片识别手机号的配置
		crmConfig2, err := company.GetConfigDetailByCode("card_recognition_tel")
		if err != nil {
			br.Msg = "获取配置失败"
			br.ErrMsg = "获取配置失败"
			br.IsSendEmail = false
			return
		}
		if crmConfig.ConfigValue == "true" || crmConfig2.ConfigValue == "true" {
			companyName := req.CompanyName
			if companyName == "" {
				companyInfo, err := company.GetCompanyById(req.CompanyId)
				if err != nil {
					br.Msg = "查找客户失败"
					br.ErrMsg = "查找客户失败,err:" + err.Error()
					return
				}
				companyName = companyInfo.CompanyName
			}
			companyName = utils.TrimStr(companyName)
			tmpCompanyNameList, err := elastic.Analyze(companyName)
			if err != nil {
				br.Msg = "添加失败"
				br.ErrMsg = "客户名称分词失败,Err:" + err.Error()
				return
			}
			//公司名称切片
			analyzeNameList := []string{companyName}
			for _, v := range tmpCompanyNameList {
				if v == "" {
					continue
				}
				ignoreStrs := []string{"", "有限", "投资", "资本", "管理", "贸易", "资产", "公司", "股份", "集团", "有限公司"}
				if !strings.Contains(strings.Join(ignoreStrs, ","), v) && utf8.RuneCount([]byte(v)) > 1 {
					//不在上面的过滤字里面，且切出来的字符大于1位
					analyzeNameList = append(analyzeNameList, v)
				}
			}

			//名片识别出来的客户名称切片
			companyNameSlice := make([]string, 0)
			card, err := services.GetBusinessCard(req.BusinessCardUrl)
			if err != nil {
				br.Msg = "名片识别失败"
				br.ErrMsg = "名片识别失败,Err:" + err.Error()
				return
			}
			//if card.Errno != 0 {
			//	br.Msg = "您上传了非名片图片，请重新上传"
			//	br.ErrMsg = "名片识别失败,ErrMsg:" + card.ErrorMsg + ";errCode:" + strconv.Itoa(card.Errno)
			//	return
			//}
			//var mobileStr string
			//for _, v := range card.WordsResult {
			//	mobileStr += v.Words + ","
			//}
			isFlag := false
			if len(card.WordsResult.MOBILE) > 0 {
				mobileStr := strings.Join(card.WordsResult.MOBILE, ",")
				//if req.MobileOne != "" {
				//	if strings.Contains(mobileStr, req.MobileOne) || mobileStr == "" {
				//		isFlag = true
				//	} else {
				//		isFlag = false
				//	}
				//}
				//
				//if isFlag == false && req.MobileTwo != "" {
				//	if strings.Contains(mobileStr, req.MobileTwo) {
				//		isFlag = true
				//	} else {
				//		isFlag = false
				//	}
				//}
				if req.MobileOne != "" && strings.Contains(mobileStr, req.MobileOne) {
					isFlag = true
				}
				if req.MobileTwo != "" && strings.Contains(mobileStr, req.MobileTwo) {
					isFlag = true
				}
				//如果百度识别出来了客户名称，那么将识别出来的客户名称添加到待校验客户名称切片中
				if len(card.WordsResult.COMPANY) > 0 && card.WordsResult.COMPANY[0] != "" {
					companyNameSlice = card.WordsResult.COMPANY
				}
			}
			//如果百度未识别出来手机号或者公司名称，那么进行阿里识别
			if !isFlag || (len(companyNameSlice) == 0 && crmConfig.ConfigValue == "true") {
				//阿里云识别
				aliyunResult, errMsg, err := services.AliyunOcrBusinessCard(req.BusinessCardUrl)
				if err != nil {
					br.Msg = "识别失败"
					br.ErrMsg = "识别失败,Err:" + err.Error()
					return
				}
				if !aliyunResult.Success {
					br.Msg = "识别失败"
					br.ErrMsg = "识别失败"
					return
				}
				if errMsg != "" {
					br.Msg = errMsg
					return
				}
				//如果百度没有识别出来手机号，那么还需要阿里识别出来的手机号校验下
				if !isFlag {
					if len(aliyunResult.TelCell) > 0 {
						mobileStr := strings.Join(aliyunResult.TelCell, ",")
						if req.MobileOne != "" {
							if strings.Contains(mobileStr, req.MobileOne) {
								isFlag = true
							} else {
								isFlag = false
							}
						}
					} else {
						isFlag = true
					}
				}
				//如果阿里云识别出来了客户名称，那么将识别出来的客户名称添加到待校验客户名称切片中
				if len(aliyunResult.Company) > 0 {
					companyNameSlice = append(companyNameSlice, aliyunResult.Company...)
				}
			}

			if !isFlag && crmConfig2.ConfigValue == "true" {
				br.Msg = "名片信息与联系人手机号不符"
				br.IsSendEmail = false
				return
			}

			//校验识别出来的名片名称与传入的客户名称是否一致
			if len(companyNameSlice) > 0 && crmConfig.ConfigValue == "true" {
				isCompanyNameFlag := false //是否成功匹配客户名称
				//遍历识别出来的客户名称，然后与系统的客户名称做匹配（识别出来的名称包含系统名称的话，那么标记成功匹配）
				for _, tmpCompanyName := range companyNameSlice {
					//空串不处理
					if companyName == "" {
						continue
					}
					for _, analyzeName := range analyzeNameList {
						//如果分词出来的公司名称正好在识别出来的公司名称里面，那么就认为校验通过了
						if strings.Contains(tmpCompanyName, analyzeName) {
							isCompanyNameFlag = true
							break
						}
					}

					if isCompanyNameFlag {
						break
					}

				}
				//如果没有匹配到客户名称，那么就返回报错
				if !isCompanyNameFlag {
					br.Msg = "名片信息与公司名称不符"
					br.IsSendEmail = false
					return
				}
			}
		}
	}
	user := new(models.WxUser)
	user.RealName = utils.TrimStr(req.RealName)
	user.Sex = req.Sex
	user.CountryCode = utils.TrimStr(req.CountryCode)
	user.Mobile = utils.TrimStr(req.MobileOne)
	user.OutboundCountryCode = utils.TrimStr(req.CountryCode)
	user.OutboundMobile = utils.TrimStr(req.MobileOne)
	user.MobileTwo = utils.TrimStr(req.MobileTwo)
	user.Email = utils.TrimStr(req.Email)
	user.Position = req.Position
	user.IsMaker = req.IsMaker
	user.BusinessCardUrl = req.BusinessCardUrl
	user.CompanyId = req.CompanyId
	if req.CompanyId == 0 {
		user.CompanyId = 1
	}
	user.DepartmentName = req.DepartmentName
	user.CreatedTime = time.Now()
	//user.RegisterTime = time.Now()
	user.RegisterPlatform = 3

	newId, err := models.AddWxUser(user)
	user.UserId = newId
	if err != nil {
		br.Msg = "新增失败"
		br.ErrMsg = "新增失败,Err:" + err.Error()
		return
	}
	//如果有传入企业编号，那么需要将该联系人与销售员做绑定
	if len(companyProductList) > 0 {
		for _, companyProduct := range companyProductList {
			models.AddUserSellerRelation(newId, companyProduct.CompanyId, companyProduct.SellerId, companyProduct.ProductId, companyProduct.SellerName, req.MobileOne, req.Email)
		}
	}

	//更新客户最近阅读次数以及最近阅读时间
	go services.ModifyCompanyProductLastViewData([]int{req.CompanyId})

	//联系人信息
	userInfo, _ := json.Marshal(user)
	go services.AddWxUserOpLog(company.WxUserOpLog{
		LogType:                "add",
		UserId:                 int(user.UserId),
		CompanyId:              user.CompanyId,
		Mobile:                 user.Mobile,
		Email:                  user.Email,
		OriginalUserInfo:       "",
		UserInfo:               string(userInfo),
		OriginalUserSellerInfo: "",
		UserSellerInfo:         "",
		OpUserId:               sysUser.AdminId,
		OpUserName:             sysUser.RealName,
		CreateTime:             time.Now(),
	})

	br.Ret = 200
	br.Success = true
	br.Msg = "新增成功"
	br.Data = newId
	br.IsAddLog = true
}

// 获取当前操作员产品权限（所有产品数据）
func getSysCompanyProductList(productId, companyId int) (companyProduct []*company.CompanyProduct, err error) {
	if productId == 0 {
		tmpCompanyProduct, productErr := company.GetCompanyProductByCompanyIdAndProductId(companyId, 1)
		if productErr != nil && productErr.Error() != utils.ErrNoRow() {
			//sql异常
			err = productErr
			return
		}
		if tmpCompanyProduct != nil {
			companyProduct = append(companyProduct, tmpCompanyProduct)
		}

		tmpCompanyProduct, productErr = company.GetCompanyProductByCompanyIdAndProductId(companyId, 2)
		if productErr != nil && productErr.Error() != utils.ErrNoRow() {
			//sql异常
			err = productErr
			return
		}
		if tmpCompanyProduct != nil {
			companyProduct = append(companyProduct, tmpCompanyProduct)
		}
	} else {
		tmpCompanyProduct, productErr := company.GetCompanyProductByCompanyIdAndProductId(companyId, productId)
		if productErr != nil && productErr.Error() != utils.ErrNoRow() {
			//sql异常
			err = productErr
			return
		}
		if tmpCompanyProduct != nil {
			companyProduct = append(companyProduct, tmpCompanyProduct)
		}
	}
	return
}

// 校验用户与销售信息
func checkUserSellerRelation(companyProductList []*company.CompanyProduct, companyUser *company.CompanyUser, req *company.AddUserReq, br *models.BaseResponse) (isHas bool) {
	for _, companyProduct := range companyProductList {
		_, relationErr := models.GetUserSellerRelation(companyUser.UserId, companyProduct.SellerId)

		//找到数据了
		if relationErr == nil {
			isHas = true
			continue
		}

		//没找到数据，不存在关系
		//如果不存在关系，那么直接添加关系就好了，其他操作不做
		if relationErr.Error() == utils.ErrNoRow() {
			//添加用户与联系人的关系
			models.AddUserSellerRelation(companyUser.UserId, companyProduct.CompanyId, companyProduct.SellerId, companyProduct.ProductId, companyProduct.SellerName, companyUser.Mobile, companyUser.Email)
		} else {
			//sql异常
			br.Msg = "新增失败"
			br.ErrMsg = "判断手机号或邮箱是否存在关联关系,Err:" + relationErr.Error()
			return
		}

		//对老数据做字段数据新增处理，如果该字段已有数据则不做处理start
		{
			mobileOne := companyUser.Mobile
			mobileTwo := companyUser.MobileTwo
			email := companyUser.Email
			businessCardUrl := companyUser.BusinessCardUrl

			if req.MobileOne != "" && companyUser.Mobile == "" {
				mobileOne = utils.TrimStr(req.MobileOne)
			}
			if req.MobileTwo != "" && companyUser.MobileTwo == "" {
				mobileTwo = utils.TrimStr(req.MobileTwo)
			}
			if req.Email != "" && companyUser.Email == "" {
				email = utils.TrimStr(req.Email)
			}
			if req.BusinessCardUrl != "" && companyUser.BusinessCardUrl == "" {
				businessCardUrl = strings.Replace(req.BusinessCardUrl, " ", "", -1)
			}
			_ = company.EditCompanyUserContact(companyUser.UserId, mobileOne, mobileTwo, email, businessCardUrl)
		}
		//对老数据做字段数据新增处理，如果该字段已有数据则不做处理start

		br.Ret = 200
		br.Success = true
		br.Msg = "新增成功"
		br.Data = companyUser.UserId
		return
	}
	return
}

// List
// @Title 联系人列表
// @Description 联系人列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   CompanyId   query   int  true       "公司id，必填"
// @Param   KeyWord   query   string  true       "搜索关键词"
// @Param   ProductType   query   int  true       "产品类型"
// @Param   ProductId   query   int  true       "产品id"
// @Param   IsSubscribe   query   int  true       "是否关注了公众号: -1-默认全部; 0-未关注; 1-已关注"
// @Param   IsSubscribeHzyj   query   int  true       "是否关注了弘则研究公众号: -1-默认全部; 0-未关注; 1-已关注"
// @Param   IsSubscribeCygx   query   int  true       "是否关注了查研观向小助手公众号: -1-默认全部; 0-未关注; 1-已关注"
// @Success 200 {object} company.CompanyUserListResp
// @router /user/list [get]
func (this *CompanyUserController) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	companyId, _ := this.GetInt("CompanyId")
	keyWord := utils.TrimStr(this.GetString("KeyWord"))
	productType, _ := this.GetInt("ProductType")
	ybProductId, _ := this.GetInt("ProductId")
	isSubscribe, _ := this.GetInt("IsSubscribe", -1)
	isSubscribeHzyj, _ := this.GetInt("IsSubscribeHzyj", -1)
	isSubscribeCygx, _ := this.GetInt("IsSubscribeCygx", -1)

	// 默认是问答社区
	if productType <= 0 {
		productType = 3
	}

	if companyId <= 0 {
		br.Msg = "请选择客户"
		br.ErrMsg = "客户参数错误"
		return
	}
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	var condition string
	var pars []interface{}

	if keyWord != "" {
		condition += ` AND (a.real_name LIKE '%` + keyWord + `%' OR a.mobile LIKE '%` + keyWord + `%' OR a.email LIKE '%` + keyWord + `%') `
	}
	// 是否关注公众号
	if isSubscribe == 0 {
		condition += ` AND (c.subscribe = 0 OR ISNULL(c.subscribe)) `
	}
	if isSubscribe == 1 {
		condition += ` AND c.subscribe = 1 `
	}

	// 是否关注弘则研究公众号
	if isSubscribeHzyj == 0 {
		condition += ` AND (c.subscribe = 0 OR ISNULL(c.subscribe)) `
	}
	if isSubscribeHzyj == 1 {
		condition += ` AND c.subscribe = 1 `
	}

	// 是否关注弘则研究公众号
	if isSubscribeCygx == 0 {
		condition += ` AND (a.cygx_subscribe = 0 OR ISNULL(a.cygx_subscribe)) `
	}
	if isSubscribeCygx == 1 {
		condition += ` AND a.cygx_subscribe = 1 `
	}

	//非管理员，那么只能看到该产品下的联系人
	if sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_ADMIN {
		productId := services.GetProductId(sysUser.RoleTypeCode)
		condition += ` AND b.product_id = ? `
		pars = append(pars, productId)

		//流失客户（除非是超级管理员或者是部门管理员，要不然不允许看对应的联系人）
		//var companyProduct *company.CompanyProduct
		//当前是ficc权限，且非ficc管理员
		//if productId == 1 && sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_FICC_ADMIN {
		//	tmpCompanyProduct, _ := company.GetCompanyProductByCompanyIdAndProductId(companyId, 1)
		//	companyProduct = tmpCompanyProduct
		//}

		//权益销售查看流失客户时，可以看到非本人名下流失客户的联系人需求池 930 2024-03-25
		//if productId == 2 && sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_RAI_ADMIN {
		//	// 当前是权益权限，且非 权益管理员
		//	tmpCompanyProduct, _ := company.GetCompanyProductByCompanyIdAndProductId(companyId, 2)
		//	companyProduct = tmpCompanyProduct
		//	if companyProduct != nil && companyProduct.Status == utils.COMPANY_STATUS_LOSE {
		//		condition += ` AND seller_id=? `
		//		pars = append(pars, sysUser.AdminId)
		//	}
		//}
	}

	total, err := company.GetCompanyUserListCountV2(condition, pars, companyId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据总数失败，Err:" + err.Error()
		return
	}

	list, err := company.GetCompanyUserListV2(condition, pars, companyId, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	//获取企业客户信息
	companyInfo, err := company.GetCompanyById(companyId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取客户信息失败，Err:" + err.Error()
		return
	}

	lenList := len(list)
	if lenList > 0 {
		userIdSlice := make([]string, 0)
		mobilesSlice := make([]string, 0)
		emailsSlice := make([]string, 0)
		userIds := make([]int, 0)
		for _, v := range list {
			userIdSlice = append(userIdSlice, strconv.Itoa(int(v.UserId)))
			userIds = append(userIds, int(v.UserId))
			if v.Mobile != "" {
				mobilesSlice = append(mobilesSlice, v.Mobile)
			} else if v.Email != "" {
				emailsSlice = append(emailsSlice, v.Email)
			}
		}

		//用户浏览数据
		userIdStr := strings.Join(userIdSlice, ",")
		mobileStr := strings.Join(mobilesSlice, "','")
		mobileStr = "'" + mobileStr + "'"
		emailStr := strings.Join(emailsSlice, "','")
		emailStr = "'" + emailStr + "'"

		//userViewTotalList, _ := models.GetCountUserViewHistoryByUserIds(userIdStr)
		//userViewTotalMap := make(map[int]*models.UserViewTotalSlice)
		//for _, userView := range userViewTotalList {
		//	userViewTotalMap[userView.UserId] = userView
		//}

		//用户日评浏览数据
		//userReportViewTotalList, _ := models.GetReportViewMaxTimeByUserIds(userIdStr)
		//userReportViewTotalMap := make(map[int]*models.ReportViewRecord)
		//for _, userReportView := range userReportViewTotalList {
		//	userReportViewTotalMap[userReportView.UserId] = userReportView
		//}

		//报告统计删除晨报部分统计加入每日资讯 2021-4-9
		////手机号
		//userViewMobileTotalMap := make(map[string]*models.UserViewMobileTotalSlice)
		//userReportViewMobileTotalMap := make(map[string]*models.ReportViewMobileRecord)
		//userAdvisoryViewMobileTotalMap := make(map[string]*advisory.UserViewMobileTotalSlice)
		//userCygxArticleHistoryRecordViewMobileTotalMap := make(map[string]*models.UserViewMobileTotalSlice)
		//if len(mobilesSlice) > 0 {
		//	//用户浏览数据
		//	userViewMobileTotalList, _ := models.GetCountUserViewHistoryByMobiles(mobileStr)
		//	for _, userViewMobile := range userViewMobileTotalList {
		//		userViewMobileTotalMap[userViewMobile.Mobile] = userViewMobile
		//	}
		//
		//	//每日点评手机号数据
		//	userReportViewMobileTotalList, _ := models.GetReportViewMaxTimeByMobiles(mobileStr)
		//	for _, userReportViewMobile := range userReportViewMobileTotalList {
		//		userReportViewMobileTotalMap[userReportViewMobile.Mobile] = userReportViewMobile
		//	}
		//
		//	//每日资讯
		//	userAdvisoryViewMobileTotalList, _ := advisory.GetCountUserViewHistoryByMobiles(mobileStr)
		//	//fmt.Println(userAdvisoryViewMobileTotalList)
		//	for _, userAdvisoryViewMobile := range userAdvisoryViewMobileTotalList {
		//		userAdvisoryViewMobileTotalMap[userAdvisoryViewMobile.Mobile] = userAdvisoryViewMobile
		//	}
		//	//查研观向
		//	userCygxArticleHistoryRecordViewMobileTotalList, _ := models.GetCountCygxArticleHistoryRecordByMobiles(mobileStr)
		//	for _, userCygxArticleHistoryRecordViewMobile := range userCygxArticleHistoryRecordViewMobileTotalList {
		//		userCygxArticleHistoryRecordViewMobileTotalMap[userCygxArticleHistoryRecordViewMobile.Mobile] = userCygxArticleHistoryRecordViewMobile
		//	}
		//}

		////邮箱
		//userViewEmailTotalMap := make(map[string]*models.UserViewEmailTotalSlice)
		//userReportViewEmailTotalMap := make(map[string]*models.ReportViewEmailRecord)
		//userAdvisoryViewEmailTotalMap := make(map[string]*advisory.UserViewEmailTotalSlice)
		//userCygxViewEmailTotalMap := make(map[string]*models.UserViewEmailTotalSlice)
		//if len(emailsSlice) > 0 {
		//	//用户浏览数据
		//	userViewEmailTotalList, _ := models.GetCountUserViewHistoryByEmails(emailStr)
		//	for _, userViewEmail := range userViewEmailTotalList {
		//		userViewEmailTotalMap[userViewEmail.Email] = userViewEmail
		//	}
		//	//每日点评手机号数据
		//	userReportViewEmailTotalList, _ := models.GetReportViewMaxTimeByEmails(emailStr)
		//	for _, userReportViewEmail := range userReportViewEmailTotalList {
		//		userReportViewEmailTotalMap[userReportViewEmail.Email] = userReportViewEmail
		//	}
		//	//每日资讯
		//	userAdvisoryViewEmailTotalList, _ := advisory.GetCountUserViewHistoryByEmails(emailStr)
		//	for _, userAdvisoryViewEmail := range userAdvisoryViewEmailTotalList {
		//		userAdvisoryViewEmailTotalMap[userAdvisoryViewEmail.Email] = userAdvisoryViewEmail
		//	}
		//	//查研观向
		//	userCygxViewEmailTotalList, _ := models.GetCountCygxArticleHistoryRecordByEmails(emailStr)
		//	for _, userCygxReportViewEmail := range userCygxViewEmailTotalList {
		//		userCygxViewEmailTotalMap[userCygxReportViewEmail.Email] = userCygxReportViewEmail
		//	}
		//}

		//获取联系人关联产品的条数
		userSellerRelationTotalSlice, err := models.GetUserSellerRelationCountByUserIds(userIdStr)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取联系人与销售员信息失败，Err:" + err.Error()
			return
		}
		userSellerRelationTotalMap := make(map[int]*models.UserSellerRelationSlice)
		for _, userSellerRelationTotal := range userSellerRelationTotalSlice {
			userSellerRelationTotalMap[userSellerRelationTotal.UserId] = userSellerRelationTotal
		}
		userRecordRegisterMap := make(map[int]time.Time)
		if len(userIdSlice) > 0 {
			//用户绑定注册数据
			userRecordRegisterList, _ := models.GetUserRecordRegisterByUserIds(userIdStr)
			for _, userRecordRegister := range userRecordRegisterList {
				userRecordRegisterMap[userRecordRegister.UserId] = userRecordRegister.CreateTime
			}
		}

		// 用户图表权限设置信息
		userChartPermissionMap := make(map[int]*company_user.ChartClassifyPermission)
		userChartPermissionList, err := company_user.GetChartClassifyPermissionListByUserIds(userIdStr)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取联系人图表权限信息失败, Err:" + err.Error()
			return
		}
		for i := 0; i < len(userChartPermissionList); i++ {
			userChartPermissionMap[userChartPermissionList[i].UserId] = userChartPermissionList[i]
		}

		// 获取admin列表-匹配联系人是否为admin用户
		sysUserList, err := system.GetAdminList()
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取admin列表失败, Err:" + err.Error()
			return
		}
		sysUserMobileMap := make(map[string]int, 0)
		for i := 0; i < len(sysUserList); i++ {
			sysUserMobile := sysUserList[i].Mobile
			if sysUserMobile != "" {
				sysUserMobileMap[sysUserList[i].Mobile] = 1
			}
		}

		// 获取研报分产品统计
		//ybViewsList, e := yb.GetCompanyUserYbProductVisitCount(userIds)
		ybViewsList, e := yb.GetCompanyUserYbProductVisitCountByProductType(userIds, productType, ybProductId)
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取分产品阅读统计失败, Err:" + e.Error()
			return
		}
		userYbViewsMap := make(map[int]int)
		for _, v := range ybViewsList {
			userYbViewsMap[v.UserId] = v.VisitCount
		}

		for i := 0; i < lenList; i++ {
			item := list[i]
			//企业名称
			list[i].CompanyName = companyInfo.CompanyName

			if item.OpenId != "" {
				list[i].IsRegister = true
			} else {
				if item.RegisterPlatform == 2 {
					if item.Mobile != "" || item.Email != "" {
						list[i].IsRegister = true
					}
				} else if item.RegisterTime != "" {
					list[i].IsRegister = true
				} else {
					list[i].IsRegister = false
				}
			}

			////手机号用户累计浏览次数
			//if userView, ok := userViewMobileTotalMap[item.Mobile]; ok {
			//	list[i].ViewTotal += userView.Total
			//	if userView.CreatedTime.After(list[i].LastViewTime) {
			//		list[i].LastViewTime = userView.CreatedTime
			//		list[i].LastViewTimeStr = userView.CreatedTime.Format(utils.FormatDateTime)
			//	}
			//}
			////邮箱用户累计浏览次数
			//if userView, ok := userViewEmailTotalMap[item.Email]; ok {
			//	//总共浏览的报表数据需要调整为（手机号用户浏览晨报数+邮箱号用户浏览晨报数）
			//	list[i].ViewTotal += userView.Total
			//	if userView.CreatedTime.After(list[i].LastViewTime) {
			//		list[i].LastViewTime = userView.CreatedTime
			//		list[i].LastViewTimeStr = userView.CreatedTime.Format(utils.FormatDateTime)
			//	}
			//}
			////如果存在手机号用户日评数据，那么需要做处理
			//if reportView, ok := userReportViewMobileTotalMap[item.Mobile]; ok {
			//	//对日评数据做校验，日评时间晚于晨报时间，那么将最近一次浏览时间替换
			//	if reportView.LastViewTime.After(list[i].LastViewTime) {
			//		list[i].LastViewTime = reportView.LastViewTime
			//		list[i].LastViewTimeStr = reportView.LastViewTime.Format(utils.FormatDateTime)
			//	}
			//	//总共浏览的报表数据需要调整为（浏览晨报数+浏览日评数）
			//	list[i].ViewTotal += reportView.ViewTotal
			//}
			////如果存在手机号用户日评数据，那么需要做处理
			//if reportView, ok := userReportViewEmailTotalMap[item.Email]; ok {
			//	//对日评数据做校验，日评时间晚于晨报时间，那么将最近一次浏览时间替换
			//	if reportView.LastViewTime.After(list[i].LastViewTime) {
			//		list[i].LastViewTime = reportView.LastViewTime
			//		list[i].LastViewTimeStr = reportView.LastViewTime.Format(utils.FormatDateTime)
			//	}
			//	//总共浏览的报表数据需要调整为（浏览晨报数+浏览日评数）
			//	list[i].ViewTotal += reportView.ViewTotal
			//}
			//
			////如果存在手机号用户每日资讯，那么需要做处理
			//if advisoryView, ok := userAdvisoryViewMobileTotalMap[item.Mobile]; ok {
			//	//fmt.Println("蝴蝶眨几次眼睛")
			//	//对每日资讯数据做校验，每日资讯时间晚日评报时间，那么将最近一次浏览时间替换
			//	if advisoryView.CreatedTime.After(list[i].LastViewTime) {
			//		list[i].LastViewTime = advisoryView.CreatedTime
			//		list[i].LastViewTimeStr = advisoryView.CreatedTime.Format(utils.FormatDateTime)
			//	}
			//	//总共浏览的报表数据需要调整为（浏览晨报数+浏览日评数+每日资讯数）
			//	list[i].ViewTotal += advisoryView.Total
			//}
			////如果存在邮箱号用户每日资讯，那么需要做处理
			//if advisoryView, ok := userAdvisoryViewEmailTotalMap[item.Email]; ok {
			//	//对每日资讯数据做校验，每日资讯时间晚日评报时间，那么将最近一次浏览时间替换
			//	if advisoryView.CreatedTime.After(list[i].LastViewTime) {
			//		list[i].LastViewTime = advisoryView.CreatedTime
			//		list[i].LastViewTimeStr = advisoryView.CreatedTime.Format(utils.FormatDateTime)
			//	}
			//	//总共浏览的报表数据需要调整为（浏览晨报数+浏览日评数+每日资讯数）
			//	list[i].ViewTotal += advisoryView.Total
			//}
			//
			////如果存在手机号用户查研观向，那么需要做处理
			//if cygxView, ok := userCygxArticleHistoryRecordViewMobileTotalMap[item.Mobile]; ok {
			//	//对每日资讯数据做校验，每日资讯时间晚日评报时间，那么将最近一次浏览时间替换
			//	if cygxView.CreatedTime.After(list[i].LastViewTime) {
			//		list[i].LastViewTime = cygxView.CreatedTime
			//		list[i].LastViewTimeStr = cygxView.CreatedTime.Format(utils.FormatDateTime)
			//	}
			//	//总共浏览的报表数据需要调整为（浏览晨报数+浏览日评数+每日资讯数+查研观向）
			//	list[i].ViewTotal += cygxView.Total
			//}
			////如果存在邮箱号用户查研观向，那么需要做处理
			//if cygxView, ok := userCygxViewEmailTotalMap[item.Email]; ok {
			//	//对每日资讯数据做校验，每日资讯时间晚日评报时间，那么将最近一次浏览时间替换
			//	if cygxView.CreatedTime.After(list[i].LastViewTime) {
			//		list[i].LastViewTime = cygxView.CreatedTime
			//		list[i].LastViewTimeStr = cygxView.CreatedTime.Format(utils.FormatDateTime)
			//	}
			//	//总共浏览的报表数据需要调整为（浏览晨报数+浏览日评数+每日资讯数+查研观向）
			//	list[i].ViewTotal += cygxView.Total
			//}
			///*if reportView, ok := userReportViewTotalMap[int(item.UserId)]; ok {
			//	//对日评数据做校验，日评时间晚于晨报时间，那么将最近一次浏览时间替换
			//	if reportView.LastViewTime.After(list[i].LastViewTime) {
			//		list[i].LastViewTime = reportView.LastViewTime
			//		list[i].LastViewTimeStr = reportView.LastViewTime.Format(utils.FormatDateTime)
			//	}
			//	//总共浏览的报表数据需要调整为（浏览晨报数+浏览日评数）
			//	list[i].ViewTotal += reportView.ViewTotal
			//}*/

			list[i].ViewTotal = list[i].FiccViewTotal + list[i].RaiViewTotal
			var tmpLastViewTime time.Time
			tmpLastViewTime = list[i].FiccLastViewTime

			if !list[i].RaiLastViewTime.IsZero() {
				if tmpLastViewTime.IsZero() || list[i].RaiLastViewTime.After(tmpLastViewTime) {
					tmpLastViewTime = list[i].RaiLastViewTime
				}
			}

			list[i].LastViewTime = tmpLastViewTime
			if !tmpLastViewTime.IsZero() {
				list[i].LastViewTimeStr = tmpLastViewTime.Format(utils.FormatDateTime)
			}

			if list[i].LastViewTime.Before(time.Now().AddDate(0, 0, -7)) && list[i].IsFollow == 1 {
				list[i].NotRead = true
			}

			//如果有绑定数据，那么将数据返回对应的注册绑定数据
			if _, ok := userRecordRegisterMap[int(item.UserId)]; ok {
				list[i].IsRegister = true
				//list[i].RegisterTime = userRecordRegisterTime.Format(utils.FormatDateTime)
			}
			//是否共享联系人
			if userSellerRelationTotal, ok := userSellerRelationTotalMap[int(item.UserId)]; ok {
				//条数大于1，代表这是共享联系人
				//if userSellerRelationTotal.Total > 1 {
				//	list[i].IsShared = true
				//}
				list[i].ProductIds = userSellerRelationTotal.ProductIds
			}

			// 图表权限
			if _, isAdmin := sysUserMobileMap[list[i].Mobile]; isAdmin {
				list[i].IsChartPermissionSetting = 2
			} else {
				if _, ok := userChartPermissionMap[int(item.UserId)]; ok {
					list[i].IsChartPermissionSetting = 1
				}
			}
			// 分产品阅读统计
			list[i].YbProductViewTotal = userYbViewsMap[int(item.UserId)]
			//list[i].LastViewTimeStr = list[i].RaiLastViewTime.Format(utils.FormatDateTime)
		}

		isUserYanXuanButtonShow, err := services.CheckCompanyUserYanXuanButton(sysUser.RoleTypeCode, sysUser.Mobile)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败 CheckCompanyUserYanXuanButton ，Err:" + err.Error()
			return
		}

		if isUserYanXuanButtonShow {
			userYanxuanPermissionMap := cygxService.GetCygxUserYanxuanPermissionMapItem(userIds) // 如果是权益部门下的人，则展示研选相关的信息
			userInteractionNumMap := cygxService.GetUserInteractionNumMap(userIds)               // 如果是权益部门下的人，展示互动量相关的信息

			mfyxuserRecordRegisterMap := make(map[int]string)
			mfyxuserRecordRegisterTimeMap := make(map[int]time.Time)
			if len(userIdSlice) > 0 {
				//用户查研观向网页版注册时间
				clptuserRecordRegisterList, err := cygx.GetCygxClptSessionrByUserIdsMyfx(userIdStr)
				if err != nil {
					br.Msg = "获取失败"
					br.ErrMsg = "获取失败，GetCygxClptSessionrByUserIdsMyfx Err:" + err.Error()
					return
				}
				for _, userRecordRegister := range clptuserRecordRegisterList {
					mfyxuserRecordRegisterTimeMap[userRecordRegister.UserId] = userRecordRegister.CreateTime
					mfyxuserRecordRegisterMap[userRecordRegister.UserId] = userRecordRegister.CreateTime.Format(utils.FormatDateTime)
				}

				//买方研选网页版注册时间
				mfyxwebRecordRegisterList, err := cygx.GetCygxMfyxWebSessionByUserIdsMyfx(userIdStr)
				if err != nil {
					br.Msg = "获取失败"
					br.ErrMsg = "获取失败，GetCygxMfyxWebSessionByUserIdsMyfx Err:" + err.Error()
					return
				}
				for _, userRecordRegister := range mfyxwebRecordRegisterList {
					//如果注册时间早于查研观向网页版的，或者没有注册，就用这里的时间替换
					if userRecordRegister.CreateTime.Before(mfyxuserRecordRegisterTimeMap[userRecordRegister.UserId]) || mfyxuserRecordRegisterMap[userRecordRegister.UserId] == "" {
						mfyxuserRecordRegisterTimeMap[userRecordRegister.UserId] = userRecordRegister.CreateTime
						mfyxuserRecordRegisterMap[userRecordRegister.UserId] = userRecordRegister.CreateTime.Format(utils.FormatDateTime)
					}
				}

				mfyxuserRecordRegisterList, err := models.GetUserRecordRegisterByUserIdsMyfx(userIdStr)
				if err != nil {
					br.Msg = "获取失败"
					br.ErrMsg = "获取失败 GetUserRecordRegisterByUserIdsMyfx ，Err:" + err.Error()
					return
				}
				for _, userRecordRegister := range mfyxuserRecordRegisterList {
					//如果注册时间早于网页版的，或者网页版没有注册，就用这里的时间替换
					if userRecordRegister.CreateTime.Before(mfyxuserRecordRegisterTimeMap[userRecordRegister.UserId]) || mfyxuserRecordRegisterMap[userRecordRegister.UserId] == "" {
						mfyxuserRecordRegisterMap[userRecordRegister.UserId] = userRecordRegister.CreateTime.Format(utils.FormatDateTime)
					}
				}
			}
			for i := 0; i < lenList; i++ {
				item := list[i]
				// 分产品阅读统计
				//list[i].YbProductViewTotal = userYbViewsMap[int(item.UserId)]
				list[i].MfyxInteractionNum = userInteractionNumMap[int(item.UserId)]
				//权益销售查看用户研选的信息
				if userYanxuanPermissionMap[int(item.UserId)] != nil {
					mfyxItem := userYanxuanPermissionMap[int(item.UserId)]
					list[i].MfyxStatus = mfyxItem.Status
					list[i].MfyxStartDate = mfyxItem.StartDate
					list[i].MfyxEndDate = mfyxItem.EndDate
				} else {
					list[i].MfyxStatus = "未开通"
				}
				if mfyxuserRecordRegisterMap[int(item.UserId)] != "" {
					list[i].MfyxIsBinding = true
					list[i].MfyxBindingTime = mfyxuserRecordRegisterMap[int(item.UserId)]
				}
				//list[i].LastViewTimeStr = list[i].RaiLastViewTime.Format(utils.FormatDateTime)
			}
		}
	}

	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(company.CompanyUserListResp)
	resp.List = list
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

func (this *CompanyUserController) List2() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	companyId, _ := this.GetInt("CompanyId")
	keyWord := this.GetString("KeyWord")

	if companyId <= 0 {
		br.Msg = "请选择客户"
		br.ErrMsg = "客户参数错误"
		return
	}
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	var condition string
	var pars []interface{}

	if keyWord != "" {
		condition += ` AND (a.real_name LIKE '%` + keyWord + `%' OR a.mobile LIKE '%` + keyWord + `%' OR a.email LIKE '%` + keyWord + `%') `
	}

	total, err := company.GetCompanyUserListCount(condition, pars, companyId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据总数失败，Err:" + err.Error()
		return
	}

	list, err := company.GetCompanyUserList(condition, pars, companyId, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	lenList := len(list)
	for i := 0; i < lenList; i++ {
		item := list[i]
		if item.OpenId != "" {
			list[i].IsRegister = true
		} else {
			if item.RegisterPlatform == 2 {
				if item.Mobile != "" || item.Email != "" {
					list[i].IsRegister = true
				}
			} else {
				list[i].IsRegister = false
			}
		}
		reportView, err := models.GetReportViewMaxTime(int(item.UserId))
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取GetReportViewMaxTime失败，Err:" + err.Error()
			return
		}
		if reportView.LastViewTime.After(list[i].LastViewTime) {
			list[i].LastViewTimeStr = reportView.LastViewTime.Format(utils.FormatDateTime)
		} else {
			list[i].LastViewTimeStr = list[i].LastViewTime.Format(utils.FormatDateTime)
		}
		list[i].ViewTotal += reportView.ViewTotal
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(company.CompanyUserListResp)
	resp.List = list
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 获取客户名下联系人数量（根据当前账号角色区分）
// @Description 获取客户名下联系人数量（根据当前账号角色区分）接口
// @Param   CompanyId   query   int  true       "客户id"
// @Param   ProductId   query   int  true       "产品权限id"
// @Success 200 {object} company.CompanyUserTotal
// @router /company_user/total [get]
func (this *CompanyUserController) GetUserCountByCompanyId() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	companyId, _ := this.GetInt("CompanyId")
	if companyId <= 0 {
		br.Msg = "参数错误"
		return
	}
	productId, _ := this.GetInt("ProductId")
	//如果没有传入，那么去根据权限来获取id
	if productId <= 0 {
		productId = services.GetProductId(sysUser.RoleTypeCode)
	}

	total, err := services.GetUserCountByCompanyId(companyId, productId)
	if err != nil {
		br.Msg = "获取失败"
		br.Msg = "获取联系人总数失败,Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = company.CompanyUserTotal{
		Total: total,
	}
}

// @Title 删除客户联系人
// @Description 删除客户联系人接口
// @Param	request	body company.DeleteUserReq true "type json string"
// @router /user/delete [post]
func (this *CompanyUserController) DeleteUser() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req company.DeleteUserReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.UserId <= 0 {
		br.Msg = "参数错误！"
		return
	}

	//获取联系人详情
	userInfo, err := models.GetWxUserByUserId(req.UserId)
	if err != nil {
		br.Msg = "获取联系人异常！"
		br.ErrMsg = "获取联系人异常，Err:" + err.Error()
		return
	}
	//产品权限
	productId := services.GetProductId(sysUser.RoleTypeCode)

	//操作权限校验
	errMsg, err := checkOpCompanyUserByUserId(req.UserId, productId, sysUser.AdminId, sysUser.RoleTypeCode)
	if err != nil {
		br.Msg = "删除失败！" + errMsg
		br.ErrMsg = "删除失败，Err:" + err.Error()
		return
	}

	userRelationList := make([]*models.UserSellerRelation, 0)
	//如果不是超管权限，那么删除的时候，需要获取下联系人归属销售信息
	if productId != 0 {
		tmpUserRelationList, err := models.GetUserSellerRelationList(req.UserId)
		if err != nil {
			br.Msg = "删除失败"
			br.ErrMsg = "获取数据总数失败，Err:" + err.Error()
			return
		}
		if len(tmpUserRelationList) > 0 {
			userRelationList = append(userRelationList, tmpUserRelationList...)
		}
	}
	//联系人与销售的关系
	userSellerRelationList, err := models.GetUserSellerRelationList(int(userInfo.UserId))
	if err != nil {
		return
	}
	userSellerRelationInfo, _ := json.Marshal(userSellerRelationList)

	//删除所有的标识，并真正删除数据
	_ = models.DeleteUserSellerRelationByProductId(req.UserId, 1)
	_ = models.DeleteUserSellerRelationByProductId(req.UserId, 2)
	//真正删除用户
	err = services.DeleteWxUser(req.UserId)
	if err != nil {
		br.Msg = "删除失败！"
		br.ErrMsg = "删除失败，Err:" + err.Error()
		return
	}

	if len(userRelationList) > 0 {
		companyInfo, err := company.GetCompanyById(userRelationList[0].CompanyId)
		if err != nil {
			return
		}
		content := fmt.Sprint("联系人:", userInfo.RealName, "被删除")
		if companyInfo != nil {
			content = fmt.Sprint(companyInfo.CompanyName, "：", content)
		}
		for _, userRelation := range userRelationList {
			if userRelation.ProductId != productId {
				go services.AddCompanyMessage(sysUser.AdminId, userRelation.SellerId, userRelation.CompanyId, 0, 1, companyInfo.CompanyName, content, content)
			}

		}
	}

	//更新客户最近阅读次数以及最近阅读时间
	go services.ModifyCompanyProductLastViewData([]int{userInfo.CompanyId})

	//联系人信息
	originalUserInfo, _ := json.Marshal(userInfo)
	go services.AddWxUserOpLog(company.WxUserOpLog{
		LogType:                "delete",
		UserId:                 int(userInfo.UserId),
		CompanyId:              userInfo.CompanyId,
		Mobile:                 userInfo.Mobile,
		Email:                  userInfo.Email,
		OriginalUserInfo:       string(originalUserInfo),
		UserInfo:               "",
		OriginalUserSellerInfo: string(userSellerRelationInfo),
		UserSellerInfo:         "",
		OpUserId:               sysUser.AdminId,
		OpUserName:             sysUser.RealName,
		CreateTime:             time.Now(),
	})

	// 若该联系人为弘则研究公司下的，则同步禁用手机号关联的系统管理员
	if userInfo.CompanyId == 16 {
		go services.ForbiddenSysUserByMobile(userInfo.Mobile)
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "删除成功"
	br.IsAddLog = true
}

// @Title 编辑客户联系人
// @Description 编辑客户联系人接口
// @Param	request	body company.EditUserReq true "type json string"
// @router /user/edit [post]
func (this *CompanyUserController) EditUser() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req company.EditUserReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.UserId <= 0 {
		br.Msg = "参数错误！"
		return
	}

	//移除空格
	req.MobileOne = utils.TrimStr(req.MobileOne)
	req.MobileTwo = utils.TrimStr(req.MobileTwo)
	req.Email = utils.TrimStr(req.Email)
	req.RealName = utils.TrimStr(req.RealName)

	productId := services.GetProductId(sysUser.RoleTypeCode)

	//操作权限校验
	wxUser, err := models.GetWxUserByUserId(req.UserId)
	if err != nil {
		br.ErrMsg = "获取信息失败，Err:" + err.Error()
		br.Msg = "获取信息失败"
		return
	}
	//如果用户已经存在名片的情况下，但是二次编辑的时候前端没传名片信息，那么名片信息不做任何变更，并发送异常信息提醒
	if wxUser.BusinessCardUrl != "" && req.BusinessCardUrl == "" {
		req.BusinessCardUrl = wxUser.BusinessCardUrl
		go alarm_msg.SendAlarmMsg(fmt.Sprint("用户已经存在名片的情况下，但是二次编辑的时候前端没传名片信息。操作销售:", sysUser.RealName, "被操作UserId:", req.UserId), 3)
	}

	//获取当前操作员产品权限
	companyProductList, productErr := getSysCompanyProductList(productId, wxUser.CompanyId)
	if productErr != nil {
		br.Msg = "编辑失败！获取当前操作员产品权限异常"
		br.ErrMsg = "获取当前操作员产品权限异常，Err:" + productErr.Error()
		return
	}
	if companyProductList == nil {
		br.Msg = "编辑失败！获取当前操作员找不到产品权限"
		br.ErrMsg = "获取当前操作员找不到产品权限"
		return
	}

	//操作权限校验
	for _, v := range companyProductList {
		companyUserStatus := services.CheckCompanyUserButton(sysUser.RoleTypeCode, v.SellerId, sysUser.AdminId, v.ProductId, v.ShareSellerId, v.Status)
		if v.ShareSellerId == sysUser.AdminId {
			companyUserStatus = true
		}
		if companyUserStatus == false {
			br.Msg = "没有操作权限"
			br.ErrMsg = "没有操作权限"
			return
		}
	}

	if req.RealName == "" {
		br.Msg = "请填写姓名"
		return
	}

	oldWxUser := *wxUser //旧的联系人信息（赋值，而不是赋址）

	if req.MobileOne == "" && req.Email == "" {
		br.Msg = "请输入手机号或邮箱"
		return
	}

	//不是管理员的情况下：//手机号邮箱填写校验
	if productId != 0 {
		companyInfo, err := company.GetCompanyById(req.CompanyId)
		if err != nil {
			br.ErrMsg = "获取客户信息失败，Err:" + err.Error()
			br.Msg = "获取客户信息失败"
			return
		}

		for _, v := range companyProductList {
			//权益（海外）客户，需要有提示
			if v.ProductId == 2 && companyInfo.RegionType == "海外" {
				if req.MobileOne == "" {
					br.Msg = "请输入手机号"
				}
				if req.Email == "" {
					br.Msg = "请输入邮箱"
					br.ErrMsg = "请输入邮箱"
					return
				}
			}
		}
	}

	if req.MobileOne != "" && req.MobileOne != wxUser.Mobile {
		mobileOneItem, err := company.GetUserCountByMobile(req.MobileOne)
		if err != nil && err.Error() == utils.ErrNoRow() {
			mobileOneItem, err = company.CheckCompanyUserCountByMobileTwo(req.MobileOne)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "编辑失败"
				br.ErrMsg = "判断手机号是否存在,Err:" + err.Error()
				return
			}
		}

		if mobileOneItem != nil {
			if mobileOneItem.UserId > 0 {
				if req.CompanyId > 0 {
					//获取联系人分组信息
					userSellerGroupInfo, err := models.GetUserGroupSellerByUserId(int(mobileOneItem.UserId))
					if err != nil && err.Error() != utils.ErrNoRow() {
						br.Msg = "查询信息异常"
						br.Success = true
						br.Data = mobileOneItem
						br.IsSendEmail = false
						br.Ret = 600
						return
					}

					if req.CompanyId == mobileOneItem.CompanyId {

						//修改返回给前端用户的信息
						if userSellerGroupInfo != nil {
							mobileOneItem.SellerRealName = userSellerGroupInfo.SellerRealName
							mobileOneItem.Status = userSellerGroupInfo.Status
						}

						br.Msg = "手机号1已存在"
						br.Success = true
						br.Data = mobileOneItem
						br.IsSendEmail = false
						br.Ret = 600
						return
					} else {
						hasMove := true //是否可移动

						//如果是大于 1 的客户，那么就是非潜在客户，需要去查询对应的销售
						if mobileOneItem.CompanyId > 1 {
							//获取联系人分组信息
							userSellerGroupInfoList, err := models.GetUserGroupSellersByUserId(int(mobileOneItem.UserId))

							//根据分组校验
							if err == nil && len(userSellerGroupInfoList) > 0 {
								sellerMap := make(map[int]string)    //销售信息map
								sellerNameSlice := make([]string, 0) //销售姓名切片
								statusNameSlice := make([]string, 0) //客户状态姓名切片
								for _, v := range userSellerGroupInfoList {
									if v.Status != utils.COMPANY_STATUS_LOSE && v.Status != utils.COMPANY_STATUS_FOREVER && hasMove == true {
										hasMove = false
									}
									statusNameSlice = append(statusNameSlice, v.Status)
									if _, ok := sellerMap[v.SellerId]; ok {
										continue
									}
									sellerMap[v.SellerId] = v.SellerRealName
									sellerNameSlice = append(sellerNameSlice, v.SellerRealName)
								}
								mobileOneItem.SellerRealName = strings.Join(sellerNameSlice, "/")
								mobileOneItem.Status = strings.Join(statusNameSlice, "/")
							}
						}
						//是否可移动
						mobileOneItem.HasMove = hasMove

						br.Msg = "手机号1已存在"
						br.Success = true
						br.Data = mobileOneItem
						br.IsSendEmail = false
						br.Ret = 600
						return
					}
				} else {
					if strings.Contains(mobileOneItem.Status, "/") {
						if strings.Contains(mobileOneItem.Status, "正式") || strings.Contains(mobileOneItem.Status, "试用") {
							mobileOneItem.HasMove = false
						} else {
							mobileOneItem.HasMove = true
						}
					} else {
						if mobileOneItem.Status == utils.COMPANY_STATUS_FREEZE || //冻结
							mobileOneItem.Status == utils.COMPANY_STATUS_LOSE || //流失
							mobileOneItem.Status == utils.COMPANY_STATUS_POTENTIAL || //潜在
							mobileOneItem.Status == utils.COMPANY_STATUS_FOREVER { //永续
							mobileOneItem.HasMove = true
						}
					}
					br.Msg = "手机号1已存在"
					br.Success = true
					br.Data = mobileOneItem
					br.IsSendEmail = false
					br.Ret = 600
					return
				}
			}
		}
	}

	//手机号2校验（不需要修改，修改时间：2021年03月09日11:23:37）
	/*if req.MobileTwo != "" && req.MobileTwo != wxUser.MobileTwo {
		mobileTwoItem, err := company.GetUserCountByMobile(req.MobileTwo)
		if err != nil && err.Error() == utils.ErrNoRow() {
			mobileTwoItem, err = company.CheckCompanyUserCountByMobileTwo(req.MobileTwo)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "编辑失败"
				br.ErrMsg = "判断手机号2是否存在,Err:" + err.Error()
				return
			}
		}
		if mobileTwoItem != nil {
			if mobileTwoItem.UserId > 0 {
				if req.CompanyId > 0 {
					if req.CompanyId == mobileTwoItem.CompanyId {
						br.Msg = "手机号2已存在"
						br.Success = true
						br.Data = mobileTwoItem
						br.IsSendEmail = false
						br.Ret = 600
						return
					} else {
						if strings.Contains(mobileTwoItem.Status, "/") {
							if strings.Contains(mobileTwoItem.Status, "正式") || strings.Contains(mobileTwoItem.Status, "试用") {
								mobileTwoItem.HasMove = false
							} else {
								mobileTwoItem.HasMove = true
							}
						} else {
							if mobileTwoItem.Status == utils.COMPANY_STATUS_FREEZE || //冻结
								mobileTwoItem.Status == utils.COMPANY_STATUS_LOSE || //流失
								mobileTwoItem.Status == utils.COMPANY_STATUS_POTENTIAL || //潜在
								mobileTwoItem.Status == utils.COMPANY_STATUS_FOREVER { //永续
								mobileTwoItem.HasMove = true
							}
						}
						br.Msg = "手机号2已存在"
						br.Success = true
						br.Data = mobileTwoItem
						br.IsSendEmail = false
						br.Ret = 600
						return
					}
				} else {
					if strings.Contains(mobileTwoItem.Status, "/") {
						if strings.Contains(mobileTwoItem.Status, "正式") || strings.Contains(mobileTwoItem.Status, "试用") {
							mobileTwoItem.HasMove = false
						} else {
							mobileTwoItem.HasMove = true
						}
					} else {
						if mobileTwoItem.Status == utils.COMPANY_STATUS_FREEZE || //冻结
							mobileTwoItem.Status == utils.COMPANY_STATUS_LOSE || //流失
							mobileTwoItem.Status == utils.COMPANY_STATUS_POTENTIAL || //潜在
							mobileTwoItem.Status == utils.COMPANY_STATUS_FOREVER { //永续
							mobileTwoItem.HasMove = true
						}
					}
					br.Msg = "手机号2已存在"
					br.Success = true
					br.Data = mobileTwoItem
					br.IsSendEmail = false
					br.Ret = 600
					return
				}
			}
		}
	}*/

	if req.Email != "" && req.Email != wxUser.Email {
		emailItem, err := company.CheckCompanyUserCountByEmail(req.Email)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "编辑失败"
			br.ErrMsg = "编辑失败,Err:" + err.Error()
			return
		}
		if emailItem != nil {
			if emailItem.UserId > 0 {
				//获取联系人分组信息
				userSellerGroupInfo, err := models.GetUserGroupSellerByUserId(int(emailItem.UserId))
				if err != nil && err.Error() != utils.ErrNoRow() {
					br.Msg = "查询信息异常"
					br.Success = true
					br.Data = emailItem
					br.IsSendEmail = false
					br.Ret = 600
					return
				}

				if req.CompanyId == emailItem.CompanyId {
					//修改返回给前端用户的信息
					if userSellerGroupInfo != nil {
						emailItem.SellerRealName = userSellerGroupInfo.SellerRealName
						emailItem.Status = userSellerGroupInfo.Status
					}

					br.Msg = "邮箱已存在"
					br.Success = true
					br.Data = emailItem
					br.IsSendEmail = false
					br.Ret = 600
					return
				} else {
					hasMove := true //是否可移动

					//如果是大于 1 的客户，那么就是非潜在客户，需要去查询对应的销售
					if emailItem.CompanyId > 1 {
						//获取联系人分组信息
						userSellerGroupInfoList, err := models.GetUserGroupSellersByUserId(int(emailItem.UserId))

						//根据分组校验
						if err == nil && len(userSellerGroupInfoList) > 0 {
							sellerMap := make(map[int]string)    //销售信息map
							sellerNameSlice := make([]string, 0) //销售姓名切片
							statusNameSlice := make([]string, 0) //客户状态姓名切片
							for _, v := range userSellerGroupInfoList {
								if v.Status != utils.COMPANY_STATUS_LOSE && v.Status != utils.COMPANY_STATUS_FOREVER && hasMove == true {
									hasMove = false
								}
								statusNameSlice = append(statusNameSlice, v.Status)
								if _, ok := sellerMap[v.SellerId]; ok {
									continue
								}
								sellerMap[v.SellerId] = v.SellerRealName
								sellerNameSlice = append(sellerNameSlice, v.SellerRealName)
							}
							emailItem.SellerRealName = strings.Join(sellerNameSlice, "/")
							emailItem.Status = strings.Join(statusNameSlice, "/")
						}
					}
					//是否可移动
					emailItem.HasMove = hasMove

					br.Msg = "邮箱已存在"
					br.Success = true
					br.Data = emailItem
					br.IsSendEmail = false
					br.Ret = 600
					return
				}
			} else {
				if strings.Contains(emailItem.Status, "/") {
					if strings.Contains(emailItem.Status, "正式") || strings.Contains(emailItem.Status, "试用") {
						emailItem.HasMove = false
					} else {
						emailItem.HasMove = true
					}
				} else {
					if emailItem.Status == utils.COMPANY_STATUS_FREEZE || //冻结
						emailItem.Status == utils.COMPANY_STATUS_LOSE || //流失
						emailItem.Status == utils.COMPANY_STATUS_POTENTIAL || //潜在
						emailItem.Status == utils.COMPANY_STATUS_FOREVER { //永续
						emailItem.HasMove = true
					}
				}
				br.Msg = "邮箱已存在"
				br.Success = true
				br.Data = emailItem
				br.IsSendEmail = false
				br.Ret = 600
				return
			}
		}
	}
	//if wxUser.BusinessCardUrl != req.BusinessCardUrl && utils.RunMode == "release" {

	if wxUser.BusinessCardUrl != req.BusinessCardUrl {
		// 获取图片识别客户名称的配置
		crmConfig, err := company.GetConfigDetailByCode("card_recognition_company_name")
		if err != nil {
			br.Msg = "获取配置失败"
			br.ErrMsg = "获取配置失败"
			br.IsSendEmail = false
			return
		}
		// 获取图片识别手机号的配置
		crmConfig2, err := company.GetConfigDetailByCode("card_recognition_tel")
		if err != nil {
			br.Msg = "获取配置失败"
			br.ErrMsg = "获取配置失败"
			br.IsSendEmail = false
			return
		}
		if crmConfig.ConfigValue == "true" || crmConfig2.ConfigValue == "true" {
			//companyName := wxUser.CompanyName
			//if companyName == "" {
			companyInfo, err := company.GetCompanyById(req.CompanyId)
			if err != nil {
				br.Msg = "查找客户失败"
				br.ErrMsg = "查找客户失败,err:" + err.Error()
				return
			}
			companyName := companyInfo.CompanyName
			//}
			companyName = utils.TrimStr(companyName)
			tmpCompanyNameList, err := elastic.Analyze(companyName)
			if err != nil {
				br.Msg = "添加失败"
				br.ErrMsg = "客户名称分词失败,Err:" + err.Error()
				return
			}
			//公司名称切片
			analyzeNameList := []string{companyName}
			for _, v := range tmpCompanyNameList {
				if v == "" {
					continue
				}
				ignoreStrs := []string{"", "有限", "投资", "资本", "管理", "贸易", "资产", "公司", "股份", "集团", "有限公司"}
				if !strings.Contains(strings.Join(ignoreStrs, ","), v) && utf8.RuneCount([]byte(v)) > 1 {
					//不在上面的过滤字里面，且切出来的字符大于1位
					analyzeNameList = append(analyzeNameList, v)
				}
			}

			//名片识别出来的客户名称切片
			companyNameSlice := make([]string, 0)
			card, err := services.GetBusinessCard(req.BusinessCardUrl)
			if err != nil {
				br.Msg = "名片识别失败"
				br.ErrMsg = "名片识别失败,Err:" + err.Error()
				return
			}
			//if card.Errno != 0 {
			//	br.Msg = "您上传了非名片图片，请重新上传"
			//	br.ErrMsg = "名片识别失败,ErrMsg:" + card.ErrorMsg + ";errCode:" + strconv.Itoa(card.Errno)
			//	return
			//}
			//var mobileStr string
			//for _, v := range card.WordsResult {
			//	mobileStr += v.Words + ","
			//}
			isFlag := false
			if len(card.WordsResult.MOBILE) > 0 {
				mobileStr := strings.Join(card.WordsResult.MOBILE, ",")
				//if req.MobileOne != "" {
				//	if strings.Contains(mobileStr, req.MobileOne) || mobileStr == "" {
				//		isFlag = true
				//	} else {
				//		isFlag = false
				//	}
				//}
				//
				//if isFlag == false && req.MobileTwo != "" {
				//	if strings.Contains(mobileStr, req.MobileTwo) {
				//		isFlag = true
				//	} else {
				//		isFlag = false
				//	}
				//}
				if req.MobileOne != "" && strings.Contains(mobileStr, req.MobileOne) {
					isFlag = true
				}
				if req.MobileTwo != "" && strings.Contains(mobileStr, req.MobileTwo) {
					isFlag = true
				}
				//如果百度识别出来了客户名称，那么将识别出来的客户名称添加到待校验客户名称切片中
				if len(card.WordsResult.COMPANY) > 0 && card.WordsResult.COMPANY[0] != "" {
					companyNameSlice = card.WordsResult.COMPANY
				}
			}
			//如果百度未识别出来手机号或者公司名称，那么进行阿里识别
			if !isFlag || (len(companyNameSlice) == 0 && crmConfig.ConfigValue == "true") {
				//阿里云识别
				aliyunResult, errMsg, err := services.AliyunOcrBusinessCard(req.BusinessCardUrl)
				if err != nil {
					br.Msg = "识别失败"
					br.ErrMsg = "识别失败,Err:" + err.Error()
					return
				}
				if !aliyunResult.Success {
					br.Msg = "识别失败"
					br.ErrMsg = "识别失败"
					return
				}
				if errMsg != "" {
					br.Msg = errMsg
					return
				}
				//如果百度没有识别出来手机号，那么还需要阿里识别出来的手机号校验下
				if !isFlag {
					if len(aliyunResult.TelCell) > 0 {
						mobileStr := strings.Join(aliyunResult.TelCell, ",")
						if req.MobileOne != "" {
							if strings.Contains(mobileStr, req.MobileOne) {
								isFlag = true
							} else {
								isFlag = false
							}
						}
					} else {
						isFlag = true
					}
				}
				//如果阿里云识别出来了客户名称，那么将识别出来的客户名称添加到待校验客户名称切片中
				if len(aliyunResult.Company) > 0 {
					companyNameSlice = append(companyNameSlice, aliyunResult.Company...)
				}
			}

			if !isFlag && crmConfig2.ConfigValue == "true" {
				br.Msg = "名片信息与联系人手机号不符"
				br.IsSendEmail = false
				return
			}

			//校验识别出来的名片名称与传入的客户名称是否一致
			if len(companyNameSlice) > 0 && crmConfig.ConfigValue == "true" {
				isCompanyNameFlag := false //是否成功匹配客户名称
				//遍历识别出来的客户名称，然后与系统的客户名称做匹配（识别出来的名称包含系统名称的话，那么标记成功匹配）
				for _, tmpCompanyName := range companyNameSlice {
					//空串不处理
					if companyName == "" {
						continue
					}
					for _, analyzeName := range analyzeNameList {
						//如果分词出来的公司名称正好在识别出来的公司名称里面，那么就认为校验通过了
						if strings.Contains(tmpCompanyName, analyzeName) {
							isCompanyNameFlag = true
							break
						}
					}

					if isCompanyNameFlag {
						break
					}

				}
				//如果没有匹配到客户名称，那么就返回报错
				if !isCompanyNameFlag {
					br.Msg = "名片信息与公司名称不符"
					br.IsSendEmail = false
					return
				}
			}
		}
	}

	//UPDATE  wx_user
	//			SET
	//			  last_updated_time = NOW(),
	//			  position = ?,
	//			  is_maker = ?,
	//			  business_card_url = ?,
	//			  mobile_two= ?,
	//			  department_name=?,
	//              company_id=?,country_code=?

	//待更新字段
	updateCol := []string{"RealName", "Mobile", "MobileTwo", "Email", "Sex", "LastUpdatedTime", "Position", "IsMaker", "BusinessCardUrl", "DepartmentName", "CompanyId", "CountryCode"}
	//外呼手机号、外呼手机号区号
	if wxUser.OutboundMobile == "" || wxUser.OutboundMobile == wxUser.Mobile {
		wxUser.OutboundMobile = req.MobileOne
		wxUser.OutboundCountryCode = req.CountryCode
		//外呼字段数据修改
		updateCol = append(updateCol, "OutboundMobile", "OutboundCountryCode")
	}
	wxUser.RealName = req.RealName
	wxUser.Mobile = req.MobileOne
	wxUser.MobileTwo = req.MobileTwo
	wxUser.Email = req.Email
	wxUser.Sex = req.Sex
	wxUser.LastUpdatedTime = time.Now()
	wxUser.Position = req.Position
	wxUser.IsMaker = req.IsMaker
	wxUser.BusinessCardUrl = req.BusinessCardUrl
	wxUser.DepartmentName = req.DepartmentName
	wxUser.CompanyId = req.CompanyId
	wxUser.CountryCode = req.CountryCode
	fmt.Println("wxUser 2", wxUser)
	err = wxUser.Update(updateCol)
	//err = company.EditCompanyUser(&req)
	if err != nil {
		br.Msg = "编辑失败！"
		br.ErrMsg = "编辑失败，Err:" + err.Error()
		return
	}

	//更新客户最近阅读次数以及最近阅读时间
	go services.ModifyCompanyProductLastViewData([]int{wxUser.CompanyId})

	//联系人信息
	originalUserInfo, _ := json.Marshal(oldWxUser)
	userInfo, _ := json.Marshal(wxUser)
	go services.AddWxUserOpLog(company.WxUserOpLog{
		LogType:                "edit",
		UserId:                 int(wxUser.UserId),
		CompanyId:              wxUser.CompanyId,
		Mobile:                 wxUser.Mobile,
		Email:                  wxUser.Email,
		OriginalUserInfo:       string(originalUserInfo),
		UserInfo:               string(userInfo),
		OriginalUserSellerInfo: "",
		UserSellerInfo:         "",
		OpUserId:               sysUser.AdminId,
		OpUserName:             sysUser.RealName,
		CreateTime:             time.Now(),
	})

	br.Ret = 200
	br.Success = true
	br.Msg = "编辑成功"
	br.IsAddLog = true
}

// @Title 潜在用户列表
// @Description 潜在用户列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   ApplyMethod   query   int  true       "申请方式，0：全部，1:未申请，2:已付费客户申请试用，3:非客户申请试用"
// @Param   KeyWord   query   string  true       "搜索关键词"
// @Success 200 {object} models.PotentialUserListResp
// @router /potential/user/list [get]
func (this *CompanyController) PotentialUserList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	keyWord := this.GetString("KeyWord")
	applyMethod, _ := this.GetInt("ApplyMethod")

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)

	var condition string
	var pars []interface{}
	if applyMethod > 0 {
		condition += ` AND apply_method=? `
		pars = append(pars, applyMethod-1)
	}

	if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER {
		condition += ` AND apply_method=? `
		pars = append(pars, 1)
	}

	//非管理员不让看数据
	if sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_ADMIN {
		list := make([]*models.PotentialUserItem, 0)
		page := paging.GetPaging(currentIndex, pageSize, 0)
		resp := new(models.PotentialUserListResp)
		resp.List = list
		resp.Paging = page
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		br.Data = resp
		return
	}

	if keyWord != "" {
		condition += ` AND (a.real_name LIKE '%` + keyWord + `%' OR a.mobile LIKE '%` + keyWord + `%' OR a.email LIKE '%` + keyWord + `%') `
	}

	total, err := models.GetPotentialUserListCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取分页数据失败，Err:" + err.Error()
		return
	}
	list, err := models.GetPotentialUserList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	listLen := len(list)

	mobilesSlice := make([]string, 0)
	emailsSlice := make([]string, 0)
	for _, v := range list {
		if v.Mobile != "" {
			mobilesSlice = append(mobilesSlice, v.Mobile)
		} else if v.Email != "" {
			emailsSlice = append(emailsSlice, v.Email)
		}
	}

	//用户浏览数据
	mobileStr := strings.Join(mobilesSlice, "','")
	mobileStr = "'" + mobileStr + "'"
	emailStr := strings.Join(emailsSlice, "','")
	emailStr = "'" + emailStr + "'"

	//userViewTotalList, _ := models.GetCountUserViewHistoryByUserIds(userIdStr)
	//userViewTotalMap := make(map[int]*models.UserViewTotalSlice)
	//for _, userView := range userViewTotalList {
	//	userViewTotalMap[userView.UserId] = userView
	//}

	//用户日评浏览数据
	//userReportViewTotalList, _ := models.GetReportViewMaxTimeByUserIds(userIdStr)
	//userReportViewTotalMap := make(map[int]*models.ReportViewRecord)
	//for _, userReportView := range userReportViewTotalList {
	//	userReportViewTotalMap[userReportView.UserId] = userReportView
	//}
	//手机号
	userViewMobileTotalMap := make(map[string]*models.UserViewMobileTotalSlice)
	userReportViewMobileTotalMap := make(map[string]*models.ReportViewMobileRecord)
	if len(mobilesSlice) > 0 {
		//用户浏览数据
		userViewMobileTotalList, _ := models.GetCountUserViewHistoryByMobiles(mobileStr)
		for _, userViewMobile := range userViewMobileTotalList {
			userViewMobileTotalMap[userViewMobile.Mobile] = userViewMobile
		}

		//每日点评手机号数据
		userReportViewMobileTotalList, _ := models.GetReportViewMaxTimeByMobiles(mobileStr)
		for _, userReportViewMobile := range userReportViewMobileTotalList {
			userReportViewMobileTotalMap[userReportViewMobile.Mobile] = userReportViewMobile
		}
	}

	//邮箱
	userViewEmailTotalMap := make(map[string]*models.UserViewEmailTotalSlice)
	userReportViewEmailTotalMap := make(map[string]*models.ReportViewEmailRecord)
	if len(emailsSlice) > 0 {
		//用户浏览数据
		userViewEmailTotalList, _ := models.GetCountUserViewHistoryByEmails(emailStr)
		for _, userViewEmail := range userViewEmailTotalList {
			userViewEmailTotalMap[userViewEmail.Email] = userViewEmail
		}
		//每日点评手机号数据
		userReportViewEmailTotalList, _ := models.GetReportViewMaxTimeByEmails(emailStr)
		for _, userReportViewEmail := range userReportViewEmailTotalList {
			userReportViewEmailTotalMap[userReportViewEmail.Email] = userReportViewEmail
		}
	}

	for i := 0; i < listLen; i++ {
		item := list[i]
		//item, err := models.GetReportViewMaxTime(list[i].UserId)
		//if err != nil {
		//	br.Msg = "获取失败"
		//	br.ErrMsg = "获取GetReportViewMaxTime失败，Err:" + err.Error()
		//	return
		//}
		//list[i].ViewTotal += item.ViewTotal

		//手机号用户累计浏览次数
		if userView, ok := userViewMobileTotalMap[item.Mobile]; ok {
			list[i].ViewTotal += userView.Total
			if userView.CreatedTime.After(list[i].LastViewTime) {
				list[i].LastViewTime = userView.CreatedTime
				list[i].LastViewTimeStr = userView.CreatedTime.Format(utils.FormatDateTime)
			}
		}
		//邮箱用户累计浏览次数
		if userView, ok := userViewEmailTotalMap[item.Email]; ok {
			//总共浏览的报表数据需要调整为（手机号用户浏览晨报数+邮箱号用户浏览晨报数）
			list[i].ViewTotal += userView.Total
			if userView.CreatedTime.After(list[i].LastViewTime) {
				list[i].LastViewTime = userView.CreatedTime
				list[i].LastViewTimeStr = userView.CreatedTime.Format(utils.FormatDateTime)
			}
		}

		//如果存在手机号用户日评数据，那么需要做处理
		if reportView, ok := userReportViewMobileTotalMap[item.Mobile]; ok {
			//对日评数据做校验，日评时间晚于晨报时间，那么将最近一次浏览时间替换
			if reportView.LastViewTime.After(list[i].LastViewTime) {
				list[i].LastViewTime = reportView.LastViewTime
				list[i].LastViewTimeStr = reportView.LastViewTime.Format(utils.FormatDateTime)
			}
			//总共浏览的报表数据需要调整为（浏览晨报数+浏览日评数）
			list[i].ViewTotal += reportView.ViewTotal
		}
		//如果存在手机号用户日评数据，那么需要做处理
		if reportView, ok := userReportViewEmailTotalMap[item.Email]; ok {
			//对日评数据做校验，日评时间晚于晨报时间，那么将最近一次浏览时间替换
			if reportView.LastViewTime.After(list[i].LastViewTime) {
				list[i].LastViewTime = reportView.LastViewTime
				list[i].LastViewTimeStr = reportView.LastViewTime.Format(utils.FormatDateTime)
			}
			//总共浏览的报表数据需要调整为（浏览晨报数+浏览日评数）
			list[i].ViewTotal += reportView.ViewTotal
		}
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(models.PotentialUserListResp)
	resp.List = list
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 标记潜在用户
// @Description 标记潜在用户接口
// @Param	request	body models.PotentialUserDealReq true "type json string"
// @Success Ret=200 标记成功
// @router /potential/user/deal [post]
func (this *CompanyController) PotentialUserDeal() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req models.PotentialUserDealReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	// 标记处理
	err = services.DealPotentialUser(req.UserId, sysUser.AdminId)
	if err != nil {
		br.Msg = "标记失败"
		br.ErrMsg = "标记失败,Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "标记成功"
}

// @Title 删除潜在用户
// @Description 删除潜在用户接口
// @Param	request	body models.PotentialUserDeleteReq true "type json string"
// @Success Ret=200 删除成功
// @router /potential/user/delete [post]
func (this *CompanyController) PotentialUserDelete() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req models.PotentialUserDeleteReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	//删除用户
	err = services.DeleteWxUser(req.UserId)
	if err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "删除失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "删除成功"
}

// @Title 移动潜在用户
// @Description 移动潜在用户接口
// @Param	request	body models.PotentialUserMoveReq true "type json string"
// @Success Ret=200 移动成功
// @router /potential/user/move [post]
func (this *CompanyController) PotentialUserMove() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req models.PotentialUserMoveReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.UserId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "客户id错误"
		return
	}

	//如果移动客户编号小于等于0，那么移动到潜在客户
	if req.CompanyId <= 0 {
		req.CompanyId = 1
	}
	wxUser, err := models.GetWxUserByUserId(req.UserId)
	if err != nil {
		br.Msg = "移动失败"
		br.ErrMsg = "获取用户信息失败,Err:" + err.Error()
		return
	}
	oldWxUser := *wxUser

	if req.Mobile == "" {
		req.Mobile = wxUser.Mobile
	}
	if req.Email == "" {
		req.Email = wxUser.Email
	}
	if req.Mobile == "" && req.Email == "" {
		br.Msg = "手机号和邮箱不能同时为空"
		return
	}
	//校验手机号
	if req.Mobile != "" && wxUser.Mobile != req.Mobile {
		count, err := models.CheckUserMobileIsRegister(req.UserId, req.Mobile)
		if err != nil {
			br.Msg = "校验数据失败"
			br.ErrMsg = "校验数据失败，Err:" + err.Error()
			return
		}
		if count > 0 {
			br.Msg = "该手机号已经注册过用户"
			return
		}
	}
	//校验邮箱
	if req.Email != "" && wxUser.Email != req.Email {
		if !utils.ValidateEmailFormatat(req.Email) {
			br.Msg = "请输入正确的邮箱（包含@）"
			return
		}
		count, err := models.CheckUserEmailIsRegister(req.UserId, req.Email)
		if err != nil {
			br.Msg = "校验数据失败"
			br.ErrMsg = "校验数据失败，Err:" + err.Error()
			return
		}
		if count > 0 {
			br.Msg = "该邮箱已经注册过用户"
			br.IsSendEmail = false
			return
		}
	}

	updateCol := make([]string, 0)

	if wxUser.OutboundMobile == "" || wxUser.Mobile == wxUser.OutboundMobile {
		wxUser.OutboundMobile = req.Mobile
		wxUser.OutboundCountryCode = req.CountryCode
		updateCol = append(updateCol, "OutboundMobile", "OutboundCountryCode")
	}
	if req.Email != "" {
		wxUser.Email = req.Email
		updateCol = append(updateCol, "Email")
	}
	if req.RealName != "" {
		wxUser.RealName = req.RealName
		updateCol = append(updateCol, "RealName")
	}
	if req.Mobile != "" {
		wxUser.Mobile = req.Mobile
		updateCol = append(updateCol, "Mobile")
	}
	if req.CountryCode != "" {
		wxUser.CountryCode = req.CountryCode
		updateCol = append(updateCol, "CountryCode")
	}
	if req.Position != "" {
		wxUser.Position = req.Position
		updateCol = append(updateCol, "Position")
	}
	if wxUser.DepartmentName == "" && req.DepartmentName != "" {
		wxUser.DepartmentName = req.DepartmentName
		updateCol = append(updateCol, "DepartmentName")
	}
	wxUser.Sex = req.Sex
	wxUser.IsMaker = req.IsMaker
	updateCol = append(updateCol, "Sex", "IsMaker")

	//名片匹配
	if req.BusinessCardUrl != "" {
		//if req.BusinessCardUrl != "" && utils.RunMode == "release" {
		// 获取图片识别手机号的配置
		crmConfig2, err := company.GetConfigDetailByCode("card_recognition_tel")
		if err != nil {
			br.Msg = "获取配置失败"
			br.ErrMsg = "获取配置失败"
			br.IsSendEmail = false
			return
		}
		if crmConfig2.ConfigValue == "true" {
			card, err := services.GetBusinessCard(req.BusinessCardUrl)
			if err != nil {
				br.Msg = "名片识别失败"
				br.ErrMsg = "名片识别失败,Err:" + err.Error()
				return
			}
			isFlag := false
			if len(card.WordsResult.MOBILE) > 0 {
				mobileStr := strings.Join(card.WordsResult.MOBILE, ",")
				//if req.Mobile != "" {
				//	if strings.Contains(mobileStr, req.Mobile) || mobileStr == "" {
				//		isFlag = true
				//	} else {
				//		isFlag = false
				//	}
				//}
				if req.Mobile != "" && strings.Contains(mobileStr, req.Mobile) {
					isFlag = true
				}
			}
			if !isFlag {
				//阿里云识别
				//if utils.RunMode == "release" {
				aliyunResult, errMsg, err := services.AliyunOcrBusinessCard(req.BusinessCardUrl)
				if err != nil {
					br.Msg = "识别失败"
					br.ErrMsg = "识别失败,Err:" + err.Error()
					return
				}
				if !aliyunResult.Success {
					br.Msg = "识别失败"
					br.ErrMsg = "识别失败"
					return
				}
				if errMsg != "" {
					br.Msg = errMsg
					return
				}
				if len(aliyunResult.TelCell) > 0 {
					mobileStr := strings.Join(aliyunResult.TelCell, ",")
					if req.Mobile != "" {
						if strings.Contains(mobileStr, req.Mobile) {
							isFlag = true
						} else {
							isFlag = false
						}
					}
				} else {
					isFlag = true
				}
				//}
			}

			if !isFlag && crmConfig2.ConfigValue == "true" {
				br.Msg = "名片信息与联系人手机号不符"
				return
			}
		}

		wxUser.BusinessCardUrl = req.BusinessCardUrl
		updateCol = append(updateCol, "BusinessCardUrl")
	}

	productId := services.GetProductId(sysUser.RoleTypeCode)
	companyProductList, _ := getSysCompanyProductList(productId, req.CompanyId)

	//联系人与销售的关系
	userSellerRelationList, err := models.GetUserSellerRelationList(int(wxUser.UserId))
	if err != nil {
		return
	}
	userSellerRelationInfo, _ := json.Marshal(userSellerRelationList)

	err = services.MovePotentialUser(req.UserId, req.CompanyId, req.RealName, req.Mobile, req.Email, req.Remark, companyProductList, wxUser, updateCol)
	//err = models.MovePotentialUser(req.UserId, req.CompanyId, req.RealName, req.Mobile, req.Email, req.Remark)
	if err != nil {
		br.Msg = "移动失败"
		br.ErrMsg = "移动失败,Err:" + err.Error()
		return
	}

	//更新客户最近阅读次数以及最近阅读时间
	go services.ModifyCompanyProductLastViewData([]int{req.CompanyId})

	//联系人信息
	originalUserInfo, _ := json.Marshal(oldWxUser)
	userInfo, _ := json.Marshal(wxUser)
	go services.AddWxUserOpLog(company.WxUserOpLog{
		LogType:                "move",
		UserId:                 int(wxUser.UserId),
		CompanyId:              wxUser.CompanyId,
		Mobile:                 wxUser.Mobile,
		Email:                  wxUser.Email,
		OriginalUserInfo:       string(originalUserInfo),
		UserInfo:               string(userInfo),
		OriginalUserSellerInfo: string(userSellerRelationInfo),
		UserSellerInfo:         "",
		OpUserId:               sysUser.AdminId,
		OpUserName:             sysUser.RealName,
		CreateTime:             time.Now(),
	})
	br.Ret = 200
	br.Success = true
	br.Msg = "移动成功"
}

// @Title 移动联系人
// @Description 移动联系接口，将联系人从自己名下移动到另一个客户销售名下
// @Param	request	body models.UserMoveReq true "type json string"
// @Success Ret=200 移动成功
// @router /user/move [post]
func (this *CompanyController) UserMove() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req models.UserMoveReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.UserId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "联系人id错误"
		return
	}
	if req.CompanyId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "客户id错误"
		return
	}
	if req.SellerId < 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "销售id错误"
		return
	}

	wxUser, err := models.GetWxUserByUserId(req.UserId)
	if err != nil {
		br.Msg = "移动失败"
		br.ErrMsg = "获取用户信息失败,Err:" + err.Error()
		return
	}
	oldWxUser := *wxUser
	if wxUser.CompanyId == req.CompanyId {
		br.Msg = "移动失败"
		br.ErrMsg = "该联系人属于该客户"
		return
	}
	//产品id
	productId := services.GetProductId(sysUser.RoleTypeCode)
	//操作权限校验
	errMsg, err := checkOpCompanyUserByCompanyId(wxUser.CompanyId, productId, sysUser.AdminId, sysUser.RoleTypeCode)
	if err != nil {
		br.Msg = "移动失败！" + errMsg
		br.ErrMsg = "移动失败，Err:" + err.Error()
		return
	}

	//联系人与销售的关系
	userSellerRelationList, err := models.GetUserSellerRelationList(int(wxUser.UserId))
	if err != nil {
		return
	}
	userSellerRelationInfo, _ := json.Marshal(userSellerRelationList)

	err = services.MoveUser(req.UserId, req.CompanyId, req.SellerId, wxUser, sysUser.AdminId)
	//err = models.MovePotentialUser(req.UserId, req.CompanyId, req.RealName, req.Mobile, req.Email, req.Remark)
	if err != nil {
		br.Msg = "移动失败"
		br.ErrMsg = "移动失败,Err:" + err.Error()
		return
	}

	//更新客户最近阅读次数以及最近阅读时间
	go services.ModifyCompanyProductLastViewData([]int{wxUser.CompanyId, req.CompanyId})

	//联系人信息
	originalUserInfo, _ := json.Marshal(oldWxUser)
	userInfo, _ := json.Marshal(wxUser)
	{
		// 最新的联系人信息
		newWxUser, err := models.GetWxUserByUserId(req.UserId)
		if err == nil {
			userInfo, _ = json.Marshal(newWxUser)
		}
	}
	go services.AddWxUserOpLog(company.WxUserOpLog{
		LogType:                "move",
		UserId:                 int(wxUser.UserId),
		CompanyId:              wxUser.CompanyId,
		Mobile:                 wxUser.Mobile,
		Email:                  wxUser.Email,
		OriginalUserInfo:       string(originalUserInfo),
		UserInfo:               string(userInfo),
		OriginalUserSellerInfo: string(userSellerRelationInfo),
		UserSellerInfo:         "",
		OpUserId:               sysUser.AdminId,
		OpUserName:             sysUser.RealName,
		CreateTime:             time.Now(),
	})

	br.Ret = 200
	br.Success = true
	br.Msg = "移动成功"
	br.IsAddLog = true
}

// @Title 搜索客户
// @Description 搜索客户接口
// @Param   KeyWord   query   string  true       "搜索关键词"
// @Success 200 {object} company.CompanySearchResp
// @router /potential/company/search [get]
func (this *CompanyUserController) CompanySearch() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var err error
	keyWord := this.GetString("KeyWord")
	item := make([]*company.CompanyItem, 0)
	if keyWord != "" {
		item, err = company.GetCompanyBySearch(keyWord)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取失败"
			br.ErrMsg = "获取数据失败，Err:" + err.Error()
			return
		}
	}
	resp := new(company.CompanySearchResp)
	resp.List = item
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 企查查模糊查询客户接口
// @Description 企查查模糊查询客户
// @Param   KeyWord   query   string  true       "搜索关键词"
// @Success 200 {object} services.Result
// @router /potential/company/qccSearch [get]
func (this *CompanyUserController) CompanyQCCSearch() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var err error
	var results []services.Result
	keyWord := this.GetString("KeyWord")
	if keyWord != "" {
		results, err = services.QCCFuzzySearch(keyWord)
		if err != nil {
			br.Data = results
			br.Msg = "获取数据失败," + err.Error()
			br.Ret = 200
			br.Success = true
			return
		}
	}
	br.Data = results
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
}

// @Title 检测客户名称或社会信用码重复
// @Description 检测客户名称或社会信用码重复接口(新增/编辑客户页面使用)
// @Param   CompanyName   query   string  true       "客户名称"
// @Param   CreditCode   query   string  true       "社会统一信用码"
// @Success 200 {object} company.CheckCompanyInfoRepeatResp
// @router /check/RepeatCompanyInfo [get]
func (this *CompanyController) CheckCompanyInfoRepeat() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	roleTypeCode := sysUser.RoleTypeCode
	productId := services.GetProductId(roleTypeCode)
	companyName := this.GetString("CompanyName")
	creditCode := this.GetString("CreditCode")
	var status, comanyId, repeatStatus int
	var productName string

	if productId == 0 {
		productId = 1
		checkProductId := 2

		if creditCode != "" {
			codeItem, err := company.CheckCompanyProductByCreditCode(creditCode, productId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "校验社会信用码是否存在失败"
				br.ErrMsg = "校验社会信用码是否存在失败,Err:" + err.Error()
				return
			}
			//存在ficc权限
			if codeItem != nil && codeItem.CompanyId > 0 {
				repeatStatus = 1
				goto Loop
			}
			codeCheckItem, err := company.CheckCompanyProductByCreditCode(creditCode, checkProductId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "校验社会信用码是否存在失败"
				br.ErrMsg = "校验社会信用码是否存在失败,Err:" + err.Error() + " productId:" + strconv.Itoa(productId) + ";checkProductId:" + strconv.Itoa(checkProductId)
				return
			}
			if codeCheckItem != nil && codeCheckItem.CompanyId > 0 {
				status = 1
				repeatStatus = 1
				productName = codeCheckItem.ProductName
				comanyId = codeCheckItem.CompanyId
				goto Loop
			}
		}

		if companyName != "" {
			nameItem, err := company.CheckCompanyProductByName(companyName, productId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "校验客户名称是否存在失败"
				br.ErrMsg = "校验客户名称是否存在失败,Err:" + err.Error()
				return
			}
			if nameItem != nil && nameItem.CompanyId > 0 {
				repeatStatus = 2
				goto Loop
			}
			nameCheckItem, err := company.CheckCompanyProductByName(companyName, checkProductId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "校验客户名称是否存在失败"
				br.ErrMsg = "校验客户名称是否存在失败,Err:" + err.Error() + " productId:" + strconv.Itoa(productId) + ";checkProductId:" + strconv.Itoa(checkProductId)
				return
			}
			if nameCheckItem != nil && nameCheckItem.CompanyId > 0 {
				status = 1
				repeatStatus = 2
				productName = nameCheckItem.ProductName
				comanyId = nameCheckItem.CompanyId
				goto Loop
			}
		}

		productId = 2
		checkProductId = 1

		if creditCode != "" {
			codeItem, err := company.CheckCompanyProductByCreditCode(creditCode, productId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "校验社会信用码是否存在失败"
				br.ErrMsg = "校验社会信用码是否存在失败,Err:" + err.Error()
				return
			}
			if codeItem != nil && codeItem.CompanyId > 0 {
				repeatStatus = 1
				goto Loop
			}
			codeCheckItem, err := company.CheckCompanyProductByCreditCode(creditCode, checkProductId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "校验社会信用码是否存在失败"
				br.ErrMsg = "校验社会信用码是否存在失败,Err:" + err.Error() + " productId:" + strconv.Itoa(productId) + ";checkProductId:" + strconv.Itoa(checkProductId)
				return
			}
			if codeCheckItem != nil && codeCheckItem.CompanyId > 0 {
				status = 1
				repeatStatus = 1
				productName = codeCheckItem.ProductName
				comanyId = codeCheckItem.CompanyId
				goto Loop
			}
		}

		if companyName != "" {
			nameItem, err := company.CheckCompanyProductByName(companyName, productId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "校验客户名称是否存在失败"
				br.ErrMsg = "校验客户名称是否存在失败,Err:" + err.Error()
				return
			}
			if nameItem != nil && nameItem.CompanyId > 0 {
				repeatStatus = 2
				goto Loop
			}
			nameCheckItem, err := company.CheckCompanyProductByName(companyName, checkProductId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "校验客户名称是否存在失败"
				br.ErrMsg = "校验客户名称是否存在失败,Err:" + err.Error() + " productId:" + strconv.Itoa(productId) + ";checkProductId:" + strconv.Itoa(checkProductId)
				return
			}
			if nameCheckItem != nil && nameCheckItem.CompanyId > 0 {
				status = 1
				repeatStatus = 2
				productName = nameCheckItem.ProductName
				comanyId = nameCheckItem.CompanyId
				goto Loop
			}
		}

	} else {
		checkProductId := 0
		if productId == 1 {
			checkProductId = 2
		} else if productId == 2 {
			checkProductId = 1
		}
		if creditCode != "" {
			codeItem, err := company.CheckCompanyProductByCreditCode(creditCode, productId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "校验社会信用码是否存在失败"
				br.ErrMsg = "校验社会信用码是否存在失败,Err:" + err.Error()
				return
			}
			if codeItem != nil && codeItem.CompanyId > 0 {
				repeatStatus = 1
				goto Loop
			}
			codeCheckItem, err := company.CheckCompanyProductByCreditCode(creditCode, checkProductId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "校验社会信用码是否存在失败"
				br.ErrMsg = "校验社会信用码是否存在失败,Err:" + err.Error() + " productId:" + strconv.Itoa(productId) + ";checkProductId:" + strconv.Itoa(checkProductId)
				return
			}
			if codeCheckItem != nil && codeCheckItem.CompanyId > 0 {
				status = 1
				repeatStatus = 1
				productName = codeCheckItem.ProductName
				comanyId = codeCheckItem.CompanyId
				goto Loop
			}
		}
		if companyName != "" {
			nameItem, err := company.CheckCompanyProductByName(companyName, productId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "校验客户名称是否存在失败"
				br.ErrMsg = "校验客户名称是否存在失败,Err:" + err.Error()
				return
			}
			if nameItem != nil && nameItem.ProductName != "" {
				repeatStatus = 2
				goto Loop
			}
			nameCheckoutItem, err := company.CheckCompanyProductByName(companyName, checkProductId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "校验客户名称是否存在失败"
				br.ErrMsg = "校验客户名称是否存在失败,Err:" + err.Error() + " productId:" + strconv.Itoa(productId) + ";checkProductId:" + strconv.Itoa(checkProductId)
				return
			}
			if nameCheckoutItem != nil && nameCheckoutItem.CompanyId > 0 {
				status = 1
				repeatStatus = 2
				productName = nameCheckoutItem.ProductName
				comanyId = nameCheckoutItem.CompanyId
				goto Loop
			}
		}

	}
Loop:
	resp := new(company.CheckCompanyInfoRepeatResp)
	resp.Status = status
	resp.RepeatStatus = repeatStatus
	resp.ProductName = productName
	resp.CompanyId = comanyId
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// ViewReportList
// @Title 联系人阅读报告记录
// @Description 联系人阅读报告记录
// @Param   UserId   query   int  true       "用户id"
// @Param   TxtType   query   int  true       "类型0全部，1权益，2ficc"
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   LastViewTime   query   string  true       "最近一次的阅读时间，没有的话，那就是获取最新数据"
// @Success 200 {object} company.ViewReportListResp
// @router /view/report/list [get]
func (this *CompanyUserController) ViewReportList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	userId, _ := this.GetInt("UserId")
	txtType, _ := this.GetInt("TxtType")
	pageSize, _ := this.GetInt("PageSize")
	lastViewTime := this.GetString("LastViewTime")
	if userId <= 0 {
		br.Msg = "参数错误"
		return
	}
	// 默认20条数据
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if userId > 0 {

	}
	item, err := models.GetWxUserByUserId(userId)
	if err != nil {
		br.Msg = "获取失败"
		br.Msg = "获取联系人信息失败,Err:" + err.Error()
		return
	}

	var lastViewTimeT time.Time
	if lastViewTime != `` {
		lastViewTimeT, err = time.ParseInLocation(utils.FormatDateTime, lastViewTime, time.Local)
		if err != nil {
			br.Msg = "获取失败"
			br.Msg = "最近一次阅读时间转换异常,Err:" + err.Error()
			return
		}
	}

	list := make([]*company.ViewReportList, 0)
	recordList := make([]*models.UserReportViewRecord, 0)

	obj := models.UserReportViewRecord{}

	var baseCondition string // 基础条件
	var basePars []interface{}
	if item.Mobile != "" {
		baseCondition = ` AND mobile = ? `
		basePars = append(basePars, item.Mobile)
	} else if item.Email == "" {
		baseCondition = ` AND email = ? `
		basePars = append(basePars, item.Email)
	}

	// 阅读记录汇总数
	total := item.FiccViewTotal + item.RaiViewTotal

	switch txtType {
	case 1:
		baseCondition += ` AND source = ? `
		basePars = append(basePars, 4)

		total = item.RaiViewTotal
		if lastViewTimeT.IsZero() {
			if item.RaiLastViewTime != `` && item.RaiLastViewTime != `0000-00-00 00:00:00` {
				lastViewTimeT, _ = time.ParseInLocation(utils.FormatDateTime, item.RaiLastViewTime, time.Local)
			} else {
				lastViewTimeT = time.Now()
			}
			// 默认要把最新的记录列出来，所以往后加1s
			lastViewTime = lastViewTimeT.Add(1 * time.Second).Format(utils.FormatDateTime)
		}
	// 权益
	case 2: // ficc
		baseCondition += ` AND source in (?,?,?) `
		basePars = append(basePars, 1, 2, 3)
		total = item.FiccViewTotal

		if lastViewTimeT.IsZero() {
			if item.FiccLastViewTime != `` && item.FiccLastViewTime != `0000-00-00 00:00:00` {
				lastViewTimeT, _ = time.ParseInLocation(utils.FormatDateTime, item.FiccLastViewTime, time.Local)
			} else {
				lastViewTimeT = time.Now()
			}
			// 默认要把最新的记录列出来，所以往后加1s
			lastViewTime = lastViewTimeT.Add(1 * time.Second).Format(utils.FormatDateTime)
		}
	default:
		if lastViewTimeT.IsZero() {
			var ficcViewTime, raiViewTime time.Time
			if item.FiccLastViewTime != `` && item.FiccLastViewTime != `0000-00-00 00:00:00` {
				ficcViewTime, _ = time.ParseInLocation(utils.FormatDateTime, item.FiccLastViewTime, time.Local)
			}
			if item.RaiLastViewTime != `` && item.RaiLastViewTime != `0000-00-00 00:00:00` {
				raiViewTime, _ = time.ParseInLocation(utils.FormatDateTime, item.RaiLastViewTime, time.Local)
			}

			// 如果两个都没有值的话，那么就是当前时间
			if ficcViewTime.IsZero() && raiViewTime.IsZero() {
				lastViewTimeT = time.Now()
			} else if !ficcViewTime.IsZero() && !raiViewTime.IsZero() {
				if ficcViewTime.After(raiViewTime) {
					lastViewTimeT = ficcViewTime
				} else {
					lastViewTimeT = raiViewTime
				}
			} else if !ficcViewTime.IsZero() {
				lastViewTimeT = ficcViewTime
			} else {
				lastViewTimeT = raiViewTime
			}
			// 默认要把最新的记录列出来，所以往后加1s
			lastViewTime = lastViewTimeT.Add(1 * time.Second).Format(utils.FormatDateTime)
		}
	}

	// 开始实际的查询
	{
		condition := baseCondition
		pars := basePars

		condition += `AND create_time <  ?`
		pars = append(pars, lastViewTime)

		total, items, err := obj.GetViewReportList(lastViewTimeT.Year(), condition, pars, pageSize)
		if err != nil {
			br.Msg = "获取失败"
			br.Msg = "获取失败,Err:" + err.Error()
			return
		}

		recordList = append(recordList, items...)

		// 查询去年的表
		if total < int64(pageSize) {
			secondCondition := baseCondition
			secondPars := basePars

			secondCondition += `AND create_time <  ?`
			secondPars = append(secondPars, lastViewTime)

			_, items, err = obj.GetViewReportList(lastViewTimeT.Year(), secondCondition, secondPars, int(total)-pageSize)
			if err != nil {
				br.Msg = "获取失败"
				br.Msg = "获取失败,Err:" + err.Error()
				return
			}

			recordList = append(recordList, items...)
		}
	}

	viewReportMap := make(map[string]company.ViewReportList) // 阅读记录map
	sourceReportIdListMap := make(map[int8][]int)

	for _, v := range recordList {
		tmpList, ok := sourceReportIdListMap[v.Source]
		if !ok {
			tmpList = make([]int, 0)
		}
		tmpList = append(tmpList, v.ReportId)
		sourceReportIdListMap[v.Source] = tmpList

		tmpTxtType := `ficc`
		if v.Source == 4 {
			tmpTxtType = `rights`
		}
		stopTime := `--`
		if v.StopTime > 0 {
			stopTime = fmt.Sprint(stopTime)
		}
		viewReportMap[fmt.Sprint(v.Source, "_", v.ReportId)] = company.ViewReportList{
			ResearchReportName: "",
			ReportType:         "",
			CreatedTime:        v.CreateTime,
			TxtType:            tmpTxtType,
			MatchTypeName:      "--",
			StopTime:           stopTime,
		}
	}

	// 获取报告详情
	for source, reportIdList := range sourceReportIdListMap {
		switch source {
		case 1: // rddp报告
			tmpReportList, err := models.GetReportByIdList(reportIdList)
			if err != nil {
				br.Msg = "获取失败"
				br.Msg = "获取weekly报告详情失败,Err:" + err.Error()
				return
			}
			for _, v := range tmpReportList {
				tmpKey := fmt.Sprint(source, "_", v.Id)
				if tmpInfo, ok := viewReportMap[tmpKey]; ok {
					tmpInfo.ResearchReportName = v.Title
					tmpInfo.ReportType = `rddp`
					tmpInfo.MatchTypeName = v.ClassifyNameFirst
					viewReportMap[tmpKey] = tmpInfo
				}
			}
		case 2: // weekly报告
			tmpReportList, err := models.GetResearchReportListByIdList(reportIdList)
			if err != nil {
				br.Msg = "获取失败"
				br.Msg = "获取weekly报告详情失败,Err:" + err.Error()
				return
			}
			for _, v := range tmpReportList {
				tmpKey := fmt.Sprint(source, "_", v.ResearchReportId)
				if tmpInfo, ok := viewReportMap[tmpKey]; ok {
					tmpInfo.ResearchReportName = v.ResearchReportName
					tmpInfo.ReportType = v.Type
					viewReportMap[tmpKey] = tmpInfo
				}
			}
		case 3: // weekly_report商品的报告（应该是作废了）；
			tmpReportList, err := models.GetChartPermissionByIdList(reportIdList)
			if err != nil {
				br.Msg = "获取失败"
				br.Msg = "获取weekly报告详情失败,Err:" + err.Error()
				return
			}
			for _, v := range tmpReportList {
				tmpKey := fmt.Sprint(source, "_", v.ChartPermissionId)
				if tmpInfo, ok := viewReportMap[tmpKey]; ok {
					tmpInfo.ResearchReportName = v.ChartPermissionName
					tmpInfo.ReportType = `advisory`
					tmpInfo.MatchTypeName = v.ClassifyName
					viewReportMap[tmpKey] = tmpInfo
				}
			}
		case 4: // 察研观向的报告
			tmpReportList, err := cygx.GetArticleListByIdList(reportIdList)
			if err != nil {
				br.Msg = "获取失败"
				br.Msg = "获取weekly报告详情失败,Err:" + err.Error()
				return
			}
			for _, v := range tmpReportList {
				tmpKey := fmt.Sprint(source, "_", v.ArticleId)
				if tmpInfo, ok := viewReportMap[tmpKey]; ok {
					tmpInfo.ResearchReportName = v.Title
					tmpInfo.ReportType = `cygx`
					tmpInfo.MatchTypeName = v.MatchTypeName
					viewReportMap[tmpKey] = tmpInfo
				}
			}

		}
	}

	// 报告标题处理
	for _, v := range recordList {
		tmpKey := fmt.Sprint(v.Source, "_", v.ReportId)
		if tmpInfo, ok := viewReportMap[tmpKey]; ok {
			stopTime := `--`
			if v.StopTime > 0 {
				stopTime = fmt.Sprint(v.StopTime)
			}
			list = append(list, &company.ViewReportList{
				ResearchReportName: tmpInfo.ResearchReportName,
				ReportType:         tmpInfo.ReportType,
				CreatedTime:        v.CreateTime,
				TxtType:            tmpInfo.TxtType,
				MatchTypeName:      tmpInfo.MatchTypeName,
				StopTime:           stopTime,
			})
		}
	}

	// 类型处理
	for k, v := range list {
		if v.ReportType == "day" {
			list[k].MatchTypeName = "晨报"
		} else if v.ReportType == "week" {
			list[k].MatchTypeName = "周报"
		} else if v.ReportType == "two_week" {
			list[k].MatchTypeName = "双周报"
		} else if v.ReportType == "month" {
			list[k].MatchTypeName = "月报"
		} else if v.ReportType == "rddp" {
			//list[k].MatchTypeName = "日评"
			createdTime := utils.StrTimeToTime(v.CreatedTime)
			monthStr := createdTime.Format("01")
			dayStr := strconv.Itoa(createdTime.Day())
			if len(dayStr) == 1 {
				dayStr = "0" + dayStr
			}
			list[k].ResearchReportName += "(" + monthStr + dayStr + ")"
		}
		if v.StopTime != "--" {
			list[k].StopTime += "s"
		}
	}
	resp := new(company.ViewReportListResp)
	resp.List = list
	resp.Total = total
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 导出潜在用户
// @Description 导出潜在用户接口
// @Param   ApplyMethod   query   int  true       "申请方式，0：全部，1:未申请，2:已付费客户申请试用，3:非客户申请试用"
// @Param   KeyWord   query   string  true       "搜索关键词"
// @Success Ret=200 导出成功
// @router /potential/user/export [get]
func (this *CompanyUserController) PotentialUserExport() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	keyWord := this.GetString("KeyWord")
	applyMethod, _ := this.GetInt("ApplyMethod")

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	list := make([]*models.PotentialUserItem, 0)
	//管理员才让导出数据
	if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
		var condition string
		var pars []interface{}
		if applyMethod > 0 {
			condition += ` AND apply_method=? `
			pars = append(pars, applyMethod-1)
		}
		if keyWord != "" {
			condition += ` AND (a.nick_name LIKE '%` + keyWord + `%' OR a.mobile LIKE '%` + keyWord + `%' OR a.email LIKE '%` + keyWord + `%') `
		}
		tmpList, err := models.GetPotentialUserListExport(condition, pars)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
		list = tmpList
	}

	dir, err := os.Executable()
	exPath := filepath.Dir(dir)
	downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	xlsxFile := xlsx.NewFile()
	if err != nil {
		br.Msg = "生成文件失败"
		br.ErrMsg = "生成文件失败"
		return
	}
	style := xlsx.NewStyle()
	alignment := xlsx.Alignment{
		Horizontal: "center",
		Vertical:   "center",
		WrapText:   true,
	}

	style.Alignment = alignment
	style.ApplyAlignment = true

	sheel, err := xlsxFile.AddSheet("客户数据")
	if err != nil {
		br.Msg = "新增Sheet失败"
		br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
		return
	}
	titleRow := sheel.AddRow()
	titleRow.AddCell().SetValue("姓名")
	titleRow.AddCell().SetValue("手机号")
	titleRow.AddCell().SetValue("邮箱")
	titleRow.AddCell().SetValue("注册时间")
	titleRow.AddCell().SetValue("公司")
	titleRow.AddCell().SetValue("申请类型")
	titleRow.AddCell().SetValue("累计阅读次数")
	titleRow.AddCell().SetValue("最后一次阅读时间")

	for _, v := range list {
		dataRow := sheel.AddRow()
		dataRow.SetHeight(20)
		dataRow.AddCell().SetString(v.RealName)
		dataRow.AddCell().SetString(v.Mobile)
		dataRow.AddCell().SetString(v.Email)
		dataRow.AddCell().SetString(v.CreatedTime)
		dataRow.AddCell().SetString(v.CompanyName)
		if v.ApplyMethod == 0 {
			dataRow.AddCell().SetString("未申请")
		} else if v.ApplyMethod == 1 {
			dataRow.AddCell().SetString("已付费客户申请试用")
		} else {
			dataRow.AddCell().SetString("非客户申请试用")
		}
		reportView, err := models.GetReportViewMaxTime(int(v.UserId))
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取GetReportViewMaxTime失败，Err:" + err.Error()
			return
		}
		if reportView.LastViewTime.After(v.LastViewTime) {
			v.LastViewTimeStr = v.LastViewTime.Format(utils.FormatDateTime)
		} else {
			v.LastViewTimeStr = v.LastViewTime.Format(utils.FormatDateTime)
		}
		v.ViewTotal += reportView.ViewTotal
		dataRow.AddCell().SetInt(v.ViewTotal)
		if v.LastViewTimeStr == "0001-01-01 00:00:00" {
			v.LastViewTimeStr = ""
		}
		dataRow.AddCell().SetString(v.LastViewTimeStr)
	}

	err = xlsxFile.Save(downLoadnFilePath)
	if err != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败"
		return
	}
	randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
	downloadFileName := "潜在用户列表_" + randStr + ".xlsx"
	this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
	defer func() {
		os.Remove(downLoadnFilePath)
	}()
	br.Ret = 200
	br.Success = true
	br.Msg = "导出成功"
}

// @Title 获取批量导入联系人数据
// @Description 获取批量导入联系人数据
// @Param   File   query   file  true       "文件"
// @Param   CompanyId   query   file  true       "客户id"
// @Success 200 {object} models.ImportListResp
// @router /import/list [post]
func (this *CompanyUserController) ImportList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请重新登录"
		return
	}
	file, h, err := this.GetFile("File")
	if err != nil {
		br.Msg = "获取文件失败"
		br.ErrMsg = "获取文件失败，Err:" + err.Error()
		return
	}
	companyId, _ := this.GetInt("CompanyId")
	if companyId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "客户id为0"
		return
	}

	//产品id
	productId := services.GetProductId(sysUser.RoleTypeCode)

	//操作权限校验
	errMsg, err := checkOpCompanyUserByCompanyId(companyId, productId, sysUser.AdminId, sysUser.RoleTypeCode)
	if err != nil {
		br.Msg = "导入失败！" + errMsg
		br.ErrMsg = "导入失败，Err:" + err.Error()
		return
	}
	//userBusinessCardCount := 0
	//if productId > 0 {
	//	tmpUserBusinessCardCount, err := models.GetCompanyUserBusinessCardCountByProductId(companyId, productId)
	//	if err != nil {
	//		br.Msg = "导入失败"
	//		br.ErrMsg = "判断是否已经存在上传名片联系人失败,err:" + err.Error()
	//		return
	//	}
	//	userBusinessCardCount = tmpUserBusinessCardCount
	//} else {
	//	tmpUserBusinessCardCount, err := company.GetCompanyUserBusinessCardCount(companyId)
	//	if err != nil {
	//		br.Msg = "导入失败"
	//		br.ErrMsg = "判断是否已经存在上传名片联系人失败,err:" + err.Error()
	//		return
	//	}
	//	userBusinessCardCount = tmpUserBusinessCardCount
	//}
	//
	//if userBusinessCardCount <= 0 {
	//	br.Msg = "请先至少添加一位名片联系人"
	//	return
	//}

	//客户信息
	companyInfo, err := company.GetCompanyById(companyId)
	if err != nil {
		br.Msg = "导入异常"
		br.Msg = "导入异常：" + err.Error()
		return
	}

	uploadDir := "static/xls"
	err = os.MkdirAll(uploadDir, 766)
	if err != nil {
		br.Msg = "存储目录创建失败"
		br.ErrMsg = "存储目录创建失败,Err:" + err.Error()
		return
	}
	path := uploadDir + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + h.Filename
	defer file.Close()
	err = this.SaveToFile("File", path)
	if err != nil {
		br.Msg = "文件保存失败"
		br.ErrMsg = "文件保存失败，Err:" + err.Error()
		return
	}
	xlFile, err := xlsx.OpenFile(path)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "打开文件失败，Err:" + err.Error() + ";path:" + path
		return
	}
	existUser := make([]*models.WxUser, 0)

	//excel中已经存在的数据，用来判断excel中是否存在相同手机号/邮箱，避免重复提交
	excelData := make(map[string]string)
	//重复数据
	repeatUser := make([]*models.WxUser, 0)

	// 遍历sheet页读取
	for _, sheet := range xlFile.Sheets {
		//遍历行读取
		maxRow := sheet.MaxRow
		fmt.Println("maxRow:", maxRow)
		fmt.Println("maxRow")
		for i := 0; i < maxRow; i++ {
			if i == 0 {
				row := sheet.Row(i)
				cells := row.Cells
				for k, cell := range cells {
					text := cell.String()
					if k == 0 {
						if text != "姓名" {
							br.Msg = "模板格式错误"
							br.ErrMsg = "模板格式错误，title:" + text
							return
						}
					}
					if k == 1 {
						if !strings.Contains(text, "性别") {
							br.Msg = "模板格式错误"
							br.ErrMsg = "模板格式错误，title:" + text
							return
						}
					}
					if k == 2 {
						if !strings.Contains(text, "国际区号（中国大陆填写：86）") {
							br.Msg = "模板格式错误"
							br.ErrMsg = "模板格式错误，title:" + text
							return
						}
					}
					if k == 3 {
						if !strings.Contains(text, "手机号") {
							br.Msg = "模板格式错误"
							br.ErrMsg = "模板格式错误，title:" + text
							return
						}
					}
					if k == 4 {
						if !strings.Contains(text, "邮箱") {
							br.Msg = "模板格式错误"
							br.ErrMsg = "模板格式错误，title:" + text
							return
						}
					}
					if k == 5 {
						if !strings.Contains(text, "是否决策人") {
							br.Msg = "模板格式错误"
							br.ErrMsg = "模板格式错误，title:" + text
							return
						}
					}
					if k == 6 {
						if !strings.Contains(text, "职位") {
							br.Msg = "模板格式错误"
							br.ErrMsg = "模板格式错误，title:" + text
							return
						}
					}
					if k == 7 {
						if !strings.Contains(text, "部门") {
							br.Msg = "模板格式错误"
							br.ErrMsg = "模板格式错误，title:" + text
							return
						}
					}
				}
			}
			if i >= 1 {
				row := sheet.Row(i)
				cells := row.Cells
				var userName, sex, countryCode, mobileOne, email, isMaker, position, departmentName string
				for k, cell := range cells {
					if k == 0 {
						userName = cell.String()
					}
					if k == 1 {
						sex = cell.String()
					}
					if k == 2 {
						countryCode = cell.String()
					}
					if k == 3 {
						mobileOne = cell.String()
					}
					if k == 4 {
						email = cell.String()
					}
					if k == 5 {
						isMaker = cell.String()
					}
					if k == 6 {
						position = cell.String()
					}
					if k == 7 {
						departmentName = cell.String()
					}
				}

				//移除空格
				mobileOne = utils.TrimStr(mobileOne)
				email = utils.TrimStr(email)

				//这些字段都没有的话，系统认为excel到底了
				if userName == "" && sex == "" && mobileOne == "" {
					break
				}
				if userName == "" {
					continue
				}

				//如果手机号或者邮箱都没有填写的情况下
				if mobileOne == "" && email == "" {
					continue
				}
				if mobileOne != "" && countryCode == "" {
					br.Msg = "导入数据中存在【国际区号】为空的联系人，请检查"
					return
				}
				//如果是权益，且是海外用户的情况下，那么手机号、邮箱有一个没有填写的情况下，那么退出当前循环
				if productId == 2 && companyInfo.RegionType == "海外" && (mobileOne == "" || email == "") {
					continue
				}

				item := new(models.WxUser)
				item.CountryCode = countryCode
				item.RealName = userName
				if sex == "男" {
					item.Sex = 1
				} else if sex == "女" {
					item.Sex = 2
				} else {
					item.Sex = 0
				}
				item.Mobile = mobileOne
				item.Email = email
				if isMaker == "是" {
					item.IsMaker = 1
				} else {
					item.IsMaker = 0
				}
				item.Position = position
				item.DepartmentName = departmentName

				if mobileOne != "" {
					if _, ok := excelData[mobileOne]; ok {
						//将用户插入其中，然后退出当前循环，进入下一循环
						repeatUser = append(repeatUser, item)
						continue
					}
					excelData[mobileOne] = ""
				}
				if email != "" {
					if _, ok := excelData[email]; ok {
						//将用户插入其中，然后退出当前循环，进入下一循环
						repeatUser = append(repeatUser, item)
						continue
					}
					excelData[mobileOne] = ""
				}

				//没问题数据
				existUser = append(existUser, item)
			}
		}
	}

	//defer func() {
	//	os.Remove(path)
	//}()
	br.Msg = "获取成功"
	br.Ret = 200
	br.Success = true
	br.Data = models.ImportListResp{
		ValidUser:  existUser,
		RepeatUser: repeatUser,
	}
}

// 需要更新的联系人数据实体
type UpdateWxUser struct {
	OldWxUser models.WxUser  `description:"旧的联系人数据orm实体（未变更前的）"`
	WxUser    *models.WxUser `description:"联系人数据orm实体"`
	Cols      []string       `description:"需要修改的字段名切片"`
}

// @Title 批量导入联系人数据
// @Description 批量导入联系人数据
// @Param   File   query   file  true       "文件"
// @Param   CompanyId   query   file  true       "客户id"
// @Success 600 {object} []*company.CompanyUser
// @Success 200 Ret=200 导入成功
// @router /import [post]
func (this *CompanyUserController) Import() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请重新登录"
		return
	}
	file, h, err := this.GetFile("File")
	if err != nil {
		br.Msg = "获取文件失败"
		br.ErrMsg = "获取文件失败，Err:" + err.Error()
		return
	}
	companyId, _ := this.GetInt("CompanyId")
	if companyId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "客户id为0"
		return
	}
	//产品id
	productId := services.GetProductId(sysUser.RoleTypeCode)

	//操作权限校验
	errMsg, err := checkOpCompanyUserByCompanyId(companyId, productId, sysUser.AdminId, sysUser.RoleTypeCode)
	if err != nil {
		br.Msg = "导入失败！" + errMsg
		br.ErrMsg = "导入失败，Err:" + err.Error()
		return
	}
	//userBusinessCardCount := 0
	//if productId > 0 {
	//	tmpUserBusinessCardCount, err := models.GetCompanyUserBusinessCardCountByProductId(companyId, productId)
	//	if err != nil {
	//		br.Msg = "导入失败"
	//		br.ErrMsg = "判断是否已经存在上传名片联系人失败,err:" + err.Error()
	//		return
	//	}
	//	userBusinessCardCount = tmpUserBusinessCardCount
	//} else {
	//	tmpUserBusinessCardCount, err := company.GetCompanyUserBusinessCardCount(companyId)
	//	if err != nil {
	//		br.Msg = "导入失败"
	//		br.ErrMsg = "判断是否已经存在上传名片联系人失败,err:" + err.Error()
	//		return
	//	}
	//	userBusinessCardCount = tmpUserBusinessCardCount
	//}
	//
	//if userBusinessCardCount <= 0 {
	//	br.Msg = "请先至少添加一位名片联系人"
	//	return
	//}

	uploadDir := "static/xls"
	err = os.MkdirAll(uploadDir, 766)
	if err != nil {
		br.Msg = "存储目录创建失败"
		br.ErrMsg = "存储目录创建失败,Err:" + err.Error()
		return
	}
	path := uploadDir + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + h.Filename
	defer file.Close()
	err = this.SaveToFile("File", path)
	if err != nil {
		br.Msg = "文件保存失败"
		br.ErrMsg = "文件保存失败，Err:" + err.Error()
		return
	}
	xlFile, err := xlsx.OpenFile(path)
	if err != nil {
		br.Msg = "文件导入失败"
		br.ErrMsg = "文件导入失败，Err:" + err.Error()
		return
	}

	//获取当前操作员产品权限列表
	companyProductList, productErr := getSysCompanyProductList(productId, companyId)
	if productErr != nil {
		br.Msg = "新增失败"
		br.ErrMsg = "新增失败，获取当前操作员产品权限异常,Err:" + productErr.Error()
		return
	}
	if companyProductList == nil {
		br.Msg = "新增失败"
		br.ErrMsg = "新增失败，获取当前操作员找不到产品权限"
		return
	}

	//客户信息
	companyInfo, err := company.GetCompanyById(companyId)
	if err != nil {
		br.Msg = "导入异常"
		br.Msg = "导入异常：" + err.Error()
		return
	}

	//已存在联系人的切片
	existUser := make([]*company.CompanyUser, 0)
	//待添加销售员与联系人关系的切片
	notRelationUser := make([]map[int]*company.CompanyUser, 0)
	//允许添加的联系人
	needAddUser := make([]*models.WxUserDetail, 0)

	//excel中已经存在的数据，用来判断excel中是否存在相同手机号/邮箱，避免重复提交
	excelData := make(map[string]string)

	//需要更新的数据实体切片
	updateWxUserSlice := make([]UpdateWxUser, 0)

	// 遍历sheet页读取
	for _, sheet := range xlFile.Sheets {
		//遍历行读取
		maxRow := sheet.MaxRow
		for i := 0; i < maxRow; i++ {
			if i == 0 {
				row := sheet.Row(i)
				cells := row.Cells
				for k, cell := range cells {
					text := cell.String()
					if k == 0 {
						if text != "姓名" {
							br.Msg = "模板格式错误"
							br.ErrMsg = "模板格式错误，title:" + text
							return
						}
					}
					if k == 1 {
						if !strings.Contains(text, "性别") {
							br.Msg = "模板格式错误"
							br.ErrMsg = "模板格式错误，title:" + text
							return
						}
					}
					if k == 2 {
						if !strings.Contains(text, "国际区号（中国大陆填写：86）") {
							br.Msg = "模板格式错误"
							br.ErrMsg = "模板格式错误，title:" + text
							return
						}
					}
					if k == 3 {
						if !strings.Contains(text, "手机号") {
							br.Msg = "模板格式错误"
							br.ErrMsg = "模板格式错误，title:" + text
							return
						}
					}
					if k == 4 {
						if !strings.Contains(text, "邮箱") {
							br.Msg = "模板格式错误"
							br.ErrMsg = "模板格式错误，title:" + text
							return
						}
					}
					if k == 5 {
						if !strings.Contains(text, "是否决策人") {
							br.Msg = "模板格式错误"
							br.ErrMsg = "模板格式错误，title:" + text
							return
						}
					}
					if k == 6 {
						if !strings.Contains(text, "职位") {
							br.Msg = "模板格式错误"
							br.ErrMsg = "模板格式错误，title:" + text
							return
						}
					}
					if k == 7 {
						if !strings.Contains(text, "部门") {
							br.Msg = "模板格式错误"
							br.ErrMsg = "模板格式错误，title:" + text
							return
						}
					}
				}
			}
			if i >= 1 {
				row := sheet.Row(i)
				cells := row.Cells
				var userName, sex, countryCode, mobileOne, email, isMaker, position, departmentName string
				for k, cell := range cells {
					if k == 0 {
						userName = cell.String()
					}
					if k == 1 {
						sex = cell.String()
					}
					if k == 2 {
						countryCode = strings.Replace(cell.String(), "+", "", -1)
						countryCode = strings.Replace(countryCode, "-", "", -1)
						countryCode = strings.Replace(countryCode, " ", "", -1)
					}
					if k == 3 {
						mobileOne = cell.String()
					}
					if k == 4 {
						email = cell.String()
					}
					if k == 5 {
						isMaker = cell.String()
					}
					if k == 6 {
						position = cell.String()
					}
					if k == 7 {
						departmentName = cell.String()
					}
				}

				//移除空格
				mobileOne = utils.TrimStr(mobileOne)
				email = utils.TrimStr(email)

				//这些字段都没有的话，系统认为excel到底了
				if userName == "" && sex == "" && mobileOne == "" {
					break
				}

				if userName == "" {
					br.Msg = "导入数据中存在【姓名】为空的联系人，请检查"
					return
				}
				if sex == "" {
					br.Msg = "导入数据中存在【性别】为空的联系人，请检查"
					return
				}
				if mobileOne != "" && countryCode == "" {
					br.Msg = "导入数据中存在【国际区号】为空的联系人，请检查"
					return
				}
				// 大陆区号校验手机号
				if mobileOne != "" && (countryCode == "86" || countryCode == "086" || countryCode == "+86" || countryCode == "+086") {
					if !utils.ValidateMobileFormatat(mobileOne) {
						br.Msg = "导入数据中存在【大陆手机号】格式有误的联系人，请检查"
						return
					}
				}

				//如果手机号或者邮箱都没有填写的情况下
				if mobileOne == "" && email == "" {
					continue
				}
				//如果是权益，且是海外用户的情况下，那么手机号、邮箱有一个没有填写的情况下，那么退出当前循环
				if productId == 2 && companyInfo.RegionType == "海外" && (mobileOne == "" || email == "") {
					continue
				}
				if isMaker == "" {
					br.Msg = "导入数据中存在【决策人】为空的联系人，请检查"
					return
				}

				item := new(models.WxUserDetail)

				item.RealName = userName
				if sex == "男" {
					item.Sex = 1
				} else if sex == "女" {
					item.Sex = 2
				} else {
					item.Sex = 0
				}
				item.Mobile = mobileOne
				item.Email = email
				if isMaker == "是" {
					item.IsMaker = 1
				} else {
					item.IsMaker = 0
				}
				item.Position = position
				item.DepartmentName = departmentName
				item.SellerRealName = companyProductList[0].SellerName
				item.CompanyName = companyProductList[0].CompanyName

				var mobileOneItem, emailItem *company.CompanyUser
				var mobileNotRelationUserMap, emailNotRelationUserMap map[int]*company.CompanyUser

				//手机号校验
				if mobileOne != "" {
					if _, ok := excelData[mobileOne]; ok {
						br.Msg = "excel表数据异常，存在重复的手机号:" + mobileOne + "，请检查excel表格数据"
						br.ErrMsg = "excel表数据异常，存在重复的手机号:" + mobileOne + "，请检查excel表格数据"
						return
					}
					excelData[mobileOne] = ""

					tmpMobileOneItem, err := company.GetUserCountByMobile(mobileOne)
					if err != nil && err.Error() != utils.ErrNoRow() {
						br.Msg = "新增失败"
						br.ErrMsg = "判断手机号1是否存在,Err:" + err.Error()
						return
					}
					mobileOneItem = tmpMobileOneItem

					if mobileOneItem != nil {
						if mobileOneItem.UserId > 0 {
							hasMove := true //是否可移动

							//如果是大于 1 的客户，那么就是非潜在客户，需要去查询对应的销售
							if mobileOneItem.CompanyId > 1 {
								//获取联系人分组信息
								userSellerGroupInfoList, err := models.GetUserGroupSellersByUserId(int(mobileOneItem.UserId))

								//根据分组校验
								if err == nil && len(userSellerGroupInfoList) > 0 {
									sellerMap := make(map[int]string)    //销售信息map
									sellerNameSlice := make([]string, 0) //销售姓名切片
									for _, v := range userSellerGroupInfoList {
										if v.Status != utils.COMPANY_STATUS_LOSE && v.Status != utils.COMPANY_STATUS_FOREVER && hasMove == true {
											hasMove = false
										}
										if _, ok := sellerMap[v.SellerId]; ok {
											continue
										}
										sellerMap[v.SellerId] = v.SellerRealName
										sellerNameSlice = append(sellerNameSlice, v.SellerRealName)
									}
									mobileOneItem.SellerRealName = strings.Join(sellerNameSlice, "/")
								}
							}

							item.SellerRealName = mobileOneItem.SellerRealName

							item.CompanyName = mobileOneItem.CompanyName

							//判断该联系人的 客户企业编号 是否与 当前客户编号 一致，如果不一致，那么将该联系人加入到已经存在的联系人列表中去，并终止当前循环，进入下一循环。
							if mobileOneItem.CompanyId != companyId {
								mobileOneItem.HasMove = hasMove //是否可移动

								if hasMove {
									if mobileOneItem.RealName != item.RealName {
										mobileOneItem.RealName = item.RealName
									}
									if mobileOneItem.DepartmentName != item.DepartmentName {
										mobileOneItem.DepartmentName = item.DepartmentName
									}
									if mobileOneItem.RealName != item.RealName {
										mobileOneItem.RealName = item.RealName
									}
								}
								mobileOneItem.CountryCode = countryCode
								existUser = append(existUser, mobileOneItem)
								continue
							}

							//判断该用户与当前账号是否存在关系，如果没有关系，那么直接返回
							notRelationUserMap, checkErr := checkProductListUser(*item, mobileOneItem, companyProductList)
							//sql异常
							if checkErr != nil && checkErr.Error() != utils.ErrNoRow() {
								br.Msg = "新增失败"
								br.ErrMsg = "新增失败,Err:" + checkErr.Error()
								return
							}
							mobileNotRelationUserMap = notRelationUserMap
						}
					}
				}
				//邮箱校验
				if email != "" {
					if _, ok := excelData[email]; ok {
						br.Msg = "excel表数据异常，存在重复的邮箱:" + email + "，请检查excel表格数据"
						br.ErrMsg = "excel表数据异常，存在重复的邮箱:" + email + "，请检查excel表格数据"
						return
					}
					excelData[email] = ""

					tmpEmailItem, err := company.CheckCompanyUserCountByEmail(email)
					if err != nil && err.Error() != utils.ErrNoRow() {
						br.Msg = "新增失败"
						br.ErrMsg = "新增失败,Err:" + err.Error()
						return
					}
					emailItem = tmpEmailItem
					if emailItem != nil {
						if emailItem.UserId > 0 {
							hasMove := true //是否可移动

							//如果是大于 1 的客户，那么就是非潜在客户，需要去查询对应的销售
							if emailItem.CompanyId > 1 {
								//获取联系人分组信息
								userSellerGroupInfoList, err := models.GetUserGroupSellersByUserId(int(emailItem.UserId))

								//根据分组校验
								if err == nil && len(userSellerGroupInfoList) > 0 {
									sellerMap := make(map[int]string)    //销售信息map
									sellerNameSlice := make([]string, 0) //销售姓名切片
									for _, v := range userSellerGroupInfoList {
										if v.Status != utils.COMPANY_STATUS_LOSE && v.Status != utils.COMPANY_STATUS_FOREVER && hasMove == true {
											hasMove = false
										}
										if _, ok := sellerMap[v.SellerId]; ok {
											continue
										}
										sellerMap[v.SellerId] = v.SellerRealName
										sellerNameSlice = append(sellerNameSlice, v.SellerRealName)
									}
									emailItem.SellerRealName = strings.Join(sellerNameSlice, "/")
								}
							}

							item.SellerRealName = emailItem.SellerRealName

							item.CompanyName = emailItem.CompanyName

							//判断该联系人的 客户企业编号 是否与 当前客户编号 一致，如果不一致，那么将该联系人加入到已经存在的联系人列表中去，并终止当前循环，进入下一循环。
							if emailItem.CompanyId != companyId {
								emailItem.HasMove = hasMove //是否可移动

								if hasMove {
									if emailItem.RealName != item.RealName {
										emailItem.RealName = item.RealName
									}
									if emailItem.DepartmentName != item.DepartmentName {
										emailItem.DepartmentName = item.DepartmentName
									}
									if emailItem.RealName != item.RealName {
										emailItem.RealName = item.RealName
									}
								}
								emailItem.CountryCode = countryCode
								existUser = append(existUser, emailItem)
								continue
							}

							//判断该用户与当前账号是否存在关系，如果没有关系，那么直接返回
							notRelationUserMap, checkErr := checkProductListUser(*item, emailItem, companyProductList)
							//sql异常
							if checkErr != nil && checkErr.Error() != utils.ErrNoRow() {
								br.Msg = "新增失败"
								br.ErrMsg = "新增失败,Err:" + checkErr.Error()
								return
							}
							//判断该用户与销售是否存在关系，如果不存在，那么加入到 待添加关系 的切片中
							emailNotRelationUserMap = notRelationUserMap
						}
					}
				}

				//如果系统已存在该联系人，那么逻辑处理后退出当前循环，进入下一循环
				if mobileOneItem != nil || emailItem != nil {
					//如果既存在该手机号联系人，也存在该邮箱联系人；那么需要去判断 这 两个 联系人 是不是同一个，
					//如果不是同一个联系人的话，那么只添加对应的关系，不去修改对应的数据
					var wxUserItem *models.WxUser
					var oldTmpWxUserItem models.WxUser
					cols := make([]string, 0)

					if mobileOneItem != nil && emailItem != nil {
						//如果两个联系人 不是 同一个
						if mobileOneItem.UserId != emailItem.UserId {
							notRelationUser = append(notRelationUser, mobileNotRelationUserMap, emailNotRelationUserMap)
							//wxUserItem = mobileOneItem
						} else {
							//如果两个联系人 是 同一个
							notRelationUser = append(notRelationUser, mobileNotRelationUserMap)

							tmpWxUserItem, err := models.GetWxUserByUserId(int(mobileOneItem.UserId))
							if err != nil {
								br.Msg = "导入失败"
								br.ErrMsg = "查询联系人信息失败,Err:" + err.Error()
								return
							}
							oldTmpWxUserItem := *tmpWxUserItem
							if tmpWxUserItem.IsMaker != item.IsMaker {
								tmpWxUserItem.IsMaker = item.IsMaker
								cols = append(cols, "IsMaker")
							}
							if tmpWxUserItem.DepartmentName != item.DepartmentName {
								tmpWxUserItem.DepartmentName = item.DepartmentName
								cols = append(cols, "DepartmentName")
							}
							if tmpWxUserItem.RealName != item.RealName {
								tmpWxUserItem.RealName = item.RealName
								cols = append(cols, "RealName")
							}
							if len(cols) > 0 {
								updateWxUser := UpdateWxUser{
									OldWxUser: oldTmpWxUserItem,
									WxUser:    tmpWxUserItem,
									Cols:      cols,
								}
								updateWxUserSlice = append(updateWxUserSlice, updateWxUser)
							}
							wxUserItem = tmpWxUserItem
						}
					} else if mobileOneItem != nil {
						//如果只存在 手机号联系人
						notRelationUser = append(notRelationUser, mobileNotRelationUserMap)

						//获取联系人orm实体类
						tmpWxUserItem, err := models.GetWxUserByUserId(int(mobileOneItem.UserId))
						if err != nil {
							br.Msg = "导入失败"
							br.ErrMsg = "查询联系人信息失败,Err:" + err.Error()
							return
						}
						oldTmpWxUserItem = *tmpWxUserItem
						if tmpWxUserItem.IsMaker != item.IsMaker {
							tmpWxUserItem.IsMaker = item.IsMaker
							cols = append(cols, "IsMaker")
						}
						if tmpWxUserItem.DepartmentName != item.DepartmentName && item.DepartmentName != "" {
							tmpWxUserItem.DepartmentName = item.DepartmentName
							cols = append(cols, "DepartmentName")
						}
						if tmpWxUserItem.RealName != item.RealName && item.RealName != "" {
							tmpWxUserItem.RealName = item.RealName
							cols = append(cols, "RealName")
						}
						if tmpWxUserItem.Email != item.Email && item.Email != "" {
							tmpWxUserItem.Email = item.Email
							cols = append(cols, "Email")
						}
						wxUserItem = tmpWxUserItem
					} else if emailItem != nil {
						//如果只存在 邮箱联系人
						notRelationUser = append(notRelationUser, emailNotRelationUserMap)

						//获取联系人orm实体类
						tmpWxUserItem, err := models.GetWxUserByUserId(int(emailItem.UserId))
						if err != nil {
							br.Msg = "导入失败"
							br.ErrMsg = "查询联系人信息失败,Err:" + err.Error()
							return
						}
						oldTmpWxUserItem = *tmpWxUserItem
						if tmpWxUserItem.IsMaker != item.IsMaker {
							tmpWxUserItem.IsMaker = item.IsMaker
							cols = append(cols, "IsMaker")
						}
						if tmpWxUserItem.DepartmentName != item.DepartmentName && item.DepartmentName != "" {
							tmpWxUserItem.DepartmentName = item.DepartmentName
							cols = append(cols, "DepartmentName")
						}
						if tmpWxUserItem.RealName != item.RealName && item.RealName != "" {
							tmpWxUserItem.RealName = item.RealName
							cols = append(cols, "RealName")
						}
						if tmpWxUserItem.Email != item.Email && item.Email != "" {
							tmpWxUserItem.Email = item.Email
							cols = append(cols, "Email")
						}
						wxUserItem = tmpWxUserItem
					}

					//如果变更字段数量大于0
					if len(cols) > 0 {
						updateWxUser := UpdateWxUser{
							OldWxUser: oldTmpWxUserItem,
							WxUser:    wxUserItem,
							Cols:      cols,
						}
						updateWxUserSlice = append(updateWxUserSlice, updateWxUser)
					}
					continue
				}

				//确实系统中不存在该用户
				item.CountryCode = countryCode
				needAddUser = append(needAddUser, item)
			}
		}
	}

	fmt.Println("表格中用户与系统中存在用户没有冲突")
	//如果表格中用户与系统中存在用户 没有冲突，那么继续执行
	for _, user := range needAddUser {
		if user.RealName != "" && (user.Mobile != "" || user.Email != "") {
			userData := new(models.WxUser)
			userData.RealName = user.RealName
			userData.Sex = user.Sex
			userData.Mobile = user.Mobile
			userData.CountryCode = user.CountryCode
			userData.OutboundMobile = user.Mobile
			userData.OutboundCountryCode = user.CountryCode
			userData.Email = user.Email
			userData.Position = user.Position
			userData.IsMaker = user.IsMaker
			userData.CompanyId = companyId
			userData.DepartmentName = user.DepartmentName
			userData.CountryCode = user.CountryCode

			//判断该手机号、邮箱是否已经添加，如果已经添加，那么就不再添加
			var key string
			if user.Mobile != "" {
				key = "wx_user:mobile:" + userData.Mobile
			} else {
				key = "wx_user:email:" + userData.Email
			}
			isHas := utils.Rc.IsExist(key)
			if isHas == false {
				newId, err := models.AddWxUser(userData)
				userData.UserId = newId
				if err != nil {
					br.Msg = "导入失败"
					br.ErrMsg = "导入失败,Err:" + err.Error()
					return
				}
				//添加联系人与销售员的关系
				for _, companyProduct := range companyProductList {
					models.AddUserSellerRelation(newId, companyProduct.CompanyId, companyProduct.SellerId, companyProduct.ProductId, companyProduct.SellerName, user.Mobile, user.Email)
				}

				//联系人信息
				userInfo, _ := json.Marshal(userData)
				go services.AddWxUserOpLog(company.WxUserOpLog{
					LogType:                "import",
					UserId:                 int(userData.UserId),
					CompanyId:              userData.CompanyId,
					Mobile:                 userData.Mobile,
					Email:                  userData.Email,
					OriginalUserInfo:       "",
					UserInfo:               string(userInfo),
					OriginalUserSellerInfo: "",
					UserSellerInfo:         "",
					OpUserId:               sysUser.AdminId,
					OpUserName:             sysUser.RealName,
					CreateTime:             time.Now(),
				})
			}
		}
	}

	//添加已经存在的联系人与销售员关系
	fmt.Println("开始添加已经存在的联系人与销售员关系")
	for _, notRelationUserMap := range notRelationUser {
		if item, ok := notRelationUserMap[1]; ok {
			//添加联系人与销售员的关系
			mobileOne := item.Mobile
			mobileTwo := item.MobileTwo
			email := item.Email
			businessCardUrl := item.BusinessCardUrl
			//对老数据做新增字段处理
			_ = company.EditCompanyUserContact(item.UserId, mobileOne, mobileTwo, email, businessCardUrl)

			models.AddUserSellerRelation(item.UserId, item.CompanyId, item.SellerId, 1, item.SellerName, item.Mobile, item.Email)
		}

		if item, ok := notRelationUserMap[2]; ok {
			//添加联系人与销售员的关系
			mobileOne := item.Mobile
			mobileTwo := item.MobileTwo
			email := item.Email
			businessCardUrl := item.BusinessCardUrl
			//对老数据做新增字段处理
			_ = company.EditCompanyUserContact(item.UserId, mobileOne, mobileTwo, email, businessCardUrl)

			models.AddUserSellerRelation(item.UserId, item.CompanyId, item.SellerId, 2, item.SellerName, item.Mobile, item.Email)
		}
	}

	fmt.Println("开始更新联系人信息")
	for _, updateWxUser := range updateWxUserSlice {
		_ = updateWxUser.WxUser.Update(updateWxUser.Cols)

		//联系人信息
		originalUserInfo, _ := json.Marshal(updateWxUser.OldWxUser)
		userInfo, _ := json.Marshal(updateWxUser.WxUser)
		go services.AddWxUserOpLog(company.WxUserOpLog{
			LogType:                "import",
			UserId:                 int(updateWxUser.WxUser.UserId),
			CompanyId:              updateWxUser.WxUser.CompanyId,
			Mobile:                 updateWxUser.WxUser.Mobile,
			Email:                  updateWxUser.WxUser.Email,
			OriginalUserInfo:       string(originalUserInfo),
			UserInfo:               string(userInfo),
			OriginalUserSellerInfo: "",
			UserSellerInfo:         "",
			OpUserId:               sysUser.AdminId,
			OpUserName:             sysUser.RealName,
			CreateTime:             time.Now(),
		})
	}

	defer func() {
		os.Remove(path)
	}()

	if len(existUser) > 0 {
		br.Ret = 600
		br.Msg = "系统中已存在用户"
		br.IsSendEmail = false
		br.Data = existUser
		return
	}

	//更新客户最近阅读次数以及最近阅读时间
	go services.ModifyCompanyProductLastViewData([]int{companyId})

	br.Msg = "导入成功"
	br.Ret = 200
	br.Success = true
}

// @Title 客户的联系人导出
// @Description 客户的联系人导出接口
// @Param   CompanyId   query   int  true       "公司id，必填"
// @Param   KeyWord   query   string  true       "搜索关键词"
// @Success 200 {object} company.CompanyUserListResp
// @router /user/exportByCompanyId [get]
func (this *CompanyUserController) Export() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	companyId, _ := this.GetInt("CompanyId")
	keyWord := utils.TrimStr(this.GetString("KeyWord"))

	if companyId <= 0 {
		br.Msg = "请选择客户"
		br.ErrMsg = "客户参数错误"
		return
	}

	var startSize int

	var condition string
	var pars []interface{}

	if keyWord != "" {
		condition += ` AND (a.real_name LIKE '%` + keyWord + `%' OR a.mobile LIKE '%` + keyWord + `%' OR a.email LIKE '%` + keyWord + `%') `
	}

	//非管理员，那么只能看到该产品下的联系人
	if sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_ADMIN {
		productId := services.GetProductId(sysUser.RoleTypeCode)
		condition += ` AND b.product_id = ? `
		pars = append(pars, productId)
	}

	list, err := company.GetCompanyUserListV2(condition, pars, companyId, startSize, 100000)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	//获取企业客户信息
	companyInfo, err := company.GetCompanyById(companyId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取客户信息失败，Err:" + err.Error()
		return
	}

	lenList := len(list)
	if lenList > 0 {
		userIdSlice := make([]string, 0)
		mobilesSlice := make([]string, 0)
		emailsSlice := make([]string, 0)
		for _, v := range list {
			userIdSlice = append(userIdSlice, strconv.Itoa(int(v.UserId)))
			if v.Mobile != "" {
				mobilesSlice = append(mobilesSlice, v.Mobile)
			} else if v.Email != "" {
				emailsSlice = append(emailsSlice, v.Email)
			}
		}

		//用户浏览数据
		userIdStr := strings.Join(userIdSlice, ",")
		mobileStr := strings.Join(mobilesSlice, "','")
		mobileStr = "'" + mobileStr + "'"
		emailStr := strings.Join(emailsSlice, "','")
		emailStr = "'" + emailStr + "'"

		//userViewTotalList, _ := models.GetCountUserViewHistoryByUserIds(userIdStr)
		//userViewTotalMap := make(map[int]*models.UserViewTotalSlice)
		//for _, userView := range userViewTotalList {
		//	userViewTotalMap[userView.UserId] = userView
		//}

		//用户日评浏览数据
		//userReportViewTotalList, _ := models.GetReportViewMaxTimeByUserIds(userIdStr)
		//userReportViewTotalMap := make(map[int]*models.ReportViewRecord)
		//for _, userReportView := range userReportViewTotalList {
		//	userReportViewTotalMap[userReportView.UserId] = userReportView
		//}

		//报告统计删除晨报部分统计加入每日资讯 2021-4-9
		//手机号
		userViewMobileTotalMap := make(map[string]*models.UserViewMobileTotalSlice)
		userReportViewMobileTotalMap := make(map[string]*models.ReportViewMobileRecord)
		userAdvisoryViewMobileTotalMap := make(map[string]*advisory.UserViewMobileTotalSlice)
		userCygxArticleHistoryRecordViewMobileTotalMap := make(map[string]*models.UserViewMobileTotalSlice)
		if len(mobilesSlice) > 0 {
			//用户浏览数据
			userViewMobileTotalList, _ := models.GetCountUserViewHistoryByMobiles(mobileStr)
			for _, userViewMobile := range userViewMobileTotalList {
				userViewMobileTotalMap[userViewMobile.Mobile] = userViewMobile
			}

			//每日点评手机号数据
			userReportViewMobileTotalList, _ := models.GetReportViewMaxTimeByMobiles(mobileStr)
			for _, userReportViewMobile := range userReportViewMobileTotalList {
				userReportViewMobileTotalMap[userReportViewMobile.Mobile] = userReportViewMobile
			}

			//每日资讯
			userAdvisoryViewMobileTotalList, _ := advisory.GetCountUserViewHistoryByMobiles(mobileStr)
			//fmt.Println(userAdvisoryViewMobileTotalList)
			for _, userAdvisoryViewMobile := range userAdvisoryViewMobileTotalList {
				userAdvisoryViewMobileTotalMap[userAdvisoryViewMobile.Mobile] = userAdvisoryViewMobile
			}
			//查研观向
			userCygxArticleHistoryRecordViewMobileTotalList, _ := models.GetCountCygxArticleHistoryRecordByMobiles(mobileStr)
			for _, userCygxArticleHistoryRecordViewMobile := range userCygxArticleHistoryRecordViewMobileTotalList {
				userCygxArticleHistoryRecordViewMobileTotalMap[userCygxArticleHistoryRecordViewMobile.Mobile] = userCygxArticleHistoryRecordViewMobile
			}
		}

		//邮箱
		userViewEmailTotalMap := make(map[string]*models.UserViewEmailTotalSlice)
		userReportViewEmailTotalMap := make(map[string]*models.ReportViewEmailRecord)
		userAdvisoryViewEmailTotalMap := make(map[string]*advisory.UserViewEmailTotalSlice)
		userCygxViewEmailTotalMap := make(map[string]*models.UserViewEmailTotalSlice)
		if len(emailsSlice) > 0 {
			//用户浏览数据
			userViewEmailTotalList, _ := models.GetCountUserViewHistoryByEmails(emailStr)
			for _, userViewEmail := range userViewEmailTotalList {
				userViewEmailTotalMap[userViewEmail.Email] = userViewEmail
			}
			//每日点评手机号数据
			userReportViewEmailTotalList, _ := models.GetReportViewMaxTimeByEmails(emailStr)
			for _, userReportViewEmail := range userReportViewEmailTotalList {
				userReportViewEmailTotalMap[userReportViewEmail.Email] = userReportViewEmail
			}
			//每日资讯
			userAdvisoryViewEmailTotalList, _ := advisory.GetCountUserViewHistoryByEmails(emailStr)
			for _, userAdvisoryViewEmail := range userAdvisoryViewEmailTotalList {
				userAdvisoryViewEmailTotalMap[userAdvisoryViewEmail.Email] = userAdvisoryViewEmail
			}
			//查研观向
			userCygxViewEmailTotalList, _ := models.GetCountCygxArticleHistoryRecordByEmails(emailStr)
			for _, userCygxReportViewEmail := range userCygxViewEmailTotalList {
				userCygxViewEmailTotalMap[userCygxReportViewEmail.Email] = userCygxReportViewEmail
			}
		}

		//获取联系人关联产品的条数
		//userSellerRelationTotalSlice, err := models.GetUserSellerRelationCountByUserIds(userIdStr)
		//if err != nil {
		//	br.Msg = "获取失败"
		//	br.ErrMsg = "获取联系人与销售员信息失败，Err:" + err.Error()
		//	return
		//}
		//userSellerRelationTotalMap := make(map[int]*models.UserSellerRelationSlice)
		//for _, userSellerRelationTotal := range userSellerRelationTotalSlice {
		//	userSellerRelationTotalMap[userSellerRelationTotal.UserId] = userSellerRelationTotal
		//}

		userRecordRegisterMap := make(map[int]time.Time)
		if len(userIdSlice) > 0 {
			//用户绑定注册数据
			userRecordRegisterList, _ := models.GetUserRecordRegisterByUserIds(userIdStr)
			for _, userRecordRegister := range userRecordRegisterList {
				userRecordRegisterMap[userRecordRegister.UserId] = userRecordRegister.CreateTime
			}
		}
		for i := 0; i < lenList; i++ {
			item := list[i]
			//企业名称
			list[i].CompanyName = companyInfo.CompanyName
			//手机号用户累计浏览次数
			if userView, ok := userViewMobileTotalMap[item.Mobile]; ok {
				list[i].ViewTotal += userView.Total
				if userView.CreatedTime.After(list[i].LastViewTime) {
					list[i].LastViewTime = userView.CreatedTime
					list[i].LastViewTimeStr = userView.CreatedTime.Format(utils.FormatDateTime)
				}
			}
			//邮箱用户累计浏览次数
			if userView, ok := userViewEmailTotalMap[item.Email]; ok {
				//总共浏览的报表数据需要调整为（手机号用户浏览晨报数+邮箱号用户浏览晨报数）
				list[i].ViewTotal += userView.Total
				if userView.CreatedTime.After(list[i].LastViewTime) {
					list[i].LastViewTime = userView.CreatedTime
					list[i].LastViewTimeStr = userView.CreatedTime.Format(utils.FormatDateTime)
				}
			}

			if item.OpenId != "" {
				list[i].IsRegister = true
			} else {
				if item.RegisterPlatform == 2 {
					if item.Mobile != "" || item.Email != "" {
						list[i].IsRegister = true
					}
				} else if item.RegisterTime != "" {
					list[i].IsRegister = true
				} else {
					list[i].IsRegister = false
				}
			}
			//如果存在手机号用户日评数据，那么需要做处理
			if reportView, ok := userReportViewMobileTotalMap[item.Mobile]; ok {
				//对日评数据做校验，日评时间晚于晨报时间，那么将最近一次浏览时间替换
				if reportView.LastViewTime.After(list[i].LastViewTime) {
					list[i].LastViewTime = reportView.LastViewTime
					list[i].LastViewTimeStr = reportView.LastViewTime.Format(utils.FormatDateTime)
				}
				//总共浏览的报表数据需要调整为（浏览晨报数+浏览日评数）
				list[i].ViewTotal += reportView.ViewTotal
			}
			//如果存在手机号用户日评数据，那么需要做处理
			if reportView, ok := userReportViewEmailTotalMap[item.Email]; ok {
				//对日评数据做校验，日评时间晚于晨报时间，那么将最近一次浏览时间替换
				if reportView.LastViewTime.After(list[i].LastViewTime) {
					list[i].LastViewTime = reportView.LastViewTime
					list[i].LastViewTimeStr = reportView.LastViewTime.Format(utils.FormatDateTime)
				}
				//总共浏览的报表数据需要调整为（浏览晨报数+浏览日评数）
				list[i].ViewTotal += reportView.ViewTotal
			}

			//如果存在手机号用户每日资讯，那么需要做处理
			if advisoryView, ok := userAdvisoryViewMobileTotalMap[item.Mobile]; ok {
				//fmt.Println("蝴蝶眨几次眼睛")
				//对每日资讯数据做校验，每日资讯时间晚日评报时间，那么将最近一次浏览时间替换
				if advisoryView.CreatedTime.After(list[i].LastViewTime) {
					list[i].LastViewTime = advisoryView.CreatedTime
					list[i].LastViewTimeStr = advisoryView.CreatedTime.Format(utils.FormatDateTime)
				}
				//总共浏览的报表数据需要调整为（浏览晨报数+浏览日评数+每日资讯数）
				list[i].ViewTotal += advisoryView.Total
			}
			//如果存在邮箱号用户每日资讯，那么需要做处理
			if advisoryView, ok := userAdvisoryViewEmailTotalMap[item.Email]; ok {
				//对每日资讯数据做校验，每日资讯时间晚日评报时间，那么将最近一次浏览时间替换
				if advisoryView.CreatedTime.After(list[i].LastViewTime) {
					list[i].LastViewTime = advisoryView.CreatedTime
					list[i].LastViewTimeStr = advisoryView.CreatedTime.Format(utils.FormatDateTime)
				}
				//总共浏览的报表数据需要调整为（浏览晨报数+浏览日评数+每日资讯数）
				list[i].ViewTotal += advisoryView.Total
			}

			//如果存在手机号用户查研观向，那么需要做处理
			if cygxView, ok := userCygxArticleHistoryRecordViewMobileTotalMap[item.Mobile]; ok {
				//对每日资讯数据做校验，每日资讯时间晚日评报时间，那么将最近一次浏览时间替换
				if cygxView.CreatedTime.After(list[i].LastViewTime) {
					list[i].LastViewTime = cygxView.CreatedTime
					list[i].LastViewTimeStr = cygxView.CreatedTime.Format(utils.FormatDateTime)
				}
				//总共浏览的报表数据需要调整为（浏览晨报数+浏览日评数+每日资讯数+查研观向）
				list[i].ViewTotal += cygxView.Total
			}
			//如果存在邮箱号用户查研观向，那么需要做处理
			if cygxView, ok := userCygxViewEmailTotalMap[item.Email]; ok {
				//对每日资讯数据做校验，每日资讯时间晚日评报时间，那么将最近一次浏览时间替换
				if cygxView.CreatedTime.After(list[i].LastViewTime) {
					list[i].LastViewTime = cygxView.CreatedTime
					list[i].LastViewTimeStr = cygxView.CreatedTime.Format(utils.FormatDateTime)
				}
				//总共浏览的报表数据需要调整为（浏览晨报数+浏览日评数+每日资讯数+查研观向）
				list[i].ViewTotal += cygxView.Total
			}
			/*if reportView, ok := userReportViewTotalMap[int(item.UserId)]; ok {
				//对日评数据做校验，日评时间晚于晨报时间，那么将最近一次浏览时间替换
				if reportView.LastViewTime.After(list[i].LastViewTime) {
					list[i].LastViewTime = reportView.LastViewTime
					list[i].LastViewTimeStr = reportView.LastViewTime.Format(utils.FormatDateTime)
				}
				//总共浏览的报表数据需要调整为（浏览晨报数+浏览日评数）
				list[i].ViewTotal += reportView.ViewTotal
			}*/

			//如果有绑定数据，那么将数据返回对应的注册绑定数据
			if _, ok := userRecordRegisterMap[int(item.UserId)]; ok {
				list[i].IsRegister = true
				//list[i].RegisterTime = userRecordRegisterTime.Format(utils.FormatDateTime)
			}
			//是否共享联系人
			//if userSellerRelationTotal, ok := userSellerRelationTotalMap[int(item.UserId)]; ok {
			//	//条数大于1，代表这是共享联系人
			//	if userSellerRelationTotal.Total > 1 {
			//		list[i].IsShared = true
			//	}
			//}
		}
	}

	dir, err := os.Executable()
	exPath := filepath.Dir(dir)
	downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	xlsxFile := xlsx.NewFile()
	if err != nil {
		br.Msg = "生成文件失败"
		br.ErrMsg = "生成文件失败"
		return
	}
	style := xlsx.NewStyle()
	alignment := xlsx.Alignment{
		Horizontal: "center",
		Vertical:   "center",
		WrapText:   true,
	}

	style.Alignment = alignment
	style.ApplyAlignment = true

	sheel, err := xlsxFile.AddSheet("联系人数据")
	if err != nil {
		br.Msg = "新增Sheet失败"
		br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
		return
	}
	sheel.SetColWidth(0, 0, 18)
	sheel.SetColWidth(1, 2, 24)
	sheel.SetColWidth(3, 3, 20)
	sheel.SetColWidth(4, 4, 40)

	titleRow := sheel.AddRow()

	cellName := titleRow.AddCell()
	cellName.SetStyle(style)
	cellName.SetValue("姓名")

	cellMobile := titleRow.AddCell()
	cellMobile.SetStyle(style)
	cellMobile.SetValue("手机号")

	cellEmail := titleRow.AddCell()
	cellEmail.SetStyle(style)
	cellEmail.SetValue("邮箱")

	cellMark := titleRow.AddCell()
	cellMark.SetStyle(style)
	cellMark.SetValue("是否决策人")

	cellCompanyName := titleRow.AddCell()
	cellCompanyName.SetStyle(style)
	cellCompanyName.SetValue("客户名称")

	for _, v := range list {
		dataRow := sheel.AddRow()
		dataRow.SetHeight(20)

		isMark := "否"
		if v.IsMaker == 1 {
			isMark = "是"
		}

		cellDataName := dataRow.AddCell()
		cellDataName.SetStyle(style)
		cellDataName.SetValue(v.RealName)

		cellDataMobile := dataRow.AddCell()
		cellDataMobile.SetStyle(style)
		cellDataMobile.SetValue(v.Mobile)

		cellDataEmail := dataRow.AddCell()
		cellDataEmail.SetStyle(style)
		cellDataEmail.SetValue(v.Email)

		cellDataMark := dataRow.AddCell()
		cellDataMark.SetStyle(style)
		cellDataMark.SetValue(isMark)

		cellDataCompanyName := dataRow.AddCell()
		cellDataCompanyName.SetStyle(style)
		cellDataCompanyName.SetValue(companyInfo.CompanyName)

	}
	err = xlsxFile.Save(downLoadnFilePath)
	if err != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败"
		return
	}
	randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
	downloadFileName := "联系人列表_" + randStr + ".xlsx"
	this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
	defer func() {
		os.Remove(downLoadnFilePath)
	}()
	br.Ret = 200
	br.Success = true
	br.Msg = "导出成功"
}

// 检测产品
func checkProductListUser(item models.WxUserDetail, companyUser *company.CompanyUser, companyProductList []*company.CompanyProduct) (notRelationUserMap map[int]*company.CompanyUser, err error) {
	notRelationUserMap = make(map[int]*company.CompanyUser)
	//判断该用户与当前账号是否存在关系，如果没有关系，那么直接返回
	for _, companyProduct := range companyProductList {
		_, relationErr := models.GetUserSellerRelation(companyUser.UserId, companyProduct.SellerId)
		//找到数据了
		if relationErr == nil {
			continue
		}

		//sql异常
		if relationErr.Error() != utils.ErrNoRow() {
			err = relationErr
			return
		}

		//没找到数据，不存在关系
		//如果不存在关系，那么直接添加关系就好了，其他操作不做
		if relationErr.Error() == utils.ErrNoRow() {
			if item.Mobile != "" && companyUser.Mobile == "" {
				companyUser.Mobile = strings.Replace(item.Mobile, " ", "", -1)
			}
			if item.Email != "" && companyUser.Email == "" {
				companyUser.Email = strings.Replace(companyUser.Email, " ", "", -1)
			}
			companyUser.SellerId = companyProduct.SellerId
			companyUser.SellerName = companyProduct.SellerName
			companyUser.DepartmentId = companyProduct.DepartmentId
			companyUser.GroupId = companyProduct.GroupId

			notRelationUserMap[companyProduct.ProductId] = companyUser
		}
	}
	return
}

// @Title 下载模板
// @Description 下载模板
// @Success 200
// @router /template [get]
func (this *CompanyUserController) TemplateDownload() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	this.Ctx.Output.Download("./static/导入联系人模板.xlsx", "导入联系人模板.xlsx")
	br.Ret = 200
	br.Success = true
	br.Msg = "下载成功"
}

//百度
//func init() {
//	fmt.Println("start")
//	businessCardUrl := `https://hongze.oss-accelerate.aliyuncs.com/static/images/202101/20210111/wB3ELOuH8AxTvrIDXHaFTn9Z0WXB.jpg`
//	services.GetBdGeneralBasic(businessCardUrl)
//	fmt.Println("end")
//}

//阿里云
//func init() {
//	fmt.Println("start")
//	businessCardUrl := `https://hongze.oss-accelerate.aliyuncs.com/static/images/202101/20210111/wB3ELOuH8AxTvrIDXHaFTn9Z0WXB.jpg`
//	aliyunResult, err := services.AliyunBusinessCardOcr(businessCardUrl)
//
//	if err != nil {
//		fmt.Println("line 1026")
//		return
//	}
//	if !aliyunResult.Success {
//		fmt.Println("line 1026")
//		return
//	}
//
//	mobileStr := strings.Join(aliyunResult.TelCell, ",")
//	mobileOne:="18366208402"
//	if strings.Contains(mobileStr, mobileOne) {
//		fmt.Println("true")
//	} else {
//		fmt.Println("false")
//	}
//	fmt.Println("end")
//}

// 获取是否拥有操作权限
func checkOpCompanyUserByUserId(userId, productId, opId int, roleTypeCode string) (errMsg string, err error) {
	userInfo, userErr := models.GetWxUserByUserId(userId)
	if userErr != nil {
		errMsg = "查询用户信息失败"
		err = errors.New("查询用户信息失败，Err:" + userErr.Error())
		return
	}
	//产品权限

	//获取当前操作员产品权限
	companyProductList, productErr := getSysCompanyProductList(productId, userInfo.CompanyId)
	if productErr != nil {
		errMsg = "获取当前操作员产品权限异常"
		err = errors.New("删除失败，获取当前操作员产品权限异常，Err:" + productErr.Error())
		return
	}
	if companyProductList == nil {
		errMsg = "删除失败"
		err = errors.New("删除失败，获取当前操作员找不到产品权限")
		return
	}

	//操作权限校验
	for _, v := range companyProductList {
		companyUserStatus := services.CheckCompanyUserButton(roleTypeCode, v.SellerId, opId, v.ProductId, v.ShareSellerId, v.Status)
		if companyUserStatus == false {
			errMsg = "没有操作权限"
			err = errors.New("没有操作权限")
			return
		}
	}
	return
}

// 获取是否拥有操作权限
func checkOpCompanyUserByCompanyId(companyId, productId, opId int, roleTypeCode string) (errMsg string, err error) {
	//获取当前操作员产品权限
	companyProductList, productErr := getSysCompanyProductList(productId, companyId)
	if productErr != nil {
		errMsg = "获取当前操作员产品权限异常"
		err = errors.New("删除失败，获取当前操作员产品权限异常，Err:" + productErr.Error())
		return
	}
	if companyProductList == nil {
		errMsg = "删除失败"
		err = errors.New("删除失败，获取当前操作员找不到产品权限")
		return
	}
	//操作权限校验
	for _, v := range companyProductList {
		companyUserStatus := services.CheckCompanyUserButton(roleTypeCode, v.SellerId, opId, v.ProductId, v.ShareSellerId, v.Status)
		if companyUserStatus == false {
			errMsg = "没有操作权限"
			err = errors.New("没有操作权限")
			return
		}
	}
	return
}

// @Title FICC申请单-移动潜在用户
// @Description FICC申请单移动潜在用户接口
// @Param	request	body models.ApplyRecordPotentialUserMoveReq true "type json string"
// @Success Ret=200 移动成功
// @router /potential/user/moveByApplyRecord [post]
func (this *CompanyController) ApplyRecordPotentialUserMove() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req models.ApplyRecordPotentialUserMoveReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.UserId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "客户id错误"
		return
	}
	wxUser, err := models.GetWxUserByUserId(req.UserId)

	//如果移动客户编号小于等于0，那么移动到潜在客户
	if req.CompanyId <= 0 {
		req.CompanyId = 1
	}

	if err != nil {
		br.Msg = "移动失败，该潜在用户已被删除"
		br.ErrMsg = "获取用户信息失败,Err:" + err.Error()
		return
	}
	if req.Mobile == "" {
		req.Mobile = wxUser.Mobile
	}
	if req.Email == "" {
		req.Email = wxUser.Email
	}
	if req.Mobile == "" && req.Email == "" {
		br.Msg = "手机号和邮箱不能同时为空"
		return
	}
	//校验手机号
	if req.Mobile != "" && wxUser.Mobile != req.Mobile {
		count, err := models.CheckUserMobileIsRegister(req.UserId, req.Mobile)
		if err != nil {
			br.Msg = "校验数据失败"
			br.ErrMsg = "校验数据失败，Err:" + err.Error()
			return
		}
		if count > 0 {
			br.Msg = "该手机号已经注册过用户"
			return
		}
	}
	//校验邮箱
	if req.Email != "" && wxUser.Email != req.Email {
		if !utils.ValidateEmailFormatat(req.Email) {
			br.Msg = "请输入正确的邮箱（包含@）"
			return
		}
		count, err := models.CheckUserEmailIsRegister(req.UserId, req.Email)
		if err != nil {
			br.Msg = "校验数据失败"
			br.ErrMsg = "校验数据失败，Err:" + err.Error()
			return
		}
		if count > 0 {
			br.Msg = "该邮箱已经注册过用户"
			br.IsSendEmail = false
			return
		}
	}

	updateCol := make([]string, 0)

	if wxUser.OutboundMobile == "" || wxUser.Mobile == wxUser.OutboundMobile {
		wxUser.OutboundMobile = req.Mobile
		wxUser.OutboundCountryCode = req.CountryCode
		updateCol = append(updateCol, "OutboundMobile", "OutboundCountryCode")
	}
	if req.Email != "" {
		wxUser.Email = req.Email
		updateCol = append(updateCol, "Email")
	}
	if req.RealName != "" {
		wxUser.RealName = req.RealName
		updateCol = append(updateCol, "RealName")
	}
	if req.Mobile != "" {
		wxUser.Mobile = req.Mobile
		updateCol = append(updateCol, "Mobile")
	}
	if req.CountryCode != "" {
		wxUser.CountryCode = req.CountryCode
		updateCol = append(updateCol, "CountryCode")
	}
	if req.Position != "" {
		wxUser.Position = req.Position
		updateCol = append(updateCol, "Position")
	}
	if wxUser.DepartmentName == "" && req.DepartmentName != "" {
		wxUser.DepartmentName = req.DepartmentName
		updateCol = append(updateCol, "DepartmentName")
	}
	wxUser.Sex = req.Sex
	wxUser.IsMaker = req.IsMaker
	updateCol = append(updateCol, "Sex", "IsMaker")

	//名片匹配
	if req.BusinessCardUrl != "" {
		//if req.BusinessCardUrl != "" && utils.RunMode == "release" {
		// 获取图片识别手机号的配置
		crmConfig2, err := company.GetConfigDetailByCode("card_recognition_tel")
		if err != nil {
			br.Msg = "获取配置失败"
			br.ErrMsg = "获取配置失败"
			br.IsSendEmail = false
			return
		}
		if crmConfig2.ConfigValue == "true" {
			card, err := services.GetBusinessCard(req.BusinessCardUrl)
			if err != nil {
				br.Msg = "名片识别失败"
				br.ErrMsg = "名片识别失败,Err:" + err.Error()
				return
			}
			isFlag := false
			if len(card.WordsResult.MOBILE) > 0 {
				mobileStr := strings.Join(card.WordsResult.MOBILE, ",")
				//if req.Mobile != "" {
				//	if strings.Contains(mobileStr, req.Mobile) || mobileStr == "" {
				//		isFlag = true
				//	} else {
				//		isFlag = false
				//	}
				//}

				if req.Mobile != "" && strings.Contains(mobileStr, req.Mobile) {
					isFlag = true
				}
			}

			if !isFlag {
				//阿里云识别
				//if utils.RunMode == "release" {
				aliyunResult, errMsg, err := services.AliyunOcrBusinessCard(req.BusinessCardUrl)
				if err != nil {
					br.Msg = "识别失败"
					br.ErrMsg = "识别失败,Err:" + err.Error()
					return
				}
				if !aliyunResult.Success {
					br.Msg = "识别失败"
					br.ErrMsg = "识别失败"
					return
				}
				if errMsg != "" {
					br.Msg = errMsg
					return
				}
				if len(aliyunResult.TelCell) > 0 {
					mobileStr := strings.Join(aliyunResult.TelCell, ",")
					if req.Mobile != "" {
						if strings.Contains(mobileStr, req.Mobile) {
							isFlag = true
						} else {
							isFlag = false
						}
					}
				} else {
					isFlag = true
				}
				//}
			}

			if !isFlag && crmConfig2.ConfigValue == "true" {
				br.Msg = "名片信息与联系人手机号不符"
				return
			}
		}

		wxUser.BusinessCardUrl = req.BusinessCardUrl
		updateCol = append(updateCol, "BusinessCardUrl")
	}

	productId := services.GetProductId(sysUser.RoleTypeCode)
	companyProductList, _ := getSysCompanyProductList(productId, req.CompanyId)

	err = services.MovePotentialUserByApplyRecord(sysUser.AdminId, req.UserId, req.CompanyId, req.ApplyRecordId, req.RealName, req.Mobile, req.Email, req.Remark, companyProductList, wxUser, updateCol)
	if err != nil {
		br.Msg = "移动失败"
		br.ErrMsg = "移动失败,Err:" + err.Error()
		return
	}

	//更新客户最近阅读次数以及最近阅读时间
	go services.ModifyCompanyProductLastViewData([]int{req.CompanyId})

	br.Ret = 200
	br.Success = true
	br.Msg = "移动成功"
	br.IsAddLog = true
}

// @Title 新增联系人图表分类权限
// @Description 新增联系人图表分类权限接口
// @Param	request	body request.SaveCompanyUserChartClassifyPermissionReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /user/addChartClassifyPermission [post]
func (this *CompanyUserController) AddCompanyUserChartClassifyPermission() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	var req request.SaveCompanyUserChartClassifyPermissionReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.UserId <= 0 {
		br.Msg = "参数丢失：联系人ID"
		br.ErrMsg = "参数丢失，联系人ID"
		return
	}

	if req.StartTime == "" || req.EndTime == "" {
		br.Msg = "请选择开始结束时间"
		br.ErrMsg = "请选择开始结束时间"
		br.IsSendEmail = false
		return
	}

	startTime, err := time.Parse(utils.FormatDate, req.StartTime)
	if err != nil {
		br.Msg = "开始时间格式有误"
		br.ErrMsg = "开始时间转换失败, Err:" + err.Error()
		return
	}
	endTime, err := time.Parse(utils.FormatDate, req.EndTime)
	if err != nil {
		br.Msg = "结束时间格式有误"
		br.ErrMsg = "结束时间转换失败, Err:" + err.Error()
		return
	}

	if startTime.After(endTime) {
		br.Msg = "结束时间不能小于开始时间"
		br.ErrMsg = "结束时间不能小于开始时间"
		br.IsSendEmail = false
		return
	}

	_, err = company_user.GetChartClassifyPermissionByUserId(req.UserId)
	if err == nil {
		br.Msg = "请勿重复设置图表权限"
		br.ErrMsg = "请勿重复设置图表权限"
		br.IsSendEmail = false
		return
	}

	// 判断是否允许设置
	userInfo, err := models.GetWxUserByUserId(req.UserId)
	if err != nil {
		br.Msg = "联系人信息有误"
		br.ErrMsg = "联系人信息有误, Err: " + err.Error()
		return
	}
	companyInfo, err := company.GetCompanyById(userInfo.CompanyId)
	if err != nil {
		br.Msg = "获取客户信息失败"
		br.ErrMsg = "获取客户信息失败, Err: " + err.Error()
		return
	}
	companyProductInfo, err := company.GetCompanyProductByCompanyIdAndProductId(userInfo.CompanyId, 1)
	if err != nil {
		br.Msg = "获取客户产品信息失败"
		br.ErrMsg = "获取客户产品信息失败, Err: " + err.Error()
		return
	}
	companyStatus := companyProductInfo.Status
	if companyStatus != utils.COMPANY_STATUS_FOREVER {
		// 非永续客户
		if companyStatus == utils.COMPANY_STATUS_TRY_OUT || companyStatus == utils.COMPANY_STATUS_FORMAL {
			// 正式/试用
			expireTimeStr := companyProductInfo.EndDate
			expireTime, _ := time.ParseInLocation(utils.FormatDate, expireTimeStr, time.Local)
			// 服务结束时间小于设置的结束时间则不允许设置
			if endTime.After(expireTime.AddDate(0, 0, 1)) {
				br.Msg = "终止日期不允许超过服务日期, 服务终止日期为: " + expireTimeStr
				br.IsSendEmail = false
				return
			}
		} else {
			br.Msg = "当前客户不允许设置图表权限, 客户状态为: " + companyStatus
			br.IsSendEmail = false
			return
		}
	}

	item := &company_user.ChartClassifyPermission{
		UserId:     req.UserId,
		CompanyId:  companyInfo.CompanyId,
		StartTime:  startTime,
		EndTime:    endTime,
		Enabled:    req.Enabled,
		CreateTime: time.Now(),
	}
	_, err = company_user.AddChartClassifyPermission(item)
	if err != nil {
		br.Msg = "新增图表权限失败"
		br.ErrMsg = "新增图表权限失败, Err:" + err.Error()
		return
	}

	// 操作记录
	{
		record := &company_user.CompanyUserChartPermissionOperationRecord{
			Type:       1,
			CompanyId:  companyInfo.CompanyId,
			UserId:     req.UserId,
			AdminId:    sysUser.AdminId,
			StartTime:  startTime,
			EndTime:    endTime,
			Enabled:    req.Enabled,
			CreateTime: time.Now(),
		}
		go company_user.AddChartPermissionOperationRecord(record)
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// @Title 编辑联系人图表分类权限
// @Description 编辑联系人图表分类权限接口
// @Param	request	body request.SaveCompanyUserChartClassifyPermissionReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /user/editChartClassifyPermission [post]
func (this *CompanyUserController) EditCompanyUserChartClassifyPermission() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	var req request.SaveCompanyUserChartClassifyPermissionReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.UserId <= 0 {
		br.Msg = "参数丢失：联系人ID"
		br.ErrMsg = "参数丢失，联系人ID"
		return
	}

	if req.StartTime == "" || req.EndTime == "" {
		br.Msg = "请选择开始结束时间"
		br.ErrMsg = "请选择开始结束时间"
		br.IsSendEmail = false
		return
	}

	startTime, err := time.Parse(utils.FormatDate, req.StartTime)
	if err != nil {
		br.Msg = "开始时间格式有误"
		br.ErrMsg = "开始时间转换失败, Err:" + err.Error()
		return
	}
	endTime, err := time.Parse(utils.FormatDate, req.EndTime)
	if err != nil {
		br.Msg = "结束时间格式有误"
		br.ErrMsg = "结束时间转换失败, Err:" + err.Error()
		return
	}

	if startTime.After(endTime) {
		br.Msg = "结束时间不能小于开始时间"
		br.ErrMsg = "结束时间不能小于开始时间"
		br.IsSendEmail = false
		return
	}

	// 判断是否允许设置
	userInfo, err := models.GetWxUserByUserId(req.UserId)
	if err != nil {
		br.Msg = "联系人信息有误"
		br.ErrMsg = "联系人信息有误, Err: " + err.Error()
		return
	}
	companyInfo, err := company.GetCompanyById(userInfo.CompanyId)
	if err != nil {
		br.Msg = "获取客户信息失败"
		br.ErrMsg = "获取客户信息失败, Err: " + err.Error()
		return
	}
	companyProductInfo, err := company.GetCompanyProductByCompanyIdAndProductId(userInfo.CompanyId, 1)
	if err != nil {
		br.Msg = "获取客户产品信息失败"
		br.ErrMsg = "获取客户产品信息失败, Err: " + err.Error()
		return
	}
	companyStatus := companyProductInfo.Status
	if companyStatus != utils.COMPANY_STATUS_FOREVER {
		// 非永续客户
		if companyStatus == utils.COMPANY_STATUS_TRY_OUT || companyStatus == utils.COMPANY_STATUS_FORMAL {
			// 正式/试用
			expireTimeStr := companyProductInfo.EndDate
			expireTime, _ := time.ParseInLocation(utils.FormatDate, expireTimeStr, time.Local)
			// 服务结束时间小于设置的结束时间则不允许设置
			if endTime.After(expireTime.AddDate(0, 0, 1)) {
				br.Msg = "终止日期不允许超过服务日期, 服务终止日期为: " + expireTimeStr
				br.IsSendEmail = false
				return
			}
		} else {
			br.Msg = "当前客户不允许设置图表权限, 客户状态为: " + companyStatus
			br.IsSendEmail = false
			return
		}
	}

	permissionInfo, err := company_user.GetChartClassifyPermissionByUserId(req.UserId)
	if err != nil {
		br.Msg = "获取联系人图表分类权限失败"
		br.ErrMsg = "获取联系人图表分类权限失败, Err:" + err.Error()
		return
	}

	permissionInfo.CompanyId = companyInfo.CompanyId
	permissionInfo.Enabled = req.Enabled
	permissionInfo.StartTime = startTime
	permissionInfo.EndTime = endTime
	permissionInfo.UpdateTime = time.Now()
	err = permissionInfo.Update([]string{"CompanyId", "Enabled", "StartTime", "EndTime", "UpdateTime"})
	if err != nil {
		br.Msg = "编辑联系人图表分类权限失败"
		br.ErrMsg = "编辑联系人图表分类权限失败, Err:" + err.Error()
		return
	}

	// 操作记录
	{
		record := &company_user.CompanyUserChartPermissionOperationRecord{
			Type:       2,
			CompanyId:  companyInfo.CompanyId,
			UserId:     req.UserId,
			AdminId:    sysUser.AdminId,
			StartTime:  startTime,
			EndTime:    endTime,
			Enabled:    req.Enabled,
			CreateTime: time.Now(),
		}
		go company_user.AddChartPermissionOperationRecord(record)
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// @Title 获取联系人图表分类权限详情
// @Description 获取联系人图表分类权限详情接口
// @Param	UserId   query   int   true   "联系人ID，必填"
// @Success 200 {object} response.CompanyUserChartClassifyPermissionDetailResp
// @router /user/getChartClassifyPermissionDetail [get]
func (this *CompanyUserController) GetCompanyUserChartClassifyPermissionDetail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	reqUserId := this.GetString("UserId", "")
	userId, _ := strconv.Atoi(reqUserId)
	if userId <= 0 {
		br.Msg = "参数丢失：联系人ID"
		return
	}
	userInfo, err := models.GetWxUserByUserId(userId)
	if err != nil {
		br.Msg = "联系人信息有误"
		br.ErrMsg = "联系人信息有误, Err: " + err.Error()
		return
	}

	permissionInfo, err := company_user.GetChartClassifyPermissionByUserId(userId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取联系人图表分类权限失败"
		br.ErrMsg = "获取联系人图表分类权限失败, Err:" + err.Error()
		return
	}

	resp := new(response.CompanyUserChartClassifyPermissionDetailResp)

	// 客户服务日期
	companyProductInfo, err := company.GetCompanyProductByCompanyIdAndProductId(userInfo.CompanyId, 1)
	if err != nil {
		br.Msg = "获取客户产品信息失败"
		br.ErrMsg = "获取客户产品信息失败, Err: " + err.Error()
		return
	}
	companyStatus := companyProductInfo.Status
	// 0-不允许设置 1-允许设置最大90天 2-90天
	nowTime := time.Now()
	free := 0
	if companyStatus == utils.COMPANY_STATUS_FOREVER {
		// 永续客户
		free = 2
		resp.ExpireDay = "2199-12-31"
	} else if companyStatus == utils.COMPANY_STATUS_TRY_OUT || companyStatus == utils.COMPANY_STATUS_FORMAL {
		free = 1
		resp.ExpireDay = companyProductInfo.EndDate
	} else {
		resp.ExpireDay = nowTime.Format(utils.FormatDate)
	}

	var startTime, endTime time.Time
	if permissionInfo != nil {
		// 已设置
		startTime = permissionInfo.StartTime
		endTime = permissionInfo.EndTime
		resp.ChartPermissionId = permissionInfo.Id
		resp.UserId = permissionInfo.UserId
		resp.StartTime = permissionInfo.StartTime.Format(utils.FormatDate)
		resp.EndTime = permissionInfo.EndTime.Format(utils.FormatDate)
		resp.Enabled = permissionInfo.Enabled
	} else {
		// 初次设置
		startTime = nowTime
		endTime = startTime.Add(89 * 24 * time.Hour) // 实际验证时以结束日期的23时59分为过期时间所以此处日期-1
		if free == 0 {
			endTime = nowTime
		} else if free == 1 {
			expireTime, _ := time.ParseInLocation(utils.FormatDate, companyProductInfo.EndDate, time.Local)
			sub := expireTime.Sub(nowTime)
			diff := int(sub.Hours() / 24)
			if diff < 90 {
				// 小于90天则终止时间为服务结束时间
				endTime = expireTime
			}
		}

		resp.StartTime = startTime.Format(utils.FormatDate)
		resp.EndTime = endTime.Format(utils.FormatDate)
		resp.UserId = userId
		resp.Enabled = 0 // 默认关闭
	}
	// 计算阅读时长天数
	subDuration := endTime.Sub(startTime)
	subHours := subDuration.Hours()
	subDays := int(subHours / 24)
	resp.DayDuration = subDays + 1

	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// GetOtherProduct
// @Title 获取其他分产品的筛选列表
// @Description 获取联系人图表分类权限详情接口
// @Param	UserId   query   int   true   "联系人ID，必填"
// @Success 200 {object} response.CompanyUserChartClassifyPermissionDetailResp
// @router /user/otherProductList [get]
func (this *CompanyUserController) GetOtherProduct() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	resp := make([]response.OtherProductTypeListResp, 0)
	statisticFlag, _ := this.GetBool("StatisticFlag")

	questionItem := response.OtherProductTypeListResp{
		ProductId:   0,
		ProductType: 3,
		ProductName: "问答社区",
	}
	roadVideoItem := response.OtherProductTypeListResp{
		ProductId:   2,
		ProductType: 2,
		ProductName: "线上路演",
	}
	videoItem := response.OtherProductTypeListResp{
		ProductId:   1,
		ProductType: 2,
		ProductName: "5分钟小视频",
	}
	if !statisticFlag {
		resp = append(resp, questionItem, roadVideoItem, videoItem)
	}

	voiceSectionList, err := yb.GetAllEnableVoiceSectionList()
	if err != nil {
		br.Msg = "获取数据失败"
		br.ErrMsg = "获取语音播报版块, Err: " + err.Error()
		return
	}
	for _, v := range voiceSectionList {
		resp = append(resp, response.OtherProductTypeListResp{
			ProductId:   v.SectionId,
			ProductType: 1,
			ProductName: v.SectionName,
		})
	}
	if statisticFlag {
		resp = append(resp, questionItem, roadVideoItem, videoItem)
	}

	// 全部
	resp = append(resp, response.OtherProductTypeListResp{
		ProductId:   0,
		ProductType: 99,
		ProductName: "全部",
	})

	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

//func init() {
//	BusinessCardUrl := `https://hongze.oss-accelerate.aliyuncs.com/static/images/202107/20210715/R5xT6jw331gPwHZlsIg90cuSbuFW.jpeg`
//	BusinessCardUrl = `https://hongze.oss-accelerate.aliyuncs.com/static/images/202102/20210224/Bdr3Dv8oZDvsAnkzUpx8uA3S4odB.jpg`
//	BusinessCardUrl = `https://hongze.oss-accelerate.aliyuncs.com/static/images/202202/20220215/0glY7kgE07OLBHTnxxwS6u2cAxRx.png`
//	BusinessCardUrl = `https://hongze.oss-accelerate.aliyuncs.com/static/images/202206/20220614/ZHEUpbNtUfE09ZVp6qfQxSPUrLfS.jpg`
//	card, err := services.GetBusinessCard(BusinessCardUrl)
//	if err != nil {
//		fmt.Println("名片识别失败,Err:" + err.Error())
//		return
//	}
//	fmt.Println(card)
//
//	fmt.Println("company:", card.WordsResult.COMPANY)
//	fmt.Println("===================")
//
//	{
//		aliyunResult, err := services.AliyunBusinessCardOcr(BusinessCardUrl)
//		if err != nil {
//			fmt.Println("名片识别失败2,Err:" + err.Error())
//			return
//		}
//		fmt.Println(aliyunResult)
//		fmt.Println("company:", aliyunResult.Company)
//	}
//
//}

// @Title 联系人名单匹配导入
// @Description 联系人名单匹配导入
// @Param   File  query  file  true  "文件"
// @Success 200 {object} company.UserImportMatchResp
// @router /list/match/import [post]
func (this *CompanyUserController) ImportListMatch() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请重新登录"
		return
	}
	file, h, err := this.GetFile("File")
	if err != nil {
		br.Msg = "获取文件失败"
		br.ErrMsg = "获取文件失败，Err:" + err.Error()
		return
	}
	defer func() {
		_ = file.Close()
	}()
	ext := path.Ext(h.Filename)
	if ext != ".xlsx" && ext != ".xls" {
		br.Msg = "请上传Excel文件"
		return
	}

	uploadDir := "static/xls"
	err = os.MkdirAll(uploadDir, 766)
	if err != nil {
		br.Msg = "存储目录创建失败"
		br.ErrMsg = "存储目录创建失败,Err:" + err.Error()
		return
	}
	uploadPath := uploadDir + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + h.Filename
	err = this.SaveToFile("File", uploadPath)
	if err != nil {
		br.Msg = "文件保存失败"
		br.ErrMsg = "文件保存失败，Err:" + err.Error()
		return
	}
	defer func() {
		_ = os.Remove(uploadPath)
	}()
	xlFile, err := xlsx.OpenFile(uploadPath)
	if err != nil {
		br.Msg = "文件导入失败"
		br.ErrMsg = "文件导入失败，Err:" + err.Error()
		return
	}

	dataList := make([]*company.UserImportMatch, 0)
	mobileArr := make([]string, 0)

	// 遍历sheet页读取
	for _, sheet := range xlFile.Sheets {
		// 遍历行读取
		maxRow := sheet.MaxRow
		for i := 0; i < maxRow; i++ {
			// 首行
			if i == 0 {
				row := sheet.Row(i)
				cells := row.Cells
				for k, cell := range cells {
					text := cell.String()
					if k == 0 {
						if text != "姓名" {
							br.Msg = "匹配失败, 请按模板导入"
							br.ErrMsg = "模板格式错误，title:" + text
							return
						}
					}
					if k == 1 {
						if text != "国际（区号）" {
							br.Msg = "匹配失败, 请按模板导入"
							br.ErrMsg = "模板格式错误，title:" + text
							return
						}
					}
					if k == 2 {
						if text != "手机号" {
							br.Msg = "匹配失败, 请按模板导入"
							br.ErrMsg = "模板格式错误，title:" + text
							return
						}
					}
					if k == 3 {
						if text != "客户公司" {
							br.Msg = "匹配失败, 请按模板导入"
							br.ErrMsg = "模板格式错误，title:" + text
							return
						}
					}
				}
			}
			// 数据行
			if i >= 1 {
				row := sheet.Row(i)
				cells := row.Cells
				var userName, countryCode, mobile, companyName string
				for k, cell := range cells {
					if k == 0 {
						userName = utils.TrimStr(cell.String())
					}
					if k == 1 {
						countryCode = utils.TrimStr(cell.String())
					}
					if k == 2 {
						mobile = utils.TrimStr(cell.String())
					}
					if k == 3 {
						companyName = utils.TrimStr(cell.String())
					}
				}
				// 手机号为空则读取下一行
				if mobile == "" {
					continue
				}
				// mobile列存在"86-11位手机号"这种格式
				if strings.Contains(mobile, "-") {
					mobileArr := strings.Split(mobile, "-")
					if len(mobileArr) == 2 {
						countryCode = mobileArr[0]
						mobile = mobileArr[1]
					}
				}

				mobileArr = append(mobileArr, mobile)
				item := &company.UserImportMatch{
					UserName:    userName,
					CountryCode: countryCode,
					Mobile:      mobile,
					CompanyName: companyName,
				}
				dataList = append(dataList, item)
			}
		}
	}
	mobileLen := len(mobileArr)
	if mobileLen == 0 {
		br.Msg = "匹配失败, 无有效数据"
		br.ErrMsg = "匹配失败, 无有效数据"
		return
	}

	// 根据手机号查询联系人信息
	var userCond string
	var userPars []interface{}
	userCond += ` AND mobile IN (` + utils.GetOrmInReplace(mobileLen) + `)`
	userPars = append(userPars, mobileArr)
	userList, e := company.GetCompanyUsersByCondition(userCond, userPars)
	if e != nil {
		br.Msg = "匹配失败, 请按模板导入"
		br.ErrMsg = "匹配失败, 获取联系人信息失败, Err: " + e.Error()
		return
	}
	companyIds := make([]int, 0)
	mobileCompanyIdMap := make(map[string]int, 0)
	for i := range userList {
		companyIds = append(companyIds, userList[i].CompanyId)
		mobileCompanyIdMap[userList[i].Mobile] = userList[i].CompanyId
	}
	companyLen := len(companyIds)

	// 查询客户、客户产品
	var productCond string
	var productPars []interface{}
	if companyLen > 0 {
		productCond += ` AND a.company_id IN (` + utils.GetOrmInReplace(companyLen) + `)`
		productPars = append(productPars, companyIds)
	}
	productList, e := company.GetCompanyProductsByCondition(productCond, productPars)
	if e != nil {
		br.Msg = "匹配失败, 请按模板导入"
		br.ErrMsg = "匹配失败, 获取客户产品信息失败, Err: " + e.Error()
		return
	}
	ficcProductMap := make(map[int]*company.CompanyProduct, 0)
	raiProductMap := make(map[int]*company.CompanyProduct, 0)
	for i := range productList {
		if productList[i].ProductId == 1 {
			ficcProductMap[productList[i].CompanyId] = productList[i]
		} else {
			raiProductMap[productList[i].CompanyId] = productList[i]
		}
	}

	// 根据客户信息返回数据
	for i := range dataList {
		companyId := mobileCompanyIdMap[dataList[i].Mobile]
		if companyId == 0 {
			continue
		}
		ficc := ficcProductMap[companyId]
		if ficc != nil {
			dataList[i].SysCompanyName = ficc.CompanyName
			dataList[i].FiccStatus = ficc.Status
			dataList[i].FiccSeller = ficc.SellerName
		}
		rai := raiProductMap[companyId]
		if rai != nil {
			dataList[i].SysCompanyName = rai.CompanyName
			dataList[i].RaiStatus = rai.Status
			dataList[i].RaiSeller = rai.SellerName
		}
	}

	// 缓存导入数据, 导出时用缓存数据生成Excel
	var code, cacheKey string
	dataJson, e := json.Marshal(dataList)
	if e == nil {
		code = fmt.Sprint(time.Now().UnixNano())
		cacheKey = utils.CACHE_KEY_COMPANY_MATCH_PRE + code
		_ = utils.Rc.Put(cacheKey, string(dataJson), time.Minute*30)
	}

	resp := new(company.UserImportMatchResp)
	resp.List = dataList
	resp.Code = code

	br.Data = resp
	br.Msg = "匹配成功"
	br.Ret = 200
	br.Success = true
}

// @Title 联系人名单匹配结果下载
// @Description 联系人名单匹配结果下载
// @Param   Code  query  string  true  "导入时返回的Code"
// @Success 200 Ret=200 匹配成功
// @router /list/match/download [get]
func (this *CompanyUserController) ImportListMatchDownload() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请重新登录"
		return
	}
	code := this.GetString("Code")
	if code == "" {
		br.Msg = "参数有误"
		return
	}
	cacheKey := utils.CACHE_KEY_COMPANY_MATCH_PRE + code

	// 获取导入时的缓存数据
	dataJson, e := utils.Rc.RedisString(cacheKey)
	if e != nil {
		br.Msg = "获取导出数据失败"
		br.ErrMsg = "获取导出数据失败, Err: " + e.Error()
		return
	}
	if dataJson == "" {
		br.Msg = "匹配数据已失效, 请重新匹配"
		return
	}
	dataList := make([]*company.UserImportMatch, 0)
	if e = json.Unmarshal([]byte(dataJson), &dataList); e != nil {
		br.Msg = "匹配数据已失效, 请重新匹配"
		return
	}
	if len(dataList) == 0 {
		br.Msg = "匹配数据已失效, 请重新匹配"
		return
	}

	// 生成Excel表格
	dir, err := os.Executable()
	exPath := filepath.Dir(dir)
	downloadPath := exPath + "/company_match_" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	excelFile := xlsx.NewFile()
	if err != nil {
		br.Msg = "生成文件失败"
		br.ErrMsg = "生成文件失败"
		return
	}
	style := xlsx.NewStyle()
	alignment := xlsx.Alignment{
		Horizontal: "center",
		Vertical:   "center",
		WrapText:   true,
	}
	style.Alignment = alignment
	style.ApplyAlignment = true

	// 新增Sheet和表头
	sheet, err := excelFile.AddSheet("客户名单")
	if err != nil {
		br.Msg = "新增Sheet失败"
		br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
		return
	}
	titleRow := sheet.AddRow()
	titleRow.AddCell().SetValue("姓名")
	titleRow.AddCell().SetValue("国际（区号）")
	titleRow.AddCell().SetValue("手机号")
	titleRow.AddCell().SetValue("客户公司")
	titleRow.AddCell().SetValue("系统客户")
	titleRow.AddCell().SetValue("FICC状态")
	titleRow.AddCell().SetValue("FICC销售")
	titleRow.AddCell().SetValue("权益状态")
	titleRow.AddCell().SetValue("权益销售")

	// 表格赋值
	for _, v := range dataList {
		dataRow := sheet.AddRow()
		dataRow.SetHeight(20)
		dataRow.AddCell().SetString(v.UserName)
		dataRow.AddCell().SetString(v.CountryCode)
		dataRow.AddCell().SetString(v.Mobile)
		dataRow.AddCell().SetString(v.CompanyName)
		dataRow.AddCell().SetString(v.SysCompanyName)
		dataRow.AddCell().SetString(v.FiccStatus)
		dataRow.AddCell().SetString(v.FiccSeller)
		dataRow.AddCell().SetString(v.RaiStatus)
		dataRow.AddCell().SetString(v.RaiSeller)
	}

	// 输出Excel
	if e = excelFile.Save(downloadPath); e != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败"
		return
	}
	defer func() {
		_ = os.Remove(downloadPath)
	}()
	suffix := time.Now().Format(utils.FormatDateTimeUnSpace)
	downloadFileName := "客户名单匹配_" + suffix + ".xlsx"
	this.Ctx.Output.Download(downloadPath, downloadFileName)

	br.Msg = "导出成功"
	br.Ret = 200
	br.Success = true
}

// Follow
// @Title 关注联系人
// @Description 关注联系人
// @Param	request	body request.ApplyMarkReq true "type json string"
// @Success 200 {object} 标记处理成功
// @router /follow [post]
func (this *CompanyUserController) Follow() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser is Empty"
		br.Ret = 408
		return
	}

	var req request.FollowReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.UserId <= 0 {
		br.Msg = "用户ID异常"
		br.ErrMsg = "用户ID异常"
		return
	}

	// 查公司里有多少已关注，上限三个
	count, err := models.GetCompanyFollowCount(req.CompanyId)
	if err != nil {
		br.Msg = "操作失败！ "
		br.ErrMsg = "操作失败，Err:" + err.Error()
		return
	}
	if count == 3 && req.Type == 1 {
		br.Msg = "关注失败，特别关注已达上限（上限三个）"
		br.ErrMsg = "关注失败，特别关注已达上限（上限三个）"
		return
	}

	// 关注或取关
	err = models.SetUserFollow(req.UserId, req.Type)
	if err != nil {
		br.Msg = "操作失败！ "
		br.ErrMsg = "操作失败，Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// @Title 开通或者关闭用户研选权限
// @Description 开通或者关闭用户研选权限
// @Param	request	body request.ApplyMarkReq true "type json string"
// @Success 200 {object} 操作成功
// @router /update/user/yananxuan/permission [post]
func (this *CompanyUserController) UpadteUserYanxuanPermission() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser is Empty"
		br.Ret = 408
		return
	}
	var req cygx.UpdateUserYanxuanPermissionReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	userId := req.UserId
	if userId <= 0 {
		br.Msg = "用户ID异常"
		br.ErrMsg = "用户ID异常"
		return
	}

	//获取联系人详情
	userInfo, err := models.GetWxUserByUserId(req.UserId)
	if err != nil {
		br.Msg = "获取联系人异常！"
		br.ErrMsg = "获取联系人异常，Err:" + err.Error()
		return
	}

	if userInfo.BusinessCardUrl == "" {
		br.Msg = "该联系人尚未添加名片，请点击编辑，上传名片后再开通试用"
		return
	}

	companyInfo, err := company.GetCompanyById(userInfo.CompanyId)
	if err != nil {
		br.Msg = "查找客户失败"
		br.ErrMsg = "查找客户失败,err:" + err.Error()
		return
	}

	// 查询用户是否开通过
	count, err := cygx.GetCygxUserYanxuanPermissionCountByUserId(userId)
	if err != nil {
		br.Msg = "操作失败！ "
		br.ErrMsg = "操作失败，Err:" + err.Error()
		return
	}

	item := new(cygx.CygxUserYanxuanPermission)
	if req.Type == 0 {
		item.Status = "未开通"
	} else {
		item.Status = "试用"
	}
	item.UserId = userId
	item.CompanyId = companyInfo.CompanyId
	item.CompanyName = companyInfo.CompanyName
	item.StartDate = time.Now().Format(utils.FormatDate)
	item.EndDate = time.Now().AddDate(0, 2, 0).Format(utils.FormatDate) // 试用期两个月
	item.Mobile = userInfo.Mobile
	item.Email = userInfo.Email
	item.RealName = userInfo.RealName
	item.AdminId = sysUser.AdminId
	item.AdminRealName = sysUser.RealName
	item.CreatedTime = time.Now()
	item.LastUpdatedTime = time.Now()
	item.ModifyTime = time.Now()
	if count == 0 {
		_, err = cygx.AddCygxUserYanxuanPermission(item) // 添加
	} else {
		if req.Type == 0 {
			err = cygx.UpdateCygxUserYanxuanPermissionClose(userId) // 关闭
		} else {
			err = cygx.UpdateCygxUserYanxuanPermissionOpen(item) // 开通
		}
	}
	if err != nil {
		br.Msg = "操作失败！ "
		br.ErrMsg = "操作失败，Err:" + err.Error()
		return
	}
	go cygxService.AddCygxUserYanxuanPermissionLog(item)
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// @Title 客户联系人详情
// @Description 客户联系人详情接口
// @Param   UserId  query  int	  true  "用户ID"
// @router /user/detail [get]
func (this *CompanyUserController) DetailUser() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	userId, _ := this.GetInt("UserId")
	if userId <= 0 {
		br.Msg = "参数错误！"
		return
	}
	wxUser, err := models.GetWxUserByUserId(userId)
	if err != nil {
		br.ErrMsg = "获取信息失败，Err:" + err.Error()
		br.Msg = "获取信息失败"
		return
	}
	resp := new(models.WxUserResp)
	resp.Detail = wxUser
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// ListByReport
// @Title 联系人列表
// @Description 联系人列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   CompanyId   query   int  true       "公司id，必填"
// @Param   SortParam	query	int	false	"排序字段：1-点击量；2-点击时间"
// @Param   SortType	query	int	false	"排序方式：1-倒序；2-正序"
// @Success 200 {object} company.CompanyUserListResp
// @router /user/listByReport [get]
func (this *CompanyUserController) ListByReport() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	companyId, _ := this.GetInt("CompanyId")

	sortParam, _ := this.GetInt("SortParam", 2)
	sortType, _ := this.GetInt("SortType", 1)

	if companyId <= 0 {
		br.Msg = "请选择客户"
		br.ErrMsg = "客户参数错误"
		return
	}
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	var order string
	sortArr := []int{1, 2}
	if utils.InArrayByInt(sortArr, sortParam) && utils.InArrayByInt(sortArr, sortType) {
		pMap := map[int]string{1: "ficc_view_total", 2: "ficc_last_view_time"}
		tMap := map[int]string{1: "DESC", 2: "ASC"}
		order = fmt.Sprintf(` ORDER BY %s %s`, pMap[sortParam], tMap[sortType])
	}

	total, err := company.GetCompanyUserListByReportCount(companyId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据总数失败，Err:" + err.Error()
		return
	}

	list, err := company.GetCompanyUserListByReport(companyId, startSize, pageSize, order)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	respList := make([]*company.CompanyViewResp, 0)
	for i := range list {
		v := &company.CompanyViewResp{
			UserId:       int(list[i].UserId),
			UserName:     list[i].RealName,
			Mobile:       list[i].Mobile,
			Email:        list[i].Email,
			ViewTotal:    list[i].FiccViewTotal,
			LastViewTime: list[i].FiccLastViewTime.Format(utils.FormatDateTime),
		}
		if v.LastViewTime == "0001-01-01 00:00:00" {
			v.LastViewTime = ""
		}
		respList = append(respList, v)
	}

	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := &company.CompanyViewPageListResp{
		Paging: page,
		List:   respList,
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}
