package controllers

import (
	"encoding/json"
	"eta/eta_mini_crm_ht/models"
	"eta/eta_mini_crm_ht/models/request"
	"eta/eta_mini_crm_ht/models/response"
	"eta/eta_mini_crm_ht/services"
	"eta/eta_mini_crm_ht/utils"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"math"
	"strings"
	"time"

	"github.com/beego/beego/v2/client/orm"
)

type UserController struct {
	BaseAuthController
}

// Add
// @Title 添加新客户
// @Description 添加新客户
// @Param   request	body request.UserAddReq true "type json string"
// @Success 200 {object} request.UserAddReq
// @router /add [post]
func (this *UserController) Add() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	var req request.UserAddReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.RealName == "" {
		br.Msg = "请输入姓名"
		return
	}
	req.Phone = strings.TrimSpace(req.Phone)
	req.Email = strings.TrimSpace(req.Email)
	if req.Phone == "" && req.Email == "" {
		br.Msg = "至少输入一个手机号或邮箱"
		return
	}

	var userByPhone, userByEmail *models.User
	if req.Phone != "" {
		if req.AreaCode == "86" {
			if !utils.ValidateMobileFormatat(req.Phone) {
				br.Msg = "手机号格式有误, 请检查"
				return
			}
		}
		userByPhone, err = models.GetUserByPhone(req.Phone, req.AreaCode)
		if err != nil && err != orm.ErrNoRows {
			br.Msg = "添加用户失败"
			br.ErrMsg = "查询用户失败，系统错误，Err:" + err.Error()
			return
		}
		if userByPhone != nil {
			switch userByPhone.Status {
			case 0:
				userByPhone.Status = 2
			case 1:
				userByPhone.Status = 2
			default:
				br.Msg = "手机号已存在，请重新输入"
				return
			}
		}
	}
	if req.Email != "" {
		if !utils.ValidateEmailFormatat(req.Email) {
			br.Msg = "邮箱格式有误, 请检查"
			return
		}
		userByEmail, err = models.GetUserByEmail(req.Email)
		if err != nil && err != orm.ErrNoRows {
			br.Msg = "添加用户失败"
			br.ErrMsg = "查询用户失败，系统错误，Err:" + err.Error()
			return
		}
		if userByEmail != nil {
			switch userByEmail.Status {
			case 0:
				userByEmail.Status = 2
			case 1:
				userByEmail.Status = 2
			default:
				br.Msg = "邮箱已存在，请重新输入"
				return
			}
		}
	}
	if req.SellerId <= 0 {
		br.Msg = "请选择营业部/销售"
		return
	}
	if req.ValidStartTime == "" || req.ValidEndTime == "" {
		br.Msg = "请选择合理的有效期范围"
		return
	}

	validStartTime, err := time.Parse(utils.FormatDate, req.ValidStartTime)
	if err != nil {
		br.Msg = "错误的日期格式"
		return
	}
	validEndTime, err := time.Parse(utils.FormatDate, req.ValidEndTime)
	if err != nil {
		br.Msg = "错误的日期格式"
		return
	}
	if !validStartTime.Before(validEndTime) {
		br.Msg = "请选择合理的有效期范围"
		return
	}
	if req.Company == "" {
		br.Msg = "请输入所属公司"
		return
	}
	if userByPhone != nil && userByEmail != nil && userByPhone.UserId != userByEmail.UserId {
		br.Msg = "邮箱已存在，请重新输入"
		return
	}

	user := &models.User{}
	curTime := time.Now()
	if userByPhone == nil && userByEmail == nil {
		user.CreateTime = curTime
		user.ModifyTime = curTime
	}
	if userByEmail != nil {
		user = userByEmail
	}
	if userByPhone != nil {
		user = userByPhone
	}
	validStartTime = validStartTime.Local().Add(-time.Hour * 8)
	validEndTime = validEndTime.Local().Add(-time.Hour*8 + time.Hour*24 - time.Second)
	if curTime.Before(validEndTime) {
		user.Status = 2
	} else {
		br.Msg = "有效期截至时间必须大于当前时间"
		return
	}

	user.RealName = req.RealName
	user.AreaCode = req.AreaCode
	user.Phone = req.Phone
	user.Email = req.Email
	user.SellerId = req.SellerId
	user.ValidStartTime = validStartTime
	user.ValidEndTime = validEndTime
	user.Company = req.Company
	user.ModifyTime = curTime
	err = models.SaveUser(user, req.ChartPermission)
	if err != nil {
		br.Msg = "添加客户失败"
		br.ErrMsg = "添加客户失败，系统错误，Err:" + err.Error()
		return
	}

	if user.Status == 2 {
		userRecord := &models.UserChangeRecord{}
		userRecord.UserId = user.UserId
		userRecord.SysUserId = this.SysUser.SysUserId
		userRecord.Content = this.SysUser.SysRealName + "新增用户"
		userRecord.Insert()
	}

	br.Msg = "添加成功"
	br.Success = true
	br.Ret = 200

}

