package eta_business

import (
	"encoding/json"
	"eta/eta_forum_admin/controllers"
	"eta/eta_forum_admin/models"
	"eta/eta_forum_admin/models/eta_business"
	"eta/eta_forum_admin/models/system"
	eta_business2 "eta/eta_forum_admin/services/eta_business"
	"eta/eta_forum_admin/utils"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"github.com/tealeg/xlsx"
	"os"
	"strings"
	"time"
)

// 客户联系人管理
type EtaBusinessUserController struct {
	controllers.BaseAuthController
}

// 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 *EtaBusinessUserController) 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")
	positionStatus, _ := this.GetInt("PositionStatus", -1)
	enabled, _ := this.GetInt("Enabled", -1)
	businessCode := this.GetString("BusinessCode")
	etaBusinessId, _ := this.GetInt("EtaBusinessId")
	keyword := utils.TrimStr(this.GetString("Keyword"))

	sortType := this.GetString("SortType")
	sortParam := this.GetString("SortParam")

	/*if businessCode <= 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 (real_name LIKE '%` + keyword + `%' OR mobile LIKE '%` + keyword + `%' OR email LIKE '%` + keyword + `%') `
	}

	if businessCode != "" {
		condition += ` AND business_code = ? `
		pars = append(pars, businessCode)
	}

	if etaBusinessId != 0 {
		condition += ` AND eta_business_id = ? `
		pars = append(pars, etaBusinessId)
	}

	if positionStatus >= 0 {
		condition += ` AND position_status = ? `
		pars = append(pars, positionStatus)
	}

	if enabled >= 0 { // 0-禁用 1-启用
		condition += ` AND enabled = ? `
		pars = append(pars, enabled)
	}
	order := ""
	if sortParam == "LastLoginTime" {
		if sortType == "desc" || sortType == "asc" {
			order = " last_login_time " + sortType
		}
	}
	total, err := models.GetUserCountByCondition(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据总数失败,Err:" + err.Error()
		return
	}

	list, err := models.GetUserPageListByCondition(condition, pars, order, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败,Err:" + err.Error()
		return
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(models.UserListResp)
	userList := make([]*models.BusinessUser, 0)
	if len(list) == 0 {
		resp.List = userList
		resp.Paging = page
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		br.Data = resp
		return
	}
	// 查找商户信息
	businessCodeStr := make([]string, 0)
	businessCodeMap := make(map[string]*eta_business.EtaBusiness)
	for _, v := range list {
		if _, ok := businessCodeMap[v.BusinessCode]; ok {
			continue
		}
		businessCodeStr = append(businessCodeStr, v.BusinessCode)
	}
	obj := new(eta_business.EtaBusiness)
	condition1 := " AND business_code IN (" + utils.GetOrmInReplace(len(businessCodeStr)) + ") "
	var pars1 []interface{}
	pars1 = append(pars1, businessCodeStr)
	businessList, err := obj.GetItemsByCondition(condition1, pars1, []string{}, "")
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取商户信息失败,Err:" + err.Error()
		return
	}
	for _, v := range businessList {
		businessCodeMap[v.BusinessCode] = v
	}

	for _, v := range list {
		tmp := new(models.BusinessUser)
		if businessInfo, ok := businessCodeMap[v.BusinessCode]; ok {
			tmp.BusinessName = businessInfo.BusinessName
			tmp.BusinessSellerId = businessInfo.SellerId
			tmp.BusinessSellerName = businessInfo.SellerName
		}
		tmp.BusinessCode = v.BusinessCode
		tmp.EtaBusinessId = v.EtaBusinessId
		tmp.UserId = v.UserId
		tmp.RealName = v.RealName
		tmp.Mobile = v.Mobile
		tmp.CountryCode = v.CountryCode
		tmp.Email = v.Email
		tmp.Enabled = v.Enabled
		tmp.PositionStatus = v.PositionStatus
		tmp.Position = v.Position
		tmp.DepartmentName = v.DepartmentName
		// 判断time类型是否为零值
		if !v.LastLoginTime.IsZero() {
			tmp.LastLoginTime = v.LastLoginTime.Format(utils.FormatDateTime)
		}
		tmp.CreatedTime = v.CreatedTime.Format(utils.FormatDateTime)
		tmp.LastUpdatedTime = v.LastUpdatedTime.Format(utils.FormatDateTime)
		userList = append(userList, tmp)
	}
	resp.List = userList
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 新增客户联系人
// @Description 新增客户联系人接口
// @Param	request	body company.AddUserReq true "type json string"
// @router /user/add [post]
func (this *EtaBusinessUserController) 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 models.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
	}

	if req.Mobile == "" {
		br.Msg = "请输入手机号"
		br.IsSendEmail = false
		return
	}

	if req.EtaBusinessId == 0 {
		br.Msg = "请选择客户"
		br.IsSendEmail = false
		return
	}

	if req.CountryCode == "" {
		req.CountryCode = "86"
	}

	//空格移除
	req.Mobile = utils.TrimStr(req.Mobile)
	req.RealName = utils.TrimStr(req.RealName)
	//判断该手机号、邮箱是否已经添加,如果已经添加,那么就不再添加
	var key string
	if req.Mobile != "" {
		key = fmt.Sprintf("user:mobile:%s_%s", req.CountryCode, req.Mobile)
	}
	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)
	}

	businessObj := new(eta_business.EtaBusiness)

	businessInfo, err := businessObj.GetItemById(req.EtaBusinessId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "商户不存在"
			return
		}
		br.Msg = "客户信息有误"
		br.ErrMsg = "获取客户信息失败, Err: " + err.Error()
		return
	}
	//操作权限校验
	ok := eta_business2.CheckBusinessUserButton(sysUser.RoleTypeCode, businessInfo.SellerId, sysUser.AdminId)
	if !ok {
		br.Msg = "没有操作权限"
		br.ErrMsg = "没有操作权限"
		return
	}
	//systemUser models.Company.CompanyUser
	//var sysemUser company.CompanyUser
	//校验主手机号
	mobileItem, err := models.GetUserByMobileCountryCode(req.Mobile, req.CountryCode)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "校验手机号有误"
		br.ErrMsg = "校验手机号有误, Err: " + err.Error()
		return
	}
	if err == nil && mobileItem.UserId > 0 {
		br.Msg = "手机号已存在"
		br.Success = true
		br.Data = mobileItem
		br.IsSendEmail = false
		br.Ret = 600
		return
	}
	err = nil

	user := new(models.User)
	user.RealName = utils.TrimStr(req.RealName)
	user.CountryCode = utils.TrimStr(req.CountryCode)
	user.Mobile = utils.TrimStr(req.Mobile)
	user.UserName = user.Mobile
	user.Position = req.Position
	user.PositionStatus = req.PositionStatus
	user.Enabled = 1
	user.BusinessCode = businessInfo.BusinessCode
	user.EtaBusinessId = businessInfo.EtaBusinessId
	user.DepartmentName = req.DepartmentName
	user.CreatedTime = time.Now()
	user.RegisterTime = time.Now()
	user.LastUpdatedTime = time.Now()
	user.SellerId = sysUser.AdminId
	user.SellerName = sysUser.RealName
	newId, err := models.AddUser(user)
	user.UserId = int(newId)
	if err != nil {
		br.Msg = "新增失败"
		br.ErrMsg = "新增失败,Err:" + err.Error()
		return
	}

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

// @Title 删除客户联系人
// @Description 删除客户联系人接口
// @Param	request	body company.DeleteUserReq true "type json string"
// @router /user/delete [post]
func (this *EtaBusinessUserController) 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 models.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.GetUserByUserId(req.UserId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "用户不存在"
			return
		}
		br.Msg = "获取联系人异常!"
		br.ErrMsg = "获取联系人异常,Err:" + err.Error()
		return
	}
	// 查询商户关联的销售信息
	businessObj := new(eta_business.EtaBusiness)

	businessInfo, err := businessObj.GetItemByBusinessCode(userInfo.BusinessCode)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "商户不存在"
			return
		}
		br.Msg = "客户信息有误"
		br.ErrMsg = "获取客户信息失败, Err: " + err.Error()
		return
	}
	//操作权限校验
	ok := eta_business2.CheckBusinessUserButton(sysUser.RoleTypeCode, businessInfo.SellerId, sysUser.AdminId)
	if !ok {
		br.Msg = "删除失败,没有权限"
		br.ErrMsg = "删除失败,没有权限"
		return
	}

	err = models.DeleteUser(req.UserId)
	if err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "删除失败,Err:" + err.Error()
		return
	}

	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 *EtaBusinessUserController) 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 models.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.Mobile = utils.TrimStr(req.Mobile)
	req.RealName = utils.TrimStr(req.RealName)

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

	if req.Mobile == "" {
		br.Msg = "请输入手机号"
		br.IsSendEmail = false
		return
	}

	if req.EtaBusinessId == 0 {
		br.Msg = "请选择客户"
		br.IsSendEmail = false
		return
	}

	if req.CountryCode == "" {
		req.CountryCode = "86"
	}

	//操作权限校验
	userInfo, err := models.GetUserByUserId(req.UserId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "用户不存在"
			return
		}
		br.ErrMsg = "获取信息失败,Err:" + err.Error()
		br.Msg = "获取信息失败"
		return
	}

	businessObj := new(eta_business.EtaBusiness)

	businessInfo, err := businessObj.GetItemById(req.EtaBusinessId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "商户不存在"
			return
		}
		br.Msg = "客户信息有误"
		br.ErrMsg = "获取客户信息失败, Err: " + err.Error()
		return
	}
	//操作权限校验
	ok := eta_business2.CheckBusinessUserButton(sysUser.RoleTypeCode, businessInfo.SellerId, sysUser.AdminId)
	if !ok {
		br.Msg = "没有操作权限"
		br.ErrMsg = "没有操作权限"
		return
	}

	if req.Mobile != "" && req.Mobile != userInfo.Mobile && req.CountryCode != userInfo.CountryCode {
		mobileItem, e := models.GetUserByMobileCountryCode(req.Mobile, req.CountryCode)
		if e != nil && e.Error() != utils.ErrNoRow() {
			br.Msg = "校验手机号有误"
			br.ErrMsg = "校验手机号有误, Err: " + err.Error()
			return
		}
		if e == nil && mobileItem.UserId > 0 && mobileItem.UserId != req.UserId {
			{
				br.Msg = "手机号已存在"
				br.Success = true
				br.Data = mobileItem
				br.IsSendEmail = false
				br.Ret = 600
				return
			}
		}
	}

	//待更新字段
	updateCol := []string{"RealName", "Mobile", "UserName", "LastUpdatedTime", "Position", "PositionStatus", "DepartmentName", "BusinessCode", "EtaBusinessId", "BusinessCode", "CountryCode"}

	userInfo.RealName = req.RealName
	userInfo.Mobile = req.Mobile
	userInfo.UserName = userInfo.Mobile
	userInfo.LastUpdatedTime = time.Now()
	userInfo.Position = req.Position
	userInfo.DepartmentName = req.DepartmentName
	userInfo.BusinessCode = businessInfo.BusinessCode
	userInfo.EtaBusinessId = businessInfo.EtaBusinessId
	userInfo.CountryCode = req.CountryCode
	userInfo.PositionStatus = req.PositionStatus
	err = userInfo.Update(updateCol)
	if err != nil {
		br.Msg = "编辑失败!"
		br.ErrMsg = "编辑失败,Err:" + err.Error()
		return
	}

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

// @Title 获取批量导入联系人数据
// @Description 获取批量导入联系人数据
// @Param   File   query   file  true       "文件"
// @Param   CompanyId   query   file  true       "客户id"
// @Success 200 {object} models.ImportListResp
// @router /user/import/list [post]
func (this *EtaBusinessUserController) 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
	}

	//todo 没有选择对应的商户所以无操作权限校验

	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.BusinessUser, 0)
	addUser := make([]*models.BusinessUser, 0)
	//excel中已经存在的数据,用来判断excel中是否存在相同手机号/邮箱,避免重复提交
	excelData := make(map[string]string)
	//重复数据
	repeatUser := make([]*models.BusinessUser, 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 == 1 {
				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, "手机号") {
							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 >= 2 {
				row := sheet.Row(i)
				cells := row.Cells
				var userName, countryCode, mobileOne, position, departmentName, businessName, creditCode, positionStatus string
				for k, cell := range cells {
					if k == 0 {
						userName = cell.String()
					}
					if k == 1 {
						countryCode = cell.String()
					}
					if k == 2 {
						mobileOne = cell.String()
					}
					if k == 3 {
						position = cell.String()
					}
					if k == 4 {
						departmentName = cell.String()
					}
					if k == 5 {
						businessName = cell.String()
					}
					if k == 6 {
						creditCode = cell.String()
					}
					if k == 7 {
						positionStatus = cell.String()
					}
				}

				//移除空格
				mobileOne = utils.TrimStr(mobileOne)
				//这些字段都没有的话,系统认为excel到底了
				if userName == "" {
					utils.FileLog.Info("姓名必填")
					continue
				}

				//如果手机号或者邮箱都没有填写的情况下
				if mobileOne == "" {
					utils.FileLog.Info("手机号必填")
					continue
				}
				if countryCode == "" {
					countryCode = "86"
				}

				if businessName == "" && creditCode == "" {
					utils.FileLog.Info("导入数据中存在【姓名】和【社会信用码】都为空的用户,请检查")
					continue
				}

				if positionStatus != "在职" && positionStatus != "离职" {
					utils.FileLog.Info("导入数据中存在【在职状态】为空或不在【在职】和【离职】的用户,请检查")
					continue
				}

				item := new(models.BusinessUser)
				item.CountryCode = countryCode
				item.RealName = userName
				if positionStatus == "在职" {
					item.PositionStatus = 1
				} else {
					item.PositionStatus = 0
				}
				item.Mobile = mobileOne
				item.UserName = item.Mobile
				item.Position = position
				item.DepartmentName = departmentName
				// 查询商户信息
				if creditCode != "" {
					businessObj := new(eta_business.EtaBusiness)
					businessInfo := new(eta_business.EtaBusiness)
					businessInfo, err = businessObj.GetItemByCreditCode(creditCode)
					if err != nil {
						if err.Error() == utils.ErrNoRow() {
							utils.FileLog.Info("商户不存在")
							continue
						}
						utils.FileLog.Info("获取商户信息失败, Err: " + err.Error())
						continue
					}
					item.BusinessCode = businessInfo.BusinessCode
					item.BusinessName = businessInfo.BusinessName
				}
				if item.BusinessCode == "" && businessName != "" {
					businessObj := new(eta_business.EtaBusiness)
					businessInfo := new(eta_business.EtaBusiness)
					businessInfo, err = businessObj.GetItemByBusinessName(businessName)
					if err != nil {
						if err.Error() == utils.ErrNoRow() {
							utils.FileLog.Info("商户不存在")
							continue
						}
						utils.FileLog.Info("获取商户信息失败, Err: " + err.Error())
						continue
					}
					item.BusinessCode = businessInfo.BusinessCode
					item.BusinessName = businessInfo.BusinessName
				}
				if _, ok := excelData[item.CountryCode+"_"+item.Mobile]; ok {
					//将用户插入其中,然后退出当前循环,进入下一循环
					//repeatUser = append(repeatUser, item)
					continue
				}
				excelData[item.CountryCode+"_"+item.Mobile] = item.CountryCode

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

	// 判断系统里该手机号是否已存在
	mobiles := make([]string, 0)
	for k, _ := range excelData {
		mobile := strings.Split(k, "_")[1]
		mobiles = append(mobiles, mobile)
	}

	// 查询系统里是否存在
	existUserMap := make(map[string]struct{})
	if len(mobiles) > 0 {
		existUsers, e := models.GetUserByMobiles(mobiles)
		if e != nil {
			br.Msg = "查询用户失败"
			br.ErrMsg = "查询用户失败,Err:" + e.Error()
			return
		}
		for _, user := range existUsers {
			existUserMap[user.CountryCode+"_"+user.Mobile] = struct{}{}
		}
	}
	for _, v := range existUser {
		if _, ok := existUserMap[v.CountryCode+"_"+v.Mobile]; ok {
			repeatUser = append(repeatUser, v)
		} else {
			addUser = append(addUser, v)
		}
	}
	//defer func() {
	//	os.Remove(path)
	//}()
	br.Msg = "获取成功"
	br.Ret = 200
	br.Success = true
	br.Data = models.ImportListResp{
		ValidUser:  addUser,
		RepeatUser: repeatUser,
	}
}

// @Title 批量导入联系人数据
// @Description 批量导入联系人数据
// @Param   File   query   file  true       "文件"
// @Param   CompanyId   query   file  true       "客户id"
// @Success 600 {object} []*company.CompanyUser
// @Success 200 Ret=200 导入成功
// @router /user/import [post]
func (this *EtaBusinessUserController) Import() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请重新登录"
		return
	}
	var req models.ImportUserReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败,Err:" + err.Error()
		return
	}

	/*file, h, err := this.GetFile("File")
	if err != nil {
		br.Msg = "获取文件失败"
		br.ErrMsg = "获取文件失败,Err:" + err.Error()
		return
	}

	//todo 没有选择对应的商户所以无操作权限校验

	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.User, 0)
	addUser := make([]*models.User, 0)
	//excel中已经存在的数据,用来判断excel中是否存在相同手机号/邮箱,避免重复提交
	excelData := make(map[string]string)

	// 遍历sheet页读取
	for _, sheet := range xlFile.Sheets {
		//遍历行读取
		maxRow := sheet.MaxRow
		fmt.Println("maxRow:", maxRow)
		fmt.Println("maxRow")
		for i := 0; i < maxRow; i++ {
			if i == 1 {
				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, "手机号") {
							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 >= 2 {
				row := sheet.Row(i)
				cells := row.Cells
				var userName, countryCode, mobileOne, position, departmentName, businessName, creditCode, positionStatus string
				for k, cell := range cells {
					if k == 0 {
						userName = cell.String()
					}
					if k == 1 {
						countryCode = cell.String()
					}
					if k == 2 {
						mobileOne = cell.String()
					}
					if k == 3 {
						position = cell.String()
					}
					if k == 4 {
						departmentName = cell.String()
					}
					if k == 5 {
						businessName = cell.String()
					}
					if k == 6 {
						creditCode = cell.String()
					}
					if k == 7 {
						positionStatus = cell.String()
					}
				}

				//移除空格
				mobileOne = utils.TrimStr(mobileOne)
				//这些字段都没有的话,系统认为excel到底了
				if userName == "" {
					utils.FileLog.Info("姓名必填")
					continue
				}

				//如果手机号或者邮箱都没有填写的情况下
				if mobileOne == "" {
					utils.FileLog.Info("手机号必填")
					continue
				}
				if countryCode == "" {
					utils.FileLog.Info("导入数据中存在【国际区号】为空的用户,请检查")
					continue
				}

				if businessName == "" && creditCode == "" {
					utils.FileLog.Info("导入数据中存在【姓名】和【社会信用码】都为空的用户,请检查")
					continue
				}

				item := new(models.User)
				item.CountryCode = countryCode
				item.RealName = userName
				if positionStatus == "在职" {
					item.PositionStatus = 1
				} else if positionStatus == "离职" {
					item.PositionStatus = 0
				}
				item.Mobile = mobileOne
				item.UserName = item.Mobile
				item.Position = position
				item.DepartmentName = departmentName
				// 查询商户信息
				if creditCode != "" {
					businessObj := new(eta_business.EtaBusiness)
					businessInfo := new(eta_business.EtaBusiness)
					businessInfo, err = businessObj.GetItemByCreditCode(creditCode)
					if err != nil {
						if err.Error() == utils.ErrNoRow() {
							utils.FileLog.Info("商户不存在")
							continue
						}
						utils.FileLog.Info("获取商户信息失败, Err: " + err.Error())
						continue
					}
					item.BusinessCode = businessInfo.BusinessCode
					item.EtaBusinessId = businessInfo.EtaBusinessId
				}
				if item.BusinessCode == "" && businessName != "" {
					businessObj := new(eta_business.EtaBusiness)
					businessInfo := new(eta_business.EtaBusiness)
					businessInfo, err = businessObj.GetItemByBusinessName(businessName)
					if err != nil {
						if err.Error() == utils.ErrNoRow() {
							utils.FileLog.Info("商户不存在")
							continue
						}
						utils.FileLog.Info("获取商户信息失败, Err: " + err.Error())
						continue
					}
					item.BusinessCode = businessInfo.BusinessCode
					item.EtaBusinessId = businessInfo.EtaBusinessId
				}
				if _, ok := excelData[item.CountryCode+"_"+item.Mobile]; ok {
					//将用户插入其中,然后退出当前循环,进入下一循环
					//repeatUser = append(repeatUser, item)
					continue
				}
				excelData[item.CountryCode+"_"+item.Mobile] = item.CountryCode

				//没问题数据
				existUser = append(existUser, item)
			}
		}
	}
	*/
	excelUser := make([]*models.User, 0)
	addUser := make([]*models.User, 0)
	//excel中已经存在的数据,用来判断excel中是否存在相同手机号/邮箱,避免重复提交
	excelData := make(map[string]string)
	for _, v := range req.ValidUser {
		// 查询商户信息
		item := new(models.User)
		if v.CountryCode == "" {
			v.CountryCode = "86"
		}
		item.CountryCode = v.CountryCode
		item.RealName = v.RealName
		item.PositionStatus = v.PositionStatus
		item.Mobile = v.Mobile
		item.UserName = v.Mobile
		item.Position = v.Position
		item.DepartmentName = v.DepartmentName
		if v.BusinessCode != "" {
			businessObj := new(eta_business.EtaBusiness)
			businessInfo := new(eta_business.EtaBusiness)
			businessInfo, err = businessObj.GetItemByBusinessCode(v.BusinessCode)
			if err != nil {
				if err.Error() == utils.ErrNoRow() {
					utils.FileLog.Info("商户不存在")
					continue
				}
				utils.FileLog.Info("获取商户信息失败, Err: " + err.Error())
				continue
			}
			item.BusinessCode = businessInfo.BusinessCode
			item.EtaBusinessId = businessInfo.EtaBusinessId
		}
		if _, ok := excelData[item.CountryCode+"_"+item.Mobile]; ok {
			//将用户插入其中,然后退出当前循环,进入下一循环
			//repeatUser = append(repeatUser, item)
			continue
		}
		excelData[item.CountryCode+"_"+item.Mobile] = item.CountryCode
		//没问题数据
		excelUser = append(excelUser, item)
	}
	// 判断系统里该手机号是否已存在
	mobiles := make([]string, 0)
	for k, _ := range excelData {
		mobile := strings.Split(k, "_")[1]
		mobiles = append(mobiles, mobile)
	}

	// 查询系统里是否存在
	existUserMap := make(map[string]struct{})
	if len(mobiles) > 0 {
		existUsers, e := models.GetUserByMobiles(mobiles)
		if e != nil {
			br.Msg = "查询用户失败"
			br.ErrMsg = "查询用户失败,Err:" + e.Error()
			return
		}
		for _, user := range existUsers {
			existUserMap[user.CountryCode+"_"+user.Mobile] = struct{}{}
		}
	}
	for _, v := range excelUser {
		if _, ok := existUserMap[v.CountryCode+"_"+v.Mobile]; !ok {
			addUser = append(addUser, v)
		}
	}
	fmt.Println("表格中用户与系统中存在用户没有冲突")
	//如果表格中用户与系统中存在用户 没有冲突,那么继续执行
	for _, user := range addUser {
		if user.RealName != "" && user.Mobile != "" {
			userData := new(models.User)
			userData.RealName = user.RealName
			userData.UserName = user.Mobile
			userData.Mobile = user.Mobile
			userData.CountryCode = user.CountryCode
			userData.Email = user.Email
			userData.Position = user.Position
			userData.PositionStatus = user.PositionStatus
			userData.BusinessCode = user.BusinessCode
			userData.EtaBusinessId = user.EtaBusinessId
			userData.DepartmentName = user.DepartmentName
			userData.CountryCode = user.CountryCode
			userData.CreatedTime = time.Now()
			userData.LastUpdatedTime = time.Now()
			userData.Enabled = 1
			userData.SellerId = sysUser.AdminId
			userData.SellerName = sysUser.RealName
			//判断该手机号、邮箱是否已经添加,如果已经添加,那么就不再添加
			var key string
			key = "user:mobile:" + userData.Mobile

			isHas := utils.Rc.IsExist(key)
			if isHas == false {
				newId, err := models.AddUser(userData)
				userData.UserId = int(newId)
				if err != nil {
					br.Msg = "导入失败"
					br.ErrMsg = "导入失败,Err:" + err.Error()
					return
				}
			}
		}
	}
	/*defer func() {
		os.Remove(path)
	}()*/

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

