package controllers

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

//公司未续约操作

type CompanyRenewalController struct {
	BaseAuthController
}

// @Title 新建归因
// @Description 新建归因接口
// @Param	request	body company.CompanyAscribeAddReq true "type json string"
// @Success 200 {object} "保存成功"
// @router /company_ascribe/add [post]
func (this *CompanyRenewalController) CompanyAscribeAdd() {
	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.CompanyAscribeAddReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	ascribeContent := req.AscribeContent
	var condition string
	var pars []interface{}
	condition += " AND ascribe_content = ? "
	pars = append(pars, ascribeContent)
	total, err := company.GetCompanyAscribeCount(condition, pars)
	if err != nil {
		br.Msg = "新建失败"
		br.ErrMsg = "获取失败，GetCompanyAscribeCount Err:" + err.Error()
		return
	}
	if total > 0 {
		br.Msg = "此归因已存在"
		return
	}
	item := new(company.CompanyAscribe)
	item.AscribeContent = ascribeContent
	item.AdminId = sysUser.AdminId
	item.CreateTime = time.Now()
	item.ModifyTime = time.Now()
	newId, err := company.AddCompanyAscribe(item)
	if err != nil {
		br.Msg = "新建失败"
		br.ErrMsg = "新建失败，Err:" + err.Error()
		return
	}
	detail := new(company.CompanyAscribeResp)
	detail.CompanyAscribeId = int(newId)
	detail.AscribeContent = ascribeContent
	resp := new(company.CompanyAscribeDetailResp)
	resp.Detail = detail
	br.Ret = 200
	br.Success = true
	br.Data = resp
	br.Msg = "新建成功"
}