// edit
// @Title 编辑客户
// @Description 编辑客户
// @Param   request	body request.UserEidtReq true "type json string"
// @Success 200 {object} request.UserAddReq
// @router /edit [post]
func (this *UserController) Edit() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	var req request.UserEidtReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.RealName == "" {
		br.Msg = "请输入姓名"
		return
	}
	req.Phone = strings.TrimSpace(req.Phone)
	req.Email = strings.TrimSpace(req.Email)
	if req.Phone == "" && req.Email == "" {
		br.Msg = "至少输入一个手机号或邮箱"
		return
	}
	if req.Phone != "" {
		if req.AreaCode == "86" {
			if !utils.ValidateMobileFormatat(req.Phone) {
				br.Msg = "手机号格式有误, 请检查"
				return
			}
		}
		user, err := models.GetUserByPhone(req.Phone, req.AreaCode)
		if err != nil && err != orm.ErrNoRows {
			br.Msg = "编辑用户失败"
			br.ErrMsg = "查询用户失败，系统错误，Err:" + err.Error()
			return
		}
		if user != nil && user.UserId != req.UserId {
			br.Msg = "手机号已存在，请重新输入"
			return
		}
	}
	if req.Email != "" {
		if !utils.ValidateEmailFormatat(req.Email) {
			br.Msg = "邮箱格式有误, 请检查"
			return
		}

		user, err := models.GetUserByEmail(req.Email)
		if err != nil && err != orm.ErrNoRows {
			br.Msg = "编辑用户失败"
			br.ErrMsg = "查询用户失败，系统错误，Err:" + err.Error()
			return
		}
		if user != nil && user.UserId != req.UserId {
			br.Msg = "邮箱已存在，请重新输入"
			return
		}
	}
	if req.SellerId <= 0 {
		br.Msg = "请选择营业部/销售"
		return
	}
	if req.ValidStartTime == "" || req.ValidEndTime == "" {
		br.Msg = "请选择合理的有效期范围"
		return
	}

	validStartTime, err := time.Parse(utils.FormatDate, req.ValidStartTime)
	if err != nil {
		br.Msg = "错误的日期格式"
		return
	}
	validStartTime = validStartTime.In(time.Local).Add(-time.Hour * 8)
	validEndTime, err := time.Parse(utils.FormatDate, req.ValidEndTime)
	if err != nil {
		br.Msg = "错误的日期格式"
		return
	}
	validEndTime = validEndTime.In(time.Local).Add(-time.Hour*8 + time.Hour*24 - time.Second)
	if !validStartTime.Before(validEndTime) {
		br.Msg = "请选择合理的有效期范围"
		return
	}
	if req.Company == "" {
		br.Msg = "请输入所属公司"
		return
	}

	if req.IsEnabled && time.Now().After(validEndTime) {
		br.Msg = "启用后，有效期必须大于当前时间"
		return
	}

	user, err := models.GetUserById(req.UserId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "用户不存在或已删除，请重新刷新页面"
			br.ErrMsg = "用户不存在或已删除，请重新刷新页面，Err:" + err.Error()
			return
		}
		br.Msg = "编辑用户失败"
		br.ErrMsg = "编辑用户失败, 系统错误，Err:" + err.Error()
		return
	}
	user.RealName = req.RealName
	user.AreaCode = req.AreaCode
	user.Phone = req.Phone
	user.Email = req.Email
	user.SellerId = req.SellerId
	user.ValidStartTime = validStartTime
	user.ValidEndTime = validEndTime
	user.Company = req.Company
	user.ModifyTime = time.Now()
	// 当用户状态初始为潜在客户时，才更新创建时间
	if user.Status == utils.UserStatusPotential {
		user.CreateTime = time.Now()
	}
	oldStatus := user.Status
	if !req.IsEnabled {
		user.Status = 0
	} else {
		user.Status = 2
	}
	err = models.SaveUser(user, req.ChartPermission)
	if err != nil {
		br.Msg = "添加客户失败"
		br.ErrMsg = "添加客户失败，系统错误，Err:" + err.Error()
		return
	}
	record := &models.UserChangeRecord{}
	record.UserId = req.UserId
	record.SysUserId = this.SysUser.SysUserId
	if oldStatus == utils.UserStatusPotential && user.Status == utils.UserStatusFormal {
		record.Content = this.SysUser.SysRealName + "新增用户"
	} else {
		record.Content = this.SysUser.SysRealName + "编辑用户"
	}
	record.Insert()

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

