package yb

import (
	"encoding/json"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"github.com/tealeg/xlsx"
	"hongze/hz_crm_api/controllers"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/system"
	"hongze/hz_crm_api/models/yb"
	"hongze/hz_crm_api/models/yb/request"
	ybResp "hongze/hz_crm_api/models/yb/response"
	"hongze/hz_crm_api/services"
	ybService "hongze/hz_crm_api/services/yb"
	"hongze/hz_crm_api/utils"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"sync"
	"time"
)

type ApplyRecordController struct {
	controllers.BaseAuthController
}

// List
// @Title 获取申请列表
// @Description 获取申请列表
// @Param   Keyword   query   string  false		"搜索关键字 string"
// @Param   State   query   string  false		"用户状态 string 潜在用户/权益用户/冻结/流失"
// @Success 200 {object} []yb.ApplyRecordListResp
// @router /apply_record/list [get]
func (this *ApplyRecordController) 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")
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	condition := ""
	pars := make([]interface{}, 0)
	// 数据权限
	condition, pars = getDataAuthWhere(condition, pars, this.SysUser)
	reqState := this.GetString("State", "")
	if reqState != "" {
		condition += " AND a.status = ?"
		pars = append(pars, reqState)
	}
	reqKeyword := this.GetString("Keyword")
	if reqKeyword != "" {
		reqKeyword = "%" + reqKeyword + "%"
		condition += " AND (a.real_name LIKE ? OR a.mobile LIKE ? OR a.email LIKE ?)"
		pars = append(pars, reqKeyword, reqKeyword, reqKeyword)
	}

	// 获取列表
	total, list, err := yb.GetApplyRecordList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取申请列表失败！"
		br.ErrMsg = "获取申请列表失败，Err:" + err.Error()
		return
	}

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

// getDataAuth 过滤数据权限
func getDataAuthWhere(condition string, pars []interface{}, sysUser *system.Admin) (newCondition string, newPars []interface{}) {
	roleCode := sysUser.RoleTypeCode
	// 超管账户不做限制
	if roleCode == utils.ROLE_TYPE_CODE_ADMIN {
		return
	}
	// 是否为FICC角色
	allowRole := []string{
		utils.ROLE_TYPE_CODE_FICC_ADMIN, utils.ROLE_TYPE_CODE_FICC_SELLER, utils.ROLE_TYPE_CODE_FICC_GROUP,
		utils.ROLE_TYPE_CODE_FICC_DEPARTMENT, utils.ROLE_TYPE_CODE_FICC_RESEARCHR, utils.ROLE_TYPE_CODE_RESEARCHR,
	}
	isAllow := false
	for _, role := range allowRole {
		if roleCode == role {
			isAllow = true
		}
	}
	if isAllow {
		// 销售ID为当前用户且客户状态为冻结
		condition += " AND b.seller_id = ?"
		pars = append(pars, sysUser.AdminId)
		condition += " AND b.status = ?"
		pars = append(pars, "冻结")
	} else {
		condition += " AND 1=2"
	}
	newCondition = condition
	newPars = pars
	return
}

