package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/mozillazg/go-pinyin"
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/eta_trial"
	"hongze/hz_crm_api/models/system"
	"hongze/hz_crm_api/services"
	"hongze/hz_crm_api/utils"
	"sort"
	"strconv"
	"strings"
	"time"
)

type ETATrialController struct {
	BaseAuthController
}

// @Title 获取所有ETA试用客户列表
// @Description 获取所有ETA试用客户列表 接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   KeyWord   query   string  true       "搜索关键词"
// @Param   IsOnlyMe   query   bool  false       "是否只看我的"
// @Param   SortParam   query   string  false       "排序字段参数，用来排序的字段， 枚举值：'Expiration':账号到期时长 、 'ModifyTime':账号更新时间 、 'LastLoginTime':最近一次登陆时间 、`ActiveTime：累计活跃时长` 、`IndexNum：累计添加指标` 、`ChartNum：累计添加图表`、`LoginNum：累计登录次数`"
// @Param   SortType   query   string  true       "如何排序，是正序还是倒序，枚举值：`asc 正序`,`desc 倒叙`"
// @Success 200 {object} models.ETATrialListRespList
// @router /list [get]
func (this *ETATrialController) 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
	}

	isOnlyMe, _ := this.GetBool("IsOnlyMe")
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	keyWord := this.GetString("KeyWord")
	keyWord = strings.Trim(keyWord, " ")
	keyWord = strings.Replace(keyWord, "'", "", -1)

	//排序参数
	sortParam := this.GetString("SortParam")
	sortType := this.GetString("SortType")

	var total int
	page := paging.GetPaging(currentIndex, pageSize, total)

	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 isOnlyMe {
		condition += ` AND seller_id = ? `
		pars = append(pars, sysUser.AdminId)
	}
	if keyWord != "" {
		condition += ` AND (user_name LIKE '%` + keyWord + `%' OR company_name LIKE '%` + keyWord + `%' ) `
	}

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

	sortStr := ``
	if sortParam != "" && sortType != "" {
		if sortParam == "Expiration" {
			if sortType == "asc" {
				sortStr = "ORDER BY modify_time ASC "
			} else {
				sortStr = "ORDER  BY modify_time DESC "
			}
		} else if sortParam == "ModifyTime" {
			if sortType == "asc" {
				sortStr = "ORDER BY modify_time ASC "
			} else {
				sortStr = "ORDER  BY modify_time DESC "
			}
		} else if sortParam == "LastLoginTime" {
			if sortType == "asc" {
				sortStr = "ORDER BY last_login_time ASC "
			} else {
				sortStr = "ORDER  BY last_login_time DESC "
			}
		} else if sortParam == "ActiveTime" {
			if sortType == "asc" {
				sortStr = "ORDER BY active_time ASC"
			} else {
				sortStr = "ORDER  BY active_time DESC"
			}
		} else if sortParam == "IndexNum" {
			if sortType == "asc" {
				sortStr = "ORDER BY index_num ASC"
			} else {
				sortStr = "ORDER  BY index_num DESC"
			}
		} else if sortParam == "ChartNum" {
			if sortType == "asc" {
				sortStr = "ORDER BY chart_num ASC"
			} else {
				sortStr = "ORDER  BY chart_num DESC"
			}
		} else if sortParam == "LoginNum" {
			if sortType == "asc" {
				sortStr = "ORDER BY login_num ASC"
			} else {
				sortStr = "ORDER  BY login_num DESC"
			}
		} else if sortParam == "LastLoginDuration" {
			if sortType == "asc" {
				sortStr = "ORDER BY last_login_duration ASC"
			} else {
				sortStr = "ORDER  BY last_login_duration DESC"
			}
		}
	} else {
		sortStr = "ORDER BY create_time DESC "
	}

	list, err := eta_trial.GetETATrialList(condition, sortStr, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取权限列表失败"
		br.ErrMsg = "获取权限列表失败,Err:" + err.Error()
		return
	}

	mobileSlice := make([]string, 0)
	for _, item := range list {
		activeTime, _ := strconv.Atoi(item.ActiveTime)
		item.ActiveTime = utils.GetDurationFormatBySecond(activeTime)

		// 最近一次登录时长
		loginDuration, _ := strconv.Atoi(item.LastLoginDuration)
		item.LastLoginDuration = utils.GetDurationFormatBySecond(loginDuration)

		//到期时间
		modifyTime, err := time.Parse(utils.FormatDateTime, item.ModifyTime)
		if err != nil {
			br.Msg = "时间转化失败"
			br.ErrMsg = "时间转化失败,Err:" + err.Error()
			return
		}

		var expired int

		expiredTime := modifyTime.AddDate(0, 0, 14).Format(utils.FormatDate)
		expired, err = utils.GetDaysBetween2Date(utils.FormatDate, expiredTime, time.Now().Format(utils.FormatDate))
		if err != nil {
			br.Msg = "时间计算失败"
			br.ErrMsg = "时间计算失败,CalculationDate Err:" + err.Error()
			return
		}
		item.Expiration = expired
		mobileSlice = append(mobileSlice, "'"+item.Mobile+"'")
	}

	if len(mobileSlice) > 0 {
		mobiles := strings.Join(mobileSlice, ",")
		recordList, err := eta_trial.GetEtaTrialRecordParts(mobiles)
		if err != nil {
			br.Msg = "获取记录失败"
			br.ErrMsg = "获取记录失败,GetEtaTrialRecordParts Err:" + err.Error()
			return
		}

		recordMap := make(map[string]string)
		for _, v := range recordList {
			if _, ok := recordMap[v.Mobile]; !ok {
				recordMap[v.Mobile] = v.Part
			}
		}

		for _, item := range list {
			item.InterestModule = recordMap[item.Mobile]
		}
	}

	//待审批数量
	condition = ` AND approval_status = '待审批' `
	pars = []interface{}{}
	totalApproval, err := eta_trial.GetETATrialApprovalListCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据总数失败，Err:" + err.Error()
		return
	}

	page = paging.GetPaging(currentIndex, pageSize, total)
	resp := new(eta_trial.ETATrialListRespList)
	resp.List = list
	resp.Paging = page
	resp.ApprovalNum = totalApproval

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

	return
}

