package cygx

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/cygx"
	"hongze/hz_crm_api/services"
	cygxService "hongze/hz_crm_api/services/cygx"
	"hongze/hz_crm_api/services/elastic"
	"hongze/hz_crm_api/utils"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

// YanxuanSpecialController 研选专栏
type YanxuanSpecialController struct {
	controllers.BaseAuthController
}

// @Title 新增研选专栏作者
// @Description 新增研选专栏作者
// @Param	request	body help_doc.AddHelpDocReq true "type json string"
// @Success 200 {object} models.AddEnglishReportResp
// @router /yanxuan_special/author/add [post]
func (this *YanxuanSpecialController) 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 cygx.AddCygxYanxuanSpecialAuthorReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.UserId <= 0 {
		br.Msg = "请输入用户信息"
		return
	}
	if req.RealName == "" {
		br.Msg = "请输入真实姓名"
		return
	}
	if req.Mobile == "" {
		br.Msg = "请输入手机号"
		return
	}

	//获取关联公司的用户信息
	infoUser, err := cygx.GetUserAndCompanyNameList(req.UserId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	rnd := utils.GetRandInt(1, 5)
	item := cygx.CygxYanxuanSpecialAuthor{
		UserId:      req.UserId,
		RealName:    req.RealName,
		Mobile:      req.Mobile,
		MobileInit:  infoUser.Mobile,
		CompanyName: infoUser.CompanyName,
		CompanyId:   infoUser.CompanyId,
		InviteName:  req.InviteName,
		Remark:      req.Remark,
		CreateTime:  time.Now(),
		ModifyTime:  time.Now(),
		HeadImg:     utils.CYGX_YANXUAN_SPECIAL_HEAD_IMG_URL + strconv.Itoa(rnd) + ".png",
		BgImg:       utils.CYGX_YANXUAN_SPECIAL_BG_IMG_URL + strconv.Itoa(rnd) + "a.png",
		BgImgDown:   utils.CYGX_YANXUAN_SPECIAL_BG_IMG_URL + strconv.Itoa(rnd) + "b.png",
		BgImgPc:     utils.CYGX_YANXUAN_SPECIAL_BG_IMG_URL_PC + strconv.Itoa(rnd) + ".png",
		Status:      1,
	}

	_, err = cygx.AddCygxYanxuanSpecialAuthor(&item)
	if err != nil {
		br.Msg = "新增失败"
		br.ErrMsg = "新增失败，Err:" + err.Error()
		return
	}

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

// @Title 禁用/启用研选专栏作者
// @Description 禁用/启用研选专栏作者
// @Param	request	body help_doc.AddHelpDocReq true "type json string"
// @Success 200 {object} models.AddEnglishReportResp
// @router /yanxuan_special/author/enable [post]
func (this *YanxuanSpecialController) AuthorEnable() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req cygx.EnableCygxYanxuanSpecialAuthorReq
	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
	}
	if req.Status <= 0 {
		br.Msg = "参数错误"
		return
	}
	if tmpErr := cygx.EnableYanxuanSpecialAuthor(req.UserId, req.Status); tmpErr != nil {
		br.Msg = "启用/禁用作者失败"
		br.ErrMsg = "启用/禁用作者失败, Err:" + tmpErr.Error()
		return
	}

	if req.Status == 1 {
		br.Msg = "启用成功"
	} else {
		br.Msg = "禁用成功"
	}

	br.Ret = 200
	br.Success = true
}