func getDataAuthWhereV2(condition string, pars []interface{}, sysUser *system.Admin) (newCondition string, newPars []interface{}, err error) {
	roleCode := sysUser.RoleTypeCode
	// 超管账户不做限制
	if roleCode == utils.ROLE_TYPE_CODE_ADMIN || roleCode == utils.ROLE_TYPE_CODE_FICC_ADMIN {
		return
	}
	// 是否为FICC角色
	allowRole := []string{
		utils.ROLE_TYPE_CODE_FICC_ADMIN, utils.ROLE_TYPE_CODE_FICC_SELLER, utils.ROLE_TYPE_CODE_FICC_GROUP, utils.ROLE_TYPE_CODE_FICC_TEAM,
		utils.ROLE_TYPE_CODE_FICC_DEPARTMENT, utils.ROLE_TYPE_CODE_FICC_RESEARCHR, utils.ROLE_TYPE_CODE_RESEARCHR,
	}
	isAllow := false
	for _, role := range allowRole {
		if roleCode == role {
			isAllow = true
		}
	}

	if isAllow {
		// 超管和ficc 管理员，才允许看潜在用户和流失用户，
		condition += ` and y.status != "潜在用户" and y.status is not null and y.status != "权益用户" and y.status != "流失"`
		// 如果是ficc销售主管，查询对应的小组
		if roleCode == utils.ROLE_TYPE_CODE_FICC_GROUP && sysUser.GroupId > 0 {
			subAdmins, tErr := system.GetSysUserByParentIdGroupId(sysUser.GroupId)
			if tErr != nil && tErr.Error() != utils.ErrNoRow() {
				err = tErr
				return
			}
			var sellerIdsStr string
			for _, v := range subAdmins {
				// 只能看比主管权限低的角色
				if v.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER || v.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_TEAM || v.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_RESEARCHR || v.RoleTypeCode == utils.ROLE_TYPE_CODE_RESEARCHR {
					sellerIdsStr += strconv.Itoa(v.AdminId) + ","
				}
			}
			if sellerIdsStr != "" {
				sellerIdsStr += strconv.Itoa(sysUser.AdminId)
				// 销售ID为当前用户且客户状态为冻结
				condition += " AND bp.seller_id in (" + sellerIdsStr + ")"
			} else {
				condition += " AND bp.seller_id = ?"
				pars = append(pars, sysUser.AdminId)
			}
		} else if roleCode == utils.ROLE_TYPE_CODE_FICC_TEAM && sysUser.GroupId > 0 { // 如果是ficc 销售组长
			subAdmins, tErr := system.GetAdminByGroupId(sysUser.GroupId)
			if tErr != nil && tErr.Error() != utils.ErrNoRow() {
				err = tErr
				return
			}
			var sellerIdsStr string
			for _, v := range subAdmins {
				// 只能看比主管权限低的角色
				if v.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER || v.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_RESEARCHR || v.RoleTypeCode == utils.ROLE_TYPE_CODE_RESEARCHR {
					sellerIdsStr += strconv.Itoa(v.AdminId) + ","
				}
			}
			if sellerIdsStr != "" {
				sellerIdsStr += strconv.Itoa(sysUser.AdminId)
				// 销售ID为当前用户且客户状态为冻结
				condition += " AND bp.seller_id in (" + sellerIdsStr + ")"
			} else {
				condition += " AND bp.seller_id = ?"
				pars = append(pars, sysUser.AdminId)
			}
		} else { // 如果是ficc 销售
			condition += " AND bp.seller_id = ?"
			pars = append(pars, sysUser.AdminId)
		}
	} else {
		condition += " AND 1=2"
	}
	newCondition = condition
	newPars = pars
	return
}