// @Title 新增用户
// @Description 新增用户 接口
// @Success 200 {object} models.ETATrialAddReq
// @router /add [post]
func (this *ETATrialController) Add() {
	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 eta_trial.ETATrialAddReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	resp := new(eta_trial.ETATrialListResp)

	//提交审批
	approvalIds := make([]int, 0)
	for _, v := range req.List {
		if v.CompanyName == "" {
			br.Msg = "请填写公司名称"
			return
		}
		if v.UserName == "" {
			br.Msg = "请填写客户名称"
			return
		}
		if v.Position == "" {
			br.Msg = "职务不可为空"
			return
		}
		if v.Mobile == "" {
			br.Msg = "手机号不可为空"
			return
		}

		//检查是否为禁用客户
		item, e := eta_trial.GetETATrialByMobile(v.Mobile)
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = e
		}
		if item != nil {
			if item.Enabled == 0 {
				//放入被禁用客户列表中
				respItem := eta_trial.ETATrialAddRespItem{
					UserName:    v.UserName,
					CompanyName: v.CompanyName,
					Position:    v.Position,
					Mobile:      v.Mobile,
					Seller:      item.Seller,
				}
				resp.BannedList = append(resp.BannedList, &respItem)
				continue
			} else {
				//客户已在正常使用中
				//放入已提交申请列表中
				respItem := eta_trial.ETATrialAddRespItem{
					UserName:    v.UserName,
					CompanyName: v.CompanyName,
					Position:    v.Position,
					Mobile:      v.Mobile,
					Seller:      item.Seller,
				}
				resp.RepeatList = append(resp.RepeatList, &respItem)
				continue
			}
		}

		seller, e := system.GetSysAdminById(sysUser.AdminId)
		if e != nil {
			err = e
			return
		}

		//检查是否历史已提交
		approval, e := eta_trial.GetETATrialApprovalByMobile(v.Mobile)
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = e
		}
		if approval != nil && approval.ApprovalStatus == "待审批" {
			//处于待审批状态
			//放入已提交申请列表中
			respItem := eta_trial.ETATrialAddRespItem{
				UserName:    v.UserName,
				CompanyName: v.CompanyName,
				Position:    v.Position,
				Mobile:      v.Mobile,
				Seller:      approval.Seller,
			}
			resp.RepeatList = append(resp.RepeatList, &respItem)
			continue
		}

		//检查是否公司内部人员
		mobileCount, err := eta_trial.GetSysAdminCountByMobile(v.Mobile, 0)
		if err != nil {
			br.Msg = "判断手机号是否存在失败"
			br.ErrMsg = "判断手机号是否存在失败，Err:" + err.Error()
			return
		}
		if mobileCount > 0 {
			//放入内部人员列表中
			respItem := eta_trial.ETATrialAddRespItem{
				UserName:    v.UserName,
				CompanyName: v.CompanyName,
				Position:    v.Position,
				Mobile:      v.Mobile,
				Seller:      "",
			}
			resp.InternalList = append(resp.InternalList, &respItem)
			continue
		}

		var approvalId int64
		if approval != nil && (approval.ApprovalStatus == "驳回" || approval.ApprovalStatus == "已撤回") && v.Mobile == approval.Mobile {
			//若是被驳回后重新申请且手机号相同的，更新审批记录
			e = eta_trial.ResubmitTrialNoReasons(v.UserName, v.CompanyName, v.Position, approval.ApprovalId)
			if e != nil {
				err = e
				return
			}
			approvalId = int64(approval.ApprovalId)
		} else {
			//加入审批列表
			approvalItem := eta_trial.EtaTrialApproval{
				UserName:        v.UserName,
				CompanyName:     v.CompanyName,
				Position:        v.Position,
				Mobile:          v.Mobile,
				SellerId:        seller.AdminId,
				Seller:          seller.RealName,
				CreateTime:      time.Now(),
				ModifyTime:      time.Now(),
				ApprovalContent: "申请账号",
				ApplyMethod:     1,
				ApprovalStatus:  "待审批",
			}

			approvalId, e = eta_trial.AddETATrialApproval(&approvalItem)
			if e != nil {
				err = e
				return
			}
		}

		//放入成功列表中
		respItem := eta_trial.ETATrialAddRespItem{
			UserName:    v.UserName,
			CompanyName: v.CompanyName,
			Position:    v.Position,
			Mobile:      v.Mobile,
			Seller:      seller.RealName,
		}
		resp.SuccessList = append(resp.SuccessList, &respItem)

		//新增待办消息
		msgItem := new(company.CompanyApprovalMessage)
		msgItem.CreateUserId = sysUser.AdminId
		msgItem.ReceiveUserId = -1
		msgItem.MessageStatus = 1 // 已读, 不再亮红点, 但是消息要有
		msgItem.Remark = seller.RealName + "申请试用账号"
		msgItem.Content = seller.RealName + "申请试用账号"
		msgItem.CompanyName = v.CompanyName
		msgItem.CreateTime = time.Now()
		msgItem.ModifyTime = time.Now()
		msgItem.CompanyApprovalId = int(approvalId)
		msgItem.OperationStatus = 1
		msgItem.MessageType = 1    //1:申请消息，2:审批结果，3：文字消息
		msgItem.SourceType = 9     //消息来源
		msgItem.ApprovalStatus = 1 //审批状态,1:待审批，2:已审批，3:已驳回
		err = company.AddCompanyApprovalMessage(msgItem)

		approvalIds = append(approvalIds, int(approvalId))
	}

	// 2023-08-01默认审批通过, 不再进行人工审批, 也不发送待办消息
	if len(approvalIds) > 0 {
		go func() {
			for _, v := range approvalIds {
				_ = services.ApprovalApply(v)
			}
		}()
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "提交成功"
	br.Data = resp

	return
}