// Check
// @Title 编辑客户
// @Description 编辑客户
// @Param   request	body request.UserEidtReq true "type json string"
// @Success 200 {object} request.UserAddReq
// @router /check [post]
func (this *UserController) Check() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

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

	req.Phone = strings.TrimSpace(req.Phone)
	req.Email = strings.TrimSpace(req.Email)
	if req.Phone == "" && req.Email == "" {
		br.Msg = "至少输入一个手机号或邮箱"
		return
	}
	userCheckResp := new(response.UserCheckResp)

	if req.Phone != "" {
		if req.AreaCode == "86" {
			if !utils.ValidateMobileFormatat(req.Phone) {
				br.Msg = "手机号格式有误, 请检查"
				return
			}
		}
		user, err := models.GetUserByPhone(req.Phone, req.AreaCode)
		if err != nil && err != orm.ErrNoRows {
			br.Msg = "编辑用户失败"
			br.ErrMsg = "查询用户失败，系统错误，Err:" + err.Error()
			return
		}
		if user != nil {
			userCheckResp.UserId = user.UserId
			userCheckResp.Status = user.Status
			if user.Status == utils.UserStatusNo {
				br.Ret = 200
				br.Success = true
				br.Msg = "该用户已被禁用，确认启用并更新用户信息吗？"
				br.Data = userCheckResp
				return
			}
			if user.Status == utils.UserStatusPotential {
				br.Ret = 200
				br.Success = true
				br.Msg = "该用户已在潜在列表，确认转客户并更新用户信息吗？"
				br.Data = userCheckResp
				return
			}
			if user.Status == utils.UserStatusFormal {
				br.Msg = "手机号已存在，请重新输入"
				return
			}
		}

	}
	if req.Email != "" {
		if !utils.ValidateEmailFormatat(req.Email) {
			br.Msg = "邮箱格式有误, 请检查"
			return
		}

		user, err := models.GetUserByEmail(req.Email)
		if err != nil && err != orm.ErrNoRows {
			br.Msg = "编辑用户失败"
			br.ErrMsg = "查询用户失败，系统错误，Err:" + err.Error()
			return
		}
		if user != nil {
			userCheckResp.UserId = user.UserId
			if user.Status == 0 {
				br.Ret = 200
				br.Success = true
				br.Msg = "该用户已被禁用，确认启用并更新用户信息吗？"
				br.Data = userCheckResp
				return
			}
			if user.Status == 1 {
				br.Ret = 200
				br.Success = true
				br.Msg = "该用户已被禁用，确认启用并更新用户信息吗？"
				br.Data = userCheckResp
				return
			}
			if user.Status == 2 {
				br.Msg = "邮箱已存在，请重新输入"
				return
			}
			return
		}
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "邮箱或手机号合格"
}

