package controllers

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

// CompanyServiceRecordController 客户-沟通记录
type CompanyServiceRecordController struct {
	BaseAuthController
}

// ServiceRecordList
// @Title 沟通记录列表
// @Description 沟通记录列表
// @Param   CompanyId  query  int  true  "客户ID"
// @Param   CompanyType  query  int  true  "客户类型，0：中文客户，1：英文客户"
// @Success Ret=200 获取成功
// @router /service_record/list [get]
func (this *CompanyServiceRecordController) ServiceRecordList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录, SysUser Is Empty"
		br.Ret = 408
		return
	}
	companyId, _ := this.GetInt("CompanyId", 0)
	if companyId <= 0 {
		br.Msg = "参数有误"
		return
	}
	companyType, _ := this.GetInt("CompanyType", 2)

	recordOB := new(company.CompanyServiceRecord)
	recordCond := fmt.Sprintf(` AND %s = ? AND company_type = ? `, company.CompanyServiceRecordColumns.CompanyId)
	recordPars := make([]interface{}, 0)
	recordPars = append(recordPars, companyId, companyType)
	records, e := recordOB.GetItemsByCondition(recordCond, recordPars, []string{}, "")
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取客户沟通记录失败, Err: " + e.Error()
		return
	}
	respList := make([]*company.CompanyServiceRecordItem, 0)
	for _, r := range records {
		respList = append(respList, &company.CompanyServiceRecordItem{
			CompanyServiceRecordId: r.CompanyServiceRecordId,
			Content:                r.Content,
			SysAdminId:             r.SysAdminId,
			SysAdminName:           r.SysAdminName,
			CreateTime:             r.CreateTime.Format(utils.FormatDateTime),
			Mark:                   r.Mark,
		})
	}

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

// ServiceRecordAdd
// @Title 新增沟通记录
// @Description 新增沟通记录
// @Param	request	body company.CompanyServiceRecordAddReq true "type json string"
// @Success Ret=200 操作成功
// @router /service_record/add [post]
func (this *CompanyServiceRecordController) ServiceRecordAdd() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		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.CompanyServiceRecordAddReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + e.Error()
		return
	}
	if req.CompanyId <= 0 {
		br.Msg = "参数有误"
		return
	}
	req.Content = strings.TrimSpace(req.Content)
	if req.Content == "" {
		br.Msg = "请输入沟通描述"
		return
	}
	//if len([]rune(req.Content)) > 100 {
	//	br.Msg = "沟通描述不可超过100个字符"
	//	return
	//}

	// 默认中文客户
	if req.CompanyType == 0 {
		req.CompanyType = 2
	}

	item := new(company.CompanyServiceRecord)
	item.CompanyType = req.CompanyType
	item.CompanyId = req.CompanyId
	item.Content = req.Content
	item.SysAdminId = sysUser.AdminId
	item.SysAdminName = sysUser.RealName
	item.CreateTime = time.Now().Local()
	item.ModifyTime = time.Now().Local()

	newId, e := item.Create()
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "新增沟通记录失败, Err: " + e.Error()
		return
	}

	//权益客户新增历史备注总表
	if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
		itemRecord := new(company.CompanyHistoryRemark)
		itemRecord.CompanyId = req.CompanyId
		itemRecord.Content = req.Content
		itemRecord.SysAdminId = sysUser.AdminId
		itemRecord.SysAdminName = sysUser.RealName
		itemRecord.CreateTime = time.Now().Local()
		itemRecord.ModifyTime = time.Now().Local()
		itemRecord.ShowTime = time.Now().Local()
		itemRecord.ProductId = 2
		itemRecord.TableName = "company_service_record"
		itemRecord.TableId = newId
		go services.AddCompanyHistoryRemark(itemRecord)
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// ServiceRecordDel
// @Title 删除沟通记录
// @Description 删除沟通记录
// @Param	request	body company.CompanyServiceRecordDelReq true "type json string"
// @Success Ret=200 操作成功
// @router /service_record/del [post]
func (this *CompanyServiceRecordController) ServiceRecordDel() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		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.CompanyServiceRecordDelReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + e.Error()
		return
	}
	if req.CompanyServiceRecordId <= 0 {
		br.Msg = "参数有误"
		return
	}

	item := new(company.CompanyServiceRecord)
	if e := item.GetItemById(req.CompanyServiceRecordId); e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "沟通记录已被删除, 请刷新页面"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "获取沟通记录失败, Err: " + e.Error()
		return
	}
	if e := item.Del(); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "删除沟通记录失败, Err: " + e.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}