// @Title 申请启用
// @Description 申请启用 接口
// @Success 200 {object} models.ETATrialAddReq
// @router /apply/enable [post]
func (this *ETATrialController) ApplyEnable() {
	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 eta_trial.ETAAddEnableReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	seller, e := system.GetSysAdminById(sysUser.AdminId)
	if e != nil {
		err = e
		return
	}

	approval, err := eta_trial.GetETATrialApprovalByMobile(req.Mobile)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败！"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	var approvalId int64
	if approval != nil && (approval.ApprovalStatus == "驳回" || approval.ApprovalStatus == "已撤回") && req.Mobile == approval.Mobile {
		//若是被驳回或撤回后申请且手机号相同的，更新审批记录
		err = eta_trial.ResubmitTrial(approval.ApprovalId, req.ApplyReasons)
		if err != nil {
			br.Msg = "更新失败！"
			br.ErrMsg = "更新失败，Err:" + err.Error()
			return
		}
		approvalId = int64(approval.ApprovalId)
	} else if approval != nil && approval.ApprovalStatus == "待审批" && approval.ApprovalContent == "申请启用" {
		br.Msg = "该客户已在审批中！"
		br.ErrMsg = "该客户已在审批中！"
		return
	} else {
		//加入审批列表
		approvalItem := eta_trial.EtaTrialApproval{
			UserName:        req.UserName,
			CompanyName:     req.CompanyName,
			Position:        req.Position,
			Mobile:          req.Mobile,
			SellerId:        seller.AdminId,
			Seller:          seller.RealName,
			CreateTime:      time.Now(),
			ModifyTime:      time.Now(),
			ApprovalContent: "申请启用",
			ApplyMethod:     2,
			ApprovalStatus:  "待审批",
			ApplyReasons:    req.ApplyReasons,
		}

		approvalId, e = eta_trial.AddETATrialApproval(&approvalItem)
		if e != nil {
			err = e
			return
		}
	}

	//新增待办消息
	msgItem := new(company.CompanyApprovalMessage)
	msgItem.CreateUserId = sysUser.AdminId
	msgItem.ReceiveUserId = -1
	msgItem.MessageStatus = 1 // 已读, 不再亮红点, 但是消息要有
	msgItem.Remark = seller.RealName + "申请账号启用"
	msgItem.Content = seller.RealName + "申请账号启用"
	msgItem.CompanyName = req.CompanyName
	msgItem.CreateTime = time.Now()
	msgItem.ModifyTime = time.Now()
	msgItem.CompanyApprovalId = int(approvalId)
	msgItem.OperationStatus = 1
	msgItem.MessageType = 1    //1:申请消息，2:审批结果，3：文字消息
	msgItem.SourceType = 9     //消息来源
	msgItem.ApprovalStatus = 1 //审批状态,1:待审批，2:已审批，3:已驳回
	err = company.AddCompanyApprovalMessage(msgItem)

	// 2023-08-01默认审批通过, 不再进行人工审批
	go func() {
		_ = services.ApprovalApply(int(approvalId))
	}()

	br.Ret = 200
	br.Success = true
	br.Msg = "提交成功"
}

// @Title 撤回
// @Description 撤回申请 接口
// @Success 200 {object} models.ETATrialAddReq
// @router /apply/revoke [post]
func (this *ETATrialController) ApplyRevoke() {
	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 eta_trial.RevokeReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	mobile := req.Mobile
	mobile = strings.Trim(mobile, " ")
	mobile = strings.Replace(mobile, "'", "", -1)

	approval, err := eta_trial.GetETATrialApprovalByMobile(mobile)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "待审批信息不存在"
			br.ErrMsg = "待审批信息不存在,手机号:" + mobile
			return
		}
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取信息失败,Err:" + err.Error()
		return
	}
	if approval == nil {
		br.Msg = "待审批信息不存在"
		br.ErrMsg = "待审批信息不存在,手机号:" + mobile
		return
	}

	if approval.ApprovalStatus != "待审批" {
		br.Msg = "客户状态为：" + approval.ApprovalStatus + ";不可进行撤回操作"
		br.ErrMsg = "客户状态为：" + approval.ApprovalStatus + ";不可进行撤回操作"
		return
	}
	//撤回审批单
	err = eta_trial.RevokeApproval(mobile)
	if err != nil {
		br.Msg = "撤回失败"
		br.ErrMsg = "撤回失败,Err:" + err.Error()
		return
	}

	// 更新审批消息状态为已读
	go func() {
		cond := ` AND company_approval_id = ? AND source_type = ? AND message_status = ?`
		pars := make([]interface{}, 0)
		pars = append(pars, approval.ApprovalId, 9, 0)
		if e := company.ModifyCompanyApprovalMessageStatusByCond(cond, pars); e != nil {
			br.Msg = "操作失败"
			br.ErrMsg = "更新销售ETA试用消息已读状态失败, Err: " + e.Error()
			return
		}
	}()
	br.Ret = 200
	br.Success = true
	br.Msg = "撤回成功"
}