// List
// @Title 用户列表
// @Description 用户列表
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   SellerId   query   string  true       "销售id"
// @Param   Status   query   int  true       "用户状态"
// @Param   KeyWord   query   string  true       "手机号/邮箱/姓名"
// @Param   IsRegistered   query   string  true       "是否注册"
// @Param   IsSubscribed   query   string  true       "是否关注"
// @Param   RegisterStartDate   query   string  true       "注册开始时间"
// @Param   RegisterEndDate   query   string  true       "注册结束时间"
// @Param   CreateStartDate   query   string  true       "创建开始时间"
// @Param   CreateEndDate   query   string  true       "创建结束时间"
// @Param   SortParam   query   string  true       "排序字段"
// @Param   SortType   query   string  true       "排序方式"
// @Success 200 {object} response.UserListResp
// @router /list [get]
func (this *UserController) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	sellerIdStr := this.GetString("SellerId")
	status := this.GetString("Status")
	keyWord := this.GetString("KeyWord")
	IsRegistered := this.GetString("IsRegistered")
	IsSubscribed := this.GetString("IsSubscribed")
	registerStartDate := this.GetString("RegisterStartDate")
	registerEndDate := this.GetString("RegisterEndDate")
	createStartDate := this.GetString("CreateStartDate")
	createEndDate := this.GetString("CreateEndDate")
	sortParma := this.GetString("SortParam")
	sortType := this.GetString("SortType")

	var condition string
	var sortCondition string
	var pars []interface{}

	if keyWord != "" {
		condition += ` AND (u.real_name LIKE ? OR u.phone LIKE ? OR u.email LIKE ?) `
		pars = utils.GetLikeKeywordPars(pars, keyWord, 3)
	}

	if pageSize <= 0 {
		pageSize = utils.PageSize20
	} else if pageSize > utils.PageSize100 {
		pageSize = utils.PageSize100
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}

	if sortParma != "" && sortType != "" {
		sortCondition = " ORDER BY "
		var param, sort string
		switch sortParma {
		case "RegisterTime":
			param = "u.register_time"
		case "CreateTime":
			param = "u.create_time"
		case "RestDate":
			param = "u.valid_end_time"
		}
		switch sortType {
		case "asc":
			sort = " ASC "
		case "desc":
			sort = " DESC "
		}
		if param != "" && sort != "" {
			sortCondition += param + " " + sort
		} else {
			sortCondition = ""
		}
	}
	if sortCondition == "" {
		sortCondition = " ORDER BY u.create_time DESC"
	}

	if sellerIdStr != "" {
		sellerIds := strings.Split(sellerIdStr, ",")
		if len(sellerIds) != 0 {
			condition += ` AND ( `
			for i, id := range sellerIds {
				if i == 0 {
					condition += ` u.seller_id = ? `
					pars = append(pars, id)
				} else {
					condition += ` OR u.seller_id = ? `
					pars = append(pars, id)
				}
			}
			condition += `) `
		}
	}
	switch status {
	case "禁用":
		condition += " AND u.status=? "
		pars = append(pars, 0)
	case "潜在":
		condition += " AND u.status=? "
		pars = append(pars, 1)
	case "正式":
		condition += " AND u.status=? "
		pars = append(pars, 2)
	case "":
		condition += " AND (u.status=? OR u.status=?) "
		pars = append(pars, 0, 2)
	}
	switch IsRegistered {
	case "是":
		condition += " AND u.is_registered=? "
		pars = append(pars, true)
	case "否":
		condition += " AND u.is_registered=? "
		pars = append(pars, false)
	}
	switch IsSubscribed {
	case "是":
		condition += " AND u.is_subscribed=? "
		pars = append(pars, true)
	case "否":
		condition += " AND u.is_subscribed=? "
		pars = append(pars, false)
	}
	if registerStartDate != "" {
		registerStartTime, er := time.Parse(utils.FormatDate, registerStartDate)
		if er != nil {
			br.Msg = "日期格式有误"
			return
		}
		condition += " AND u.register_time>=? "
		registerStartDateStr := registerStartTime.Format(utils.FormatDateTime)
		pars = append(pars, registerStartDateStr)
	}
	if registerEndDate != "" {
		registerEndTime, er := time.Parse(utils.FormatDate, registerEndDate)
		if er != nil {
			br.Msg = "日期格式有误"
			return
		}
		condition += " AND u.register_time<=? "
		// 结束时间包含今天
		registerEndTime = registerEndTime.Add(23*time.Hour + 59*time.Minute + 59*time.Second)
		registerEndDateStr := registerEndTime.Format(utils.FormatDateTime)
		pars = append(pars, registerEndDateStr)
	}
	if createStartDate != "" {
		createStartTime, er := time.Parse(utils.FormatDate, createStartDate)
		if er != nil {
			br.Msg = "日期格式有误"
			return
		}
		condition += " AND u.create_time>=? "
		createStartDateStr := createStartTime.Format(utils.FormatDateTime)
		pars = append(pars, createStartDateStr)
	}
	if createEndDate != "" {
		createEndTime, er := time.Parse(utils.FormatDate, createEndDate)
		if er != nil {
			br.Msg = "日期格式有误"
			return
		}
		condition += " AND u.create_time<=? "
		// 结束时间包含今天
		createEndTime = createEndTime.Add(23*time.Hour + 59*time.Minute + 59*time.Second)
		createEndDateStr := createEndTime.Format(utils.FormatDateTime)
		pars = append(pars, createEndDateStr)
	}
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	} else if pageSize > utils.PageSize100 {
		pageSize = utils.PageSize100
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize := utils.StartIndex(currentIndex, pageSize)

	total, err := models.GetUserCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	userList, err := models.GetUserListByConditonSort(condition, sortCondition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "查询用户失败"
		br.Msg = "查询用户失败，系统错误，Err:" + err.Error()
		return
	}
	for _, u := range userList {
		if u.ValidEndTime == "" {
			u.RestDate = 0
		} else {
			endTime, err := time.Parse(utils.FormatDateTime, u.ValidEndTime)
			if err != nil {
				br.Msg = "用户有效时间格式有误"
				br.ErrMsg = "用户有效时间格式有误，Err:" + err.Error()
				return
			}
			// 对天数向上取整
			daysBetween := int(math.Ceil(time.Until(endTime).Hours() / 24))
			if daysBetween < 0 {
				daysBetween = 0
			}
			u.RestDate = daysBetween
		}
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(response.UserListResp)
	resp.Paging = page
	resp.List = userList

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

// PotentialList
// @Title 潜在用户列表
// @Description 潜在用户列表
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   KeyWord   query   string  true       "手机号/邮箱"
// @Param   RegisterStartDate   query   string  true       "注册开始时间"
// @Param   RegisterEndDate   query   string  true       "注册结束时间"
// @Param   LastUpdateStartDate query   string  true       "最后一次阅读开始时间"
// @Param   LastUpdateEndDate   query   string  true       "最后一次阅读结束时间"
// @Param   SortParam   query   string  true       "排序字段"
// @Param   SortType   query   string  true       "排序方式"
// @Success 200 {object} response.UserListResp
// @router /potential/list [get]
func (this *UserController) PotentialList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	keyWord := this.GetString("KeyWord")
	registerStartDate := this.GetString("RegisterStartDate")
	registerEndDate := this.GetString("RegisterEndDate")
	lastUpdateStartDate := this.GetString("LastUpdateStartDate")
	lastUpdateEndDate := this.GetString("LastUpdateEndDate")
	sortParma := this.GetString("SortParam")
	sortType := this.GetString("SortType")

	var sortCondition string
	var condition string
	var pars []interface{}

	if keyWord != "" {
		condition += ` AND ( u.phone LIKE ? OR u.email LIKE ?) `
		pars = utils.GetLikeKeywordPars(pars, keyWord, 2)
	}

	if pageSize <= 0 {
		pageSize = utils.PageSize20
	} else if pageSize > utils.PageSize100 {
		pageSize = utils.PageSize100
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}

	if sortParma != "" && sortType != "" {
		sortCondition = " ORDER BY "
		var param, sort string
		switch sortParma {
		case "RegisterTime":
			param = "u.register_time"
		case "LastUpdateTime":
			param = "last_update_time"
		case "ReadCnt":
			param = "read_cnt"
		}
		switch sortType {
		case "asc":
			sort = " ASC "
		case "desc":
			sort = " DESC "
		}
		if param != "" && sort != "" {
			sortCondition += param + " " + sort
		} else {
			sortCondition = ""
		}
	}

	if registerStartDate != "" {
		registerStartTime, er := time.Parse(utils.FormatDate, registerStartDate)
		if er != nil {
			br.Msg = "日期格式有误"
			return
		}
		condition += " AND u.register_time>=? "
		registerStartDateStr := registerStartTime.Format(utils.FormatDateTime)
		pars = append(pars, registerStartDateStr)
	}
	if registerEndDate != "" {
		registerEndTime, er := time.Parse(utils.FormatDate, registerEndDate)
		if er != nil {
			br.Msg = "日期格式有误"
			return
		}
		condition += " AND u.register_time<=? "
		// 结束时间包含今天
		registerEndTime = registerEndTime.Add(23*time.Hour + 59*time.Minute + 59*time.Second)
		registerEndDateStr := registerEndTime.Format(utils.FormatDateTime)
		pars = append(pars, registerEndDateStr)
	}
	if lastUpdateStartDate != "" {
		lastUpdateStartTime, er := time.Parse(utils.FormatDate, lastUpdateStartDate)
		if er != nil {
			br.Msg = "日期格式有误"
			return
		}
		condition += " AND ur.create_time>=? "

		lastUpdateStartDateStr := lastUpdateStartTime.Format(utils.FormatDateTime)
		pars = append(pars, lastUpdateStartDateStr)
	}
	if lastUpdateEndDate != "" {
		lastUpdateEndTime, er := time.Parse(utils.FormatDate, lastUpdateEndDate)
		if er != nil {
			br.Msg = "日期格式有误"
			return
		}
		// 结束时间包含今天
		lastUpdateEndTime = lastUpdateEndTime.Add(23*time.Hour + 59*time.Minute + 59*time.Second)
		lastUpdateEndDateStr := lastUpdateEndTime.Format(utils.FormatDateTime)
		condition += " AND ur.create_time<=? "
		pars = append(pars, lastUpdateEndDateStr)
	}
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	} else if pageSize > utils.PageSize100 {
		pageSize = utils.PageSize100
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize := utils.StartIndex(currentIndex, pageSize)

	total, err := models.GetPotentialUserCountByConditonV2(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	resp := new(response.UserListResp)
	if total == 0 {
		page := paging.GetPaging(currentIndex, pageSize, total)
		resp.Paging = page
		br.Msg = "获取成功"
		br.Ret = 200
		br.Success = true
		br.Data = resp
		return
	}
	userList, err := models.GetPotentialUserIdsByConditonV2(condition, pars, sortCondition, startSize, pageSize)
	if err != nil {
		br.Msg = "查询用户失败"
		br.Msg = "查询用户失败，系统错误，Err:" + err.Error()
		return
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp.Paging = page
	resp.List = userList

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

// PotentialEdit
// @Title 编辑潜在客户（转客户）
// @Description 编辑潜在客户（转客户）
// @Param   request	body request.UserEidtReq true "type json string"
// @Success 200 {object} request.UserAddReq
// @router /potential/edit [post]
func (this *UserController) PotentialEdit() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	var req request.UserEidtReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.RealName == "" {
		br.Msg = "请输入姓名"
		return
	}
	req.Phone = strings.TrimSpace(req.Phone)
	req.Email = strings.TrimSpace(req.Email)
	if req.Phone == "" && req.Email == "" {
		br.Msg = "至少输入一个手机号或邮箱"
		return
	}
	if req.Phone != "" {
		if req.AreaCode == "86" {
			if !utils.ValidateMobileFormatat(req.Phone) {
				br.Msg = "手机号格式有误, 请检查"
				return
			}
		}
		user, err := models.GetUserByPhone(req.Phone, req.AreaCode)
		if err != nil && err != orm.ErrNoRows {
			br.Msg = "编辑用户失败"
			br.ErrMsg = "查询用户失败，系统错误，Err:" + err.Error()
			return
		}
		if user != nil && user.UserId != req.UserId {
			br.Msg = "手机号已存在，请重新输入"
			return
		}
	}
	if req.Email != "" {
		if !utils.ValidateEmailFormatat(req.Email) {
			br.Msg = "邮箱格式有误, 请检查"
			return
		}

		user, err := models.GetUserByEmail(req.Email)
		if err != nil && err != orm.ErrNoRows {
			br.Msg = "编辑用户失败"
			br.ErrMsg = "查询用户失败，系统错误，Err:" + err.Error()
			return
		}
		if user != nil && user.UserId != req.UserId {
			br.Msg = "邮箱已存在，请重新输入"
			return
		}
	}
	if req.SellerId <= 0 {
		br.Msg = "请选择营业部/销售"
		return
	}
	if req.ValidStartTime == "" || req.ValidEndTime == "" {
		br.Msg = "请选择合理的有效期范围"
		return
	}

	validStartTime, err := time.Parse(utils.FormatDate, req.ValidStartTime)
	if err != nil {
		br.Msg = "错误的日期格式"
		return
	}
	validStartTime = validStartTime.In(time.Local).Add(-time.Hour * 8)
	validEndTime, err := time.Parse(utils.FormatDate, req.ValidEndTime)
	if err != nil {
		br.Msg = "错误的日期格式"
		return
	}
	validEndTime = validEndTime.In(time.Local).Add(-time.Hour*8 + time.Hour*24 - time.Second)
	if !validStartTime.Before(validEndTime) {
		br.Msg = "请选择合理的有效期范围"
		return
	}
	if req.Company == "" {
		br.Msg = "请输入所属公司"
		return
	}

	if req.IsEnabled && time.Now().After(validEndTime) {
		br.Msg = "启用后，有效期必须大于当前时间"
		return
	}

	user, err := models.GetUserById(req.UserId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "用户不存在或已删除，请重新刷新页面"
			br.ErrMsg = "用户不存在或已删除，请重新刷新页面，Err:" + err.Error()
			return
		}
		br.Msg = "编辑用户失败"
		br.ErrMsg = "编辑用户失败, 系统错误，Err:" + err.Error()
		return
	}
	user.RealName = req.RealName
	user.AreaCode = req.AreaCode
	user.Phone = req.Phone
	user.Email = req.Email
	user.SellerId = req.SellerId
	user.ValidStartTime = validStartTime
	user.ValidEndTime = validEndTime
	user.Company = req.Company
	user.ModifyTime = time.Now()
	// 当用户状态初始为潜在客户时，才更新创建时间
	if user.Status == utils.UserStatusPotential {
		user.CreateTime = time.Now()
	}
	oldStatus := user.Status
	if !req.IsEnabled {
		user.Status = 0
	} else {
		user.Status = 2
	}
	err = models.SaveUser(user, req.ChartPermission)
	if err != nil {
		br.Msg = "添加客户失败"
		br.ErrMsg = "添加客户失败，系统错误，Err:" + err.Error()
		return
	}
	record := &models.UserChangeRecord{}
	record.UserId = req.UserId
	record.SysUserId = this.SysUser.SysUserId
	if oldStatus == utils.UserStatusPotential && user.Status == utils.UserStatusFormal {
		record.Content = this.SysUser.SysRealName + "新增用户"
	} else {
		record.Content = this.SysUser.SysRealName + "编辑用户"
	}
	record.Insert()

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

// Detail
// @Title 用户详情信息
// @Description 用户详情信息
// @Param   UserId   query   int  true       "用户id"
// @Success 200 {object} models.LoginResp
// @router /detail [get]
func (this *UserController) Detail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	UserId, _ := this.GetInt("UserId")
	if UserId <= 0 {
		br.Msg = "查询用户不存在"
		return
	}
	user, err := models.GetUserViewById(UserId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "用户不存在或已删除，请刷新页面"
			return
		}
		br.Msg = "查询用户失败"
		br.ErrMsg = "查询用户失败，系统错误，Err:" + err.Error()
		return
	}
	if user == nil {
		br.Msg = "用户不存在或已删除，请刷新页面"
		return
	}
	permissionList, err := services.GetUserPermissionById(UserId)
	if err != nil {
		br.Msg = "用户权限获取失败，请重新尝试"
		return
	}
	permissionMap := make(map[string][]string)
	for _, pm := range permissionList {
		permissionMap[pm.ParentName] = append(permissionMap[pm.ParentName], pm.PermissionName)
	}
	resp := new(response.UserDetailResp)
	resp.Detail = user
	resp.Permission = permissionMap

	br.Msg = "查询成功"
	br.Ret = 200
	br.Success = true
	br.Data = resp
}

// Delete
// @Title 系统用户详情信息
// @Description 用户详情信息
// @Param   request	body request.UserDeleteReq true "type json string"
// @Success 200 {object} models.LoginResp
// @router /delete [post]
func (this *UserController) Delete() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

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

	err = models.DeleteUserById(req.UserId)
	if err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "删除失败，系统错误，Err:" + err.Error()
		return
	}
	br.Msg = "删除成功"
	br.Success = true
	br.Ret = 200
}

