package services

import (
	"fmt"
	"github.com/mozillazg/go-pinyin"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/eta_trial"
	"hongze/hz_crm_api/services/alarm_msg"
	"hongze/hz_crm_api/utils"
	"strconv"
	"time"
)

// UpdateOldTrialUsersManualAuth 更新原试用客户手工录入权限(一次性)
func UpdateOldTrialUsersManualAuth() (err error) {
	// 从ETA试用平台的edb库中读取手工数据分类
	classifyList, e := eta_trial.GetETATrialManualClassify()
	if e != nil {
		fmt.Println(e.Error())
		return
	}
	classifyIds := make([]int, 0)
	for i := range classifyList {
		classifyIds = append(classifyIds, classifyList[i].ClassifyId)
	}

	// 查询未分配手工权限的试用客户Ids
	userList, e := eta_trial.GetNoAuthTrialUserIds()
	if e != nil {
		fmt.Println(e.Error())
		return
	}
	if len(userList) == 0 {
		fmt.Println("无客户需要更新手工权限")
		return
	}
	fmt.Println("classifyIds", classifyIds)

	// 遍历试用客户, ETA试用平台data库新增manual_user用户关联、manual_user_classify权限关联
	for i := range userList {
		fmt.Printf("用户%d-%s正在更新\n", userList[i].AdminId, userList[i].RealName)
		e = eta_trial.InsertTrialUserManualAuth(userList[i].AdminId, userList[i].RealName, classifyIds)
		if e != nil {
			fmt.Println(e.Error())
			return
		}
		fmt.Println("更新成功")
		//break // 试一个先
	}
	return
}

// CreateTrialUserManualAuth 新增试用客户手工录入权限
// 鉴于DB注册时即使不同库也不能同名的情况, 以下均使用原生SQL
func CreateTrialUserManualAuth(adminId int, adminRealName string) (err error) {
	defer func() {
		if err != nil {
			alarm_msg.SendAlarmMsg(fmt.Sprintf("新增试用客户手工录入权限失败, ErrMsg: %s", err.Error()), 3)
		}
	}()

	// 从ETA试用平台的edb库中读取手工数据分类
	classifyList, e := eta_trial.GetETATrialManualClassify()
	if e != nil {
		err = fmt.Errorf("获取手工数据分类失败, Err: %s", e.Error())
		return
	}
	classifyIds := make([]int, 0)
	for i := range classifyList {
		classifyIds = append(classifyIds, classifyList[i].ClassifyId)
	}

	// 新增用户及权限
	e = eta_trial.InsertTrialUserManualAuth(adminId, adminRealName, classifyIds)
	if e != nil {
		err = fmt.Errorf("新增手工数据权限失败, Err: %s", e.Error())
		return
	}
	return
}

