package cygx

import (
	"encoding/json"
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hz_crm_api/controllers"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/cygx"
	"hongze/hz_crm_api/services"
	cygxService "hongze/hz_crm_api/services/cygx"
	"hongze/hz_crm_api/utils"
	"strconv"
)

// 权益小程序
type ApplyRecordController struct {
	controllers.BaseAuthController
}

// @Title 权益申请记录列表
// @Description权益申请记录接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   KeyWord   query   string  true       "搜索关键词"
// @Param   CustomType   query   int  true       "用户类型1：潜在用户，2：现有客户"
// @Success 200 {object} cygx.CygxApplyRecordListResp
// @router /apply/record/list [get]
func (this *ApplyRecordController) ListSysRole() {
	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"
		return
	}
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	keyWord := this.GetString("KeyWord")

	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 keyWord != "" {
		//condition += ` AND (b.seller_name LIKE '%` + keyWord + `%' OR a.mobile LIKE '%` + keyWord + `%' OR c.email LIKE '%` + keyWord + `%' )  `
		condition += ` AND a.mobile LIKE '%` + keyWord + `%'  `
	}

	customType, _ := this.GetInt("CustomType")
	if customType > 0 {
		if customType == 1 {
			condition += ` AND a.company_id_type=1  `
		} else if customType == 3 {
			condition += ` AND a.company_id_type = 3  `
		} else {
			condition += ` AND a.company_id_type NOT IN (1,3) `
		}
	}

	//权益申请销售只能看到自己名下的客户的申请 查研观向11.1
	companyIds, err := cygxService.GetAdminLookUserCompanyIdsBySelf(sysUser)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，GetAdminLookUserCompanyIds Err:" + err.Error()
		return
	}
	lencompanyIds := len(companyIds)
	if lencompanyIds > 0 {
		condition += ` AND a.company_id_pay  IN (` + utils.GetOrmInReplace(lencompanyIds) + `)`
		pars = append(pars, companyIds)
	}

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

	list, err := cygx.GetCygxApplyRecord(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	var sellerCompanyIds []int
	var microvideoIds []int
	var userIds []int
	for _, v := range list {
		if v.Source == "roadshow" {
			microvideoIds = append(microvideoIds, v.SourceId)
		}
		sellerCompanyIds = append(sellerCompanyIds, v.CompanyIdPay)
		userIds = append(userIds, v.UserId)
	}
	sellNameMap := services.GetSellNameMapByCompanyIds(sellerCompanyIds)
	lenmicrovideoIds := len(microvideoIds)
	mapmicrovideoChartPermissionId := make(map[int]int) //产业视频ID所对应的行业ID
	mapmicrovideoIndustryId := make(map[int]int)        //产业视频ID所对应的行业ID
	if lenmicrovideoIds > 0 {
		var conditionmicrovideo string
		var parsmicrovideo []interface{}
		conditionmicrovideo = ` AND video_id IN (` + utils.GetOrmInReplace(lenmicrovideoIds) + `)`
		parsmicrovideo = append(parsmicrovideo, microvideoIds)
		listmicrovideo, err := cygx.GetMicroRoadshowVideoList(conditionmicrovideo, "", parsmicrovideo, 0, lenmicrovideoIds)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取数据失败，Err:" + err.Error()
			return
		}
		for _, v := range listmicrovideo {
			mapmicrovideoChartPermissionId[v.VideoId] = v.ChartPermissionId
			mapmicrovideoIndustryId[v.VideoId] = v.IndustryId
		}
	}

	//处理用户的邮箱
	mapUserEmail := make(map[int]string) //用户UserId所对应的邮箱
	lenUserId := len(userIds)
	if lenUserId > 0 {
		userList, err := models.GetWxUserByUserIds(userIds)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取数据失败，Err:" + err.Error()
			return
		}

		for _, v := range userList {
			mapUserEmail[int(v.UserId)] = v.Email
		}
	}

	for i, v := range list {
		v.Email = mapUserEmail[v.UserId]
		if list[i].SellerName == "/" {
			list[i].SellerName = ""
		}
		if v.InviteeCompanyNum == 1 {
			list[i].IsInviteeComanyExistence = true
		}
		if v.InviteeMobile == "" && v.InviteeEmail != "" {
			list[i].InviteeMobile = v.InviteeEmail
		}
		if v.InviteeCompany != "" {
			list[i].ApplySource = "免费送月卡"
		}
		list[i].SellerName = sellNameMap[v.CompanyIdPay]
		//用户状态，1：潜在客户 、2：现有客户 、3：FICC客户 、4：现有客户（正式，无对应权限） 、5：现有客户（试用，无对应权限）  、6：现有客户（试用暂停） 、7：现有客户（冻结） 、8：现有客户（流失）
		switch v.CompanyIdType {
		case 1:
			list[i].CompanyIdTypeName = "潜在客户"
		case 2:
			list[i].CompanyIdTypeName = "现有客户"
		case 3:
			list[i].CompanyIdTypeName = "FICC客户"
		case 4:
			list[i].CompanyIdTypeName = "现有客户（正式，无对应权限） "
		case 5:
			list[i].CompanyIdTypeName = "现有客户（试用，无对应权限）"
		case 6:
			list[i].CompanyIdTypeName = "现有客户（试用暂停）"
		case 7:
			list[i].CompanyIdTypeName = "现有客户（冻结）"
		case 8:
			list[i].CompanyIdTypeName = "现有客户（流失）"
		case 9:
			list[i].CompanyIdTypeName = "永续客户"
		}

		switch v.RegisterPlatform {
		case 1:
			list[i].ApplicationSource = "查研小程序"
		case 2:
			list[i].ApplicationSource = "网页版"
		case 5:
			list[i].ApplicationSource = "研选小程序"
		case 6:
			list[i].ApplicationSource = "买方研选网页版"
		}

		switch v.InviteCompanySource {
		case 2:
			list[i].ApplicationSource += "(络町)"
		}

		switch v.Source {
		case "article": //文章详情
			list[i].HttpUrl = utils.CYGX_WEB_URL + "/material/info/" + strconv.Itoa(v.SourceId)
		case "activity": //活动详情
			list[i].HttpUrl = utils.CYGX_WEB_URL + "/activity/detail/" + strconv.Itoa(v.SourceId)
		case "activityvoice": //活动音频详情
			list[i].HttpUrl = utils.CYGX_WEB_URL + "/activity/detail/" + strconv.Itoa(v.SourceId)
		case "activityvideo": //活动视频详情
			list[i].HttpUrl = utils.CYGX_WEB_URL + "/activity/detail/" + strconv.Itoa(v.SourceId)
		case "productinterior": //产品内测
			list[i].HttpUrl = utils.CYGX_WEB_URL + "/internal/article/" + strconv.Itoa(v.SourceId)
		case "roadshow": //产业视频
			list[i].HttpUrl = utils.CYGX_WEB_URL + "/indepth/info/" + strconv.Itoa(mapmicrovideoChartPermissionId[v.SourceId]) + "/" + strconv.Itoa(mapmicrovideoIndustryId[v.SourceId])
		case "researchsummary": //本周研究汇总
			list[i].HttpUrl = utils.CYGX_WEB_URL + "/summary/2/" + strconv.Itoa(v.SourceId)
		case "minutessummary": //上周纪要汇总
			list[i].HttpUrl = utils.CYGX_WEB_URL + "/summary/1/" + strconv.Itoa(v.SourceId)
		case "reportselection": //报告精选（重点公司）
			list[i].HttpUrl = utils.CYGX_WEB_URL + "/recent/" + strconv.Itoa(v.SourceId)
		case "yanxuanspecial": //研选专栏
			list[i].HttpUrl = utils.CYGX_WEB_URL + "/column/detail/" + strconv.Itoa(v.SourceId)
		}
	}

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

// @Title 处理
// @Description 处理接口
// @Param	request	body  cygx.CygxDealReq true "type json string"
// @Success 200 删除成功
// @router /apply/record/deal [post]
func (this *ApplyRecordController) Delete() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req cygx.CygxDealReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ApplyRecordId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "参数错误,ApplyRecordId 小于等于0 "
		return
	}
	err = cygx.DealCygxApplyRecord(req.ApplyRecordId, this.SysUser.AdminId)
	if err != nil {
		br.Msg = "处理失败"
		br.ErrMsg = "处理失败，Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "处理成功"
}
