package controllers

import (
	"encoding/json"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/utils"
	"strings"
	"time"
)

// 客户审批消息管理
type CompanyApprovalMessageController struct {
	BaseAuthController
}

// @Title 待办消息列表
// @Description 待办消息列表接口
// @Success 200 {object} company.CompanyApprovalMessageListResp
// @router /message/list [get]
func (this *CompanyApprovalMessageController) SearchList() {
	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
	}
	sysUserId := sysUser.AdminId
	var startTime string
	if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER {
		startTime = time.Now().AddDate(0, -1, 0).Format(utils.FormatDateTime)
	}

	list, err := company.GetCompanyApprovalMessageList(sysUserId, startTime)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	total, err := company.GetCompanyApprovalMessageCount(sysUserId, startTime)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	resp := new(company.CompanyApprovalMessageListResp)
	resp.List = list
	resp.Total = total
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 待办消息列表（V2版本）
// @Description 待办消息列表接口（V2版本）
// @Success 200 {object} company.CompanyApprovalMessageListResp
// @router /message/listV2 [get]
func (this *CompanyApprovalMessageController) MessageList() {
	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
	}
	sysUserId := sysUser.AdminId
	var startTime string
	if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER {
		startTime = time.Now().AddDate(0, -1, 0).Format(utils.FormatDateTime)
	}

	list, err := company.GetCompanyApprovalMessageList(sysUserId, startTime)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	//超管，管理员消息
	if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN {
		startTime = time.Now().AddDate(0, -1, 0).Format(utils.FormatDateTime)
		adminList, err := company.GetAdminCompanyApprovalMessageList(startTime)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}

		list = append(list, adminList...)
	}

	companyMessageList := make([]*company.CompanyApprovalMessageList, 0)
	contractMessageList := make([]*company.CompanyApprovalMessageList, 0)
	sealMessageList := make([]*company.CompanyApprovalMessageList, 0)
	edbReplaceMessageList := make([]*company.CompanyApprovalMessageList, 0)
	etaTrialMessageList := make([]*company.ETATrialApprovalMessageList, 0)
	businessTripList := make([]*company.CompanyApprovalMessageList, 0)

	for i := 0; i < len(list); i++ {
		//if list[i].SourceType == 1
		switch list[i].SourceType {
		case 1:
			companyMessageList = append(companyMessageList, list[i])
		case 2:
			contractMessageList = append(contractMessageList, list[i])
		case 3:
			sealMessageList = append(sealMessageList, list[i])
			//case 4:
			//	edbReplaceMessageList = append(edbReplaceMessageList, list[i])
		case 9:
			item := company.ETATrialApprovalMessageList{
				Id:            list[i].Id,
				MessageStatus: list[i].MessageStatus,
				SourceType:    list[i].SourceType,
				Remark:        list[i].Remark,
				Content:       list[i].Content,
				CompanyName:   list[i].CompanyName,
				CreateTime:    list[i].CreateTime,
				RealName:      list[i].RealName,
			}
			if strings.Contains(item.Remark, "通过") {
				item.Redirect = 1
			} else {
				item.Redirect = 2
			}
			etaTrialMessageList = append(etaTrialMessageList, &item)
		case 10:
			businessTripList = append(businessTripList, list[i])
		}
	}
	companyMessageResp := company.CompanyApprovalMessageListResp{
		List:  companyMessageList,
		Total: len(companyMessageList),
	}
	contractMessageResp := company.CompanyApprovalMessageListResp{
		List:  contractMessageList,
		Total: len(contractMessageList),
	}
	sealMessageResp := company.CompanyApprovalMessageListResp{
		List:  sealMessageList,
		Total: len(sealMessageList),
	}

	edbReplaceMessageResp := company.CompanyApprovalMessageListResp{
		List:  edbReplaceMessageList,
		Total: len(edbReplaceMessageList),
	}

	etaTrialMessageResp := company.ETATrialApprovalMessageListResp{
		List:  etaTrialMessageList,
		Total: len(etaTrialMessageList),
	}

	businessTripResp := company.CompanyApprovalMessageListResp{
		List:  businessTripList,
		Total: len(businessTripList),
	}

	resp := company.CompanyApprovalMessageListV2Resp{
		Company:      companyMessageResp,
		Contract:     contractMessageResp,
		Seal:         sealMessageResp,
		EdbReplace:   edbReplaceMessageResp,
		ETATrial:     etaTrialMessageResp,
		BusinessTrip: businessTripResp,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 消息已读
// @Description 消息已读接口
// @Param	request	body company.CompanyApprovalMessageReadReq true "type json string"
// @Success Ret=200 申请成功
// @router /message/read [post]
func (this *CompanyApprovalMessageController) MessageRead() {
	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 company.CompanyApprovalMessageReadReq
	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 = "参数错误"
		br.ErrMsg = "参数错误，客户id小于等于0"
		return
	}
	item, e := company.GetCompanyApprovalMessageById(req.Id)
	if e != nil {
		if e.Error() != utils.ErrNoRow() {
			br.Msg = "消息已被删除, 请刷新页面"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "获取消息失败, Err: " + e.Error()
		return
	}

	// 如果是ETA试用消息且为普通销售, 已读其中一条那么所有该接收者的ETA试用消息均变为已读
	if item.SourceType == 9 && (sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER) {
		cond := ` AND receive_user_id = ? AND source_type = ? AND message_status = ?`
		pars := make([]interface{}, 0)
		pars = append(pars, sysUser.AdminId, 9, 0)
		if e := company.ModifyCompanyApprovalMessageStatusByCond(cond, pars); e != nil {
			br.Msg = "操作失败"
			br.ErrMsg = "更新销售ETA试用消息已读状态失败, Err: " + e.Error()
			return
		}
	} else {
		err = company.ModifyCompanyApprovalMessageStatus(req.Id)
		if err != nil {
			br.Msg = "修改失败！"
			br.ErrMsg = "修改已读失败，Err:" + err.Error()
			return
		}
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "已读成功"
}