// @Title 开启/禁用用户
// @Description 开启/禁用用户接口
// @Param	request	body system.SysuserEditReq true "type json string"
// @Success 200 操作成功
// @router /editEnabled [post]
func (this *UserController) EditEnabled() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req request.UserEditEnabledReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	user, err := models.GetUserById(req.UserId)
	if err != nil {
		br.Msg = "获取数据失败"
		br.ErrMsg = "获取系统用户数据失败，Err:" + err.Error()
		return
	}
	if !req.IsEnabled {
		user.Status = 0
		err = user.Update([]string{"status"})
		if err != nil {
			br.Msg = "修改失败"
			br.ErrMsg = "修改系统用户数据失败，Err:" + err.Error()
			return
		}
	} else {
		validStartTime, err := time.Parse(utils.FormatDate, req.ValidStartTime)
		if err != nil {
			br.Msg = "日期格式不正确"
			return
		}
		validEndTime, err := time.Parse(utils.FormatDate, req.ValidEndTime)
		if err != nil {
			br.Msg = "日期格式不正确"
			return
		}
		if !validEndTime.After(validStartTime) {
			br.Msg = "有效期结束日期在开始日期之前，日期格式不正确"
			return
		}
		validStartTime = validStartTime.Local().Add(-time.Hour * 8)
		validEndTime = validEndTime.Local().Add(-time.Hour*8 + time.Hour*24 - time.Second)
		curTime := time.Now()
		if curTime.After(validEndTime) {
			br.Msg = "有效期已到期，请重新设置"
			return
		}
		user.Status = 2
		user.ModifyTime = curTime
		user.ValidStartTime = validStartTime
		user.ValidEndTime = validEndTime
		err = user.Update([]string{"status", "modify_time", "valid_start_time", "valid_end_time"})
		if err != nil {
			br.Msg = "修改失败"
			br.ErrMsg = "修改系统用户数据失败，Err:" + err.Error()
			return
		}
	}
	// 记录操作
	record := &models.UserChangeRecord{}
	record.UserId = req.UserId
	record.SysUserId = this.SysUser.SysUserId
	if user.Status == 0 {
		record.Content = this.SysUser.SysRealName + "禁用用户"
	} else {
		record.Content = this.SysUser.SysRealName + "启用用户"
	}
	record.Insert()

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