// MarkHandle
// @Title 处理申请记录
// @Description 处理申请记录
// @Param	request	body request.ApplyMarkReq true "type json string"
// @Success 200 {object} 标记处理成功
// @router /apply_record/mark_handle [post]
func (this *ApplyRecordController) MarkHandle() {
	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.ApplyMarkReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ApplyRecordId <= 0 && req.UserId <= 0 {
		br.Msg = "申请记录ID或者用户ID异常"
		br.ErrMsg = "申请记录ID或者用户ID异常"
		return
	}

	// 标记处理
	err = ybService.MarkApplyRecord(req.ApplyRecordId, this.SysUser.AdminId, req.UserId)
	if err != nil {
		br.Msg = "标记处理失败! "
		br.ErrMsg = "标记处理失败，Err:" + err.Error()
		return
	}

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

// ListV2
// @Title 获取用户申请列表
// @Description 获取用户申请列表
// @Param   KeyWord   query   string  false		"搜索关键字 string"
// @Param   States   query   string  false		"用户状态 string 潜在用户/权益用户/冻结/流失"
// @Success 200 {object} []yb.ApplyRecordListRespV2
// @router /apply_record/listV2 [get]
func (this *ApplyRecordController) UserApplyList() {
	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")
	markGroup := this.GetString("MarkGroup")
	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	condition := ""
	pars := make([]interface{}, 0)
	// 数据权限
	condition, pars, err := getDataAuthWhereV2(condition, pars, this.SysUser)
	if err != nil {
		br.Msg = "权限查询出错"
		br.ErrMsg = "权限查询出错：" + err.Error()
		return
	}
	reqState := this.GetString("States", "")
	if reqState != "" {
		statusSlice := strings.Split(reqState, ",")
		conditionSub := ""
		if len(statusSlice) == 0 {
			br.Msg = "入参：状态格式出错"
			return
		}
		for _, v := range statusSlice {
			if v == "潜在用户" {
				conditionSub += ` or y.status = "潜在用户" or y.status is null or y.status = "权益用户"`
			} else {
				conditionSub += ` or y.status = "` + v + `"`
			}
		}
		conditionSubByte := []byte(conditionSub)
		conditionSub = string(conditionSubByte[4:])
		condition += ` AND (` + conditionSub + `)`
	}
	reqKeyword := this.GetString("KeyWord")
	if reqKeyword != "" {
		reqKeyword = "%" + reqKeyword + "%"
		condition += " AND (a.real_name LIKE ? OR a.mobile LIKE ? OR a.email LIKE ? OR (a.company_id > 1 AND b.company_name LIKE ?) OR (a.company_id = 1 AND a.note LIKE ?))"
		pars = append(pars, reqKeyword, reqKeyword, reqKeyword, reqKeyword, reqKeyword)
	}
	if markGroup != "" {
		condition += `AND (y.mark_group = `+"'"+markGroup+"'"+ ` OR a.mark_group = `+"'"+markGroup+"')"
	}
	if startDate != "" {
		startDate += " 00:00:00"
		condition += ` AND IF(y.apply_record_id > 0,y.create_time, a.created_time) >= '` + startDate + `' `
	}
	if endDate != "" {
		endDate += " 23:59:59"
		condition += ` AND IF(y.apply_record_id > 0,y.create_time, a.created_time) <= '` + endDate + `' `
	}

	reqApplyStatus := this.GetString("ApplyStatus")
	if reqApplyStatus != "" {
		if reqApplyStatus == "已申请" {
			condition += " AND y.apply_record_id > 0"
		} else if reqApplyStatus == "未申请" {
			condition += " AND ISNULL(y.apply_record_id) = 1"
		}
	}

	// 获取列表
	w := sync.WaitGroup{}
	var list []*yb.ApplyListV2
	var total int
	startTime := "2022-01-01"
	w.Add(1)
	go func() {
		defer w.Done()
		list, err = yb.GetApplyRecordListV2(condition, pars, startTime, startSize, pageSize)
	}()
	if err != nil {
		br.Msg = "获取申请列表失败！"
		br.ErrMsg = "获取申请列表失败，Err:" + err.Error()
		return
	}
	w.Add(1)
	go func() {
		defer w.Done()
		total, err = yb.GetApplyRecordTotal(condition, pars, startTime)
	}()
	w.Wait()
	if err != nil {
		br.Msg = "获取申请列表总数失败！"
		br.ErrMsg = "获取申请列表总数失败，Err:" + err.Error()
		return
	}
	mobilesSlice := make([]string, 0)
	emailsSlice := make([]string, 0)
	userIdsStr := ""
	for _, v := range list {
		userIdsStr += "," + strconv.Itoa(v.UserId)
		if v.Mobile != "" {
			mobilesSlice = append(mobilesSlice, v.Mobile)
		} else if v.Email != "" {
			emailsSlice = append(emailsSlice, v.Email)
		}
	}
	//统计申请数
	userApplyTotalMap := make(map[int]int)
	if userIdsStr != "" {
		userIdsStr = strings.Trim(userIdsStr, ",")
		userApplyTotal, tErr := yb.GetTotalByUserIds(userIdsStr)
		if tErr != nil {
			br.Msg = "获取申请数失败！"
			br.ErrMsg = "获取申请数失败，Err:" + tErr.Error()
			return
		}
		for _, v := range userApplyTotal {
			userApplyTotalMap[v.UserId] = v.Total
		}
	}

	w2 := sync.WaitGroup{}
	mobileTotalMap := make(map[string]int)
	lastTimeMobileMap := make(map[string]time.Time)
	w2.Add(1)
	//统计阅读数
	go func() {
		defer w2.Done()
		mobileTotalMap, lastTimeMobileMap = ybService.GetUserViewTotalByMobiles(mobilesSlice)
	}()

	emailTotalMap := make(map[string]int)
	lastTimeEmailMap := make(map[string]time.Time)
	w2.Add(1)
	go func() {
		defer w2.Done()
		emailTotalMap, lastTimeEmailMap = ybService.GetUserViewTotalByEmails(emailsSlice)
	}()
	w2.Wait()
	for k, v := range list {
		if v.OpStatus == 1 && v.MarkGroup == "" {
			list[k].OpStatus = 0
		}
		sourceStr := ""
		if v.ApplyRecordId > 0 {
			if v.SourceAgent == 3 {
				sourceStr = "弘则研究"
			} else if v.SourceAgent == 1 {
				switch v.Source {
				case 1:
					sourceStr = "我的（小程序)"
				case 2:
					sourceStr = "活动（小程序)"
				case 3:
					sourceStr = "图库（小程序)"
				case 4:
					sourceStr = "研报（小程序)"
				case 5:
					sourceStr = "问答社区（小程序)"
				default:
					if v.FromPage != "" {
						sourceStr = v.FromPage + "（小程序)"
					} else {
						sourceStr = "研报（小程序)"
					}
				}
			} else if v.SourceAgent == 2 || v.SourceAgent == 4 {
				switch v.Source {
				case 1:
					sourceStr = "我的（PC端)"
				case 2:
					sourceStr = "活动（PC端)"
				case 3:
					sourceStr = "图库（PC端)"
				case 4:
					sourceStr = "研报（PC端)"
				case 5:
					sourceStr = "问答社区（PC端)"
				default:
					if v.FromPage != "" {
						sourceStr = v.FromPage + "（PC端)"
					} else {
						sourceStr = "研报（PC端)"
					}
				}
			}
		} else if v.RegisterSource != 0 {
			switch v.RegisterSource {
			case 1:
				sourceStr = "弘则研究"
			case 2:
				sourceStr = "研报（PC端）"
			case 5:
				sourceStr = "活动（小程序）"
			case 6:
				sourceStr = "研报（小程序）"
			default:
				sourceStr = ""
			}
		}
		list[k].SourceStr = sourceStr

		// 统计申请数
		if applyTotal, ok := userApplyTotalMap[v.UserId]; ok {
			list[k].ApplyTotal = applyTotal
		}
		//统计阅读数
		if num, ok := mobileTotalMap[v.Mobile]; ok {
			list[k].ViewTotal += num
		}
		if num, ok := emailTotalMap[v.Email]; ok {
			list[k].ViewTotal += num
		}

		//最新阅读时间
		if t, ok := lastTimeMobileMap[v.Mobile]; ok {
			if list[k].LastViewTime.Before(t) {
				list[k].LastViewTime = t
			}
		}

		if t, ok := lastTimeEmailMap[v.Email]; ok {
			if list[k].LastViewTime.Before(t) {
				list[k].LastViewTime = t
			}
		}

		list[k].LastViewTimeStr = list[k].LastViewTime.Format(utils.FormatDateTime)
		if list[k].LastViewTimeStr == "0001-01-01 00:00:00" {
			list[k].LastViewTimeStr = ""
		}
		list[k].LastTimeStr = list[k].LastTime.Format(utils.FormatDateTime)

		if v.Status == "权益用户" {
			list[k].Status = "潜在用户"
		}
		//查询是否展示潜在用户删除按钮权限
		if v.CompanyId == 1 && list[k].Status == "潜在用户" {
			list[k].DelBtn = true
		}
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := ybResp.ApplyRecordListV2Resp{
		List:   list,
		Paging: page,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// ApplyExport
// @Title 导出用户申请列表
// @Description 导出用户申请列表
// @Param   KeyWord   query   string  false		"搜索关键字 string"
// @Param   State   query   string  false		"用户状态 string 潜在用户/权益用户/冻结/流失"
// @Success Ret=200 导出成功
// @router /apply_record/listV2/export [get]
func (this *ApplyRecordController) ApplyExport() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	reqKeyword := this.GetString("KeyWord")
	reqState := this.GetString("States")
	markGroup := this.GetString("MarkGroup")
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	//管理员才让导出数据
	if sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_ADMIN && sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_FICC_ADMIN {
		br.Msg = "没有权限"
		br.ErrMsg = "没有权限"
		return
	}
	var condition string
	var pars []interface{}
	if reqState != "" {
		statusSlice := strings.Split(reqState, ",")
		conditionSub := ""
		if len(statusSlice) == 0 {
			br.Msg = "入参：状态格式出错"
			return
		}
		for _, v := range statusSlice {
			if v == "潜在用户" {
				conditionSub += ` or y.status = "潜在用户" or y.status is null or y.status = "权益用户"`
			} else {
				conditionSub += ` or y.status = "` + v + `"`
			}
		}
		conditionSubByte := []byte(conditionSub)
		conditionSub = string(conditionSubByte[4:])
		condition += ` AND (` + conditionSub + `)`
	}
	if reqKeyword != "" {
		reqKeyword = "%" + reqKeyword + "%"
		condition += " AND (a.real_name LIKE ? OR a.mobile LIKE ? OR a.email LIKE ? OR (a.company_id > 1 AND b.company_name LIKE ?) OR (a.company_id = 1 AND a.note LIKE ?))"
		pars = append(pars, reqKeyword, reqKeyword, reqKeyword, reqKeyword, reqKeyword)
	}
	reqApplyStatus := this.GetString("ApplyStatus")
	if reqApplyStatus != "" {
		if reqApplyStatus == "已申请" {
			condition += " AND y.apply_record_id > 0"
		} else if reqApplyStatus == "未申请" {
			condition += " AND y.apply_record_id is null"
		}
	}
	if markGroup != "" {
		condition += `AND (y.mark_group = `+"'"+markGroup+"'"+ ` OR a.mark_group = `+"'"+markGroup+"')"
	}
	startTime := "2022-01-01"
	list, err := yb.GetApplyRecordListV2Export(condition, pars, startTime)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	mobilesSlice := make([]string, 0)
	emailsSlice := make([]string, 0)
	userIdsStr := ""
	for _, v := range list {
		userIdsStr += "," + strconv.Itoa(v.UserId)
		if v.Mobile != "" {
			mobilesSlice = append(mobilesSlice, v.Mobile)
		} else if v.Email != "" {
			emailsSlice = append(emailsSlice, v.Email)
		}
	}
	userIdsStr = strings.Trim(userIdsStr, ",")
	//统计申请数
	userApplyTotalMap := make(map[int]int)
	if userIdsStr != "" {
		userApplyTotal, err := yb.GetTotalByUserIds(userIdsStr)
		if err != nil {
			br.Msg = "获取申请数失败！"
			br.ErrMsg = "获取申请数失败，Err:" + err.Error()
			return
		}
		for _, v := range userApplyTotal {
			userApplyTotalMap[v.UserId] = v.Total
		}
	}

	w := sync.WaitGroup{}
	mobileTotalMap := make(map[string]int)
	lastTimeMobileMap := make(map[string]time.Time)
	w.Add(1)
	//统计阅读数
	go func() {
		defer w.Done()
		mobileTotalMap, lastTimeMobileMap = ybService.GetUserViewTotalByMobiles(mobilesSlice)
	}()

	emailTotalMap := make(map[string]int)
	lastTimeEmailMap := make(map[string]time.Time)
	w.Add(1)
	go func() {
		defer w.Done()
		emailTotalMap, lastTimeEmailMap = ybService.GetUserViewTotalByEmails(emailsSlice)
	}()
	w.Wait()
	for k, v := range list {
		sourceStr := ""
		if v.ApplyRecordId > 0 {
			if v.SourceAgent == 3 {
				sourceStr = "弘则研究"
			} else if v.SourceAgent == 1 {
				switch v.Source {
				case 1:
					sourceStr = "我的（小程序)"
				case 2:
					sourceStr = "活动（小程序)"
				case 3:
					sourceStr = "图库（小程序)"
				case 4:
					sourceStr = "研报（小程序)"
				case 5:
					sourceStr = "问答社区（小程序)"
				default:
					if v.FromPage != "" {
						sourceStr = v.FromPage + "（小程序)"
					} else {
						sourceStr = "研报（小程序)"
					}
				}
			} else if v.SourceAgent == 2 {
				switch v.Source {
				case 1:
					sourceStr = "我的（PC端)"
				case 2:
					sourceStr = "活动（PC端)"
				case 3:
					sourceStr = "图库（PC端)"
				case 4:
					sourceStr = "研报（PC端)"
				case 5:
					sourceStr = "问答社区（PC端)"
				default:
					if v.FromPage != "" {
						sourceStr = v.FromPage + "（PC端)"
					} else {
						sourceStr = "研报（PC端)"
					}
				}
			}
		} else if v.RegisterSource != 0 {
			switch v.RegisterSource {
			case 1:
				sourceStr = "弘则研究"
			case 2:
				sourceStr = "研报（PC端）"
			case 5:
				sourceStr = "活动（小程序）"
			case 6:
				sourceStr = "研报（小程序）"
			default:
				sourceStr = ""
			}
		}
		list[k].SourceStr = sourceStr

		// 统计申请数
		if applyTotal, ok := userApplyTotalMap[v.UserId]; ok {
			list[k].ApplyTotal = applyTotal
		}
		//统计阅读数
		if num, ok := mobileTotalMap[v.Mobile]; ok {
			list[k].ViewTotal += num
		}
		if num, ok := emailTotalMap[v.Email]; ok {
			list[k].ViewTotal += num
		}

		//最新阅读时间
		if t, ok := lastTimeMobileMap[v.Mobile]; ok {
			if list[k].LastViewTime.Before(t) {
				list[k].LastViewTime = t
			}
		}

		if t, ok := lastTimeEmailMap[v.Email]; ok {
			if list[k].LastViewTime.Before(t) {
				list[k].LastViewTime = t
			}
		}

		list[k].LastViewTimeStr = list[k].LastViewTime.Format(utils.FormatDateTime)
		if list[k].LastViewTimeStr == "0001-01-01 00:00:00" {
			list[k].LastViewTimeStr = ""
		}
		list[k].LastTimeStr = list[k].LastTime.Format(utils.FormatDateTime)

		if v.Status == "权益用户" {
			list[k].Status = "潜在用户"
		}
	}

	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("公司")
	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.LastTimeStr)
		dataRow.AddCell().SetString(strconv.Itoa(v.ApplyTotal))
		dataRow.AddCell().SetString(v.LastViewTimeStr)
		dataRow.AddCell().SetString(strconv.Itoa(v.ViewTotal))
		dataRow.AddCell().SetString(v.CompanyName)
		dataRow.AddCell().SetString(v.OriginSellerName)
		dataRow.AddCell().SetString(v.SourceStr)
		dataRow.AddCell().SetString(v.ApplyStatus)
		dataRow.AddCell().SetString(v.Status)

	}

	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 = "导出成功"
}

// DelPotentialUser
// @Title 删除潜在用户账号和申请记录
// @Description 删除潜在用户账号和申请记录
// @Param	request	body company.DeleteUserReq true "type json string"
// @Success 200 {object} 删除成功
// @router /potential/user/del [post]
func (this *ApplyRecordController) DelPotentialUser() {
	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 = "请输入正确的用户ID"
		return
	}

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

	if userInfo.CompanyId != 1 {
		br.Msg = "该联系人已绑定客户，不允许删除！"
		return
	}

	//操作权限校验, 超管和ficc管理员有删除权限
	if sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_FICC_ADMIN && sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_ADMIN {
		br.Msg = "没有操作权限"
		return
	}
	//如果不是超管权限，那么删除的时候，需要获取下联系人归属销售信息
	//产品权限
	productId := services.GetProductId(sysUser.RoleTypeCode)
	//联系人与销售的关系
	userSellerRelationList, err := models.GetUserSellerRelationList(int(userInfo.UserId))
	if err != nil {
		br.Msg = "获取联系人关系失败"
		br.ErrMsg = "获取联系人关系失败，Err:" + err.Error()
		return
	}
	userSellerRelationInfo, _ := json.Marshal(userSellerRelationList)

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

	if len(userSellerRelationList) > 0 && productId != 0 {
		content := fmt.Sprint("联系人:", userInfo.RealName, "被删除")
		if userSellerRelationList[0].CompanyId != 1 {
			companyInfo, tErr := company.GetCompanyById(userSellerRelationList[0].CompanyId)
			if tErr != nil {
				if tErr.Error() != utils.ErrNoRow() {
					br.Msg = "获取客户信息失败"
					br.ErrMsg = "获取客户信息失败，Err:" + tErr.Error()
					return
				}
			} else {
				content = fmt.Sprint(companyInfo.CompanyName, "：", content)
				for _, userRelation := range userSellerRelationList {
					if userRelation.ProductId != productId {
						go services.AddCompanyMessage(sysUser.AdminId, userRelation.SellerId, userRelation.CompanyId, 0, 1, companyInfo.CompanyName, content, content)
					}
				}
			}
		}
	}

	//联系人信息
	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)
	}

	// 删除用户的申请记录
	go ybService.DeleteApplyUser(userInfo.UserId)

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

// MarkGroup
// @Title 标记分组
// @Description 标记分组
// @Param	request	body request.ApplyMarkReq true "type json string"
// @Success 200 {object} 标记处理成功
// @router /apply_record/mark_group [post]
func (this *ApplyRecordController) MarkGroup() {
	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.ApplyMarkGroupReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.GroupName == "" || req.UserId == 0 {
		br.Msg = "申请记录ID或者分组名异常"
		br.ErrMsg = "申请记录ID或者分组名异常"
		return
	}


	// 标记处理
	err = ybService.MarkGroupApplyRecord(req.ApplyRecordId, this.SysUser.AdminId, req.UserId, req.GroupName)
	if err != nil {
		br.Msg = "标记处理失败! "
		br.ErrMsg = "标记处理失败，Err:" + err.Error()
		return
	}

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