// @Title 删除申请
// @Description 删除申请 接口
// @Success 200 {object} models.ETATrialAddReq
// @router /apply/del [post]
func (this *ETATrialController) ApplyDel() {
	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 eta_trial.DelReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ApprovalId <= 0 {
		br.Msg = "参数有误"
		return
	}
	_, e := eta_trial.GetETATrialApprovalById(req.ApprovalId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "申请已被删除, 请刷新页面"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "获取ETA审批失败, Err: " + e.Error()
		return
	}

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

	// 更新审批消息状态为已读
	go func() {
		cond := ` AND company_approval_id = ? AND source_type = ? AND message_status = ?`
		pars := make([]interface{}, 0)
		pars = append(pars, req.ApprovalId, 9, 0)
		if e := company.ModifyCompanyApprovalMessageStatusByCond(cond, pars); e != nil {
			br.Msg = "操作失败"
			br.ErrMsg = "更新销售ETA试用消息已读状态失败, Err: " + e.Error()
			return
		}
	}()

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

// @Title 驳回申请
// @Description 驳回申请 接口
// @Param   ApprovalId   query   string  true       "审批id"
// @Param   RejectReason   query   string  true       "驳回理由"
// @Success 200 {object} models.ETATrialAddReq
// @router /apply/reject [post]
func (this *ETATrialController) ApplyReject() {
	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 eta_trial.RejectReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	approvalId := req.ApprovalId
	reason := req.RejectReason

	err = eta_trial.RejectApproval(approvalId, reason)
	if err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "删除失败,Err:" + err.Error()
		return
	}

	approval, err := eta_trial.GetETATrialApprovalById(approvalId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败,Err:" + err.Error()
		return
	}

	msgItem := new(company.CompanyApprovalMessage)
	msgItem.CreateUserId = sysUser.AdminId
	msgItem.ReceiveUserId = approval.SellerId
	msgItem.MessageStatus = 0
	msgItem.Remark = approval.UserName + approval.ApprovalContent + "驳回"
	msgItem.Content = approval.UserName + approval.ApprovalContent + "驳回"
	msgItem.CompanyName = approval.CompanyName
	msgItem.CreateTime = time.Now()
	msgItem.ModifyTime = time.Now()
	msgItem.CompanyApprovalId = approvalId
	msgItem.OperationStatus = 1
	msgItem.MessageType = 2    //1:申请消息，2:审批结果，3：文字消息
	msgItem.SourceType = 9     //消息来源
	msgItem.ApprovalStatus = 3 //审批状态,1:待审批，2:已审批，3:已驳回
	err = company.AddCompanyApprovalMessage(msgItem)

	// 更新审批消息(发给所有管理员的)为已读
	go func() {
		cond := ` AND company_approval_id = ? AND source_type = ? AND message_status = ? AND receive_user_id = -1 `
		pars := make([]interface{}, 0)
		pars = append(pars, req.ApprovalId, 9, 0)
		if e := company.ModifyCompanyApprovalMessageStatusByCond(cond, pars); e != nil {
			br.Msg = "操作失败"
			br.ErrMsg = "更新销售ETA试用消息已读状态失败, Err: " + e.Error()
			return
		}
	}()
	br.Ret = 200
	br.Success = true
	br.Msg = "驳回成功"
}

// @Title 同意申请
// @Description 同意申请 接口
// @Param   ApprovalId   query   string  true       "审批id"
// @Success 200 {object} models.ETATrialAddReq
// @router /apply/approval [post]
func (this *ETATrialController) Approval() {
	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 eta_trial.DelReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	approvalId := req.ApprovalId

	err = eta_trial.ApprovalTrial(approvalId)
	if err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "删除失败,Err:" + err.Error()
		return
	}

	approval, err := eta_trial.GetETATrialApprovalById(approvalId)
	if err != nil {
		br.Msg = "查询失败"
		br.ErrMsg = "查询失败,Err:" + err.Error()
		return
	}

	//如果是新客户申请就新增，旧客户更改账号状态即可
	if approval.ApplyMethod == 2 {
		err := eta_trial.UpdateETATrialEnable(approval.Mobile)
		if err != nil {
			br.Msg = "启用失败"
			br.ErrMsg = "启用失败,Err:" + err.Error()
			return
		}
		err = eta_trial.UpdateAdminEnable(approval.Mobile)
		if err != nil {
			br.Msg = "启用失败"
			br.ErrMsg = "启用失败,Err:" + err.Error()
			return
		}
	} else {
		//新增客户
		newItem := eta_trial.EtaTrial{
			UserName:    approval.UserName,
			CompanyName: approval.CompanyName,
			Position:    approval.Position,
			Mobile:      approval.Mobile,
			Enabled:     1,
			SellerId:    approval.SellerId,
			Seller:      approval.Seller,
			CreateTime:  time.Now(),
			ModifyTime:  time.Now(),
		}

		strResult := ""
		a := pinyin.NewArgs()
		rows := pinyin.Pinyin(newItem.UserName, a)
		for i := 0; i < len(rows); i++ {
			strResult += rows[i][0]
		}

		//若非中文
		if strResult == "" {
			strResult = newItem.UserName
		}
		list, err := eta_trial.GetETATrialByAccount(strResult)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "查询失败"
			br.ErrMsg = "查询失败,GetETATrialByAccount Err:" + err.Error()
			return
		}
		if list != nil && len(list) > 0 {
			newItem.Account = strResult + strconv.Itoa(len(list))
		} else {
			newItem.Account = strResult
		}

		//newItem.Password = utils.GetRandStringNoSpecialChar(8)
		// 初始密码固定
		newItem.Password = "123456a"

		_, err = eta_trial.AddETATrial(&newItem)
		if err != nil {
			br.Msg = "新增失败"
			br.ErrMsg = "新增失败,AddETATrial Err:" + err.Error()
			return
		}

		//新增至试用平台的Admin

		adminItem, err := eta_trial.GetSysUserByRoleAndDepartment("试用", "ETA试用客户")
		if err != nil {
			br.Msg = "获取用户信息失败"
			br.ErrMsg = "获取用户信息失败,Err:" + err.Error()
			return
		}

		admin := new(eta_trial.ETATrialAdmin)
		admin.AdminName = newItem.Account
		admin.RealName = newItem.UserName
		admin.Password = utils.MD5(newItem.Password)
		admin.LastUpdatedPasswordTime = time.Now().Format(utils.FormatDateTime)
		admin.Enabled = 1
		admin.LastLoginTime = time.Now().Format(utils.FormatDateTime)
		admin.CreatedTime = time.Now()
		admin.LastUpdatedTime = time.Now().Format(utils.FormatDateTime)
		admin.Mobile = newItem.Mobile
		admin.RoleType = 0

		admin.RoleId = adminItem.RoleId
		admin.RoleName = "试用"
		admin.RoleTypeCode = "管理员"
		admin.DepartmentId = adminItem.DepartmentId
		admin.DepartmentName = "ETA试用客户"
		admin.Role = "admin"
		admin.Position = approval.Position

		newId, err := eta_trial.AddAdmin(admin)
		if err != nil {
			br.Msg = "新增失败"
			br.ErrMsg = "新增失败，AddAdmin Err:" + err.Error()
			return
		}

		// 新增试用客户手工权限
		go func() {
			//_ = services.CreateTrialUserManualAuth(newId, admin.RealName)
			_ = services.EtaTrialManualUserAddAuth(newId, admin.RealName)
		}()
	}

	msgItem := new(company.CompanyApprovalMessage)
	msgItem.CreateUserId = sysUser.AdminId
	msgItem.ReceiveUserId = approval.SellerId
	msgItem.MessageStatus = 0
	msgItem.Remark = approval.UserName + approval.ApprovalContent + "通过"
	msgItem.Content = approval.UserName + approval.ApprovalContent + "通过"
	msgItem.CompanyName = approval.CompanyName
	msgItem.CreateTime = time.Now()
	msgItem.ModifyTime = time.Now()
	msgItem.CompanyApprovalId = approvalId
	msgItem.OperationStatus = 1
	msgItem.MessageType = 2    //1:申请消息，2:审批结果，3：文字消息
	msgItem.SourceType = 9     //消息来源
	msgItem.ApprovalStatus = 2 //审批状态,1:待审批，2:已审批，3:已驳回
	err = company.AddCompanyApprovalMessage(msgItem)

	// 更新审批消息(发给所有管理员的)为已读
	go func() {
		cond := ` AND company_approval_id = ? AND source_type = ? AND message_status = ? AND receive_user_id = -1 `
		pars := make([]interface{}, 0)
		pars = append(pars, req.ApprovalId, 9, 0)
		if e := company.ModifyCompanyApprovalMessageStatusByCond(cond, pars); e != nil {
			br.Msg = "操作失败"
			br.ErrMsg = "更新销售ETA试用消息已读状态失败, Err: " + e.Error()
			return
		}
	}()
	br.Ret = 200
	br.Success = true
	br.Msg = "审批成功"
}