// @Title 用户信息变更记录
// @Description 用户信息变更记录
// @Param   UserId   query   int  true       "用户id"
// @Success 200 操作成功
// @router /change_list [get]
func (this *UserController) ChangeList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	userId, _ := this.GetInt("UserId")
	if userId <= 0 {
		br.Msg = "用户信息错误"
		return
	}

	userRcord, err := models.GetUserChangeRecordListById(userId)
	if err != nil {
		br.Msg = "用户信息变更查询失败"
		br.ErrMsg = "用户信息变更查询失败，系统错误，Err:" + err.Error()
		return
	}
	resp := new(response.UserChangeRecordResp)
	resp.List = userRcord

	br.Data = resp
	br.Msg = "查询成功"
	br.Success = true
	br.Ret = 200
}

// GlobalSearch
// @Title 全局用户列表
// @Description 全局用户列表
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   KeyWord   query   string  true       "手机号/邮箱/姓名"
// @Param   SortParam   query   string  true       "排序字段"
// @Param   SortType   query   string  true       "排序方式"
// @Success 200 {object} response.UserListResp
// @router /global/list [get]
func (this *UserController) GlobalSearch() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	keyWord := this.GetString("KeyWord")
	sortParam := this.GetString("SortParam")
	sortType := this.GetString("SortType")

	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}

	var condition string
	var pars []interface{}
	var sortCondition string

	if keyWord == "" {
		br.Ret = 200
		br.Msg = "查询成功"
		br.Success = true
		return
	} else {
		condition = ` AND (real_name like ? OR phone like ? OR email like ?)`
		pars = utils.GetLikeKeywordPars(pars, keyWord, 3)
	}

	if sortParam != "" && sortType != "" {
		var param, sort string
		switch sortParam {
		case "RegisterTime":
			param = "register_time"
		case "ReadCnt":
			param = "read_cnt"
		case "LastUpdateTime":
			param = "last_update_time"
		}
		switch sortType {
		case "asc":
			sort = "ASC"
		case "desc":
			sort = "DESC"
		}
		if param != "" && sort != "" {
			sortCondition = ` ORDER BY ` + param + ` ` + sort
		}
	}
	if sortCondition == "" {
		sortCondition = ` ORDER BY u.register_time DESC`
	}

	startSize := utils.StartIndex(currentIndex, pageSize)
	userIds, err := models.GetUserIdListByCondition(condition, pars)
	if err != nil {
		br.Msg = "查询失败"
		br.ErrMsg = "查询失败，系统错误，Err:" + err.Error()
		return
	}

	userList, err := models.GetGlobalUserByCondition(userIds, sortCondition, startSize, pageSize)
	if err != nil {
		br.Msg = "查询失败"
		br.ErrMsg = "查询失败，系统错误，Err:" + err.Error()
		return
	}
	page := paging.GetPaging(currentIndex, pageSize, len(userIds))
	resp := new(response.UserListResp)
	resp.List = userList
	resp.Paging = page

	br.Data = resp
	br.Msg = "查询成功"
	br.Success = true
	br.Ret = 200
}