// @Title 移动用户至新的商户下
// @Description 移动用户至新的商户下
// @Param	request	body company.EditUserReq true "type json string"
// @router /user/changeBusiness [post]
func (this *EtaBusinessUserController) ChangeUserBusiness() {
	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.ChangeUserBusinessReq
	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
	}

	if req.EtaBusinessId == 0 {
		br.Msg = "请选择商户"
		br.IsSendEmail = false
		return
	}
	//操作权限校验
	userInfo, err := models.GetUserByUserId(req.UserId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "用户不存在"
			return
		}
		br.ErrMsg = "获取信息失败,Err:" + err.Error()
		br.Msg = "获取信息失败"
		return
	}
	if userInfo.EtaBusinessId == req.EtaBusinessId {
		br.Msg = "用户已经在该商户下"
		return
	}
	businessObj := new(eta_business.EtaBusiness)

	businessInfo, err := businessObj.GetItemById(req.EtaBusinessId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "商户不存在"
			return
		}
		br.Msg = "商户信息有误"
		br.ErrMsg = "获取商户信息失败, Err: " + err.Error()
		return
	}

	//待更新字段
	updateCol := []string{"LastUpdatedTime", "EtaBusinessId", "BusinessCode"}

	userInfo.LastUpdatedTime = time.Now()
	userInfo.EtaBusinessId = businessInfo.EtaBusinessId
	userInfo.BusinessCode = businessInfo.BusinessCode
	err = userInfo.Update(updateCol)
	if err != nil {
		br.Msg = "操作失败!"
		br.ErrMsg = "操作失败,Err:" + err.Error()
		return
	}

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