// @Title 我的审批
// @Description 我的审批 接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   KeyWord   query   string  true       "搜索关键词"
// @Param   SortType   query   string  true       "如何排序，是正序还是倒序，枚举值：`asc 正序`,`desc 倒叙`"
// @router /apply/myList [get]
func (this *ETATrialController) MyList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	keyWord := this.GetString("KeyWord")
	keyWord = strings.Trim(keyWord, " ")
	keyWord = strings.Replace(keyWord, "'", "", -1)

	//排序参数
	sortType := this.GetString("SortType")

	var total int
	page := paging.GetPaging(currentIndex, pageSize, total)

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)
	var condition string
	var pars []interface{}

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

	sortStr := ""
	if sortType == "asc" {
		sortStr = "ORDER BY a.modify_time ASC "
	} else {
		sortStr = "ORDER BY a.modify_time DESC "
	}

	pars = append(pars, sysUser.AdminId)

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

	list, err := eta_trial.GetETATrialApprovalBySellerId(condition, sortStr, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "查询失败"
		br.ErrMsg = "查询失败,Err:" + err.Error()
		return
	}

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

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

	return
}

// @Title 审批列表
// @Description 审批列表 接口
// @Param   SortParam   query   int  false       "排序字段参数，用来排序的字段  "
// @Param   ListParam   query   int  false       "筛选字段参数，用来筛选的字段， 枚举值：1:全部 、 2:待审批 、 3:已审批  "
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   KeyWord   query   string  true       "搜索关键词"
// @Param   SortType   query   string  true       "如何排序，是正序还是倒序，枚举值：`asc 正序`,`desc 倒叙`"
// @Success 200 {object} models.ETATrialAddReq
// @router /apply/list [get]
func (this *ETATrialController) ApplyList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	keyWord := this.GetString("KeyWord")
	keyWord = strings.Trim(keyWord, " ")
	keyWord = strings.Replace(keyWord, "'", "", -1)

	//排序参数
	sortParam := this.GetString("SortParam")
	listParam, _ := this.GetInt("ListParam")
	sortType := this.GetString("SortType")

	var total int
	page := paging.GetPaging(currentIndex, pageSize, total)

	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 (user_name LIKE '%` + keyWord + `%' OR company_name LIKE '%` + keyWord + `%' OR mobile LIKE '%` + keyWord + `%') `
	}

	sortStr := ""
	if listParam == 0 {
		condition += ` AND approval_status = '待审批' `
	} else if listParam == 2 {
		condition += ` AND approval_status = '待审批' `
	} else if listParam == 3 {
		condition += ` AND approval_status = '已审批' OR approval_status = '驳回' `
	}

	if sortType == "asc" {
		sortStr = "ORDER BY modify_time ASC "
	} else {
		sortStr = "ORDER  BY modify_time DESC "
	}
	if sortParam == "Expiration" {
		if sortType == "asc" {
			sortStr = "ORDER BY modify_time ASC "
		} else {
			sortStr = "ORDER  BY modify_time DESC "
		}
	} else if sortParam == "ModifyTime" {
		if sortType == "asc" {
			sortStr = "ORDER BY modify_time ASC "
		} else {
			sortStr = "ORDER  BY modify_time DESC "
		}
	}

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

	list, err := eta_trial.GetETATrialApprovalList(condition, sortStr, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "查询失败"
		br.ErrMsg = "查询失败,Err:" + err.Error()
		return
	}

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

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

	return
}

// @Title 账号列表
// @Description 账号列表 接口
// @Param   SortParam   query   string  false       "排序字段参数，用来排序的字段， 枚举值：'Expiration':账号到期时长 、 'ModifyTime':账号更新时间 "
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   KeyWord   query   string  true       "搜索关键词"
// @Param   SortType   query   string  true       "如何排序，是正序还是倒序，枚举值：`asc 正序`,`desc 倒叙`"
// @Success 200 {object} models.ETATrialAddReq
// @router /apply/accountlist [get]
func (this *ETATrialController) AccountList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	keyWord := this.GetString("KeyWord")
	keyWord = strings.Trim(keyWord, " ")
	keyWord = strings.Replace(keyWord, "'", "", -1)

	//排序参数
	sortType := this.GetString("SortType")

	var total int
	page := paging.GetPaging(currentIndex, pageSize, total)

	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 (user_name LIKE '%` + keyWord + `%' OR company_name LIKE '%` + keyWord + `%' OR mobile LIKE '%` + keyWord + `%') `
	}

	condition += ` AND seller_id = ? `
	pars = append(pars, sysUser.AdminId)

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

	sortStr := ""

	if sortType == "asc" {
		sortStr = "ORDER BY modify_time ASC "
	} else {
		sortStr = "ORDER  BY modify_time DESC "
	}

	list, err := eta_trial.GetETATrialList(condition, sortStr, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取权限列表失败"
		br.ErrMsg = "获取权限列表失败,Err:" + err.Error()
		return
	}

	for _, item := range list {
		activeTime, _ := strconv.Atoi(item.ActiveTime)
		item.ActiveTime = utils.GetDurationFormatBySecond(activeTime)

		//到期时间
		modifyTime, err := time.Parse(utils.FormatDateTime, item.ModifyTime)
		if err != nil {
			br.Msg = "时间转化失败"
			br.ErrMsg = "时间转化失败,Err:" + err.Error()
			return
		}

		var expired int

		expiredTime := modifyTime.AddDate(0, 0, 14).Format(utils.FormatDate)
		expired, err = utils.GetDaysBetween2Date(utils.FormatDate, expiredTime, time.Now().Format(utils.FormatDate))
		if err != nil {
			br.Msg = "时间计算失败"
			br.ErrMsg = "时间计算失败,CalculationDate Err:" + err.Error()
			return
		}
		item.Expiration = expired
	}

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

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

	return
}

