package providers

import (
	"cmdb-backend/models"
	"cmdb-backend/pkg/config"
	"cmdb-backend/pkg/logging"
	"fmt"
	"github.com/ucloud/ucloud-sdk-go/services/uhost"
	"github.com/ucloud/ucloud-sdk-go/services/ulb"
	"github.com/ucloud/ucloud-sdk-go/ucloud"
	"github.com/ucloud/ucloud-sdk-go/ucloud/auth"
	"time"
)

func uHostClient(region string) (client *uhost.UHostClient) {
	cfg := ucloud.NewConfig()
	cfg.Region = region
	cfg.BaseUrl = "https://api.ucloud.cn"

	cred := auth.NewCredential()
	cred.PublicKey = config.GC.Vendor.UcloudAk
	cred.PrivateKey = config.GC.Vendor.UcloudSk
	client = uhost.NewClient(&cfg, &cred)
	return
}

func ulbClient(region string) (client *ulb.ULBClient) {
	cfg := ucloud.NewConfig()
	cfg.Region = region
	cfg.BaseUrl = "https://api.ucloud.cn"

	cred := auth.NewCredential()
	cred.PublicKey = config.GC.Vendor.UcloudAk
	cred.PrivateKey = config.GC.Vendor.UcloudSk
	client = ulb.NewClient(&cfg, &cred)
	return
}

func UcloudGetVmsList() {
	projectIds := models.GetProjectList(2)
	regions := models.GetRegionList(2)
	for _, projectId := range projectIds {
		for _, regionId := range regions {
			fmt.Println("projectId:", projectId, "regionId:", regionId)
			client := uHostClient(regionId)
			req := client.NewDescribeUHostInstanceRequest()
			req.ProjectId = ucloud.String(projectId)
			req.Limit = ucloud.Int(200)

			resp, err := client.DescribeUHostInstance(req)
			if err != nil {
				logging.Error("Ucloud DescribeUHostInstance API Error", err)
			}

			fmt.Println("服务器总数量", len(resp.UHostSet))
			for _, tmp := range resp.UHostSet {
				publicIp := ""
				privateIp := ""
				vPCId := ""
				subnetId := ""
				bandwidth := 0

				for _, ip := range tmp.IPSet {
					if ip.Type == "Private" {
						privateIp = ip.IP
						vPCId = ip.VPCId
						subnetId = ip.SubnetId
					} else {
						publicIp = ip.IP
						bandwidth = ip.Bandwidth
					}
				}

				systemDisk := 0
				dataDisk := 0

				for _, disk := range tmp.DiskSet {
					if disk.Type == "Boot" {
						systemDisk = disk.Size
					} else {
						dataDisk += disk.Size
					}
				}

				createTime := time.Unix(int64(tmp.CreateTime), 0)

				server := models.Server{
					Name:         tmp.Name,
					InstanceId:   tmp.UHostId,
					InstanceType: "vm",
					VendorId:     2,
					ProjectId:    projectId,
					ImageId:      tmp.BasicImageId,
					ImageName:    tmp.BasicImageName,
					Status:       tmp.State,
					ZoneId:       tmp.Zone,
					RegionId:     regionId,
					Tag:          tmp.Tag,
					Cpu:          tmp.CPU,
					Memory:       tmp.Memory,
					SystemDisk:   systemDisk,
					DataDisk:     dataDisk,
					SubnetId:     subnetId,
					PublicIp:     publicIp,
					PrivateIp:    privateIp,
					BandWith:     bandwidth,
					VpcId:        vPCId,
					CreateTime:   createTime,
				}
				fmt.Println(server)
				//if err := models.CreateServer(&server, tmp.UHostId); err != nil {
				//	logging.Error("更新服务器信息失败", err, map[string]interface{}{"hostName": server.Name})
				//}
			}
		}
	}
}

func UcloudStartVm(instanceId string, regionId string, projectId string) (err error) {
	client := uHostClient(regionId)
	req := client.NewStartUHostInstanceRequest()
	req.ProjectId = ucloud.String(projectId)
	req.UHostId = ucloud.String(instanceId)
	res, err := client.StartUHostInstance(req)
	if res.RetCode != 0 {
		logging.Error(res.Message, err)
		return
	}
	return nil
}

func UcloudStopVm(instanceId string, regionId string, projectId string) (err error) {
	client := uHostClient(regionId)
	req := client.NewStopUHostInstanceRequest()
	req.ProjectId = ucloud.String(projectId)
	req.UHostId = ucloud.String(instanceId)
	res, err := client.StopUHostInstance(req)
	if res.RetCode != 0 {
		logging.Error(res.Message, err)
		return
	}
	return nil
}