// TemporaryList
// @Title 潜在用户列表
// @Description 潜在用户列表
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   Keyword   query   string  false       "手机号"
// @Param   SortParam   query   string  false       "排序字段参数，用来排序的字段， 枚举值：0：注册时间，1：阅读数，2：最近一次阅读时间"
// @Param   SortType   query   string  true       "如何排序，是正序还是倒序，0：倒序，1：正序"
// @Success 200 {object} response.TemplateUserListResp
// @router /temporary/list [get]
func (this *UserController) TemporaryList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	keyword := this.GetString("Keyword")
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	} else if pageSize > utils.PageSize100 {
		pageSize = utils.PageSize100
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	} else if pageSize > utils.PageSize100 {
		pageSize = utils.PageSize100
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize := utils.StartIndex(currentIndex, pageSize)

	sortParamInt, _ := this.GetInt("SortParam", 0)
	sortTypeInt, _ := this.GetInt("SortType", 0)

	var sortStr = ``
	var condition string
	var pars []interface{}

	sortParamMap := map[int]string{0: "created_time", 1: "read_count", 2: "last_read_time"}
	sortTypeMap := map[int]string{0: "desc", 1: "asc"}
	sortParam, ok := sortParamMap[sortParamInt]
	if !ok {
		br.Msg = "错误的排序字段参数"
		br.ErrMsg = fmt.Sprint("错误的排序字段：", sortParamInt)
		return
	}
	sortType, ok := sortTypeMap[sortTypeInt]
	if !ok {
		br.Msg = "错误的排序字段"
		br.ErrMsg = fmt.Sprint("错误的排序字段：", sortTypeInt)
		return
	}
	sortStr = fmt.Sprintf("%s %s,updated_time desc ", sortParam, sortType)

	if keyword != "" {
		condition += ` AND mobile LIKE ? `
		pars = utils.GetLikeKeywordPars(pars, keyword, 1)
	}

	resp := new(response.TemplateUserListResp)
	total, userList, err := models.GetPageTemplateUserList(condition, pars, sortStr, startSize, pageSize)
	if err != nil {
		br.Msg = "查询用户失败"
		br.Msg = "查询用户失败，系统错误，Err:" + err.Error()
		return
	}

	list := make([]models.TemplateUsersItem, 0)
	for _, v := range userList {
		list = append(list, v.ToItem())
	}

	page := paging.GetPaging(currentIndex, pageSize, total)
	resp.Paging = page
	resp.List = list

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