package controllers

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

// Tips: company控制器近万行代码了, GoLand打开都卡...分点函数到这个控制器来=_=!

// Close
// @Title 关闭客户
// @Description 关闭客户
// @Param	request	body company.CloseCompanyReq true "type json string"
// @Success Ret=200 操作成功
// @router /close [post]
func (this *CompanyController) Close() {
	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.CloseCompanyReq
	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 = "参数异常！"
		br.ErrMsg = "CompanyId:" + strconv.Itoa(req.CompanyId)
		return
	}
	req.Remark = strings.TrimSpace(req.Remark)
	if req.Remark == "" {
		br.Msg = "请填写关闭理由"
		return
	}

	// 权限暂时只给FICC管理员和超管
	authArr := []string{utils.ROLE_TYPE_CODE_ADMIN, utils.ROLE_TYPE_CODE_FICC_ADMIN}
	if !utils.InArrayByStr(authArr, sysUser.RoleTypeCode) {
		br.Msg = "无权操作"
		br.ErrMsg = "无权操作, RoleTypeCode: " + sysUser.RoleTypeCode
		return
	}

	productId := utils.COMPANY_PRODUCT_FICC_ID
	productName := utils.COMPANY_PRODUCT_FICC_NAME
	product, e := company.GetCompanyProductByCompanyIdAndProductId(req.CompanyId, productId)
	if e != nil {
		br.Msg = "客户信息异常"
		br.ErrMsg = "获取客户信息失败, Err: " + e.Error()
		return
	}
	if product.Status != utils.COMPANY_STATUS_TRY_OUT {
		br.Msg = fmt.Sprintf("客户状态为: %s, 不可关闭", product.Status)
		br.ErrMsg = fmt.Sprintf("客户%s状态为: %s, 不可关闭", product.CompanyName, product.Status)
		return
	}

	// 客户权限
	permissions, e := company.GetCompanyReportPermission(req.CompanyId, productId)
	if e != nil {
		br.Msg = "客户权限异常"
		br.ErrMsg = "获取客户权限失败, Err: " + e.Error()
		return
	}

	// 关闭客户
	if e = company.CloseCompany(req.CompanyId, productId, req.Remark); e != nil {
		br.Msg = "关闭失败"
		br.ErrMsg = "关闭客户失败, Err: " + e.Error()
		return
	}

	// 操作记录
	go func() {
		var err error
		defer func() {
			if err != nil {
				alarm_msg.SendAlarmMsg("关闭客户-新增操作记录失败, Err: "+err.Error(), 3)
			}
		}()

		remark := "关闭客户"
		operation := utils.COMPANY_STATUS_CLOSE_FLAG
		e = services.AddCompanyOperationRecord(req.CompanyId, product.SellerId, sysUser.AdminId, productId, sysUser.AdminId, product.CompanyName,
			productName, sysUser.RealName, remark, operation, req.Remark, sysUser.RealName, "", utils.COMPANY_STATUS_CLOSE)
		if e != nil {
			err = fmt.Errorf("AddCompanyOperationRecord %s", e.Error())
			return
		}

		// 权限关闭日志
		logs := make([]*company_report_permission_log.CompanyReportPermissionLog, 0)
		for _, p := range permissions {
			l := &company_report_permission_log.CompanyReportPermissionLog{
				CompanyReportPermissionId: p.CompanyReportPermissionId,
				CompanyId:                 p.CompanyId,
				ProductId:                 productId,
				ProductName:               p.ProductName,
				SysUserId:                 sysUser.AdminId,
				SysUserName:               sysUser.RealName,
				Remark:                    remark,
				Operation:                 operation,
				Status:                    p.Status,
				CreateTime:                time.Now(),
			}
			logs = append(logs, l)
		}
		e = company_report_permission_log.MultiCreateCompanyReportPermissionLog(logs)
		if e != nil {
			err = fmt.Errorf("MultiCreateCompanyReportPermissionLog %s", e.Error())
			return
		}
	}()

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

// Close2Loss
// @Title 关闭转流失
// @Description 关闭转流失
// @Param	request	body company.Close2LossReq true "type json string"
// @Success Ret=200 操作成功
// @router /close2loss [post]
func (this *CompanyController) Close2Loss() {
	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.Close2LossReq
	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 = "参数异常！"
		br.ErrMsg = "CompanyId:" + strconv.Itoa(req.CompanyId)
		return
	}

	// 权限暂时只给FICC管理员和超管
	authArr := []string{utils.ROLE_TYPE_CODE_ADMIN, utils.ROLE_TYPE_CODE_FICC_ADMIN}
	if !utils.InArrayByStr(authArr, sysUser.RoleTypeCode) {
		br.Msg = "无权操作"
		br.ErrMsg = "无权操作, RoleTypeCode: " + sysUser.RoleTypeCode
		return
	}

	productId := utils.COMPANY_PRODUCT_FICC_ID
	productName := utils.COMPANY_PRODUCT_FICC_NAME
	product, e := company.GetCompanyProductByCompanyIdAndProductId(req.CompanyId, productId)
	if e != nil {
		br.Msg = "客户信息异常"
		br.ErrMsg = "获取客户信息失败, Err: " + e.Error()
		return
	}
	if product.Status != utils.COMPANY_STATUS_CLOSE {
		br.Msg = fmt.Sprintf("客户状态为: %s, 不可转流失", product.Status)
		br.ErrMsg = fmt.Sprintf("客户%s状态为: %s, 不可转流失", product.CompanyName, product.Status)
		return
	}

	// 转流失
	if e = company.Close2Loss(req.CompanyId, productId); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "关闭转流失失败, Err: " + e.Error()
		return
	}

	// 操作记录
	go func() {
		remark := "关闭转流失"
		operation := utils.COMPANY_STATUS_LOSE_FLAG
		_ = services.AddCompanyOperationRecord(req.CompanyId, product.SellerId, sysUser.AdminId, productId, sysUser.AdminId, product.CompanyName,
			productName, sysUser.RealName, remark, operation, remark, sysUser.RealName, "", utils.COMPANY_STATUS_LOSE)
	}()

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