<?php
namespace addons\group_buy\controller;

class AdminIndexController extends \app\admin\controller\PluginAdminBaseController
{
    public $data;
    public $PluginName = "GroupBuy";
    public function initialize()
    {
        parent::initialize();
        $this->assign("GzhxPluginPath", $this->uncamelize($this->PluginName));
        $this->data = $_POST;
    }
    public function uncamelize($camelCaps, $separator = "_")
    {
        return strtolower(preg_replace("/([a-z])([A-Z])/", "\$1" . $separator . "\$2", $camelCaps));
    }
    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 function index()
    {
        if (!empty($this->data)) {
            switch ($this->data["action"]) {
                case "set":
                    $add = [];
                    $option = [];
                    foreach ($this->data["data"] as $key => $item) {
                        if (mb_substr($key, 0, 7, "UTF-8") == "option_") {
                            $option[$key] = $item;
                        } else {
                            $add[$key] = $item;
                        }
                    }
                    $add["option"] = json_encode($option);
                    unset($add["setmoney"]);
                    $product = \Think\Db::name("group_buy_gzhx")->where("pid", "=", $this->data["data"]["pid"])->find();
                    if (!empty($product)) {
                        \Think\Db::name("group_buy_gzhx")->where("id", "=", $product["id"])->update($add);
                    } else {
                        \Think\Db::name("group_buy_gzhx")->insert($add);
                    }
                    $this->success("操作成功");
                    exit;
                    break;
                case "product":
                    $products = \Think\Db::name("group_buy_gzhx")->alias("a")->join("products c", "c.id=a.pid")->join("product_groups d", "d.id=a.gid")->join("pricing b", "c.id=b.relid")->field("a.*,c.name,d.name as group_name,b.monthly,b.annually")->where("b.type", "=", "product")->select()->toArray();
                    $this->success(["data" => $products]);
                    exit;
                    break;
                case "get":
                    $groups = \Think\Db::name("product_groups")->where("hidden", "=", 0)->select()->toArray();
                    foreach ($groups as $key => $item) {
                        $products = \Think\Db::name("products")->alias("a")->join("pricing b", "a.id=b.relid")->field("a.*,b.monthly,b.annually")->where("a.hidden", "=", 0)->where("b.type", "=", "product")->where("a.gid", "=", $item["id"])->select()->toArray();
                        $groups[$key]["products"] = $products;
                    }
                    $this->success($groups);
                    exit;
                    break;
                default:
                    $this->error($this->data["action"] . "参数不存在");
                    exit;
            }
        } else {
            $DemoClient = \Think\Db::name("clients")->where("groupid", "=", "0")->value("id") ?: 0;
            if (empty($DemoClient)) {
                $this->assign("msg", "请先注册一个没有分组的会员帐号");
                return $this->fetch("/error");
            }
            $DbConfig = \Think\Db::getConfig();
            $f = \Think\Db::name("group_buy_gzhx")->getTableFields();
            if (!in_array("product_name", $f)) {
                \Think\Db::query("ALTER TABLE `" . $DbConfig["prefix"] . "group_buy_gzhx` ADD COLUMN `product_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT '';");
            }
            $this->assign("DemoClient", $DemoClient);
            $this->assign("Title", "拼团活动");
            $this->assign("AdminApplication", $DbConfig["admin_application"]);
            return $this->fetch("/index");
        }
    }
    public function users()
    {
        if (!empty($this->data)) {
            switch ($this->data["action"]) {
                case "get":
                    $Page = isset($_GET["page"]) ? intval($_GET["page"]) : 1;
                    $count = \Think\Db::name("group_buy_gzhx")->alias("a")->join("group_buy_gzhx_user e", "e.aid=a.id")->join("products c", "c.id=a.pid")->join("product_groups d", "d.id=a.gid")->join("clients f", "f.id=e.uid")->join("pricing b", "c.id=b.relid")->field("a.*,f.username,e.add_time as e_add_time,e.id as e_id,e.status as e_status,e.num as e_num,e.type as e_type,e.end_time as e_end_time,c.description,c.name,d.name as group_name,b.monthly,b.annually")->where("b.type", "=", "product")->where("e.uuid", "=", 0);
                    $groups = \Think\Db::name("group_buy_gzhx")->alias("a")->join("group_buy_gzhx_user e", "e.aid=a.id")->join("products c", "c.id=a.pid")->join("product_groups d", "d.id=a.gid")->join("clients f", "f.id=e.uid")->join("pricing b", "c.id=b.relid")->field("a.*,e.uid as e_uid,f.username,e.add_time as e_add_time,e.id as e_id,e.status as e_status,e.num as e_num,e.type as e_type,e.end_time as e_end_time,c.description,c.name,d.name as group_name,b.monthly,b.annually")->where("b.type", "=", "product")->where("e.uuid", "=", 0)->order("e.id desc")->page($Page . ",20");
                    if (!empty($_GET["username"])) {
                        $count = $count->where("f.username", "LIKE", "%" . $_GET["username"] . "%");
                        $groups = $groups->where("f.username", "LIKE", "%" . $_GET["username"] . "%");
                    }
                    $count = $count->count();
                    $groups = $groups->select()->toArray();
                    foreach ($groups as $key => $item) {
                        $groups[$key]["user_list"] = \Think\Db::name("group_buy_gzhx_user")->alias("a")->join("clients f", "f.id=a.uid")->where("a.uuid", "=", $item["e_id"])->field("a.*,f.username")->order("a.id desc")->select()->toArray();
                    }
                    $this->success(["data" => $groups, "limit" => 20, "page" => $Page, "count" => $count]);
                    exit;
                    break;
                default:
                    $this->error($this->data["action"] . "参数不存在");
                    exit;
            }
        } else {
            $this->assign("Title", "团长列表");
            $DbConfig = \Think\Db::getConfig();
            $this->assign("AdminApplication", $DbConfig["admin_application"]);
            return $this->fetch("/users");
        }
    }
    public function member()
    {
        if (!empty($this->data)) {
            switch ($this->data["action"]) {
                case "refun":
                    $item = \Think\Db::name("group_buy_gzhx")->alias("a")->join("group_buy_gzhx_user e", "e.aid=a.id")->join("products c", "c.id=a.pid")->join("product_groups d", "d.id=a.gid")->join("clients f", "f.id=e.uid")->join("pricing b", "c.id=b.relid")->join("invoices g", "g.id=e.invoices_id")->join("invoice_items h", "h.invoice_id=g.id")->field("a.*,g.subtotal,h.description as h_description,e.id as e_id,e.uid as e_uid,e.uuid as e_uuid,f.username,e.add_time as e_add_time,e.id as e_id,e.status as e_status,e.num as e_num,e.type as e_type,e.end_time as e_end_time,c.description,c.name,d.name as group_name,b.monthly,b.annually")->where("b.type", "=", "product")->where("e.id", "=", $this->data["_id"])->where("e.uuid", ">", 0)->find();
                    $user_list = \Think\Db::name("group_buy_gzhx")->alias("a")->join("group_buy_gzhx_user e", "e.aid=a.id")->join("products c", "c.id=a.pid")->join("product_groups d", "d.id=a.gid")->join("clients f", "f.id=e.uid")->join("pricing b", "c.id=b.relid")->field("a.*,e.id as e_id,e.uid as e_uid,f.username,e.add_time as e_add_time,e.id as e_id,e.status as e_status,e.num as e_num,e.type as e_type,e.end_time as e_end_time,c.description,c.name,d.name as group_name,b.monthly,b.annually")->where("b.type", "=", "product")->where("e.id", "=", $item["e_uuid"])->where("e.uuid", "=", 0)->find();
                    $user_list["user_list"] = \Think\Db::name("group_buy_gzhx")->alias("a")->join("group_buy_gzhx_user e", "e.aid=a.id")->join("products c", "c.id=a.pid")->join("product_groups d", "d.id=a.gid")->join("clients f", "f.id=e.uid")->join("pricing b", "c.id=b.relid")->join("invoices g", "g.id=e.invoices_id")->join("invoice_items h", "h.invoice_id=g.id")->field("a.*,g.subtotal,h.description as h_description,e.uid as e_uid,e.uuid as e_uuid,f.username,e.add_time as e_add_time,e.id as e_id,e.status as e_status,e.num as e_num,e.type as e_type,e.end_time as e_end_time,c.description,c.name,d.name as group_name,b.monthly,b.annually")->where("b.type", "=", "product")->where("e.status", "=", 1)->where("e.uuid", "=", $user_list["e_id"])->order("e.id desc")->select()->toArray();
                    \Think\Db::startTrans();
                    try {
                        if ($item["e_uid"] == $user_list["e_uid"]) {
                            foreach ($user_list["user_list"] as $key => $value) {
                                $PayPrice = $value["subtotal"];
                                $InvoicesId = \Think\Db::name("Invoices")->insertGetId(["uid" => $value["e_uid"], "invoice_num" => date("YmdHis") . mt_rand(10000, 999999), "create_time" => time(), "update_time" => time(), "due_time" => time(), "paid_time" => time(), "subtotal" => $PayPrice, "status" => "Paid", "total" => $PayPrice, "payment" => "UserCustom", "type" => "recharge"]);
                                $InvoicesItemsId = \Think\Db::name("InvoiceItems")->insertGetId(["uid" => $value["e_uid"], "invoice_id" => $InvoicesId, "description" => $value["h_description"] . "管理员退款", "rel_id" => 0, "amount" => $PayPrice, "payment" => "UserCustom", "type" => "recharge"]);
                                $CreditId = \Think\Db::name("Credit")->insertGetId(["uid" => $value["e_uid"], "create_time" => time(), "description" => "Credit Applied to Invoice #" . $InvoicesId, "relid" => $InvoicesId, "amount" => $PayPrice]);
                                \Think\Db::name("clients")->where("id", "=", $value["e_uid"])->setInc("credit", $PayPrice);
                                \Think\Db::name("group_buy_gzhx_user")->where("id", "=", $value["e_id"])->update(["status" => 3]);
                            }
                            \Think\Db::name("group_buy_gzhx_user")->where("id", "=", $user_list["e_id"])->update(["status" => 3]);
                            \Think\Db::commit();
                        } else {
                            $PayPrice = $item["subtotal"];
                            $InvoicesId = \Think\Db::name("Invoices")->insertGetId(["uid" => $item["e_uid"], "invoice_num" => date("YmdHis") . mt_rand(10000, 999999), "create_time" => time(), "update_time" => time(), "due_time" => time(), "paid_time" => time(), "subtotal" => $PayPrice, "status" => "Paid", "total" => $PayPrice, "payment" => "UserCustom", "type" => "recharge"]);
                            $InvoicesItemsId = \Think\Db::name("InvoiceItems")->insertGetId(["uid" => $item["e_uid"], "invoice_id" => $InvoicesId, "description" => $item["h_description"] . "管理员退款", "rel_id" => 0, "amount" => $PayPrice, "payment" => "UserCustom", "type" => "recharge"]);
                            $CreditId = \Think\Db::name("Credit")->insertGetId(["uid" => $item["e_uid"], "create_time" => time(), "description" => "Credit Applied to Invoice #" . $InvoicesId, "relid" => $InvoicesId, "amount" => $PayPrice]);
                            \Think\Db::name("clients")->where("id", "=", $item["e_uid"])->setInc("credit", $PayPrice);
                            \Think\Db::name("group_buy_gzhx_user")->where("id", "=", $item["e_id"])->update(["status" => 3]);
                            \Think\Db::name("group_buy_gzhx_user")->where("id", "=", $item["e_uuid"])->setDec("num", 1);
                            \Think\Db::commit();
                        }
                    } catch (\Exception $e) {
                        \Think\Db::rollback();
                        $this->error(var_export($e, true));
                    }
                    $this->success("OK");
                    exit;
                    break;
                case "get":
                    $Page = isset($_GET["page"]) ? intval($_GET["page"]) : 1;
                    $count = \Think\Db::name("group_buy_gzhx")->alias("a")->join("group_buy_gzhx_user e", "e.aid=a.id")->join("products c", "c.id=a.pid")->join("product_groups d", "d.id=a.gid")->join("clients f", "f.id=e.uid")->join("pricing b", "c.id=b.relid")->field("a.*,f.username,e.add_time as e_add_time,e.id as e_id,e.status as e_status,e.num as e_num,e.type as e_type,e.end_time as e_end_time,c.description,c.name,d.name as group_name,b.monthly,b.annually")->where("b.type", "=", "product")->where("e.uuid", ">", 0);
                    $groups = \Think\Db::name("group_buy_gzhx")->alias("a")->join("group_buy_gzhx_user e", "e.aid=a.id")->join("products c", "c.id=a.pid")->join("product_groups d", "d.id=a.gid")->join("clients f", "f.id=e.uid")->join("pricing b", "c.id=b.relid")->join("invoices g", "g.id=e.invoices_id")->field("a.*,g.subtotal,e.id as e_id,e.uid as e_uid,e.uuid as e_uuid,f.username,e.add_time as e_add_time,e.id as e_id,e.status as e_status,e.num as e_num,e.type as e_type,e.end_time as e_end_time,c.description,c.name,d.name as group_name,b.monthly,b.annually")->where("b.type", "=", "product")->where("e.uuid", ">", 0)->order("e.id desc")->page($Page . ",20");
                    if (!empty($_GET["username"])) {
                        $count = $count->where("f.username", "LIKE", "%" . $_GET["username"] . "%");
                        $groups = $groups->where("f.username", "LIKE", "%" . $_GET["username"] . "%");
                    }
                    $count = $count->count();
                    $groups = $groups->select()->toArray();
                    foreach ($groups as $key => $item) {
                        $user_list = \Think\Db::name("group_buy_gzhx")->alias("a")->join("group_buy_gzhx_user e", "e.aid=a.id")->join("products c", "c.id=a.pid")->join("product_groups d", "d.id=a.gid")->join("clients f", "f.id=e.uid")->join("pricing b", "c.id=b.relid")->field("a.*,e.id as e_id,e.uid as e_uid,f.username,e.add_time as e_add_time,e.id as e_id,e.status as e_status,e.num as e_num,e.type as e_type,e.end_time as e_end_time,c.description,c.name,d.name as group_name,b.monthly,b.annually")->where("b.type", "=", "product")->where("e.id", "=", $item["e_uuid"])->where("e.uuid", "=", 0)->find();
                        $user_list["user_list"] = \Think\Db::name("group_buy_gzhx")->alias("a")->join("group_buy_gzhx_user e", "e.aid=a.id")->join("products c", "c.id=a.pid")->join("product_groups d", "d.id=a.gid")->join("clients f", "f.id=e.uid")->join("pricing b", "c.id=b.relid")->join("invoices g", "g.id=e.invoices_id")->field("a.*,g.subtotal,e.uid as e_uid,e.uuid as e_uuid,f.username,e.add_time as e_add_time,e.id as e_id,e.status as e_status,e.num as e_num,e.type as e_type,e.end_time as e_end_time,c.description,c.name,d.name as group_name,b.monthly,b.annually")->where("b.type", "=", "product")->where("e.status", "=", 1)->where("e.uuid", "=", $user_list["e_id"])->order("e.id desc")->select()->toArray();
                        $groups[$key]["user_list"] = $user_list;
                    }
                    $this->success(["data" => $groups, "limit" => 20, "page" => $Page, "count" => $count]);
                    exit;
                    break;
                default:
                    $this->error($this->data["action"] . "参数不存在");
                    exit;
            }
        } else {
            $this->assign("Title", "团员列表");
            $DbConfig = \Think\Db::getConfig();
            $this->assign("AdminApplication", $DbConfig["admin_application"]);
            return $this->fetch("/member");
        }
    }
}

?>