// ApprovalApply 同意审批
func ApprovalApply(approvalId int) (err error) {
	defer func() {
		if err != nil {
			tips := fmt.Sprintf("ETA试用-自动审批失败, ApprovalId: %d, Err: %s", approvalId, err.Error())
			utils.FileLog.Info("%s", tips)
			go alarm_msg.SendAlarmMsg(tips, 3)
		}
	}()

	// 获取审批
	approval, e := eta_trial.GetETATrialApprovalById(approvalId)
	if e != nil {
		err = fmt.Errorf("获取审批失败, Err: %s", e.Error())
		return
	}

	// 更新审批
	if e = eta_trial.ApprovalTrial(approvalId); e != nil {
		err = fmt.Errorf("更新审批失败, Err: %s", e.Error())
		return
	}

	// 如果是新客户申请就新增，旧客户更改账号状态即可
	if approval.ApplyMethod == 2 {
		if e = eta_trial.UpdateETATrialEnable(approval.Mobile); e != nil {
			err = fmt.Errorf("启用失败, Err: %s", e.Error())
			return
		}
		if e = eta_trial.UpdateAdminEnable(approval.Mobile); e != nil {
			err = fmt.Errorf("启用用户失败, Err: %s", e.Error())
			return
		}
	} else {
		//新增客户
		newItem := eta_trial.EtaTrial{
			UserName:    approval.UserName,
			CompanyName: approval.CompanyName,
			Position:    approval.Position,
			Mobile:      approval.Mobile,
			Enabled:     1,
			SellerId:    approval.SellerId,
			Seller:      approval.Seller,
			CreateTime:  time.Now(),
			ModifyTime:  time.Now(),
		}

		strResult := ""
		a := pinyin.NewArgs()
		rows := pinyin.Pinyin(newItem.UserName, a)
		for i := 0; i < len(rows); i++ {
			strResult += rows[i][0]
		}

		//若非中文
		if strResult == "" {
			strResult = newItem.UserName
		}
		list, e := eta_trial.GetETATrialByAccount(strResult)
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = fmt.Errorf("获取ETA试用账号失败, Err: %s", e.Error())
			return
		}
		if list != nil && len(list) > 0 {
			newItem.Account = strResult + strconv.Itoa(len(list))
		} else {
			newItem.Account = strResult
		}

		// 初始密码固定
		newItem.Password = "123456a"

		_, e = eta_trial.AddETATrial(&newItem)
		if e != nil {
			err = fmt.Errorf("新增ETA试用账号失败, Err: %s", e.Error())
			return
		}

		// 新增至试用平台的Admin
		adminItem, e := eta_trial.GetSysUserByRoleAndDepartment("试用", "ETA试用客户")
		if e != nil {
			err = fmt.Errorf("获取ETA试用admin失败, Err: %s", e.Error())
			return
		}

		admin := new(eta_trial.ETATrialAdmin)
		admin.AdminName = newItem.Account
		admin.RealName = newItem.UserName
		admin.Password = utils.MD5(newItem.Password)
		admin.LastUpdatedPasswordTime = time.Now().Format(utils.FormatDateTime)
		admin.Enabled = 1
		admin.LastLoginTime = time.Now().Format(utils.FormatDateTime)
		admin.CreatedTime = time.Now()
		admin.LastUpdatedTime = time.Now().Format(utils.FormatDateTime)
		admin.Mobile = newItem.Mobile
		admin.RoleType = 0
		admin.RoleId = adminItem.RoleId
		admin.RoleName = "试用"
		admin.RoleTypeCode = "管理员"
		admin.DepartmentId = adminItem.DepartmentId
		admin.DepartmentName = "ETA试用客户"
		admin.Role = "admin"
		admin.Position = approval.Position

		newId, e := eta_trial.AddAdmin(admin)
		if e != nil {
			err = fmt.Errorf("新增ETA试用admin失败, Err: %s", e.Error())
			return
		}

		// 新增试用客户手工权限
		go func() {
			//_ = CreateTrialUserManualAuth(newId, admin.RealName)
			_ = EtaTrialManualUserAddAuth(newId, admin.RealName)
		}()
	}

	// 推送消息给销售
	msgItem := new(company.CompanyApprovalMessage)
	msgItem.CreateUserId = 0 // 系统自动创建的消息
	msgItem.ReceiveUserId = approval.SellerId
	msgItem.MessageStatus = 0
	msgItem.Remark = approval.UserName + approval.ApprovalContent + "通过"
	msgItem.Content = approval.UserName + approval.ApprovalContent + "通过"
	msgItem.CompanyName = approval.CompanyName
	msgItem.CreateTime = time.Now()
	msgItem.ModifyTime = time.Now()
	msgItem.CompanyApprovalId = approvalId
	msgItem.OperationStatus = 1
	msgItem.MessageType = 2    //1:申请消息，2:审批结果，3：文字消息
	msgItem.SourceType = 9     //消息来源
	msgItem.ApprovalStatus = 2 //审批状态,1:待审批，2:已审批，3:已驳回
	err = company.AddCompanyApprovalMessage(msgItem)

	// 更新审批消息(发给所有管理员的)为已读
	//go func() {
	//	cond := ` AND company_approval_id = ? AND source_type = ? AND message_status = ? AND receive_user_id = -1 `
	//	pars := make([]interface{}, 0)
	//	pars = append(pars, approvalId, 9, 0)
	//	_ = company.ModifyCompanyApprovalMessageStatusByCond(cond, pars)
	//}()
	return
}