// @Title 归因列表接口
// @Description 归因列表接口
// @Param   KeyWord   query   string  true       "搜索关键词"
// @Success 200 {object} company.CompanyAscribeListResp
// @router /company_ascribe/list [get]
func (this *CompanyRenewalController) CompanyAscribeList() {
	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
	}
	keyWord := this.GetString("KeyWord")
	var condition string
	var pars []interface{}
	if keyWord != "" {
		condition += ` AND  ascribe_content LIKE '%` + keyWord + `%'  ORDER  BY  create_time DESC   `
	}
	list, err := company.GetCompanyAscribeList(condition, pars, 0, 0)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	resp := new(company.CompanyAscribeListResp)
	if len(list) == 0 {
		list = make([]*company.CompanyAscribeResp, 0)
	}
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 添加未续约备注
// @Description 添加未续约备注接口
// @Param	request	body company.CompanyNoRenewedNoteReq true "type json string"
// @Success 200 {object} "保存成功"
// @router /company_no_renewed_note/add [post]
func (this *CompanyRenewalController) CompanyNoRenewedNoteAdd() {
	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.CompanyNoRenewedNoteReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	content := req.Content
	companyId := req.CompanyId
	productId := req.ProductId
	if companyId < 1 {
		br.Msg = "公司ID错误！"
		return
	}
	if productId != 1 && productId != 2 {
		br.Msg = "ProductId错误！"
		return
	}
	item := new(company.CompanyNoRenewedNote)
	item.Content = content
	item.CompanyId = companyId
	item.AdminId = sysUser.AdminId
	item.ProductId = productId
	item.CreateTime = time.Now()
	item.ModifyTime = time.Now()
	var newId int64
	newId, err = company.AddCompanyNoRenewedNote(item)
	if err != nil {
		br.Msg = "新建失败"
		br.ErrMsg = "新建失败，Err:" + err.Error()
		return
	}

	if productId == utils.COMPANY_PRODUCT_RAI_ID {
		//权益客户新增历史备注总表
		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_no_renewed_note"
		itemRecord.TableId = int(newId)
		go services.AddCompanyHistoryRemark(itemRecord)
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "新建成功"
}

// @Title 未续约备注列表
// @Description 未续约备注列表接口
// @Param   CompanyId   query   int  true       "公司ID"
// @Param   ProductId   query   int  true       "产品ID 1：FICC ，2：权益"
// @Success 200 {object} company.CompanyAscribeListResp
// @router /company_no_renewed_note/list [get]
func (this *CompanyRenewalController) CompanyNoRenewedNoteList() {
	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
	}
	companyId, _ := this.GetInt("CompanyId")
	productId, _ := this.GetInt("ProductId")
	if companyId < 1 {
		br.Msg = "公司ID错误！"
		return
	}
	if productId != 1 && productId != 2 {
		br.Msg = "ProductId错误！"
		return
	}
	var condition string
	var pars []interface{}
	condition += ` AND  company_id  = ?  AND product_id = ?  ORDER  BY  create_time DESC   `
	pars = append(pars, companyId, productId)
	list, err := company.GetCompanyNoRenewedNoteList(condition, pars, 0, 0)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	resp := new(company.CompanyNoRenewedNoteListResp)
	if len(list) == 0 {
		list = make([]*company.CompanyNoRenewedNoteResp, 0)
	}
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 通过归因添加确认不续约
// @Description 通过归因添加确认不续约接口
// @Param	request	body company.CompanyNoRenewedNoteReq true "type json string"
// @Success 200 {object} "保存成功"
// @router /company_no_renewed_ascribe/add [post]
func (this *CompanyRenewalController) CompanyNoRenewedAscribeAdd() {
	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
	}

	//内容仅权益管理员账号可以修改
	if sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_ADMIN && sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_RAI_ADMIN {
		br.Msg = "仅管理员可修改！"
		return
	}
	var req company.CompanyNoRenewedAscribeReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	content := req.Content
	companyId := req.CompanyId
	productId := req.ProductId
	companyAscribeId := req.CompanyAscribeId

	if content == "" {
		br.Msg = "内容不能为空！"
		return
	}
	if companyId < 1 {
		br.Msg = "公司ID错误！"
		return
	}
	if productId != 1 && productId != 2 {
		if companyId < 1 {
			br.Msg = "ProductId错误！"
			return
		}
	}
	detail, err := company.GetCompanyAscribeDetail(companyAscribeId)
	if err != nil {
		br.Msg = "新建失败"
		br.ErrMsg = "新建失败，GetCompanyAscribeDetail Err:" + err.Error()
		return
	}
	var condition string
	var pars []interface{}
	condition += ` AND  company_id  = ?  AND product_id = ?  ORDER  BY  create_time DESC   `
	pars = append(pars, companyId, productId)

	total, err := company.GetCompanyNoRenewedAscribeCount(condition, pars)
	if err != nil {
		br.Msg = "新建失败"
		br.ErrMsg = "新建失败，GetCompanyNoRenewedAscribeCount Err:" + err.Error()
		return
	}
	item := new(company.CompanyNoRenewedAscribe)
	item.CompanyAscribeId = companyAscribeId
	item.AscribeContent = detail.AscribeContent
	item.Content = content
	item.ProductId = productId
	item.CompanyId = companyId
	item.AdminId = sysUser.AdminId
	item.CreateTime = time.Now()
	item.ModifyTime = time.Now()

	itemLog := new(company.CompanyNoRenewedAscribeLog)
	itemLog.CompanyAscribeId = companyAscribeId
	itemLog.AscribeContent = detail.AscribeContent
	itemLog.Content = content
	itemLog.ProductId = productId
	itemLog.CompanyId = companyId
	itemLog.AdminId = sysUser.AdminId
	itemLog.CreateTime = time.Now()
	itemLog.ModifyTime = time.Now()
	if total == 0 {
		err = company.AddCompanyNoRenewedAscribe(item, itemLog)
	} else {
		err = company.UpdateCompanyNoRenewedAscribe(item, itemLog)
	}
	if err != nil {
		br.Msg = "新建失败"
		br.ErrMsg = "新建失败，Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "新建成功"
}

// @Title 确认归因不续约详情接口
// @Description 确认归因不续约详情接口
// @Param   CompanyId   query   int  true       "公司ID"
// @Param   ProductId   query   int  true       "产品ID 1：FICC ，2：权益"
// @Success 200 {object} company.CompanyAscribeListResp
// @router /company_no_renewed_ascribe/detail [get]
func (this *CompanyRenewalController) CompanyNoRenewedAscribeAddDetail() {
	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
	}
	companyId, _ := this.GetInt("CompanyId")
	productId, _ := this.GetInt("ProductId")
	if companyId < 1 {
		br.Msg = "公司ID错误！"
		return
	}
	if productId != 1 && productId != 2 {
		br.Msg = "ProductId错误！"
		return
	}
	resp := new(company.CompanyNoRenewedAscribeDetailResp)
	detail, err := company.GetCompanyNoRenewedAscribeDetail(companyId, productId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	resp.Detail = detail
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 合同通过归因添加确认不续约
// @Description 合同通过归因添加确认不续约接口
// @Param	request	body company.CompanyNoRenewedNoteReq true "type json string"
// @Success 200 {object} "保存成功"
// @router /company_contract_no_renewed_ascribe/add [post]
func (this *CompanyRenewalController) CompanyContractNoRenewedAscribeAdd() {
	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
	}

	//内容仅权益管理员账号可以修改
	if sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_ADMIN && sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_RAI_ADMIN {
		br.Msg = "仅管理员可修改！"
		return
	}
	var req company.CompanyContractNoRenewedAscribeReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	content := req.Content
	companyAscribeId := req.CompanyAscribeId
	companyContractId := req.CompanyContractId

	if content == "" {
		br.Msg = "内容不能为空！"
		return
	}

	contractInfo, err := company.GetCompanyContractDetailByCompanyContractId(companyContractId)
	if err != nil {
		br.Msg = "获取合同失败"
		br.ErrMsg = "获取合同失败，Err:" + err.Error()
		return
	}
	companyId := contractInfo.CompanyId //公司ID
	productId := contractInfo.ProductId //权益还是FICC

	detail, err := company.GetCompanyAscribeDetail(companyAscribeId)
	if err != nil {
		br.Msg = "新建失败"
		br.ErrMsg = "新建失败，GetCompanyAscribeDetail Err:" + err.Error()
		return
	}
	var condition string
	var pars []interface{}
	condition += ` AND  company_id  = ?  AND product_id = ? AND company_contract_id = ?  `
	pars = append(pars, companyId, productId, companyContractId)

	total, err := company.GetCompanyContractNoRenewedAscribeCount(condition, pars)
	if err != nil {
		br.Msg = "新建失败"
		br.ErrMsg = "新建失败，GetCompanyContractNoRenewedAscribeCount Err:" + err.Error()
		return
	}
	item := new(company.CompanyContractNoRenewedAscribe)
	item.CompanyAscribeId = companyAscribeId
	item.AscribeContent = detail.AscribeContent
	item.Content = content
	item.ProductId = productId
	item.CompanyId = companyId
	item.CompanyContractId = companyContractId
	item.AdminId = sysUser.AdminId
	item.CreateTime = time.Now()
	item.ModifyTime = time.Now()

	itemLog := new(company.CompanyContractNoRenewedAscribeLog)
	itemLog.CompanyAscribeId = companyAscribeId
	itemLog.AscribeContent = detail.AscribeContent
	itemLog.Content = content
	itemLog.ProductId = productId
	itemLog.CompanyId = companyId
	itemLog.CompanyContractId = companyContractId
	itemLog.AdminId = sysUser.AdminId
	itemLog.CreateTime = time.Now()
	itemLog.ModifyTime = time.Now()
	if total == 0 {
		err = company.AddCompanyContractNoRenewedAscribe(item, itemLog)
	} else {
		err = company.UpdateCompanyContractNoRenewedAscribe(item, itemLog)
	}
	if err != nil {
		br.Msg = "新建失败"
		br.ErrMsg = "新建失败，Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "新建成功"
}

// @Title 合同确认归因不续约详情接口
// @Description 合同确认归因不续约详情接口
// @Param   CompanyContractId   query   int  true       "合同ID"
// @Success 200 {object} company.CompanyAscribeListResp
// @router /company_contract_no_renewed_ascribe/detail [get]
func (this *CompanyRenewalController) CompanyContractNoRenewedAscribeAddDetail() {
	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
	}
	companyContractId, _ := this.GetInt("CompanyContractId")
	if companyContractId < 1 {
		br.Msg = "合同ID错误！"
		return
	}

	resp := new(company.CompanyContractNoRenewedAscribeDetailResp)
	detail, err := company.GetCompanyContractNoRenewedAscribeDetail(companyContractId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	resp.Detail = detail
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}
