package yb

import (
	"encoding/json"
	"errors"
	"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/response"
	"hongze/hz_crm_api/services"
	"hongze/hz_crm_api/utils"
	"strconv"
	"strings"
	"time"
)

// GetRoadVideoList 路演视频列表
func GetRoadVideoList(condition string, pars []interface{}, orderStr string, startSize, pageSize int) (total int, resp *response.RoadVideoListResp, err error, errMsg string) {
	resp = new(response.RoadVideoListResp)
	total, list, e := yb.GetRoadVideoList(condition, pars, orderStr, startSize, pageSize)
	if e != nil {
		errMsg = "获取视频列表失败"
		err = errors.New("获取视频列表失败, Err:" + e.Error())
		return
	}
	if len(list) == 0 {
		return
	}
	allChartPermissionId := ""
	chartNameMap := make(map[string]string)
	reportIds := make([]int, 0)
	for _, v := range list {
		allChartPermissionId += v.ChartPermissionIds + ","
		if v.ReportId > 0 {
			reportIds = append(reportIds, v.ReportId)
		}
	}
	if allChartPermissionId != "" {
		allChartPermissionId = strings.Trim(allChartPermissionId, ",")
		chartPermissionIdSlice := strings.Split(allChartPermissionId, ",")
		chartList, e := models.GetChartPermissionByIds(chartPermissionIdSlice)
		if e != nil {
			errMsg = "品种信息有误"
			err = errors.New("获取品种信息失败, Err:" + e.Error())
			return
		}
		for _, v := range chartList {
			chartNameMap["'"+strconv.Itoa(v.ChartPermissionId)+"'"] = v.PermissionName
		}
	}

	// 视频绑定的报告标题
	reportTitleMap := make(map[int]string)
	if len(reportIds) > 0 {
		reportCond := ` AND id IN (` + utils.GetOrmInReplace(len(reportIds)) + `)`
		reportPars := make([]interface{}, 0)
		reportPars = append(reportPars, reportIds)
		fieldArr := []string{"id", "title"}
		reports, e := models.GetReportByCondition(reportCond, reportPars, fieldArr, "", false, 0, 0)
		if e != nil {
			errMsg = "获取失败"
			err = errors.New("获取视频绑定报告信息失败, Err:" + e.Error())
			return
		}
		for i := range reports {
			reportTitleMap[reports[i].Id] = reports[i].Title
		}
	}

	chartPermissionNames := ""
	chartPermissionIds := ""
	respList := make([]*response.RoadVideoItem, 0)
	for _, v := range list {
		chartPermissionNames = ""
		chartPermissionIds = ""
		if v.ChartPermissionIds != "" {
			tmpSlice := strings.Split(v.ChartPermissionIds, ",")
			if len(tmpSlice) > 0 {
				for _, cid := range tmpSlice {
					if name, ok := chartNameMap[cid]; ok {
						chartPermissionNames += name + ","
					}
					chartPermissionIds += strings.Trim(cid, "'") + ","
				}
			}
			if chartPermissionNames != "" {
				chartPermissionNames = strings.Trim(chartPermissionNames, ",")
			}
			if chartPermissionIds != "" {
				chartPermissionIds = strings.Trim(chartPermissionIds, ",")
			}
		}
		item := &response.RoadVideoItem{
			RoadVideoId:          v.RoadVideoId,
			Title:                v.Title,
			ChartPermissionIds:   chartPermissionIds,
			ChartPermissionNames: chartPermissionNames,
			CoverImgUrl:          v.CoverImgUrl,
			VideoUrl:             v.VideoUrl,
			VideoSeconds:         v.VideoSeconds,
			PublishState:         v.PublishState,
			SendThsState:         v.SendThsState,
			SendTemplateState:    v.SendTemplateState,
			AdminId:              v.AdminId,
			AdminRealName:        v.AdminRealName,
			CreateTime:           v.CreateTime.Format(utils.FormatDateTime),
			ModifyTime:           v.ModifyTime.Format(utils.FormatDateTime),
			ClickNum:             v.ClickNum,
			ReportId:             v.ReportId,
			ReportTitle:          reportTitleMap[v.ReportId],
		}
		respList = append(respList, item)
	}
	resp.List = respList
	return
}

