package service

import (
	"fmt"
	"os"
	"path/filepath"
	"runtime"
	"strings"
	"time"

	"be.ems/src/framework/cmd"
	"be.ems/src/framework/utils/file"
	"be.ems/src/modules/ne/model"
	"be.ems/src/modules/ne/repository"
)

// 实例化服务层 NeLicense 结构体
var NewNeLicense = &NeLicense{
	neLicenseRepository: repository.NewNeLicense,
}

// NeLicense 网元授权激活信息 服务层处理
type NeLicense struct {
	neLicenseRepository *repository.NeLicense // 网元授权激活信息表
}

// FindByPage 分页查询列表数据
func (r *NeLicense) FindByPage(query map[string]string) ([]model.NeLicense, int64) {
	return r.neLicenseRepository.SelectByPage(query)
}

// Find 查询列表
func (r *NeLicense) Find(neLicense model.NeLicense) []model.NeLicense {
	return r.neLicenseRepository.Select(neLicense)
}

// FindById 通过ID查询
func (r *NeLicense) FindById(id int64) model.NeLicense {
	if id <= 0 {
		return model.NeLicense{}
	}
	neLicenses := r.neLicenseRepository.SelectByIds([]int64{id})
	if len(neLicenses) > 0 {
		return neLicenses[0]
	}
	return model.NeLicense{}
}

// Insert 新增信息
func (r *NeLicense) Insert(neLicense model.NeLicense) int64 {
	return r.neLicenseRepository.Insert(neLicense)
}

// Update 修改信息
func (r *NeLicense) Update(neLicense model.NeLicense) int64 {
	return r.neLicenseRepository.Update(neLicense)
}

// DeleteByIds 批量删除信息
func (r *NeLicense) DeleteByIds(ids []int64) (int64, error) {
	// 检查是否存在
	rowIds := r.neLicenseRepository.SelectByIds(ids)
	if len(rowIds) <= 0 {
		return 0, fmt.Errorf("neLicense.noData")
	}

	if len(rowIds) == len(ids) {
		rows := r.neLicenseRepository.DeleteByIds(ids)
		return rows, nil
	}
	// 删除信息失败！
	return 0, fmt.Errorf("delete fail")
}

// FindByTypeAndID 通过网元类型和网元ID查询
func (r *NeLicense) FindByTypeAndID(neType, neId string) model.NeLicense {
	neLicenses := r.neLicenseRepository.Select(model.NeLicense{
		NeType: neType,
		NeId:   neId,
	})
	if len(neLicenses) > 0 {
		return neLicenses[0]
	}
	return model.NeLicense{}
}

// FindByNeTypeAndNeID 通过ne_type和ne_id查询信息
func (r *NeLicense) FindByNeTypeAndNeID(neType, neId string) model.NeLicense {
	neLicenses := r.neLicenseRepository.Select(model.NeLicense{
		NeType: neType,
		NeId:   neId,
	})
	if len(neLicenses) > 0 {
		return neLicenses[0]
	}
	return model.NeLicense{}
}

// ReadLicenseInfo 读取授权文件信息
// 返回激活申请码, 激活文件
func (r *NeLicense) ReadLicenseInfo(neLicense model.NeLicense) (string, string) {
	neTypeLower := strings.ToLower(neLicense.NeType)
	// 网管本地路径
	omcPath := "/usr/local/omc/backup/ne_license"
	if runtime.GOOS == "windows" {
		omcPath = fmt.Sprintf("C:%s", omcPath)
	}
	omcPath = fmt.Sprintf("%s/%s/%s", omcPath, neTypeLower, neLicense.NeId)
	// 网元端授权文件路径
	nePath := fmt.Sprintf("/usr/local/etc/%s/license", neTypeLower)

	// 网元主机的SSH客户端
	// sshClient, err := NewNeInfo.NeRunSSHClient(neLicense.NeType, neLicense.NeId)
	// if err != nil {
	// 	return "", ""
	// }
	// defer sshClient.Close()
	// // 网元主机的SSH客户端进行文件传输
	// sftpClient, err := sshClient.NewClientSFTP()
	// if err != nil {
	// 	return "", ""
	// }
	// defer sftpClient.Close()

	// 复制授权申请码到本地
	if err := file.CopyFile(nePath+"/Activation_request_code.txt", omcPath+"/Activation_request_code.txt"); err != nil {
		return "", ""
	}
	// 读取文件内容
	bytes, err := os.ReadFile(omcPath + "/Activation_request_code.txt")
	if err != nil {
		return "", ""
	}

	// 复制激活文件到本地
	licensePath := ""
	if err := file.CopyFile(nePath+"/system.ini", omcPath+"/system.ini"); err == nil {
		licensePath = omcPath + "/system.ini"
	}

	activationRequestCode := string(bytes)
	parts := strings.Split(activationRequestCode, "\n")
	if len(parts) > 1 && strings.HasPrefix(parts[0], "SN") {
		activationRequestCode = parts[1] // 获取第二行内容
	}
	return strings.TrimSpace(activationRequestCode), licensePath
}

// UploadLicense 授权文件上传到网元主机
func (r *NeLicense) UploadLicense(neLicense model.NeLicense) error {
	// 检查文件是否存在
	omcLicensePath := file.ParseUploadFileAbsPath(neLicense.LicensePath)
	if _, err := os.Stat(omcLicensePath); err != nil {
		return fmt.Errorf("file read failure")
	}

	// // 网元主机的SSH客户端
	// sshClient, err := NewNeInfo.NeRunSSHClient(neLicense.NeType, neLicense.NeId)
	// if err != nil {
	// 	return err
	// }
	// defer sshClient.Close()
	// // 网元主机的SSH客户端进行文件传输
	// sftpClient, err := sshClient.NewClientSFTP()
	// if err != nil {
	// 	return err
	// }
	// defer sftpClient.Close()

	// 网元端授权文件路径
	neTypeLower := strings.ToLower(neLicense.NeType)
	neLicensePath := fmt.Sprintf("/usr/local/etc/%s/license/system.ini", neTypeLower)
	neLicenseDir := filepath.ToSlash(filepath.Dir(neLicensePath))
	// 修改网元文件权限
	cmd.Execf("sudo mkdir -p %s && sudo chmod 775 %s && sudo touch %s && sudo chmod o+rw %s", neLicenseDir, neLicenseDir, neLicensePath, neLicensePath)

	// 尝试备份授权文件
	neLicensePathBack := fmt.Sprintf("%s/system_%s.ini", neLicensePath, time.Now().Format("20060102_150405"))
	cmd.Execf("sudo cp -rf %s/system.ini %s", neLicensePath, neLicensePathBack)

	// 上传授权文件去覆盖
	if err := file.CopyFile(omcLicensePath, neLicensePath); err != nil {
		return fmt.Errorf("please check if scp remote copy is allowed")
	}

	// 重启服务
	if neLicense.Reload {
		cmdStr := fmt.Sprintf("sudo systemctl restart %s", neTypeLower)
		switch neTypeLower {
		case "ims":
			cmdStr = "ims-stop || true && ims-start"
		case "omc":
			cmdStr = "sudo systemctl restart omc"
		}
		cmd.Exec(cmdStr)
	}
	return nil
}