// @Title 作者列表
// @Description 作者列表
// @Param	request	body help_doc.AddHelpDocReq true "type json string"
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   Status   query   string  true       "状态： 1:启用 、 2:禁用 。传其他默认所有"
// @Param   KeyWord   query   string  false       "搜索关键词"
// @Param   NickName   query   string  false       "昵称"
// @Param   SortParam   query   string  false       "排序字段参数，用来排序的字段， 枚举值：'CreatTime':开通时间 、 'articleNum':已发布文章 、 'pv':总Pv/Uv "
// @Param   SortType   query   string  true       "如何排序，是正序还是倒序，枚举值：`asc 正序`,`desc 倒叙`"
// @Success 200 {object} models.AddEnglishReportResp
// @router /yanxuan_special/author/list [get]
func (this *YanxuanSpecialController) AuthorList() {
	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")
	status, _ := this.GetInt("Status")
	keyWord := this.GetString("KeyWord")
	//排序参数
	sortParam := this.GetString("SortParam")
	sortType := this.GetString("SortType")
	nickName := this.GetString("NickName")

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)
	var condition string
	var pars []interface{}
	//作者状态处理
	if status == 1 || status == 2 {
		condition += ` AND art.status = ? `
		pars = append(pars, status)
	}

	//关键词搜索
	if keyWord != "" {
		keyWord = "%" + keyWord + "%"
		condition += ` AND art.special_name like  ? `
		pars = append(pars, keyWord)
	}

	//关键词搜索
	if nickName != "" {
		nickName = "%" + nickName + "%"
		condition += ` AND art.nick_name like  ? `
		pars = append(pars, nickName)
	}

	//排序字段以及排序方式处理
	var sortStr string
	if sortParam != "" && sortType != "" {
		if sortParam == "CreateTime" {
			if sortType == "asc" {
				sortStr = " ORDER BY art.create_time ASC "
			} else {
				sortStr = " ORDER BY art.create_time  DESC "
			}
		}

		if sortParam == "ArticleNum" {
			if sortType == "asc" {
				sortStr = " ORDER BY art.article_num ASC "
			} else {
				sortStr = " ORDER BY art.article_num  DESC  "
			}
		}

		if sortParam == "pv" {
			if sortType == "asc" {
				sortStr = " ORDER BY art.pv ASC "
			} else {
				sortStr = " ORDER BY art.pv  DESC "
			}
		}
		if sortStr == "" {
			sortStr = " ORDER BY a.publish_time  DESC " // 兼容前端老六乱传字段
		}
	} else {
		sortStr = " ORDER BY art.create_time  DESC "
	}

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

	list, tmpErr := cygx.GetYanxuanSpecialAuthorList(condition+sortStr, pars, startSize, pageSize)
	if tmpErr != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败, Err:" + tmpErr.Error()
		return
	}

	var userIds []int
	var mobiles []string
	for _, v := range list {
		userIds = append(userIds, v.UserId)
		if v.MobileInit != "" {
			mobiles = append(mobiles, v.MobileInit)
		}
	}

	listUser, err := models.GetWxUserRaiSllerListByUserMobile(mobiles)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	//获取用户当前最新的公司信息
	mapWxUserSller := make(map[string]*models.WxUserSller)
	for _, v := range listUser {
		mapWxUserSller[v.Mobile] = v
	}

	//对权益管理员跟超管展示全部手机号
	var isShow bool
	if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
		isShow = true
	}

	//获取专栏用户最新的一篇文章信息
	mapNewTime := cygxService.GetBestNewYanxuanSpecialByUserId(userIds)
	for _, v := range list {
		v.SpecialAuthorId = v.Id
		v.ArticlePublishTime = mapNewTime[v.UserId]
		mapItem := mapWxUserSller[v.MobileInit]
		if mapItem != nil {
			v.CompanyName = mapItem.CompanyName
			v.CompanyId = mapItem.CompanyId
		}
		if isShow {
			v.Mobile = v.MobileInit
		}

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

// @Title 审核列表
// @Description 审核列表
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   Status   query   string  true       "状态： 1:待审核 、 2:已发布 。默认待审核"
// @Param   Type   query   int  true       "文章类型，1：笔记、2：观点"
// @Param   KeyWord   query   string  false       "搜索关键词"
// @Param   NickName   query   string  false       "昵称"
// @Param   SortParam   query   string  false       "排序字段参数，用来排序的字段， 枚举值：'CreatTime':开通时间 、 'articleNum':已发布文章 、 'pv':总Pv/Uv "
// @Param   SortType   query   string  true       "如何排序，是正序还是倒序，枚举值：`asc 正序`,`desc 倒叙`"
// @Param   StartDate   query   string  false       "开始时间 ，列如2021-03-06 "
// @Param   EndDate   query   string  false       "结束时间，列如2021-03-06 "
// @Success 200 {object} models.AddEnglishReportResp
// @router /yanxuan_special/list [get]
func (this *YanxuanSpecialController) 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
	}

	userId, _ := this.GetInt("UserId", 0)
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	status, _ := this.GetInt("Status", 1)
	specialType, _ := this.GetInt("Type")
	keyWord := this.GetString("KeyWord")
	//排序参数
	sortParam := this.GetString("SortParam")
	sortType := this.GetString("SortType")
	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")
	nickName := this.GetString("NickName")

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

	if userId > 0 {
		condition += ` AND a.user_id = ? `
		pars = append(pars, userId)
	}
	if status == 1 {
		condition += ` AND a.status = 2 `
	}
	if status == 2 {
		condition += ` AND a.status = 3 `
	}

	if startDate != "" {
		condition += ` AND a.publish_time >= ` + "'" + startDate + " 00:00:00'"
	}
	if endDate != "" {
		condition += ` AND a.publish_time <= ` + "'" + endDate + " 23:59:59'"
	}

	//文章类型
	if specialType == 1 || specialType == 2 {
		condition += ` AND a.type =  ? `
		pars = append(pars, specialType)
	}

	//关键词搜索
	if keyWord != "" {
		keyWord = "%" + keyWord + "%"
		condition += ` AND a.title like  ? `
		pars = append(pars, keyWord)
	}

	//昵称搜索
	if nickName != "" {
		nickName = "%" + nickName + "%"
		condition += ` AND b.nick_name like  ? `
		pars = append(pars, nickName)
	}

	//排序字段以及排序方式处理
	var sortStr string
	if sortParam != "" && sortType != "" {
		if sortParam == "pv" {
			if sortType == "asc" {
				sortStr = " ORDER BY a.pv ASC "
			} else {
				sortStr = " ORDER BY a.pv  DESC "
			}
		}
		if sortStr == "" {
			sortStr = " ORDER BY a.publish_time  DESC " // 兼容前端老六乱传字段
		}
	} else {
		sortStr = " ORDER BY a.publish_time  DESC "
	}

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

	list, tmpErr := cygx.GetYanxuanSpecialList(condition+sortStr, pars, startSize, pageSize)
	if tmpErr != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败, Err:" + tmpErr.Error()
		return
	}
	pars = make([]interface{}, 0)
	listAuthor, tmpErr := cygx.GetYanxuanSpecialAuthorList("", pars, 0, 999)
	if tmpErr != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败, Err:" + tmpErr.Error()
		return
	}

	mapUserId := make(map[int]int)
	for _, v := range listAuthor {
		mapUserId[v.UserId] = v.Id
	}

	for _, v := range list {
		v.SpecialAuthorId = mapUserId[v.UserId]
		hasImg, err := utils.ArticleHasImgUrl(v.Content)
		if err != nil {
			return
		}
		if hasImg {
			v.ContentHasImg = 1
		}
		if v.DocUrl != "" {
			var docs []cygx.Doc
			err := json.Unmarshal([]byte(v.DocUrl), &docs)
			if err != nil {
				br.Msg = "参数解析异常！"
				br.ErrMsg = "参数解析失败，Err:" + err.Error()
				return
			}
			v.Docs = docs
		}
		if v.CompanyTags != "" {
			v.Tags += v.CompanyTags
		}
		if v.IndustryTags != "" {
			if v.Tags != "" {
				v.Tags += ","
			}
			v.Tags += v.IndustryTags
		}
	}
	resp := new(cygx.GetCygxYanxuanSpeciaResplItemResp)
	page := paging.GetPaging(currentIndex, pageSize, total)

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