// @Title 开启/禁用系统用户
// @Description 开启/禁用系统用户接口
// @Param	request	body system.SysuserEditReq true "type json string"
// @Success 200 操作成功
// @router /user/editEnabled [post]
func (this *EtaBusinessUserController) EditEnabled() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req models.UserEditEnabledReq
	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.GetUserByUserId(req.UserId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "用户不存在"
			return
		}
		br.ErrMsg = "获取信息失败,Err:" + err.Error()
		br.Msg = "获取信息失败"
		return
	}
	if req.Enabled != 0 && req.Enabled != 1 {
		br.Msg = "参数错误"
		return
	}
	//待更新字段
	updateCol := []string{"LastUpdatedTime", "Enabled"}

	userInfo.LastUpdatedTime = time.Now()

	userInfo.Enabled = req.Enabled
	err = userInfo.Update(updateCol)
	if err != nil {
		br.Msg = "操作失败!"
		br.ErrMsg = "操作失败,Err:" + err.Error()
		return
	}

	//todo 用户被禁用的情况下,需要将他对应的token给过期
	/*if adminItem.Enabled == 1 && req.Enabled == 0 {
		logOutSystemUser(adminItem.AdminId)
	}*/

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

// AreaCodeList
// @Title 手机号区号列表
// @Description 手机号区号列表
// @Success 200 Ret=200 获取成功
// @router /area_code/list [get]
func (this *EtaBusinessUserController) AreaCodeList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()

	type AreaCodeListResp struct {
		Name  string `description:"地区"`
		Value string `description:"区号"`
	}
	resp := make([]AreaCodeListResp, 0)
	confAuth, e := system.GetCrmConfigDetailByCode(system.ConfAreaCodeListKey)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取手机号区号配置失败, Err: " + e.Error()
		return
	}
	if confAuth.ConfigValue == "" {
		br.Msg = "获取失败"
		br.ErrMsg = "手机号区号配置为空"
		return
	}
	if e := json.Unmarshal([]byte(confAuth.ConfigValue), &resp); e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "手机号区号配置有误"
		return
	}

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

// TemplateDownload
// @Title 下载模板
// @Description 下载模板
// @Success 200 {object} models.EdbdataClassifyResp
// @Param   Source   query   int  false       "来源:1:模板1;2:模板2"
// @router /user/template [get]
func (this *EtaBusinessUserController) TemplateDownload() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	this.Ctx.Output.Download("./static/template/用户导入模版.xlsx", "用户导入模版.xlsx")
	//this.Ctx.Output.Download("./static/数据导入模板.xlsx", "数据导入模板.xlsx")

	br.Ret = 200
	br.Success = true
	br.Msg = "下载成功"
}