<?php
require_once "QCloud/TCloudAutoLoader.php";
class qcloud_light_cloud_gzhx_class
{
    private $uid = "";
    private $APiKey = "";
    private $ClassName = "qcloudLightCloudGzhxClass";
    public $Discount = 100;
    public function config()
    {
        return ["discount" => 2, "integral" => 0];
    }
    public function setConfig($data)
    {
        $this->uid = $data["aid"];
        $this->APiKey = $data["ak"];
    }
    public function get($action, $option = [])
    {
        try {
            if (empty($option["Region"])) {
                $option["Region"] = "ap-beijing";
            }
            $moduleName = empty($option["Product"]) ? "lighthouse" : $option["Product"];
            $Version = empty($option["Version"]) ? "V20200324" : $option["Version"];
            $cred = new TencentCloud\Common\Credential($this->uid, $this->APiKey);
            $httpProfile = new TencentCloud\Common\Profile\HttpProfile();
            $httpProfile->setEndpoint($moduleName . ".tencentcloudapi.com");
            $httpProfile->setReqTimeout(30);
            $clientProfile = new TencentCloud\Common\Profile\ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            $ClientName = "TencentCloud\\" . ucfirst($moduleName) . "\\" . $Version . "\\" . ucfirst($moduleName) . "Client";
            $client = new $ClientName($cred, $option["Region"], $clientProfile);
            $appAction = "TencentCloud\\" . ucfirst($moduleName) . "\\" . $Version . "\\Models\\" . ucfirst($action) . "Request";
            $req = new $appAction();
            unset($option["Region"]);
            unset($option["Product"]);
            unset($option["Version"]);
            if (!empty($option)) {
                $params = json_encode($option);
            } else {
                $params = "{}";
            }
            $req->fromJsonString($params);
            $resp = $client->{$action}($req);
            $resp = json_decode(json_encode($resp), true);
            return ["status" => 1, "info" => $resp];
        } catch (TencentCloud\Common\Exception\TencentCloudSDKException $e) {
            return ["status" => 0, "info" => "错误信息：" . $e->getMessage() . "/RequestId:" . $e->getRequestId()];
        }
    }
    public function YunApi($Action, $query, $product = NULL)
    {
        if (empty($product)) {
            $data = $this->get($Action, $query);
        } else {
            $data = $this->{$product}($Action, $query);
        }
        $data["Config"] = $this->config();
        return $data;
    }
    public function init($Action, $query, $data = NULL)
    {
        return $this->{$Action}($query);
    }
    public function setCache($file, $data)
    {
        if (!is_dir(CMF_DATA . "gzhx/" . $this->ClassName . "/")) {
            mkdir(CMF_DATA . "gzhx/" . $this->ClassName . "/", 493, true);
        }
        file_put_contents(CMF_DATA . "gzhx/" . $this->ClassName . "/" . $file, serialize(["time" => time(), "list" => $data]));
    }
    public function MonitorData($DomainInfo, $set)
    {
        $MetricArray = ["CPUUsage", "CpuLoadavg", "Cpuloadavg5m", "Cpuloadavg15m", "MemUsed", "MemUsage", "Gputemp", "Gpuutil", "GpuMemUsed", "Gpupowusage"];
        $Limit = intval($set["limit"]) ?: 11;
        $Period = intval($set["period"]) ?: 60;
        if (!empty($set["st"])) {
            $StartTime = strtotime($set["st"]);
            if (time() - $StartTime < $Period * $Limit) {
                $StartTime = time() - $Period * $Limit;
            }
        } else {
            $StartTime = time() - $Period * $Limit;
        }
        $EndTime = $StartTime + $Period * $Limit;
        if (time() - $EndTime < 0) {
            $EndTime = time();
        }
        $Info = ["Period" => $Period, "EndTime" => $EndTime, "StartTime" => $StartTime, "head" => $set["id"], "runtime" => date("y-m-d H:i:s", $DomainInfo["start_time"])];
        if (!empty($Info["runtime"]) && $Info["StartTime"] - strtotime($Info["runtime"]) < 0) {
            $Info["StartTime"] = strtotime($Info["runtime"]);
        }
        $DataFormart = "H:i";
        if (!empty($Info["head"])) {
            $MetricArray = [$Info["head"]];
            $DataFormart = "m-d H:i";
        }
        if ($Info["Period"] == 600) {
            $Info["Period"] = 300;
        }
        $query = ["Region" => $DomainInfo["region"], "Namespace" => "QCE/LIGHTHOUSE", "Instances" => [["Dimensions" => [["Name" => "InstanceId", "Value" => $DomainInfo["vid"]]]]], "Period" => $Info["Period"], "StartTime" => date("Y-m-d\\TH:i:00\\+08:00", $Info["StartTime"]), "EndTime" => date("Y-m-d\\TH:i:00\\+08:00", $Info["EndTime"]), "Product" => "monitor", "Version" => "V20180724"];
        $MetricData = [];
        foreach ($MetricArray as $k => $v) {
            $queryData = $query;
            $queryData["MetricName"] = $v;
            $result = $this->get("GetMonitorData", $queryData);
            if (!empty($result["info"]["DataPoints"][0]["Timestamps"])) {
                $Timestamps = $result["info"]["DataPoints"][0]["Timestamps"];
                $MonitorDataDate = [];
                foreach ($Timestamps as $kk => $vv) {
                    $MonitorDataDate[] = date($DataFormart, $vv);
                }
                $MetricData[$v] = ["date" => $MonitorDataDate, "value" => $result["info"]["DataPoints"][0]["Values"]];
            } else {
                $st = $Info["StartTime"];
                $et = $Info["EndTime"];
                $value = [];
                $MonitorDataDate = [];
                for ($i = 0; $i < 100; $i++) {
                    $Period = $i * $Info["Period"];
                    $t = strtotime("+" . $Period . " second", $st);
                    if ($et < $t) {
                        break;
                    }
                    $value[] = 0;
                    $MonitorDataDate[] = date($DataFormart, $t);
                }
                $MetricData[$v] = ["date" => $MonitorDataDate, "value" => $value];
            }
            usleep(20000);
        }
        return ["status" => 1, "info" => ["Period" => $Info["Period"], "data" => $MetricData, "name" => ["CPUUsage" => ["name" => "CPU 使用率(%)", "unit" => "%"], "CpuLoadavg" => ["name" => "CPU一分钟平均负载", "unit" => "%"], "Cpuloadavg5m" => ["name" => "CPU五分钟平均负载", "unit" => "%"], "Cpuloadavg15m" => ["name" => "CPU十五分钟平均负载", "unit" => "%"], "MemUsed" => ["name" => "内存使用量(MB)", "unit" => "MB"], "MemUsage" => ["name" => "内存利用率(%)", "unit" => "%"], "TcpCurrEstab" => ["name" => "TCP 连接数(个)", "unit" => "个"], "Gputemp" => ["name" => "GPU 温度(摄氏度)", "unit" => "摄氏度"], "Gpuutil" => ["name" => "GPU 使用率(%)", "unit" => "%"], "GpuMemUsed" => ["name" => "GPU 显存使用量(MBytes)", "unit" => "MBytes"], "Gpupowusage" => ["name" => "GPU 功耗(W)", "unit" => "W"]]]];
    }
    public function InternetMonitorData($DomainInfo, $set)
    {
        $MetricArray = ["LanOuttraffic", "LanIntraffic", "LanOutpkg", "LanInpkg", "WanOuttraffic", "WanIntraffic", "WanOutpkg", "WanInpkg", "AccOuttraffic", "TcpCurrEstab", "TimeOffset"];
        $Limit = intval($set["limit"]) ?: 11;
        $Period = intval($set["period"]) ?: 60;
        if (!empty($set["st"])) {
            $StartTime = strtotime($set["st"]);
            if (time() - $StartTime < $Period * $Limit) {
                $StartTime = time() - $Period * $Limit;
            }
        } else {
            $StartTime = time() - $Period * $Limit;
        }
        $EndTime = $StartTime + $Period * $Limit;
        if (time() - $EndTime < 0) {
            $EndTime = time();
        }
        $Info = ["Period" => $Period, "EndTime" => $EndTime, "StartTime" => $StartTime, "head" => $set["id"], "runtime" => date("y-m-d H:i:s", $DomainInfo["start_time"])];
        if (!empty($Info["runtime"]) && $Info["StartTime"] - strtotime($Info["runtime"]) < 0) {
            $Info["StartTime"] = strtotime($Info["runtime"]);
        }
        $DataFormart = "H:i";
        if (!empty($Info["head"])) {
            $MetricArray = [$Info["head"]];
            $DataFormart = "m-d H:i";
        }
        if ($Info["Period"] == 600) {
            $Info["Period"] = 300;
        }
        $query = ["Region" => $DomainInfo["region"], "Namespace" => "QCE/LIGHTHOUSE", "Instances" => [["Dimensions" => [["Name" => "InstanceId", "Value" => $DomainInfo["vid"]]]]], "Period" => $Info["Period"], "StartTime" => date("Y-m-d\\TH:i:00\\+08:00", $Info["StartTime"]), "EndTime" => date("Y-m-d\\TH:i:00\\+08:00", $Info["EndTime"]), "Product" => "monitor", "Version" => "V20180724"];
        $MetricData = [];
        foreach ($MetricArray as $k => $v) {
            $queryData = $query;
            $queryData["MetricName"] = $v;
            $result = $this->get("GetMonitorData", $queryData);
            if (!empty($result["info"]["DataPoints"][0]["Timestamps"])) {
                $Timestamps = $result["info"]["DataPoints"][0]["Timestamps"];
                $MonitorDataDate = [];
                foreach ($Timestamps as $kk => $vv) {
                    $MonitorDataDate[] = date($DataFormart, $vv);
                }
                $MetricData[$v] = ["date" => $MonitorDataDate, "value" => $result["info"]["DataPoints"][0]["Values"]];
            } else {
                $st = $Info["StartTime"];
                $et = $Info["EndTime"];
                $value = [];
                $MonitorDataDate = [];
                for ($i = 0; $i < 100; $i++) {
                    $Period = $i * $Info["Period"];
                    $t = strtotime("+" . $Period . " second", $st);
                    if ($et < $t) {
                        break;
                    }
                    $value[] = 0;
                    $MonitorDataDate[] = date($DataFormart, $t);
                }
                $MetricData[$v] = ["date" => $MonitorDataDate, "value" => $value];
            }
            usleep(20000);
        }
        return ["status" => 1, "info" => ["Period" => $Info["Period"], "data" => $MetricData, "name" => ["LanOuttraffic" => ["name" => "内网出带宽", "unit" => "Mbps"], "LanIntraffic" => ["name" => "内网入带宽", "unit" => "Mbps"], "LanOutpkg" => ["name" => "内网出包量", "unit" => "个/s"], "LanInpkg" => ["name" => "内网入包量", "unit" => "个/s"], "WanOuttraffic" => ["name" => "外网出带宽", "unit" => "Mbps"], "WanIntraffic" => ["name" => "外网入带宽", "unit" => "Mbps"], "WanOutpkg" => ["name" => "外网出包量", "unit" => "个/s"], "WanInpkg" => ["name" => "外网入包量", "unit" => "个/s"], "AccOuttraffic" => ["name" => "外网出流量", "unit" => "MB"], "TcpCurrEstab" => ["name" => "TCP 连接数", "unit" => "个"], "TimeOffset" => ["name" => "子机 utc 时间和 ntp 时间差值", "unit" => "s"]]]];
    }
    public function getCache($file, $time = 86400)
    {
        if (!is_dir(CMF_DATA . "gzhx/" . $this->ClassName . "/")) {
            mkdir(CMF_DATA . "gzhx/" . $this->ClassName . "/", 493, true);
        }
        $data = unserialize(file_get_contents(CMF_DATA . "gzhx/" . $this->ClassName . "/" . $file));
        if ($data["time"] && time() - $data["time"] < $time) {
            return $data["list"];
        }
        return NULL;
    }
    public function DescribeRegions()
    {
        $rr = $this->get("DescribeRegions", []);
        if ($rr["status"] != 1) {
            return $rr;
        }
        $data = [];
        foreach ($rr["info"]["RegionSet"] as $k => $v) {
            $data[$v["Region"]] = $v["RegionName"];
        }
        return ["status" => 1, "info" => $data];
    }
    public function DescribeDisksCategory($query)
    {
        $rr = $this->getCache("DescribeDisksCategory-" . $query["zone"]);
        if (!empty($rr)) {
            return $rr;
        }
        $resultVpc = $this->get("DescribeDiskConfigQuota", ["Region" => $query["region"], "DiskChargeType" => "PREPAID", "InquiryType" => "INQUIRY_CBS_CONFIG", "Product" => "cbs", "Zones" => [$query["zone"]]]);
        if ($resultVpc["status"] != 1) {
            return $resultVpc;
        }
        $config = ["CLOUD_BASIC" => "普通云硬盘", "CLOUD_PREMIUM" => "高性能云硬盘", "CLOUD_SSD" => "SSD云硬盘"];
        $list = [];
        foreach ($resultVpc["info"]["DiskConfigSet"] as $item) {
            if ($item["Available"] && !array_key_exists($item["DiskType"], $list) && array_key_exists($item["DiskType"], $config)) {
                $list[$item["DiskType"]] = $config[$item["DiskType"]];
            }
        }
        $result = ["status" => 1, "info" => ["list" => $list, "min" => 0, "max" => 1000]];
        $this->setCache("DescribeDisksCategory-" . $query["zone"], $result);
        return $result;
    }
    public function Period()
    {
        return ["1" => "1个月", "2" => "2个月", "3" => "3个月", "6" => "半年", "12" => "一年"];
    }
    public function Service()
    {
        return ["基础服务" => "基础服务"];
    }
    public function Vpc($query)
    {
        $resultVpc = $this->get("DescribeVpcs", ["Region" => $query["region"], "Product" => "vpc", "Filters" => [["Name" => "vpc-name", "Values" => ["gz-vpc"]]]]);
        if ($resultVpc["status"] != 1) {
            return $resultVpc;
        }
        $vpcId = $resultVpc["info"]["VpcSet"][0]["VpcId"];
        if (empty($vpcId)) {
            $addVpc = $this->get("CreateVpc", ["Region" => $query["region"], "Product" => "vpc", "VpcName" => "gz-vpc", "CidrBlock" => "10.0.0.0/16"]);
            if ($addVpc["status"] != 1) {
                return $addVpc;
            }
            $vpcId = $addVpc["info"]["Vpc"]["VpcId"];
        }
        $resultSubnets = $this->get("DescribeSubnets", ["Region" => $query["region"], "Product" => "vpc", "Filters" => [["Name" => "subnet-name", "Values" => ["gz-subnets"]], ["Name" => "vpc-id", "Values" => [$vpcId]], ["Name" => "zone", "Values" => [$query["zone"]]]]]);
        if ($resultSubnets["status"] != 1) {
            return $resultSubnets;
        }
        $subnetsId = $resultSubnets["info"]["SubnetSet"][0]["SubnetId"];
        if (empty($subnetsId)) {
            $addSubnets = $this->get("CreateSubnet", ["Region" => $query["region"], "Product" => "vpc", "SubnetName" => "gz-subnets", "CidrBlock" => "10.0.0.0/16", "VpcId" => $vpcId, "Zone" => $query["zone"]]);
            if ($addSubnets["status"] != 1) {
                return $addSubnets;
            }
            $subnetsId = $addSubnets["info"]["Subnet"]["SubnetId"];
        }
        $resultSecurityGroups = $this->get("DescribeSecurityGroups", ["Region" => $query["region"], "Product" => "vpc", "Filters" => [["Name" => "security-group-name", "Values" => ["gz-security"]]]]);
        if ($resultSecurityGroups["status"] != 1) {
            return $resultSecurityGroups;
        }
        $securityGroupsId = $resultSecurityGroups["info"]["SecurityGroupSet"][0]["SecurityGroupId"];
        if (empty($securityGroupsId)) {
            $addSecurityGroups = $this->get("CreateSecurityGroupWithPolicies", ["Region" => $query["region"], "Product" => "vpc", "GroupName" => "gz-security", "GroupDescription" => "gz-cn-security", "SecurityGroupPolicySet" => ["Ingress" => [["Protocol" => "TCP", "Port" => "all", "Action" => "ACCEPT", "CidrBlock" => "0.0.0.0/0"], ["Protocol" => "ICMP", "Action" => "ACCEPT", "CidrBlock" => "0.0.0.0/0"]]]]);
            if ($addSecurityGroups["status"] != 1) {
                return $addSecurityGroups;
            }
            $securityGroupsId = $addSecurityGroups["info"]["SecurityGroup"]["SecurityGroupId"];
        }
        return ["status" => 1, "vpc" => $vpcId, "subnets" => $subnetsId, "security" => $securityGroupsId];
    }
    public function RunInstances($query)
    {
        return ["status" => 0, "info" => "暂时不支持自动开通"];
    }
    public function DescribePrice($query)
    {
        $Option = ["Region" => $query["region"], "Placement" => ["Zone" => $query["zone"]], "BundleId" => $query["Instance"]["id"], "BlueprintId" => $query["osId"], "InstanceChargePrepaid" => ["Period" => intval($query["period"])], "InstanceCount" => 1];
        $rr = $this->get("InquirePriceCreateInstances", $Option);
        if ($rr["status"] != 1) {
            return $rr;
        }
        $OriginalPrice = $rr["info"]["Price"]["InstancePrice"]["OriginalPrice"];
        $DiscountPrice = $rr["info"]["Price"]["InstancePrice"]["DiscountPrice"];
        $Price = $DiscountPrice + ceil(floatval($OriginalPrice - $DiscountPrice) * $this->Discount) / 100;
        return ["status" => 1, "info" => $Price];
    }
    public function DescribeImagesReLoad($query)
    {
        $resultOSList = $this->getCache("DescribeImages-" . $query["region"] . "-renew", 8640000);
        if (!empty($resultOSList)) {
            return $resultOSList;
        }
        $resultOSList = $this->get("DescribeBlueprints", ["Region" => $query["region"], "Offset" => 0, "Limit" => 100]);
        if ($resultOSList["status"] != 1) {
            return $resultOSList;
        }
        $osList = ["windows" => [], "linux" => []];
        foreach ($resultOSList["info"]["BlueprintSet"] as $k => $v) {
            if (strtolower($v["PlatformType"]) == "windows") {
                $osList["windows"][] = ["id" => $v["BlueprintId"], "name" => $v["DisplayTitle"] . "(" . $v["DisplayVersion"] . ")"];
            } else {
                $osList["linux"][] = ["id" => $v["BlueprintId"], "name" => $v["DisplayTitle"] . "(" . $v["DisplayVersion"] . ")"];
            }
        }
        $result = ["status" => 1, "info" => $osList];
        $this->setCache("DescribeImages-" . $query["region"] . "-renew", $result);
        return $result;
    }
    public function DescribeImages($query)
    {
        $resultOSList = $this->get("DescribeBlueprints", ["Region" => $query["region"], "Offset" => 0, "Limit" => 100]);
        if ($resultOSList["status"] != 1) {
            return $resultOSList;
        }
        $DescribeBundles = $this->get("DescribeBundles", ["Region" => $query["region"], "Offset" => 0, "Limit" => 100]);
        if ($DescribeBundles["status"] != 1) {
            return $DescribeBundles;
        }
        $Bundles = [];
        foreach ($DescribeBundles["info"]["BundleSet"] as $item) {
            if ($item["BundleSalesState"] == "AVAILABLE" && $item["BundleType"] == "GENERAL_BUNDLE" && 100 < $item["MonthlyTraffic"]) {
                $OriginalPrice = $item["Price"]["InstancePrice"]["OriginalPrice"];
                $DiscountPrice = $item["Price"]["InstancePrice"]["DiscountPrice"];
                $Price = $DiscountPrice + ceil(floatval($OriginalPrice - $DiscountPrice) * $this->Discount) / 100;
                $info = ["CPU" => $item["CPU"], "InternetMaxBandwidthOut" => $item["InternetMaxBandwidthOut"], "MonthlyTraffic" => $item["MonthlyTraffic"], "SystemDiskSize" => $item["SystemDiskSize"], "Memory" => $item["Memory"], "Price" => $Price, "id" => $item["BundleId"], "LINUX_UNIX" => $item["SupportLinuxUnixPlatform"] ? 1 : 0, "WINDOWS" => $item["SupportWindowsPlatform"] ? 1 : 0];
                $Bundles[] = $info;
            }
        }
        $osList = [];
        foreach ($resultOSList["info"]["BlueprintSet"] as $k => $v) {
            $osList[$v["BlueprintId"]] = ["id" => $v["BlueprintId"], "name" => $v["DisplayTitle"], "Version" => $v["DisplayVersion"], "Description" => $v["Description"], "OsName" => $v["OsName"], "Platform" => $v["Platform"], "PlatformType" => $v["PlatformType"]];
        }
        $result = ["status" => 1, "info" => ["os" => $osList, "Bundles" => $Bundles]];
        $this->setCache("DescribeImages-" . $query["region"], $result);
        return $result;
    }
    public function Instance($query)
    {
        $rr = $this->getCache("Instance-" . $query["zone"]);
        if (!empty($rr)) {
            return $rr;
        }
        $rr = $this->get("DescribeZoneInstanceConfigInfos", ["Region" => $query["region"], "Filters" => [["Name" => "zone", "Values" => [$query["zone"]]]]]);
        if ($rr["status"] != 1) {
            return $rr;
        }
        $data = [];
        $Cpu = [];
        $Memory = [];
        foreach ($rr["info"]["InstanceTypeQuotaSet"] as $k => $v) {
            if ($v["Status"] == "SELL" && $v["InstanceChargeType"] == "PREPAID") {
                $data[] = ["InstanceType" => $v["InstanceType"], "Cpu" => $v["Cpu"], "Memory" => $v["Memory"], "CpuType" => $v["CpuType"], "Zone" => $v["Zone"]];
                if (!in_array($v["Cpu"], $Cpu)) {
                    $Cpu[] = $v["Cpu"];
                }
                if (!in_array($v["Memory"], $Memory)) {
                    $Memory[] = $v["Memory"];
                }
            }
        }
        asort($Cpu);
        asort($Memory);
        $result = ["status" => 1, "info" => ["list" => $data, "cpu" => $Cpu, "memory" => $Memory]];
        $this->setCache("Instance-" . $query["zone"], $result);
        return $result;
    }
    public function Zone($query)
    {
        $rr = $this->getCache("zone-" . $query["region"]);
        if (!empty($rr)) {
            return $rr;
        }
        $rr = $this->get("DescribeZones", ["Region" => $query["region"]]);
        if ($rr["status"] != 1) {
            return $rr;
        }
        $data = [];
        foreach ($rr["info"]["ZoneSet"] as $k => $v) {
            if ($v["ZoneState"] == "AVAILABLE") {
                $data[$v["Zone"]] = $v["ZoneName"];
            }
        }
        $result = ["status" => 1, "info" => $data];
        $this->setCache("zone-" . $query["region"], $result);
        return $result;
    }
    public function RenewInstances($data)
    {
        return ["status" => 0, "info" => "暂时不支持自动续费"];
    }
    public function Vnc($query, $op)
    {
        $result = $this->get("DescribeInstanceVncUrl", ["Region" => $query["region"], "InstanceId" => $query["vid"]]);
        if ($result["status"] === 1) {
            $result["info"]["RemoteServerUrl"] = "https://img.qcloud.com/qcloud/app/active_vnc/index.html?InstanceVncUrl=" . $result["info"]["InstanceVncUrl"];
        }
        return $result;
    }
    public function password($query, $op)
    {
        $rr = $this->get("ResetInstancesPassword", ["Region" => $query["region"], "InstanceIds" => [$query["vid"]], "Password" => $op["password"]]);
        if ($rr["status"] != 1 && strstr($rr["info"], "state")) {
            preg_match("/is in `([a-zA-Z\\-]+)` state/isu", $rr["info"], $match);
            strtoupper($match[1]);
            switch (strtoupper($match[1])) {
                case "PENDING":
                    $Status = "创建中";
                    break;
                case "LAUNCH_FAILED":
                    $Status = "创建失败";
                    break;
                case "RUNNING":
                    $Status = "运行中";
                    break;
                case "STOPPED":
                    $Status = "关机";
                    break;
                case "STARTING":
                    $Status = "开机中";
                    break;
                case "STOPPING":
                    $Status = "关机中";
                    break;
                case "REBOOTING":
                    $Status = "重启中";
                    break;
                case "SHUTDOWN":
                    $Status = "停止待销毁";
                    break;
                case "TERMINATING":
                    $Status = "销毁中";
                    break;
                default:
                    $Status = "未知";
                    return ["status" => 0, "info" => "请先关机完成后再重置密码,当前状态：" . $Status];
            }
        } else {
            return $rr;
        }
    }
    public function reloadOS($query, $op)
    {
        $rr = $this->get("ResetInstance", ["Region" => $query["region"], "InstanceId" => $query["vid"], "BlueprintId" => $op["os"]]);
        return $rr;
    }
    public function Op($query, $op)
    {
        $Option = ["Region" => $query["region"], "InstanceIds" => [$query["vid"]]];
        switch ($op["op"]) {
            case "start":
                $opBtn = "StartInstances";
                break;
            case "reboot":
                $opBtn = "RebootInstances";
                break;
            case "stop":
                $opBtn = "StopInstances";
                $rr = $this->get($opBtn, $Option);
                return $rr;
                break;
            default:
                return ["status" => 0, "info" => "不支持的操作"];
        }
    }
    public function DescribeInstanceFull($query)
    {
        $rr = $this->get("DescribeInstances", ["Region" => $query["region"], "InstanceIds" => [$query["vid"]], "Offset" => 0, "Limit" => 100]);
        if ($rr["status"] != 1) {
            return $rr;
        }
        switch ($rr["info"]["InstanceSet"][0]["InstanceState"]) {
            case "PENDING":
                $Status = "创建中";
                break;
            case "LAUNCH_FAILED":
                $Status = "创建失败";
                break;
            case "RUNNING":
                $Status = "运行中";
                break;
            case "STOPPED":
                $Status = "关机";
                break;
            case "STARTING":
                $Status = "开机中";
                break;
            case "STOPPING":
                $Status = "关机中";
                break;
            case "REBOOTING":
                $Status = "重启中";
                break;
            case "SHUTDOWN":
                $Status = "停止待销毁";
                break;
            case "TERMINATING":
                $Status = "销毁中";
                break;
            default:
                $Status = "未知";
                $Info = ["ID" => $rr["info"]["InstanceSet"][0]["InstanceId"], "工作区" => $rr["info"]["InstanceSet"][0]["Zone"], "购买时间" => date("Y-m-d H:i:s", strtotime($rr["info"]["InstanceSet"][0]["CreatedTime"])), "到期时间" => date("Y-m-d H:i:s", strtotime($rr["info"]["InstanceSet"][0]["ExpiredTime"])), "公网IP" => implode(",", $rr["info"]["InstanceSet"][0]["PublicAddresses"]), "内网IP" => implode(",", $rr["info"]["InstanceSet"][0]["PrivateAddresses"]), "Cpu" => $rr["info"]["InstanceSet"][0]["CPU"], "内存" => $rr["info"]["InstanceSet"][0]["Memory"], "带宽" => $rr["info"]["InstanceSet"][0]["InternetAccessible"]["InternetMaxBandwidthOut"], "操作系统平台" => $rr["info"]["InstanceSet"][0]["Platform"], "状态" => $Status];
                $ImageName = NULL;
                if ($ImageName === NULL) {
                    $ImageName = ["id" => $rr["info"]["InstanceSet"][0]["OsName"], "name" => $rr["info"]["InstanceSet"][0]["OsName"]];
                }
                $Info["操作系统"] = $ImageName["name"];
                $DiskConfig = ["CLOUD_BASIC" => "普通云硬盘", "CLOUD_PREMIUM" => "高性能云硬盘", "CLOUD_SSD" => "SSD云硬盘"];
                $Disk = [["name" => "系统盘", "id" => $rr["info"]["InstanceSet"][0]["SystemDisk"]["DiskId"], "type" => $DiskConfig[$rr["info"]["InstanceSet"][0]["SystemDisk"]["DiskType"]], "size" => $rr["info"]["InstanceSet"][0]["SystemDisk"]["DiskSize"]]];
                foreach ($rr["info"]["InstanceSet"][0]["DataDisks"] as $item) {
                    $Disk[] = ["name" => "数据盘", "id" => $item["DiskId"], "type" => $DiskConfig[$item["DiskType"]], "size" => $item["DiskSize"]];
                }
                return ["status" => 1, "info" => ["info" => $Info, "disk" => $Disk, "os" => $ImageName, "status" => $Status, "InstanceType" => $rr["info"]["InstanceSet"][0]["InstanceType"], "config" => $rr["info"]["InstanceSet"][0]]];
        }
    }
    public function DescribeInstance($query)
    {
        $rr = $this->get("DescribeInstances", ["Region" => $query["region"], "InstanceIds" => [$query["vid"]], "Offset" => 0, "Limit" => 100]);
        if ($rr["status"] != 1) {
            return $rr;
        }
        if ($rr["info"]["TotalCount"] < 1) {
            return ["status" => 0, "info" => "主机不存在"];
        }
        return ["status" => 1, "info" => ["vid" => $rr["info"]["InstanceSet"][0]["InstanceId"], "start_time" => date("Y-m-d H:i:s", strtotime($rr["info"]["InstanceSet"][0]["CreatedTime"])), "end_time" => date("Y-m-d H:i:s", strtotime($rr["info"]["InstanceSet"][0]["ExpiredTime"])), "domain" => implode(",", $rr["info"]["InstanceSet"][0]["PublicAddresses"]), "templete_info" => $rr["info"]["InstanceSet"][0]["CPU"] . "核" . $rr["info"]["InstanceSet"][0]["Memory"] . "G" . $rr["info"]["InstanceSet"][0]["InternetAccessible"]["InternetMaxBandwidthOut"] . "M"], "end_time" => $rr["info"]["InstanceSet"][0]["ExpiredTime"]];
    }
    public function InquiryPriceRenewInstances($query)
    {
        $rr = $this->get("InquirePriceRenewInstances", ["Region" => $query["region"], "InstanceChargePrepaid" => ["Period" => intval($query["period"])], "InstanceIds" => [$query["vid"]]]);
        if ($rr["status"] != 1) {
            return $rr;
        }
        $OriginalPrice = $rr["info"]["Price"]["InstancePrice"]["OriginalPrice"];
        $DiscountPrice = $rr["info"]["Price"]["InstancePrice"]["DiscountPrice"];
        $Price = $DiscountPrice + ceil(floatval($OriginalPrice - $DiscountPrice) * $this->Discount) / 100;
        return ["status" => 1, "info" => $Price];
    }
    public function DescribeInstances($query, $page = 1)
    {
        $rr = $this->get("DescribeInstances", ["Region" => $query["Region"], "Offset" => ($page - 1) * 100, "Limit" => 100]);
        if ($rr["status"] != 1) {
            return $rr;
        }
        $data = [];
        foreach ($rr["info"]["InstanceSet"] as $k => $v) {
            $data[$v["InstanceId"]] = ["vid" => $v["InstanceId"], "start_time" => date("Y-m-d H:i:s", strtotime($v["CreatedTime"])), "end_time" => date("Y-m-d H:i:s", strtotime($v["ExpiredTime"])), "domain" => implode(",", $v["PublicAddresses"]), "templete_info" => $v["CPU"] . "核" . $v["Memory"] . "G" . $v["InternetAccessible"]["InternetMaxBandwidthOut"] . "M"];
        }
        return ["status" => 1, "info" => ["list" => $data, "TotalCount" => $rr["info"]["TotalCount"]]];
    }
    private function SaveRegistrantProfile($query)
    {
        if (!empty($query["RegistrantProfileId"])) {
            $rr = $this->get("DeleteTemplate", ["TemplateId" => $query["RegistrantProfileId"]]);
            if ($rr["status"] != 1) {
                return $rr;
            }
        }
        switch ($query["IdentityCredentialType"]) {
            case "XYDM":
                $f_type_org = "TYDMZ";
                break;
            default:
                $f_type_org = $query["IdentityCredentialType"];
                $rr = $this->get("UploadImage", ["ImageFile" => "data:image/jpeg;base64," . $query["RegistrantProfilePic"]]);
                if ($rr["status"] != 1) {
                    return $rr;
                }
                $post = ["ContactInfo" => ["RegistrantType" => $query["RegistrantType"] == 1 ? "I" : "E", "OrganizationNameCN" => $query["ZhRegistrantOrganization"], "OrganizationName" => $query["RegistrantOrganization"], "RegistrantNameCN" => $query["ZhRegistrantName"], "RegistrantName" => $query["RegistrantName"], "ProvinceCN" => $query["ZhProvince"], "CityCN" => $query["ZhCity"], "StreetCN" => $query["ZhAddress"], "Street" => $query["Address"], "ZipCode" => $query["PostalCode"], "CountryCN" => "中国", "Telephone" => $query["Telephone"], "Email" => $query["Email"], "Province" => $query["Province"], "City" => $query["City"], "Country" => "CN"], "CertificateInfo" => ["CertificateCode" => $query["IdentityCredentialNo"], "CertificateType" => $f_type_org, "ImgUrl" => $rr["info"]["AccessUrl"]]];
                $r = $this->get("CreateTemplate", $post);
                if ($r["status"] == 1) {
                    $r["info"]["RegistrantProfileId"] = $r["info"]["Template"]["TemplateId"];
                }
                return $r;
        }
    }
    private function QueryDomainList($query)
    {
        $r = $this->get("DescribeDomainBaseInfo", ["Domain" => $query["DomainName"]]);
        if ($r["status"] != 1) {
            return $r;
        }
        $result = ["status" => 1, "info" => ["Data" => ["Domain" => [["vid" => $r["info"]["DomainInfo"]["DomainId"], "DomainName" => $query["DomainName"], "ExpirationDate" => $r["info"]["DomainInfo"]["ExpirationDate"], "RegistrationDate" => $r["info"]["DomainInfo"]["CreationDate"]]]]]];
        return $result;
    }
    private function SaveSingleTaskForCreatingOrderActivate($query)
    {
        $arr = ["Domains" => [$query["DomainName"]], "Period" => intval($query["Period"]), "TemplateId" => $query["RegistrantProfileId"], "PayMode" => 1];
        if (!empty($query["Dns1"]) && !empty($query["Dns2"])) {
            $arr["dns_host1"] = $query["Dns1"];
            $arr["dns_host2"] = $query["Dns2"];
        }
        $r = $this->get("CreateDomainBatch", $arr);
        if ($r["status"] != 1) {
            return $r;
        }
        $r["info"]["active"] = "注册中";
        $r["info"]["TaskNo"] = $r["info"]["LogId"];
        return $r;
    }
    private function QueryTaskDetailList($query)
    {
        $r = $this->get("DescribeBatchOperationLogDetails", ["LogId" => intval($query["TaskNo"])]);
        $Status = "执行中";
        switch ($r["info"]["DomainBatchDetailSet"][0]["Status"]) {
            case "doing":
                $Status = "执行中";
                break;
            case "failed":
                $Status = $r["info"]["DomainBatchDetailSet"][0]["Reason"];
                break;
            case "success":
                $Status = "执行成功";
                break;
            default:
                $Status = "等待执行";
                $result = ["status" => 1, "info" => $Status];
                return $result;
        }
    }
    public function DescribeDomainPriceList($Operation, $Year)
    {
        $cachePathDir = dirname(__FILE__) . "/suffix_cache/";
        if (!is_dir($cachePathDir)) {
            mkdir($cachePathDir, 493, true);
        }
        $cachePath = $cachePathDir . $Operation . "-" . implode("-", $Year);
        $cache = unserialize(file_get_contents($cachePath));
        if (!empty($cache) && time() - $cache["time"] < 86400) {
            $cache["info"]["cache"] = $cachePath;
            return $cache;
        }
        $r = $this->get("DescribeDomainPriceList", ["LogId" => $Operation, "Year" => $Year, "Operation" => [$Operation]]);
        if ($r["status"] != 1) {
            return $r;
        }
        $data = [];
        foreach ($r["info"]["PriceList"] as $item) {
            $Suffix = mb_substr($item["Tld"], 1, NULL, "UTF-8");
            $data[$Suffix][$item["Year"]] = ["price" => $item["RealPrice"], "suffix" => $Suffix, "year" => $item["Year"]];
        }
        $result = ["status" => 1, "info" => ["data" => $data], "time" => time()];
        file_put_contents($cachePath, serialize($result));
        return $result;
    }
    public function SaveBatchTaskForModifyingDomainDns($query)
    {
        $arr = ["Domains" => [$query["DomainName.1"]]];
        if (!empty($query["DomainNameServer.1"]) && !empty($query["DomainNameServer.2"])) {
            $arr["Dns"] = [$query["DomainNameServer.1"], $query["DomainNameServer.2"]];
        } else {
            $arr["Dns"] = ["width.dnspod.net", "escape.dnspod.net"];
        }
        $r = $this->get("ModifyDomainDNSBatch", $arr);
        return $r;
    }
    public function DescribeDomainNs($query)
    {
        $r = $this->get("DescribeDomainBaseInfo", ["Domain" => $query["DomainName"]]);
        if ($r["status"] != 1) {
            return $r;
        }
        $Ns = $r["info"]["DomainInfo"]["NameServer"];
        return ["status" => 1, "info" => $Ns];
    }
    public function DescribeDomainNameList($Offset = 0)
    {
        $r = $this->get("DescribeDomainNameList", ["Offset" => $Offset * 100, "Limit" => 100]);
        return $r;
    }
    private function TemplateData($data)
    {
        $status = "未知";
        switch ($data["AuditStatus"]) {
            case "NotUpload":
                $status = "未实名认证";
                break;
            case "InAudit":
                $status = "审核中";
                break;
            case "Approved":
                $status = "已实名认证";
                break;
            case "Reject":
                $status = $data["AuditReason"];
                break;
            default:
                return ["TemplateId" => $data["TemplateId"], "Email" => $data["ContactInfo"]["Email"], "RegistrantType" => $data["ContactInfo"]["RegistrantType"] == "E" ? 2 : 1, "ZhRegistrantOrganization" => $data["ContactInfo"]["OrganizationNameCN"], "ZhRegistrantName" => $data["ContactInfo"]["RegistrantNameCN"], "RegistrantOrganization" => $data["ContactInfo"]["OrganizationName"], "RegistrantName" => $data["ContactInfo"]["RegistrantName"], "Province" => "zhe jiang", "City" => "hang zhou shi", "Address" => "zhe jiang sheng hang zhou shi shang cheng qu 10001 hao", "Country" => "CN", "TelArea" => "86", "Telephone" => $data["ContactInfo"]["Telephone"], "TelExt" => "1234", "PostalCode" => "310024", "IdentityCredentialType" => $data["CertificateInfo"]["CertificateType"], "IdentityCredentialNo" => $data["CertificateInfo"]["CertificateCode"], "RegistrantProfilePic" => $data["CertificateInfo"]["ImgUrl"], "AuditStatus" => $status];
        }
    }
    public function DescribeTemplate($query)
    {
        $r = $this->get("DescribeTemplate", ["TemplateId" => $query["vid"]]);
        if ($r["status"] == 1) {
            $status = "未知";
            switch ($r["info"]["Template"]["AuditStatus"]) {
                case "NotUpload":
                    $status = "未实名认证";
                    break;
                case "InAudit":
                    $status = "审核中";
                    break;
                case "Approved":
                    $status = "已实名认证";
                    break;
                case "Reject":
                    $status = $r["info"]["Template"]["AuditReason"];
                    break;
                default:
                    $r["AuditStatus"] = $status;
                    return ["status" => 1, "AuditStatus" => $status, "info" => $this->TemplateData($r["info"]["Template"])];
            }
        } else {
            return $r;
        }
    }
    public function DescribeTemplateList($Offset)
    {
        $r = $this->get("DescribeTemplateList", ["Offset" => $Offset * 100, "Limit" => 100]);
        if ($r["status"] != 1) {
            return $r;
        }
        $info = ["status" => 1, "info" => ["TemplateSet" => [], "TotalCount" => $r["info"]["TotalCount"]]];
        foreach ($r["info"]["TemplateSet"] as $key => $value) {
            $info["info"]["TemplateSet"][] = $this->TemplateData($value);
        }
        return $info;
    }
    private function SaveBatchTaskForCreatingOrderRenew($query)
    {
        $QueryDomainList = $this->QueryDomainList(["DomainName" => $query["OrderRenewParam.1.DomainName"]]);
        if ($QueryDomainList["status"] != 1) {
            return $QueryDomainList;
        }
        $r = $this->get("RenewDomainBatch", ["Domains" => [$query["OrderRenewParam.1.DomainName"]], "Period" => intval($query["OrderRenewParam.1.SubscriptionDuration"]), "PayMode" => 1]);
        if ($r["status"] == 1) {
            $r["info"]["TaskNo"] = $r["info"]["LogId"];
            $r["info"]["expiredate"] = date("Y-m-d H:i:s", strtotime("+" . $query["OrderRenewParam.1.SubscriptionDuration"] . " year", strtotime($QueryDomainList["info"]["Data"]["Domain"][0]["ExpirationDate"])));
        }
        return $r;
    }
}

?>