// @Title 审批研选专栏
// @Description 审批研选专栏
// @Param	request	body help_doc.AddHelpDocReq true "type json string"
// @Success 200 {object} models.AddEnglishReportResp
// @router /yanxuan_special/enable [post]
func (this *YanxuanSpecialController) Enable() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req cygx.EnableCygxYanxuanSpecialReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.Id <= 0 {
		br.Msg = "文章id错误"
		return
	}
	if req.Status <= 0 {
		br.Msg = "参数错误"
		return
	}
	status := 0
	if req.Status == 1 {
		status = 3
	} else {
		status = 4
	}
	if tmpErr := cygx.EnableYanxuanSpecial(req.Id, status, req.Reason, sysUser.RealName); tmpErr != nil {
		br.Msg = "审批失败"
		br.ErrMsg = "审批失败, Err:" + tmpErr.Error()
		return
	}
	if req.Status == 1 {
		go cygxService.SendWxMsgSpecialFollow(req.Id)
		go services.SendWxCategoryMsgSpecialFollow(req.Id)
	}
	go cygxService.SendWxMsgSpecialAuthor(req.Id, req.Status)      // 研选专栏审核完成时，给提交人发送模板消息
	go services.SendWxCategoryMsgSpecialAuthor(req.Id, req.Status) // 研选专栏审核完成时，给提交人发送模板消息
	go cygxService.UpdateYanxuanSpecialResourceData(req.Id)        //  写入首页最新  cygx_resource_data 表
	go elastic.EsAddYanxuanSpecial(req.Id)                         //  写入es 综合搜索
	br.Msg = "审批成功"
	br.Ret = 200
	br.Success = true
}