// @Title 问卷配置
// @Description 问卷配置 接口
// @Success 200 string  "获取成功"
// @router /questionnaire/list [get]
func (this *ETATrialController) QuestionnaireList() {
	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
	}

	cond := ""
	lists, err := eta_trial.GetETATrialQuestionnaireList(cond)
	if err != nil {
		br.Msg = "获取问卷失败"
		br.ErrMsg = "获取问卷失败,Err:" + err.Error()
		return
	}

	var resp eta_trial.EtaTrialQuestionnaireResp
	for _, v := range lists {
		item := eta_trial.EtaTrialQuestionnaireRespItem{
			QuestionnaireId: v.QuestionnaireId,
			Question:        v.Question,
			Type:            v.Type,
			Sort:            v.Sort,
			Options:         strings.Split(v.Options, "~#"),
			IsMust:          v.IsMust,
			CreateTime:      v.CreateTime.Format(utils.FormatDateTime),
		}
		resp.List = append(resp.List, item)
	}

	sort.Sort(resp)

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

	return
}

// @Title 问卷保存
// @Description 问卷保存 接口
// @Param	request	body eta_trial.EtaTrialQuestionnaireSaveReq true "type json string"
// @Success 200 {object} models.ETATrialAddReq
// @router /questionnaire/save [post]
func (this *ETATrialController) QuestionnairesSave() {
	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 eta_trial.EtaTrialQuestionnaireSaveReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	questionnaireList := make([]*eta_trial.EtaTrialQuestionnaire, 0)
	for _, v := range req.List {
		if v.QuestionnaireId == 0 {
			//新增
			questionItem := &eta_trial.EtaTrialQuestionnaire{
				Question:   v.Question,
				IsMust:     v.IsMust,
				Type:       v.Type,
				Sort:       v.Sort,
				Options:    strings.Join(v.Options, "~#"),
				CreateTime: time.Now(),
			}
			questionnaireList = append(questionnaireList, questionItem)
		} else {
			//更新
			questionItem := &eta_trial.EtaTrialQuestionnaire{
				QuestionnaireId: v.QuestionnaireId,
				Question:        v.Question,
				Options:         strings.Join(v.Options, "~#"),
				Sort:            v.Sort,
				IsMust:          v.IsMust,
				CreateTime:      time.Time{},
			}
			cols := make([]string, 0)
			cols = append(cols, "question", "options", "Sort", "IsMust")
			err = questionItem.Update(cols)
			if err != nil {
				br.Msg = "更新问题失败！"
				br.ErrMsg = "更新问题失败，Err:" + err.Error()
				return
			}
		}
	}

	//批量新增问题和选项
	if len(questionnaireList) > 0 {
		err = eta_trial.AddETATrialQuestionnaire(questionnaireList)
		if err != nil {
			br.Msg = "保存问题失败！"
			br.ErrMsg = "保存问题失败，Err:" + err.Error()
			return
		}
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "保存成功"

	return
}

// @Title 问题删除
// @Description 问题删除 接口
// @Param	request	body eta_trial.EtaTrialQuestionnaireSaveReq true "type json string"
// @Success 200 {object} models.ETATrialAddReq
// @router /questionnaire/del [post]
func (this *ETATrialController) QuestionnairesDel() {
	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 eta_trial.EtaTrialQuestionnaireDelReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.QuestionnaireId <= 0 {
		br.Msg = "问题id异常！"
		br.ErrMsg = "问题id异常，Err:" + err.Error()
		return
	}

	count, err := eta_trial.GetETATrialQuestionnaireById(req.QuestionnaireId)
	if err != nil && count > 0 {
		br.Msg = "查询问题异常！"
		br.ErrMsg = "查询问题异常，Err:" + err.Error()
		return
	}

	err = eta_trial.DelETATrialQuestionnaireById(req.QuestionnaireId)
	if err != nil && count > 0 {
		br.Msg = "删除问题异常！"
		br.ErrMsg = "删除问题异常，Err:" + err.Error()
		return
	}

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

// @Title 问卷统计结果
// @Description 问卷统计结果 接口
// @Param   ListParam   query   int  false       "筛选字段参数，用来筛选的字段， 枚举值：1:全部 、 2:选择题 、 3:简答题  "
// @Success 200 {object} models.ETATrialAddReq
// @router /questionnaire/statistical [get]
func (this *ETATrialController) QuestionnairesStatistical() {
	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
	}

	listParam, _ := this.GetInt("ListParam")

	cond := ""
	if listParam == 2 {
		cond = "AND a.type = 1 OR a.type = 2 "
	} else if listParam == 3 {
		cond = "AND a.type = 3 "
	}
	list, err := eta_trial.GetETATrialQuestionnaireStatistic(cond)
	if err != nil {
		br.Msg = "获取问题统计失败！"
		br.ErrMsg = "获取问题统计失败，Err:" + err.Error()
		return
	}

	//获取单选和简答的回答数量，多选计算方式不同在计算后面统计时再计算
	questionCountList, err := eta_trial.GetETATrialQuestionnaireStatisticCount()
	if err != nil {
		br.Msg = "获取问卷记录数量失败"
		br.ErrMsg = "获取问卷记录数量失败,Err:" + err.Error()
		return
	}

	questioncountMap := make(map[int]int, 0)
	for _, v := range questionCountList {
		questioncountMap[v.QuestionnaireId] = v.Count
	}

	chooseMap := make(map[string]int, 0)
	answerCountMap := make(map[int]int, 0)
	answerMap := make(map[int][]string, 0)
	answerNameMap := make(map[int]string, 0)
	for _, v := range list {
		//问卷ID拼选项作为key，防止不同问题选项重复
		if v.Type == 1 {
			key := strconv.Itoa(v.QuestionnaireId) + v.Options
			if _, ok := chooseMap[key]; !ok {
				chooseMap[key] = v.Count
			}
		} else if v.Type == 2 {
			options := strings.Split(v.Options, "~#")
			for _, op := range options {
				key := strconv.Itoa(v.QuestionnaireId) + op
				if _, ok := chooseMap[key]; ok {
					//多选题可能出现多人同样的选择
					chooseMap[key] += v.Count
				} else {
					chooseMap[key] = v.Count
				}
				questioncountMap[v.QuestionnaireId] += v.Count
			}
		} else {
			//简答题，最多十条
			if count, ok := answerCountMap[v.QuestionnaireId]; ok && count < 11 {
				answerMap[v.QuestionnaireId] = append(answerMap[v.QuestionnaireId], v.Options)
				answerNameMap[v.QuestionnaireId] = v.UserName
				answerCountMap[v.QuestionnaireId] += 1
			} else if !ok {
				answerMap[v.QuestionnaireId] = append(answerMap[v.QuestionnaireId], v.Options)
				answerNameMap[v.QuestionnaireId] = v.UserName
				answerCountMap[v.QuestionnaireId] = 1
			}
		}
	}

	lists, err := eta_trial.GetETATrialQuestionnaireList(cond)
	if err != nil {
		br.Msg = "获取问卷失败"
		br.ErrMsg = "获取问卷失败,Err:" + err.Error()
		return
	}

	var questionList eta_trial.EtaTrialQuestionnaireResp
	for _, v := range lists {
		item := eta_trial.EtaTrialQuestionnaireRespItem{
			QuestionnaireId: v.QuestionnaireId,
			Question:        v.Question,
			Options:         strings.Split(v.Options, "~#"),
			Type:            v.Type,
			Sort:            v.Sort,
			IsMust:          v.IsMust,
			CreateTime:      v.CreateTime.Format(utils.FormatDateTime),
		}
		questionList.List = append(questionList.List, item)
	}

	sort.Sort(questionList)

	var resp []eta_trial.EtaTrialQuestionnaireRecordStatisticResp
	for _, v := range questionList.List {
		if v.Type != 3 {
			options := make([]*eta_trial.EtaTrialQuestionnaireRecordStatisticOption, 0)
			for _, op := range v.Options {
				key := strconv.Itoa(v.QuestionnaireId) + op
				opItem := eta_trial.EtaTrialQuestionnaireRecordStatisticOption{
					Option: op,
					Count:  chooseMap[key],
				}
				options = append(options, &opItem)
			}
			item := eta_trial.EtaTrialQuestionnaireRecordStatisticResp{
				QuestionnaireId: v.QuestionnaireId,
				Question:        v.Question,
				Options:         options,
				Type:            v.Type,
				IsMust:          v.IsMust,
			}
			resp = append(resp, item)
		} else {
			item := eta_trial.EtaTrialQuestionnaireRecordStatisticResp{
				QuestionnaireId: v.QuestionnaireId,
				Question:        v.Question,
				Type:            v.Type,
				IsMust:          v.IsMust,
			}

			ansList := make([]eta_trial.EtaTrialQuestionnaireRecordStatisticAnswer, 0)
			for _, val := range answerMap[v.QuestionnaireId] {
				ansItem := eta_trial.EtaTrialQuestionnaireRecordStatisticAnswer{
					Answer:   val,
					UserName: answerNameMap[v.QuestionnaireId],
				}
				ansList = append(ansList, ansItem)
			}

			item.Answers = ansList

			resp = append(resp, item)
		}
	}

	for _, v := range resp {
		if v.Type != 3 && v.Type != 4 {
			for i, op := range v.Options {
				key := strconv.Itoa(v.QuestionnaireId) + op.Option
				opCount := float64(chooseMap[key])
				count := float64(questioncountMap[v.QuestionnaireId])
				if count != 0 {
					per, _ := strconv.ParseFloat(fmt.Sprintf("%.4f", opCount/count), 64)
					op.Percentage = per
				}
				op.Index = i
			}
		}
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "保存成功"
	br.Data = resp

	return
}

// @Title 简答题列表
// @Description 简答题列表 接口
// @Success 200 string  "获取成功"
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   QuestionnaireId   query   int  true       "问题id"
// @router /questionnaire/answerList [get]
func (this *ETATrialController) QuestionnaireAnswerList() {
	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 startSize int
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	questionnaireId, _ := this.GetInt("QuestionnaireId")
	lists, err := eta_trial.GetETATrialQuestionnaireAnswerListById(questionnaireId, startSize, pageSize)
	if err != nil {
		br.Msg = "获取问卷失败"
		br.ErrMsg = "获取问卷失败,Err:" + err.Error()
		return
	}

	total, err := eta_trial.GetETATrialQuestionnaireAnswerListByIdCount(questionnaireId)
	if err != nil {
		br.Msg = "获取问卷失败"
		br.ErrMsg = "获取问卷失败,Err:" + err.Error()
		return
	}
	cond := ""
	qLists, err := eta_trial.GetETATrialQuestionnaireList(cond)
	if err != nil {
		br.Msg = "获取问卷失败"
		br.ErrMsg = "获取问卷失败,Err:" + err.Error()
		return
	}

	mustMap := make(map[int]int, 0)
	for _, v := range qLists {
		mustMap[v.QuestionnaireId] = v.IsMust
	}

	resp := new(eta_trial.QuestionnaireDetailListResp)
	for _, v := range lists {
		item := eta_trial.EtaTrialQuestionnaireRecordRespItem{
			RecordId:        v.RecordId,
			UserName:        v.UserName,
			CompanyName:     v.CompanyName,
			Position:        v.Position,
			Options:         v.Options,
			Mobile:          v.Mobile,
			Type:            v.Type,
			QuestionnaireId: v.QuestionnaireId,
			IsMust:          mustMap[v.QuestionnaireId],
			CreateTime:      v.CreateTime.Format(utils.FormatDateTime),
		}
		resp.List = append(resp.List, &item)
	}
	page := paging.GetPaging(currentIndex, pageSize, total)

	resp.Paging = page

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

	return
}

// @Title 详细数据列表
// @Description 详细数据列表 接口
// @Success 200 string  "获取成功"
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @router /questionnaire/detailList [get]
func (this *ETATrialController) QuestionnaireDetailList() {
	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 startSize int

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	total, err := eta_trial.GetETATrialQuestionnaireDetailListCount()
	if err != nil {
		br.Msg = "获取问卷数量失败"
		br.ErrMsg = "获取问卷数量失败,Err:" + err.Error()
		return
	}

	if total == 0 {
		br.Msg = "无问卷调查记录"
		br.Ret = 200
		br.Success = true
		return
	}

	lists, err := eta_trial.GetETATrialQuestionnaireDetailList(startSize, pageSize)
	if err != nil {
		br.Msg = "获取问卷失败"
		br.ErrMsg = "获取问卷失败,Err:" + err.Error()
		return
	}

	cond := ""
	qLists, err := eta_trial.GetETATrialQuestionnaireList(cond)
	if err != nil {
		br.Msg = "获取问卷失败"
		br.ErrMsg = "获取问卷失败,Err:" + err.Error()
		return
	}

	mustMap := make(map[int]int, 0)
	for _, v := range qLists {
		mustMap[v.QuestionnaireId] = v.IsMust
	}
	resp := new(eta_trial.QuestionnaireDetailListResp)

	for _, v := range lists {
		item := eta_trial.EtaTrialQuestionnaireRecordRespItem{
			RecordId:        v.RecordId,
			UserName:        v.UserName,
			CompanyName:     v.CompanyName,
			Position:        v.Position,
			Options:         v.Options,
			Mobile:          v.Mobile,
			Type:            v.Type,
			QuestionnaireId: v.QuestionnaireId,
			IsMust:          mustMap[v.QuestionnaireId],
			CreateTime:      v.CreateTime.Format(utils.FormatDateTime),
		}
		resp.List = append(resp.List, &item)
	}

	page := paging.GetPaging(currentIndex, pageSize, total)

	resp.Paging = page

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

	return
}

// @Title 详细数据查看
// @Description 详细数据查看 接口
// @Success 200 string  "获取成功"
// @Param   Mobile   query   string  true       "手机号"
// @Param   CreateTime   query   string  true       "手机号"
// @router /questionnaire/detail [get]
func (this *ETATrialController) QuestionnaireDetail() {
	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
	}

	cond := ""
	lists, err := eta_trial.GetETATrialQuestionnaireList(cond)
	if err != nil {
		br.Msg = "获取问卷失败"
		br.ErrMsg = "获取问卷失败,Err:" + err.Error()
		return
	}

	var resp eta_trial.EtaTrialQuestionnaireResp
	for _, v := range lists {
		item := eta_trial.EtaTrialQuestionnaireRespItem{
			QuestionnaireId: v.QuestionnaireId,
			Question:        v.Question,
			Options:         strings.Split(v.Options, "~#"),
			Type:            v.Type,
			Sort:            v.Sort,
			IsMust:          v.IsMust,
			CreateTime:      v.CreateTime.Format(utils.FormatDateTime),
		}
		resp.List = append(resp.List, item)
	}

	sort.Sort(resp)

	mobile := this.GetString("Mobile")
	createTime := this.GetString("CreateTime")

	timeDate, _ := time.Parse(utils.FormatDateTime, createTime)
	startDate := timeDate.AddDate(0, 0, -1).Format(utils.FormatDateTime)
	endDate := timeDate.AddDate(0, 0, 1).Format(utils.FormatDateTime)
	answerList, err := eta_trial.GetETATrialQuestionnaireDetailListByMobile(mobile, startDate, endDate)
	if err != nil {
		br.Msg = "获取问卷失败"
		br.ErrMsg = "获取问卷失败,Err:" + err.Error()
		return
	}

	answerMap := make(map[int]string)
	for _, v := range answerList {
		answerMap[v.QuestionnaireId] = v.Options
	}

	nResp := make([]eta_trial.EtaTrialQuestionnaireDetailItem, 0)
	for _, v := range lists {
		item := eta_trial.EtaTrialQuestionnaireDetailItem{
			QuestionnaireId: v.QuestionnaireId,
			Question:        v.Question,
			Type:            v.Type,
			Sort:            v.Sort,
			IsMust:          v.IsMust,
			Options:         strings.Split(v.Options, "~#"),
			UserOptions:     answerMap[v.QuestionnaireId],
			CreateTime:      v.CreateTime.Format(utils.FormatDateTime),
		}
		nResp = append(nResp, item)
	}

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

	return
}