func UcloudRebootVm(instanceId string, regionId string, projectId string) (err error) {
	client := uHostClient(regionId)
	req := client.NewRebootUHostInstanceRequest()
	req.ProjectId = ucloud.String(projectId)
	req.UHostId = ucloud.String(instanceId)
	res, err := client.RebootUHostInstance(req)
	if res.RetCode != 0 {
		logging.Error(res.Message, err)
		return
	}
	return nil
}

func UcloudDeleteVm(instanceId string, regionId string, projectId string) (err error) {
	client := uHostClient(regionId)
	//删除主机会释放绑定的EIP、挂载的数据盘资源，然后放入回收站，回收站资源会在7天后自动释放
	req := client.NewTerminateUHostInstanceRequest()
	req.ProjectId = ucloud.String(projectId)
	req.UHostId = ucloud.String(instanceId)
	req.ReleaseEIP = ucloud.Bool(true)
	req.ReleaseUDisk = ucloud.Bool(true)
	res, err := client.TerminateUHostInstance(req)
	if res.RetCode != 0 {
		logging.Error(res.Message, err)
		return
	}
	return nil
}

//func UcloudCreateVm(regionId string, projectId string, zoneId string, imageId string, instanceType string, instanceName string, password string, subnetId string, vpcId string, securityGroupId string, dataDiskSize int, dataDiskType string, chargeType string, quantity int, autoRenew int, autoRenewTime int, tag string, remark string) (err error) {
//	client := uHostClient(regionId)
//	req := client.NewCreateUHostInstanceRequest()
//	req.ProjectId = ucloud.String(projectId)
//	req.Zone = ucloud.String(zoneId)
//	req.ImageId = ucloud.String(imageId)
//	req.InstanceType = ucloud.String(instanceType)
//	req.InstanceName = ucloud.String(instanceName)
//	req.Password = ucloud.String(password)
//	req.SubnetId = ucloud.String(subnetId)
//	req.VPCId = ucloud.String(vpcId)
//	req.SecurityGroupId = ucloud.String(securityGroupId)
//	req.DataDiskSpace = ucloud.Int(dataDiskSize)
//	req.DataDiskType = ucloud.String(dataDiskType)
//	req.ChargeType = ucloud.String(chargeType)
//	req.Quantity = ucloud.Int(quantity)
//	req.AutoRenew = ucloud.Int(autoRenew)
//	req.AutoRenewTime = ucloud.Int(autoRenewTime)
//	req.Tag = ucloud.String(tag)
//	req.Remark = ucloud.String(remark)
//	res, err := client.CreateUHostInstance(req)
//	if res.RetCode != 0 {
//		logging.Error(res.Message, err)
//		return
//	}
//	return nil
//}

func UcloudGetLBList() (err error) {
	projectIds := models.GetProjectList(2)
	regions := models.GetRegionList(2)
	for _, projectId := range projectIds {
		for _, regionId := range regions {
			fmt.Println("projectId:", projectId, "regionId:", regionId)
			client := ulbClient(regionId)
			req := client.NewDescribeULBSimpleRequest()
			req.ProjectId = ucloud.String(projectId)
			req.Limit = ucloud.Int(200)

			resp, err := client.DescribeULBSimple(req)
			if err != nil {
				fmt.Println("Ucloud DescribeULBSimple API Error", err)
			}
			if resp.RetCode != 0 {
				fmt.Println("Ucloud DescribeULBSimple API Error", resp.Message)
			}

			if len(resp.DataSet) > 0 {
				for _, tmp := range resp.DataSet {
					createTime := time.Unix(int64(tmp.CreateTime), 0)

					networkType := ""
					if tmp.ULBType == "InnerMode" {
						networkType = "internal"
					} else {
						networkType = "public"
					}

					ipAddress := ""
					if len(tmp.IPSet) > 0 {
						ipAddress = tmp.IPSet[0].EIP
					} else {
						ipAddress = tmp.PrivateIP
					}

					lb := models.LoadBalancer{
						LbName:        tmp.Name,
						LbId:          tmp.ULBId,
						NetworkType:   networkType,
						IpAddress:     ipAddress,
						ListenerCount: tmp.VServerCount,
						VendorId:      2,
						RegionId:      regionId,
						ProjectId:     projectId,
						VpcId:         tmp.VPCId,
						SubnetId:      tmp.SubnetId,
						Tag:           tmp.Tag,
						CreateTime:    createTime,
					}
					fmt.Println(lb)
					//if err := models.CreateLoadBalancer(&lb, tmp.ULBId); err != nil {
					//	fmt.Println("添加负载均衡信息失败 hostName: ", lb.LbName)
					//}

					//req := client.NewDescribeULBSimpleRequest()
					//req.ProjectId = ucloud.String(projectId)
					//req.Limit = ucloud.Int(200)
					//
					//resp, err := client.DescribeULBSimple(req)
				}

			}
		}
	}
	return nil
}