// @Title 收藏详情
// @Description 收藏详情
// @Param   SpecialId    query   int  true       "每页数据条数"
// @Success 200 {object} models.AddEnglishReportResp
// @router /yanxuan_special/special_collect/list [get]
func (this *YanxuanSpecialController) SpecialCollectList() {
	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
	}
	specialId, _ := this.GetInt("SpecialId")
	var condition string
	var pars []interface{}
	condition += " AND yanxuan_special_id = ?  	ORDER BY art.create_time DESC  "
	pars = append(pars, specialId)
	list, err := cygx.GetCygxYanxuanSpecialCollectList(condition, pars, 0, 100000)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	resp := new(cygx.GetCygxYanxuanSpecialCollectResp)
	resp.List = list
	br.Data = resp
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
}

// @Title  下载PV
// @Description 下载PV接口
// @Param   SpecialId    query   int  true       "每页数据条数"
// @router /yanxuan_special/list_pv [get]
func (this *YanxuanSpecialController) ListPv() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	specialId, _ := this.GetInt("SpecialId")
	if specialId < 1 {
		br.Msg = "请输入专栏ID"
		return
	}
	var condition string
	var pars []interface{}
	condition = ` AND yanxuan_special_id = ?   ORDER BY create_time DESC  `
	pars = append(pars, specialId)

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

	var companyIds []int
	for _, v := range list {
		companyIds = append(companyIds, v.CompanyId)
	}

	listCompanyProduct, err := company.GetCompanyProductListByCompanyIds(companyIds, 2)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取销售列表失败，Err:" + err.Error()
		return
	}
	mapsCompanyStatus := make(map[int]string)
	for _, v := range listCompanyProduct {
		mapsCompanyStatus[v.CompanyId] = v.Status
	}
	//创建excel
	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
	sheet, err := xlsxFile.AddSheet("阅读明细")
	if err != nil {
		br.Msg = "新增Sheet失败"
		br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
		return
	}
	rowTitle := sheet.AddRow()
	cellA := rowTitle.AddCell()
	cellA.Value = "姓名"
	cellMobile := rowTitle.AddCell()
	cellMobile.Value = "手机号"
	cellB := rowTitle.AddCell()
	cellB.Value = "公司名称"
	cellCompanyStatus := rowTitle.AddCell()
	cellCompanyStatus.Value = "客户状态"
	cellC := rowTitle.AddCell()
	cellC.Value = "所属权益销售"
	cellD := rowTitle.AddCell()
	cellD.Value = "阅读时间"
	cellE := rowTitle.AddCell()
	cellE.Value = "阅读时长"

	for _, item := range list {
		row := sheet.AddRow()
		cellA := row.AddCell()
		cellA.Value = item.RealName
		cellMobile := row.AddCell()
		cellMobile.Value = item.Mobile
		cellB := row.AddCell()
		cellB.Value = item.CompanyName
		cellCompanyStatus := row.AddCell()
		cellCompanyStatus.Value = mapsCompanyStatus[item.CompanyId]
		cellC := row.AddCell()
		cellC.Value = item.SellerName
		cellD := row.AddCell()
		cellD.Value = item.CreateTime
		cellE := row.AddCell()
		cellE.Value = strconv.Itoa(item.StopTime)
	}
	err = xlsxFile.Save(downLoadnFilePath)
	if err != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败"
		return
	}
	downloadFileName := time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
	defer func() {
		os.Remove(downLoadnFilePath)
	}()
	br.Ret = 200
	br.Success = true
	br.Msg = "导出成功"
}

