<?php
namespace addons\qcloud_light_cloud_gzhx\controller;

class AdminIndexController extends \app\admin\controller\PluginAdminBaseController
{
    public $data;
    public $pluginName = "qcloud_light_cloud_gzhx";
    public $sdk_path = "";
    public function initialize()
    {
        parent::initialize();
        $this->data = $_POST;
        $this->assign("GzhxPluginPath", $this->pluginName);
        $this->sdk_path = realpath(dirname(__FILE__) . "/../");
    }
    public function success($arr)
    {
        echo json_encode(["status" => 1, "encrypt" => 1, "info" => $arr]);
        exit;
    }
    public function error($arr)
    {
        echo json_encode(["status" => 0, "info" => $arr]);
        exit;
    }
    public static function DownloadFile($file, $destination)
    {
        set_time_limit(0);
        $fp = fopen((string) $destination, "w+");
        $ch = curl_init(str_replace(" ", "%20", $file));
        curl_setopt($ch, CURLOPT_TIMEOUT, 50);
        curl_setopt($ch, CURLOPT_FILE, $fp);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_exec($ch);
        curl_close($ch);
        fclose($fp);
    }
    public static function UnZip($file, $destination)
    {
        $zip = new \ZipArchive();
        if ($zip->open($file) === true) {
            try {
                $zip->extractTo($destination);
                $zip->close();
                return true;
            } catch (\Think\Exception $exception) {
                $zip->close();
                return false;
            }
        } else {
            return false;
        }
    }
    public function index()
    {
        if (!empty($this->data)) {
            $action = $this->data["action"];
            if (empty($action)) {
                $action = "";
            }
            switch ($action) {
                case "":
                    $this->error("参数错误");
                    break;
                case "status":
                    \Think\Db::name("zjmf_finance_api")->where("id", "=", $this->data["id"])->update(["status" => intval($this->data["status"]) == 2 ? 2 : 1]);
                    $this->success("设置成功");
                    break;
                case "plugin":
                    $modulesPath = CMF_ROOT . "public/plugins/addons";
                    $this->DownloadFile("https://v.ximijia.cn/modules/cloud_gzhx.zip", $modulesPath . "/cloud_gzhx.zip");
                    $unSDK = $this->UnZip($modulesPath . "/cloud_gzhx.zip", $modulesPath . "/");
                    if (!$unSDK) {
                        $this->error("安装SDK失败");
                    }
                    $this->success("设置成功");
                    break;
                case "sdk":
                    $modulesPath = $this->sdk_path;
                    $this->DownloadFile("https://v.ximijia.cn/modules/qcloud/sdk.zip", $modulesPath . "/qcloudsdk.zip");
                    $unSDK = $this->UnZip($modulesPath . "/qcloudsdk.zip", $modulesPath . "/");
                    if (!$unSDK) {
                        $this->error("安装SDK失败");
                    }
                    $this->success("设置成功");
                    break;
                default:
                    \Think\Db::startTrans();
                    try {
                        $this->data["data"]["hostname"] = $this->pluginName;
                        $this->data["data"]["type"] = "manual";
                        if (empty($this->data["data"]["name"]) || empty($this->data["data"]["username"])) {
                            $this->error("请填写名称和帐号");
                        }
                        $this->data["data"]["gzhx_lighthouse"] = 1;
                        if (empty($this->data["data"]["id"])) {
                            if (empty($this->data["data"]["password"]) || empty($this->data["data"]["username"])) {
                                $this->error("请填写密钥");
                            }
                            $this->data["data"]["password"] = bin2hex(openssl_encrypt($this->data["data"]["password"], "aes-128-cbc", mb_substr(md5("hjio^*(uihkjh"), 8, 16)));
                            $this->data["data"]["id"] = \Think\Db::name("zjmf_finance_api")->insertGetId($this->data["data"]);
                        } else {
                            if (empty($this->data["data"]["password"])) {
                                if (isset($this->data["data"]["password"])) {
                                    unset($this->data["data"]["password"]);
                                }
                            } else {
                                $this->data["data"]["password"] = bin2hex(openssl_encrypt($this->data["data"]["password"], "aes-128-cbc", mb_substr(md5("hjio^*(uihkjh"), 8, 16)));
                            }
                            \Think\Db::name("zjmf_finance_api")->where("id", "=", $this->data["data"]["id"])->update($this->data["data"]);
                            $this->data["data"]["status"] = \Think\Db::name("zjmf_finance_api")->where("id", "=", $this->data["data"]["id"])->value("status");
                        }
                        \Think\Db::commit();
                        $this->success($this->data["data"]);
                    } catch (\Think\Exception $e) {
                        \Think\Db::rollback();
                        $this->error("添加错误");
                    }
            }
        }
        $server_groups = \Think\Db::name("zjmf_finance_api")->where("hostname", "=", $this->pluginName)->select()->toArray();
        foreach ($server_groups as $key => $item) {
            $server_groups[$key]["password"] = "";
        }
        if (!file_exists(CMF_ROOT . "public/plugins/addons/cloud_gzhx/CloudGzhxPlugin.php")) {
            $this->assign("sell_Plugin", false);
        } else {
            $PluginData = \Think\Db::name("plugin")->where("name", "=", "CloudGzhx")->find();
            if (empty($PluginData)) {
                $this->assign("msg", "请先在插件中心安装GZHX公有云主机销售(CloudGzhx)插件");
                return $this->fetch("/error");
            }
            $DominbygzhxPlugin = new \addons\cloud_gzhx\CloudGzhxPlugin();
            $this->assign("sell_Plugin", $DominbygzhxPlugin->info["version"]);
        }
        $this->assign("server_groups", $server_groups);
        $this->assign("sdk", file_exists($this->sdk_path . "/QCloud/TCloudAutoLoader.php"));
        $this->assign("Title", "系统设置");
        return $this->fetch("/index");
    }
    public function domain()
    {
        $group = \Think\Db::name("product_groups")->where("zjfm_api_id", "=", $_GET["id"])->find();
        if (empty($group)) {
            $group = ["name" => "公有云", "hidden" => 1, "gid" => 1, "zjfm_api_id" => $_GET["id"]];
            $group["id"] = \Think\Db::name("ProductGroups")->insertGetId($group);
        }
        $Setting = \Think\Db::name("zjmf_finance_api")->where("id", "=", $_GET["id"])->find();
        $Qcloud = $this->initApp();
        $Qcloud->setConfig(["aid" => $Setting["username"], "ak" => openssl_decrypt(hex2bin($Setting["password"]), "aes-128-cbc", mb_substr(md5("hjio^*(uihkjh"), 8, 16))]);
        if (!empty($this->data)) {
            $action = $this->data["action"];
            if (empty($action)) {
                $action = "";
            }
            switch ($action) {
                case "":
                    $this->error("参数错误");
                    break;
                case "status":
                    \Think\Db::name("products")->where("id", "=", $this->data["id"])->update(["retired" => intval($this->data["status"])]);
                    $this->success("设置成功");
                    break;
                case "product":
                    $products = $Qcloud->DescribeInstances(["Region" => $this->data["id"]]);
                    if ($products["status"] != 1) {
                        $this->error($products["info"]);
                    }
                    foreach ($products["info"]["list"] as $k => $v) {
                        $find = \Think\Db::name("gzhx_cloud")->where("vid", "=", $v["vid"])->find();
                        $save = $v;
                        $save["api_id"] = $_GET["id"];
                        $save["region"] = $this->data["id"];
                        if (empty($find)) {
                            $save["uid"] = 0;
                            \Think\Db::name("gzhx_cloud")->insert($save);
                        } else {
                            \Think\Db::name("gzhx_cloud")->where("id", "=", $find["id"])->update($save);
                        }
                    }
                    $this->success("设置成功");
                    break;
                case "setmenu":
                    \Think\Db::name("zjmf_finance_api")->where("id", "=", $_GET["id"])->update(["gzhx_domain_rebet" => intval($this->data["name"])]);
                    $this->success("设置成功");
                    break;
                default:
                    $RegionSet = $this->data["RegionSet"];
                    $SaveOption = ["name" => $RegionSet[trim($this->data["data"]["name"])], "type" => "cloud", "gid" => $group["id"], "host" => "{\"show\":\"0\",\"modify\":0,\"prefix\":\"ser\",\"rule\":{\"upper\":\"0\",\"lower\":\"0\",\"num\":\"1\",\"len_num\":12}}", "password" => "{\"show\":\"0\",\"modify\":0,\"rule\":{\"len_num\":12,\"upper\":\"1\",\"lower\":\"1\",\"num\":\"1\",\"special\":\"0\"}}", "pay_type" => "{\"pay_type\":\"recurring\",\"pay_hour_cycle\":\"720\",\"pay_day_cycle\":\"30\",\"pay_ontrial_status\":0,\"pay_ontrial_cycle\":\"0\",\"pay_ontrial_num\":\"1\",\"pay_ontrial_condition\":[],\"pay_ontrial_cycle_type\":\"day\"}", "pay_method" => "prepayment", "config_option1" => $this->data["data"]["config_option1"] == "付款后自动" ? "payment" : "", "config_option2" => trim($this->data["data"]["name"]), "zjmf_api_id" => $_GET["id"], "upstream_pid" => $_GET["id"], "api_type" => "manual", "upper_reaches_id" => $_GET["id"]];
                    \Think\Db::startTrans();
                    try {
                        if (empty($this->data["data"]["id"])) {
                            $SaveOption["retired"] = 0;
                            $SaveOption["id"] = \Think\Db::name("products")->insertGetId($SaveOption);
                        } else {
                            $SaveOption["retired"] = \Think\Db::name("products")->where("id", "=", $this->data["data"]["id"])->value("retired");
                            $r = \Think\Db::name("products")->where("id", "=", $this->data["data"]["id"])->update($SaveOption);
                            $SaveOption["id"] = $this->data["data"]["id"];
                        }
                        \Think\Db::commit();
                        $this->success($SaveOption);
                    } catch (\Think\Exception $e) {
                        \Think\Db::rollback();
                        $this->error("添加错误" . var_export($e, true));
                    }
            }
        }
        $list = \Think\Db::name("products")->where("gid", "=", $group["id"])->select()->toArray();
        foreach ($list as $k => $v) {
            if ($v["config_option1"] == "payment") {
                $list[$k]["config_option1"] = "付款后自动";
            } else {
                $list[$k]["config_option1"] = "手动开通";
            }
            $list[$k]["TotalCount"] = $Qcloud->DescribeInstances(["Region" => $v["config_option2"]])["info"]["TotalCount"] ?: 0;
        }
        $config_option2 = array_column($list, NULL, "config_option2");
        if (empty($config_option2)) {
            $config_option2 = ["null" => "null"];
        }
        $DbConfig = \Think\Db::getConfig();
        $COLUMNS = \Think\Db::name("zjmf_finance_api")->getTableFields();
        if (!in_array("gzhx_domain_rebet", $COLUMNS)) {
            \Think\Db::query("ALTER TABLE `" . $DbConfig["prefix"] . "zjmf_finance_api` ADD COLUMN `gzhx_domain_rebet` int NULL DEFAULT 0;");
        }
        $this->assign("list", $list);
        $this->assign("gzhx_domain_rebet", $Setting["gzhx_domain_rebet"]);
        $this->assign("Title", $Setting["name"]);
        $RegionSet = $Qcloud->DescribeRegions();
        $this->assign("config_option2", $config_option2);
        $this->assign("RegionSet", $RegionSet["info"]);
        return $this->fetch("/domain");
    }
    public function initApp()
    {
        if (!class_exists($this->pluginName . "_class")) {
            require_once $this->sdk_path . "/" . $this->pluginName . "_class.php";
        }
        $app = "\\" . $this->pluginName . "_class";
        $QCloud = new $app();
        return $QCloud;
    }
    public function product()
    {
        if (!empty($this->data)) {
            $action = $this->data["action"];
            if (empty($action)) {
                $action = "";
            }
            switch ($action) {
                case "":
                    $this->error("参数错误");
                    break;
                default:
                    $User = \Think\Db::name("clients")->where("username", "=", $this->data["username"])->find();
                    if (empty($User)) {
                        $this->error("用户不存在");
                        exit;
                    }
                    $domain = json_decode($this->data["domain"], true);
                    $save = [];
                    foreach ($domain as $item) {
                        $save[] = ["domain" => $item["DomainName"], "vid" => $item["DomainId"], "api_id" => $_GET["id"], "start_time" => $item["CreationDate"], "end_time" => $item["ExpirationDate"], "uid" => $User["id"]];
                    }
                    \Think\Db::startTrans();
                    try {
                        \Think\Db::name("gzhx_domain")->insertAll($save, true);
                        \Think\Db::commit();
                        $this->success($this->data["data"]);
                    } catch (\Think\Exception $e) {
                        \Think\Db::rollback();
                        $this->error("添加错误" . var_export($e, true));
                    }
            }
        }
        $Page = isset($_GET["page"]) ? intval($_GET["page"]) : 1;
        $server_groups = \Think\Db::name("zjmf_finance_api")->where("id", "=", $_GET["id"])->find();
        $config = ["aid" => $server_groups["username"], "ak" => openssl_decrypt(hex2bin($server_groups["password"]), "aes-128-cbc", mb_substr(md5("hjio^*(uihkjh"), 8, 16))];
        $QCloud = $this->initApp();
        $QCloud->setConfig($config);
        $list = $QCloud->DescribeDomainNameList($Page - 1);
        if ($list["status"] == 0) {
            $this->assign("msg", $list["info"]);
            return $this->fetch("/error");
        }
        $data = [];
        $domains = array_column($list["info"]["DomainSet"], "DomainId");
        $DomainList = [];
        if (!empty($domains)) {
            $DomainList = \Think\Db::name("gzhx_domain")->alias("a")->field("b.username,a.*")->join("clients b", "a.uid=b.id")->where("a.api_id", "=", $_GET["id"])->where("a.vid", "IN", $domains)->select()->toArray();
            $DomainList = array_column($DomainList, NULL, "vid");
        }
        $this->assign("DomainList", $DomainList);
        $this->assign("List", $list["info"]["DomainSet"]);
        $this->assign("count", $list["info"]["TotalCount"]);
        $this->assign("Page", $Page);
        $this->assign("Title", "域名列表");
        return $this->fetch("/list");
    }
    public function TemplateList()
    {
        if (!empty($this->data)) {
            $action = $this->data["action"];
            if (empty($action)) {
                $action = "";
            }
            switch ($action) {
                case "":
                    $this->error("参数错误");
                    break;
                default:
                    $User = \Think\Db::name("clients")->where("username", "=", $this->data["username"])->find();
                    if (empty($User)) {
                        $this->error("用户不存在");
                        exit;
                    }
                    $domain = json_decode($this->data["domain"], true);
                    $save = [];
                    foreach ($domain as $item) {
                        $save[] = ["config" => serialize($item), "vid" => $item["TemplateId"], "api_id" => $_GET["id"], "organization_name" => $item["ZhRegistrantOrganization"], "certificate_type" => $item["IdentityCredentialType"], "uid" => $User["id"], "status" => $item["AuditStatus"]];
                    }
                    \Think\Db::startTrans();
                    try {
                        \Think\Db::name("gzhx_domain_template")->insertAll($save, true);
                        \Think\Db::commit();
                        $this->success($this->data["data"]);
                    } catch (\Think\Exception $e) {
                        \Think\Db::rollback();
                        $this->error("添加错误" . var_export($e, true));
                    }
            }
        }
        $Page = isset($_GET["page"]) ? intval($_GET["page"]) : 1;
        $QCloud = $this->initApp();
        $server_groups = \Think\Db::name("zjmf_finance_api")->where("id", "=", $_GET["id"])->find();
        $config = ["aid" => $server_groups["username"], "ak" => openssl_decrypt(hex2bin($server_groups["password"]), "aes-128-cbc", mb_substr(md5("hjio^*(uihkjh"), 8, 16))];
        $QCloud->setConfig($config);
        $list = $QCloud->DescribeTemplateList($Page - 1);
        if ($list["status"] == 0) {
            $this->assign("msg", $list["info"]);
            return $this->fetch("/error");
        }
        $data = [];
        $domains = array_column($list["info"]["TemplateSet"], "TemplateId");
        $DomainList = [];
        if (!empty($domains)) {
            $DomainList = \Think\Db::name("gzhx_domain_template")->alias("a")->field("b.username,a.*")->join("clients b", "a.uid=b.id")->where("a.api_id", "=", $_GET["id"])->where("a.vid", "IN", $domains)->select()->toArray();
            $DomainList = array_column($DomainList, NULL, "vid");
        }
        $this->assign("DomainList", $DomainList);
        $this->assign("List", $list["info"]["TemplateSet"]);
        $this->assign("count", $list["info"]["TotalCount"]);
        $this->assign("Page", $Page);
        $this->assign("Title", "域名信息模版列表");
        return $this->fetch("/template");
    }
    public function Suffix()
    {
        $server_groups = \Think\Db::name("zjmf_finance_api")->where("id", "=", $_GET["id"])->find();
        $group = \Think\Db::name("product_groups")->where("zjfm_api_id", "=", $_GET["id"])->find();
        if (empty($group)) {
            $group = ["name" => "域名", "hidden" => 1, "gid" => 1, "zjfm_api_id" => $_GET["id"]];
            $group["id"] = \Think\Db::name("ProductGroups")->insertGetId($group);
        }
        if (!empty($this->data)) {
            $action = $this->data["action"];
            if (empty($action)) {
                $action = "";
            }
            switch ($action) {
                case "set":
                    $domain = json_decode($this->data["domain"], true);
                    $data = [];
                    $Year = ["1" => "annually", "2" => "biennially", "3" => "triennially", "4" => "fourly", "5" => "fively"];
                    foreach ($domain as $item) {
                        $Suffix = mb_substr($item["Tld"], 1, NULL, "UTF-8");
                        foreach ($item as $k => $v) {
                            $data[$v["suffix"]][$Year[$v["year"]]] = ceil($v["price"] * $this->data["username"] / 100);
                        }
                    }
                    \Think\Db::startTrans();
                    try {
                        foreach ($data as $suffix => $v) {
                            $pricing = $v;
                            $list = \Think\Db::name("products")->alias("a")->field("a.*,b.id as pricing_id")->leftJoin("pricing b", "a.id=b.relid")->where("b.type", "=", "product")->where("a.gid", "=", $group["id"])->where("a.name", "=", $suffix)->find();
                            if (empty($list)) {
                                $id = \Think\Db::name("products")->insertGetId(["name" => trim($suffix), "type" => "cloud", "gid" => $group["id"], "host" => "{\"show\":\"0\",\"modify\":0,\"prefix\":\"ser\",\"rule\":{\"upper\":\"0\",\"lower\":\"0\",\"num\":\"1\",\"len_num\":12}}", "password" => "{\"show\":\"0\",\"modify\":0,\"rule\":{\"len_num\":12,\"upper\":\"1\",\"lower\":\"1\",\"num\":\"1\",\"special\":\"0\"}}", "pay_type" => "{\"pay_type\":\"recurring\",\"pay_hour_cycle\":\"720\",\"pay_day_cycle\":\"30\",\"pay_ontrial_status\":0,\"pay_ontrial_cycle\":\"0\",\"pay_ontrial_num\":\"1\",\"pay_ontrial_condition\":[],\"pay_ontrial_cycle_type\":\"day\"}", "pay_method" => "prepayment", "config_option1" => "payment", "zjmf_api_id" => $_GET["id"], "upstream_pid" => $_GET["id"], "api_type" => "manual", "upper_reaches_id" => $_GET["id"]]);
                                $pricing["currency"] = 1;
                                $pricing["relid"] = $id;
                                $pricing["type"] = "product";
                                \Think\Db::name("pricing")->insert($pricing);
                            } else {
                                \Think\Db::name("pricing")->where("id", "=", $list["pricing_id"])->update($pricing);
                            }
                        }
                        \Think\Db::commit();
                        $this->success("OK");
                    } catch (\Think\Exception $e) {
                        \Think\Db::rollback();
                        $this->error("添加错误");
                    }
                    break;
                default:
                    $this->error("参数错误");
            }
        }
        $QCloud = $this->initApp();
        $config = ["aid" => $server_groups["username"], "ak" => openssl_decrypt(hex2bin($server_groups["password"]), "aes-128-cbc", mb_substr(md5("hjio^*(uihkjh"), 8, 16))];
        $QCloud->setConfig($config);
        $list = $QCloud->DescribeDomainPriceList("new", [1, 2, 3, 4, 5]);
        if ($list["status"] != 1) {
            $this->assign("msg", $list["info"]);
            return $this->fetch("/error");
        }
        $this->assign("Title", $server_groups["name"] . "后缀获取");
        $this->assign("DomainList", $list["info"]);
        return $this->fetch("/suffix");
    }
}

?>