// SaveRoadVideo 保存视频
func SaveRoadVideo(sysUser *system.Admin, videoId, reportId int, chartPermissionIds, title, coverImgUrl, videoUrl, videoSeconds string) (resp *response.RoadVideoItem, errMsg string, err error) {
	permissionStr := ""
	if chartPermissionIds != "" {
		chartPermissionIdSlice := strings.Split(chartPermissionIds, ",")
		chartList, e := models.GetChartPermissionByIds(chartPermissionIdSlice)
		if e != nil {
			errMsg = "品种信息有误"
			err = errors.New("获取品种信息失败, Err:" + e.Error())
			return
		}
		if len(chartPermissionIdSlice) != len(chartList) {
			errMsg = "品种信息有误"
			err = errors.New("获取品种信息失败")
			return
		}

		for _, v := range chartList {
			permissionStr += "'" + strconv.Itoa(v.ChartPermissionId) + "',"
		}
		if permissionStr != "" {
			permissionStr = strings.Trim(permissionStr, ",")
		}
	}
	resp = new(response.RoadVideoItem)
	// 更新
	nowTime := time.Now().Local()
	if videoId > 0 {
		item, e := yb.GetRoadVideoById(videoId)
		if e != nil {
			errMsg = "视频信息有误"
			err = errors.New("获取视频信息失败, Err:" + e.Error())
			return
		}
		updateCols := make([]string, 0)
		updateCols = append(updateCols, "Title", "ChartPermissionIds", "CoverImgUrl", "VideoUrl", "VideoSeconds", "ModifyTime", "ReportId")
		item.Title = title
		item.ChartPermissionIds = permissionStr
		item.CoverImgUrl = coverImgUrl
		item.VideoUrl = videoUrl
		item.VideoSeconds = videoSeconds
		item.ModifyTime = nowTime
		item.ReportId = reportId
		if e := item.Update(updateCols); e != nil {
			errMsg = "更新失败"
			err = errors.New("更新视频信息失败, Err:" + e.Error())
		}
		resp = formatRoadVideoItem(item)
		return
	}
	// 新增
	videoItem := &yb.RoadVideo{
		Title:              title,
		ChartPermissionIds: permissionStr,
		CoverImgUrl:        coverImgUrl,
		VideoUrl:           videoUrl,
		VideoSeconds:       videoSeconds,
		CreateTime:         nowTime,
		ModifyTime:         nowTime,
		AdminId:            sysUser.AdminId,
		AdminRealName:      sysUser.RealName,
		ReportId:           reportId,
	}
	if e := videoItem.Add(); e != nil {
		errMsg = "新增失败"
		err = errors.New("新增视频信息失败, Err:" + e.Error())
	}
	resp = formatRoadVideoItem(videoItem)
	return
}

func formatRoadVideoItem(item *yb.RoadVideo) (resp *response.RoadVideoItem) {
	//根据chartPermissionId，查询权限名称
	ChartPermissionNames := ""
	if item.ChartPermissionIds != "" {
		chartPermissionIdSlice := strings.Split(item.ChartPermissionIds, ",")
		chartList, e := models.GetChartPermissionByIds(chartPermissionIdSlice)
		if e == nil {
			for _, v := range chartList {
				ChartPermissionNames += v.ChartPermissionName + ","
			}
			if ChartPermissionNames != "" {
				ChartPermissionNames = strings.Trim(ChartPermissionNames, ",")
			}
		}
	}

	resp = new(response.RoadVideoItem)
	if item != nil {
		resp.RoadVideoId = item.RoadVideoId
		resp.Title = item.Title
		resp.ChartPermissionIds = item.ChartPermissionIds
		resp.ChartPermissionNames = ChartPermissionNames
		resp.CoverImgUrl = item.CoverImgUrl
		resp.VideoUrl = item.VideoUrl
		resp.VideoSeconds = item.VideoSeconds
		resp.PublishState = item.PublishState
		resp.SendThsState = item.SendThsState
		resp.SendTemplateState = item.SendTemplateState
		resp.AdminId = item.AdminId
		resp.AdminRealName = item.AdminRealName
		resp.CreateTime = item.CreateTime.Format(utils.FormatDateTime)
		resp.ModifyTime = item.ModifyTime.Format(utils.FormatDateTime)
		resp.ReportId = item.ReportId
	}
	return
}

// SoftDeleteRoadVideo 删除视频
func SoftDeleteRoadVideo(videoId int) (errMsg string, err error) {
	if _, e := yb.GetRoadVideoById(videoId); e != nil {
		errMsg = "视频信息有误"
		err = errors.New("获取视频信息失败, Err:" + e.Error())
		return
	}
	if e := yb.DeleteRoadVideo(videoId); e != nil {
		errMsg = "删除失败"
		err = errors.New("删除视频失败, Err:" + e.Error())
	}
	return
}

// PublishRoadVideo 发布/取消发布视频
func PublishRoadVideo(videoId, publishState int) (errMsg string, err error) {
	item, e := yb.GetRoadVideoById(videoId)
	if e != nil {
		errMsg = "视频信息有误"
		err = errors.New("获取视频信息失败, Err:" + e.Error())
		return
	}
	nowTime := time.Now().Local()
	updateCols := make([]string, 0)
	updateCols = append(updateCols, "PublishState", "ModifyTime")
	if publishState == 1 {
		updateCols = append(updateCols, "PublishTime")
		item.PublishTime = nowTime
	}
	item.PublishState = publishState
	item.ModifyTime = nowTime
	if e := item.Update(updateCols); e != nil {
		errMsg = "操作失败"
		err = errors.New("更新视频信息失败, Err:" + e.Error())
	}
	return
}