// @Title 审批记录
// @Description 审批记录接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Success 200 {object} models.CygxYanxuanSpecialApprovalLogListResp
// @router /yanxuan_special/approval_log_list [get]
func (this *YanxuanSpecialController) ApprovalLogList() {
	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 = utils.StartIndex(currentIndex, pageSize)
	var condition string
	var pars []interface{}
	//只是查询驳回状态的数据
	condition += ` AND a.approval_status =  2 `
	total, err := cygx.GetCygxYanxuanSpecialApprovalLogCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	condition += ` ORDER BY  create_time DESC `
	list, tmpErr := cygx.GetCygxYanxuanSpecialApprovalLogList(condition, pars, startSize, pageSize)
	if tmpErr != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败, Err:" + tmpErr.Error()
		return
	}
	pars = make([]interface{}, 0)
	listAuthor, tmpErr := cygx.GetYanxuanSpecialAuthorList("", pars, 0, 999)
	if tmpErr != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败, Err:" + tmpErr.Error()
		return
	}
	mapUserId := make(map[int]int)
	for _, v := range listAuthor {
		mapUserId[v.UserId] = v.Id
	}

	for _, v := range list {
		v.SpecialAuthorId = mapUserId[v.UserId]
	}

	resp := new(cygx.CygxYanxuanSpecialApprovalLogListResp)
	page := paging.GetPaging(currentIndex, pageSize, total)

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

// @Title 按钮是否展示接口
// @Description 按钮是否展示接口
// @Success 200 {object} models.AddEnglishReportResp
// @router /yanxuan_special/show_button [get]
func (this *YanxuanSpecialController) ShowButton() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	resp := new(cygx.CygxYanxuanSpecialShowButton)
	//configCode := utils.TPL_MSG_NEI_RONG_ZU
	//cnfNeiRong, err := cygx.GetConfigByCode(configCode)
	//if err != nil {
	//	br.Msg = "获取失败"
	//	br.ErrMsg = "获取失败，Err:" + err.Error()
	//	return
	//}
	////汪洋王芳手机号
	//configCode = utils.TPL_MSG_WANG_FANG_WANG_YANG
	//cnfWang, err := cygx.GetConfigByCode(configCode)
	//if err != nil {
	//	br.Msg = "获取失败"
	//	br.ErrMsg = "获取失败，Err:" + err.Error()
	//	return
	//}

	//文章管理专栏是否可见
	cnfArticle, err := cygx.GetConfigByCode(utils.YANXUAN_SPECIAL_ARTICLE_BUTTON_MOBILE)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	articleMobileSlice := strings.Split(cnfArticle.ConfigValue, ",")
	if utils.InArrayByStr(articleMobileSlice, sysUser.Mobile) || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
		resp.IsShowYanXuanSpecial = true
	}

	//作者管理专栏是否可见
	cnfAuthor, err := cygx.GetConfigByCode(utils.YANXUAN_SPECIAL_AUTHOR_BUTTON_MOBILE)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	authorMobileSlice := strings.Split(cnfAuthor.ConfigValue, ",")
	if utils.InArrayByStr(authorMobileSlice, sysUser.Mobile) || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
		resp.IsShowSpecialAuthor = true
	}

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

