package roadshow

import (
	"encoding/json"
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/roadshow"
	"hongze/hz_crm_api/utils"
	"strconv"
	"strings"
	"time"
)

//路演反馈

// @Title 路演反馈列表
// @Description 路演反馈列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   FeedbackType   query   int  true       "是否显示已发送反馈请求的路演，0:不显示(默认),1:显示"
// @Param   ResearcherId   query   string  true       "研究员id，多个用英文逗号隔开"
// @Success 200 {object} roadshow.FeedbackListResp
// @router /feedback/list [get]
func (this *CalendarController) FeedbackList() {
	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
	}

	feedbackType, _ := this.GetInt("FeedbackType")

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")

	researcherId := this.GetString("ResearcherId")
	var total int
	page := paging.GetPaging(currentIndex, pageSize, total)

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize10
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	var condition string
	var pars []interface{}

	condition += ` AND b.status = 2 `

	condition += ` AND a.activity_type = '路演' `

	condition += ` AND a.source = 0 `

	//结束日期小于当天
	endDate := time.Now().Format(utils.FormatDateTime)
	startDate := time.Now().AddDate(0, 0, -30).Format(utils.FormatDate)

	condition += ` AND b.end_date >= ? `
	pars = append(pars, startDate)

	condition += ` AND DATE_FORMAT(CONCAT(b.end_date," ",b.end_time),'%Y-%m-%d %H:%i:%S') <= ? `
	pars = append(pars, endDate)

	if feedbackType == 1 {
		condition += ` AND b.feedback_status IN(2,3)`
	}

	if researcherId != "" {
		condition += ` AND b.researcher_id IN(` + researcherId + `)`
	}

	resp := new(roadshow.FeedbackListResp)
	total, err := roadshow.GetFeedbackListCount(condition, pars)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取数据总数失败,GetFeedbackListCount,Err:" + err.Error()
		return
	}
	page = paging.GetPaging(currentIndex, pageSize, total)
	dataList, err := roadshow.GetFeedbackList(condition, pars, startSize, pageSize, feedbackType)
	if err != nil {
		br.Msg = "获取指标信息失败"
		br.ErrMsg = "获取数据失败,GetFeedbackList,Err:" + err.Error()
		return
	}
	var companyIdArr []string
	companyIdMap := make(map[string]string)
	for _, v := range dataList {
		if v.CompanyId > 0 {
			companyIdStr := strconv.Itoa(v.CompanyId)
			if companyIdStr != "" {
				if _, ok := companyIdMap[companyIdStr]; !ok {
					companyIdArr = append(companyIdArr, companyIdStr)
				}
				companyIdMap[companyIdStr] = companyIdStr
			}
		}
	}

	companyIdArrStr := strings.Join(companyIdArr, ",")

	var newCondition string
	var newPars []interface{}

	newCondition += ` AND product_id=1 `
	cp, err := company.GetCompanyProductsByCompanyIds(companyIdArrStr, newCondition, newPars)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取数据失败,GetCompanyProductsByCompanyIds,Err:" + err.Error()
		return
	}
	companyMap := make(map[int]string)
	for _, v := range cp {
		companyMap[v.CompanyId] = v.Status
	}
	dataListLen := len(dataList)
	for i := 0; i < dataListLen; i++ {
		companyId := dataList[i].CompanyId
		if findItem, ok := companyMap[companyId]; ok {
			dataList[i].CompanyStatus = findItem
		}
	}
	resp.Paging = page
	resp.List = dataList
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 请提交路演反馈列表
// @Description 请提交路演反馈列表接口
// @Success 200 {object} roadshow.FeedbackView
// @router /submit/feedback/list [get]
func (this *CalendarController) SubmitFeedbackList() {
	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 condition string
	var pars []interface{}

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

	condition += ` AND b.feedback_status = 2 `

	dataList, err := roadshow.GetSubmitFeedbackList(condition, pars)
	if err != nil {
		br.Msg = "获取指标信息失败"
		br.ErrMsg = "获取数据失败,GetFeedbackList,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = dataList
}

// @Title 填写意见反馈
// @Description 填写意见反馈接口
// @Param	request	body roadshow.WriteFeedbackReq true "type json string"
// @Success 200
// @router /write/feedback [post]
func (this *CalendarController) WriteFeedback() {
	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 roadshow.WriteFeedbackReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.RsCalendarResearcherId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "参数错误"
		return
	}
	if req.FeedbackContent == "" {
		br.Msg = "反馈内容不能为空"
		br.ErrMsg = "反馈内容不能为空"
		return
	}
	err = roadshow.WriteFeedback(&req)
	if err != nil {
		br.Msg = "保存反馈信息失败"
		br.ErrMsg = "保存反馈信息失败，Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "保存成功"
}

// @Title 提交路演反馈
// @Description 提交路演反馈接口
// @Param	request	body roadshow.SubmitFeedbackReq true "type json string"
// @Success 200 {object} roadshow.FeedbackView
// @router /submit/feedback [post]
func (this *CalendarController) SubmitFeedback() {
	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 roadshow.SubmitFeedbackReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	for _, v := range req.List {
		err = roadshow.SubmitFeedbackInfo(v.RsCalendarResearcherId)
		if err != nil {
			br.Msg = "保存失败！"
			br.ErrMsg = "保存失败，Err:" + err.Error()
			return
		}
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "保存成功"
}

// @Title 发送路演反馈请求
// @Description 发送路演反馈请求接口
// @Param	request	body roadshow.SubmitFeedbackReq true "type json string"
// @Success 200 {object} roadshow.FeedbackView
// @router /send/feedback [post]
func (this *CalendarController) SendFeedback() {
	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 roadshow.SubmitFeedbackReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	for _, v := range req.List {
		err = roadshow.SendFeedbackInfo(v.RsCalendarResearcherId)
		if err != nil {
			br.Msg = "保存失败！"
			br.ErrMsg = "保存失败，Err:" + err.Error()
			return
		}
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "保存成功"
}