// SendRoadVideoThsMsg 推送视频客群消息
func SendRoadVideoThsMsg(videoId int) (errMsg string, err error) {
	item, e := yb.GetRoadVideoById(videoId)
	if e != nil {
		errMsg = "视频信息有误"
		err = errors.New("获取视频信息失败, Err:" + e.Error())
		return
	}
	if item.PublishState != 1 {
		errMsg = "视频未发布, 不可推送"
		err = errors.New("视频未发布, 不可推送")
		return
	}
	if item.SendThsState != 0 {
		errMsg = "请勿重复推送"
		err = errors.New("请勿重复推送客群消息")
		return
	}
	nowTime := time.Now().Local()
	updateCols := make([]string, 0)
	updateCols = append(updateCols, "SendThsState", "SendThsTime")
	item.SendThsState = 1
	item.SendThsTime = nowTime
	if e := item.Update(updateCols); e != nil {
		err = errors.New("更新视频信息失败, Err:" + e.Error())
	}
	//go func() {
	//	_ = services.SendYbRoadVideoThs(item.RoadVideoId, item.Title, item.ChartPermissionIds)
	//}()
	return
}

// SendRoadVideoTemplateMsg 推送模板消息
func SendRoadVideoTemplateMsg(videoId int) (errMsg string, err error) {
	item, e := yb.GetRoadVideoById(videoId)
	if e != nil {
		errMsg = "视频信息有误"
		err = errors.New("获取视频信息失败, Err:" + e.Error())
		return
	}
	if item.PublishState != 1 {
		errMsg = "视频未发布, 不可推送"
		err = errors.New("视频未发布, 不可推送")
		return
	}
	if item.SendTemplateState != 0 {
		errMsg = "请勿重复推送"
		err = errors.New("请勿重复推送模板消息")
		return
	}
	updateCols := make([]string, 0)
	updateCols = append(updateCols, "SendTemplateState", "SendTemplateTime")
	item.SendTemplateState = 1
	item.SendTemplateTime = time.Now().Local()
	if e := item.Update(updateCols); e != nil {
		err = errors.New("更新视频信息失败, Err:" + e.Error())
	}
	go func() {
		_ = services.SendYbRoadVideoWxMsg(item.RoadVideoId, item.Title, item.PublishTime.Format(utils.FormatDateTime), item.ChartPermissionIds)
	}()
	return
}

func GetFiccPermission() (ret response.RoadPermissionResp, err error) {
	permissionList, err := models.GetFiccPermissionExceptTactic()
	if err != nil {
		return
	}
	permissionFirstMap := make(map[int]*response.RoadPermissionItem)

	/*//查询首页展示的图标
	permissionFirstList, err := models.GetYbChartPermissionFirst()
	if err != nil {
		return
	}*/
	permissionFirstList := make([]*response.RoadPermissionItem, 0)
	for _, v := range permissionList {
		if v.ParentId == 0 {
			tmp := &response.RoadPermissionItem{
				Id:           v.ChartPermissionId,
				ClassifyName: v.PermissionName,
			}
			permissionFirstMap[v.ChartPermissionId] = tmp
			permissionFirstList = append(permissionFirstList, tmp)
		}
	}

	for _, v := range permissionList {
		if v.ParentId > 0 {
			temp := new(response.RoadPermissionSecondItem)
			temp.ChartPermissionID = v.ChartPermissionId
			temp.ChartPermissionName = v.PermissionName
			if _, ok := permissionFirstMap[v.ParentId]; ok {
				permissionFirstMap[v.ParentId].List = append(permissionFirstMap[v.ParentId].List, temp)
			}
		}
	}

	var list []*response.RoadPermissionItem
	for _, v := range permissionFirstList {
		temp := new(response.RoadPermissionItem)
		temp.Id = v.Id
		temp.ClassifyName = v.ClassifyName
		l, ok := permissionFirstMap[v.Id]
		if ok {
			temp.List = l.List
		}
		list = append(list, temp)
	}
	ret.List = list
	return
}

// GetVideoRelationReportClassifyId 获取视频关联报告的一级分类ID列表
func GetVideoRelationReportClassifyId() (classifyIdList []int, err error) {
	// 别问为啥要从配置里拿=_=!
	confKey := "video_relation_report_classify_id"
	conf, e := company.GetConfigDetailByCode(confKey)
	if e != nil {
		err = errors.New("获取双周报分类列表失败, Err: " + e.Error())
		return
	}
	if conf.ConfigValue == "" {
		err = errors.New("双周报ID配置有误")
		return
	}
	type TwoWeekIdConf struct {
		Debug   []int
		Release []int
	}
	classifyIdConf := new(TwoWeekIdConf)
	if e = json.Unmarshal([]byte(conf.ConfigValue), &classifyIdConf); e != nil {
		err = errors.New("解析双周报ID配置失败, Err: " + e.Error())
		return
	}
	if utils.RunMode == "debug" {
		classifyIdList = classifyIdConf.Debug
	} else {
		classifyIdList = classifyIdConf.Release
	}
	return
}