// @Title 作者粉丝列表
// @Description 作者粉丝列表
// @Param   SpecialAuthorId    query   int  true       "作者ID"
// @Success 200 {object} models.AddEnglishReportResp
// @router /yanxuan_special/special_author_fans_list [get]
func (this *YanxuanSpecialController) SpecialAuthorFansList() {
	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
	}
	specialAuthorId, _ := this.GetInt("SpecialAuthorId")
	detail, err := cygx.GetCygxYanxuanSpecialAuthorItemById(specialAuthorId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	var condition string
	var pars []interface{}
	condition += " AND follow_user_id = ?  	ORDER BY a.create_time DESC  "
	pars = append(pars, detail.UserId)
	list, err := cygx.GetCygxYanxuanSpecialFollowList(condition, pars, 0, 100000)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	resp := new(cygx.GetCygxYanxuanSpecialFollowResp)
	resp.List = list
	br.Data = resp
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
}

func init_928() {
	var condition string
	var pars []interface{}
	list, err := cygx.GetYanxuanSpecialAuthorList(condition, pars, 0, 999)
	if err != nil {
		fmt.Println(err)
		return
	}

	for k, v := range list {
		fmt.Println(k)
		//获取关联公司的用户信息
		infoUser, err := cygx.GetUserAndCompanyNameList(v.UserId)
		if err != nil && err.Error() != utils.ErrNoRow() {
			fmt.Println(err)
			return
		}
		if infoUser == nil {
			continue
		}
		err = cygx.UpdateSpecialAuthormobile_init(infoUser.Mobile, infoUser.UserId)
		if err != nil {
			fmt.Println(err)
			return
		}
	}
	return
}

// @Title 修改作者信息
// @Description 修改作者信息接口
// @Param	request	body help_doc.AddHelpDocReq true "type json string"
// @router /yanxuan_special/author/update [post]
func (this *YanxuanSpecialController) AuthorUpdate() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req cygx.AddCygxYanxuanSpecialAuthorReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.UserId <= 0 {
		br.Msg = "请输入用户信息"
		return
	}
	err = cygx.UpdateYanxuanSpecialAuthorInviteName(req.InviteName, req.Remark, req.UserId)
	if err != nil {
		br.Msg = "新增失败"
		br.ErrMsg = "新增失败，Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "修改成功"
}

// @Title 作者列表
// @Description 作者列表
// @Param   KeyWord   query   string  false       "搜索关键词"
// @Success 200 {object} models.AddEnglishReportResp
// @router /yanxuan_special/author/search [get]
func (this *YanxuanSpecialController) AuthorSearch() {
	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
	}

	keyWord := this.GetString("KeyWord")
	var condition string
	var pars []interface{}
	resp := new(cygx.CygxYanxuanSpecialKeyWordListReesp)
	//关键词搜索
	if keyWord != "" {
		keyWord = "%" + keyWord + "%"
		condition += ` AND art.nick_name like  ? `
		pars = append(pars, keyWord)
		list, tmpErr := cygx.GetYanxuanSpecialAuthorList(condition, pars, 0, 99)
		if tmpErr != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败, Err:" + tmpErr.Error()
			return
		}
		if len(list) > 0 {
			for _, v := range list {
				item := new(cygx.CygxYanxuanSpecialKeyWordReesp)
				item.KeyWord = v.NickName
				resp.List = append(resp.List, item)
			}
		} else {
			resp.List = make([]*cygx.CygxYanxuanSpecialKeyWordReesp, 0)
		}
	} else {
		resp.List = make([]*cygx.CygxYanxuanSpecialKeyWordReesp, 0)
	}

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