<?php
namespace addons\pay_activity\controller\clientarea;

use Exception;

class IndexController extends \app\home\controller\PluginHomeBaseController
{
    public $data;
    public $theme = "/ajax";
    public $PluginName = "PayActivity";
    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 fetchTemplete($p)
    {
        $content = $this->fetch($this->theme . $p);
        if (!empty($this->theme)) {
            preg_match("/<GZHXPAGEBOX>([\\s\\S]*?)<\\/GZHXPAGEBOX>/isu", $content, $mth);
            return $mth[1];
        }
        return $content;
    }
    public function createNonceStr($length = 16)
    {
        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
    public function index()
    {
        $User = request()->uid;
        if (empty($User)) {
        }
        if (empty($User)) {
            $this->assign("msg", "登录失效，请重新登录");
            return $this->fetch("/error");
        }
        $Clients = \Think\Db::name("clients")->where("id", "=", $User)->find();
        if (empty($_GET["cache"])) {
            $this->assign("Title", "领取记录");
            return $this->fetch($this->theme . "/ajax");
        }
        if (!empty($this->data)) {
            $action = $this->data["action"];
            if (empty($action)) {
                $action = "";
            }
            switch ($action) {
                case "receive":
                    $gzhx_activity_user = \Think\Db::name("gzhx_activity_user")->alias("a")->field("a.*,b.title,b.end_time as activity_end_time,c.id as prize_id,c.type as prize_type,c.setting as prize_setting")->leftJoin("gzhx_activity_prize_setting c", "a.aid=c.id")->leftJoin("gzhx_activity b", "CONCAT('" . $this->PluginName . "_',b.id)=c.plugin")->where("a.plugin", "=", $this->PluginName)->where("a.uid", "=", $User)->where("a.id", "=", $this->data["id"])->find();
                    if (empty($gzhx_activity_user)) {
                        $this->error("奖品设置出错，请联系管理人员");
                    }
                    if (!empty($gzhx_activity_user["error"])) {
                        $this->error("奖品已领取");
                    }
                    if (strtotime($gzhx_activity_user["activity_end_time"]) < time()) {
                        $this->error("活动过期");
                    }
                    $prize_setting = unserialize($gzhx_activity_user["prize_setting"]);
                    if (empty($prize_setting)) {
                        $this->error("奖品设置出错，请联系管理人员002");
                    }
                    switch ($gzhx_activity_user["prize_type"]) {
                        case "现金红包":
                            try {
                                $invoice_id = \Think\Db::name("invoices")->insertGetId(["uid" => $User, "create_time" => time(), "update_time" => time(), "due_time" => time(), "subtotal" => $prize_setting["value"], "total" => $prize_setting["value"], "status" => "Unpaid", "payment" => "activity_pay", "type" => "recharge", "notes" => $this->PluginName . "抽奖"]);
                                $invoice_item_id = \Think\Db::name("invoice_items")->insertGetId(["uid" => $User, "invoice_id" => $invoice_id, "type" => "recharge", "description" => $gzhx_activity_user["msg"], "description2" => $gzhx_activity_user["msg"], "amount" => $prize_setting["value"], "due_time" => time()]);
                                $order_data = ["invoice_id" => $invoice_id, "trans_id" => "#" . date("YmdHis") . mt_rand(100, 9999), "currency" => "-", "payment" => "activity_pay", "amount_in" => $prize_setting["value"], "paid_time" => date("Y-m-d H:i:s")];
                                $Order = new \app\home\controller\OrderController();
                                $Order->orderPayHandle($order_data, "activity_pay");
                                \Think\Db::name("gzhx_activity_user")->where("id", "=", $gzhx_activity_user["id"])->update(["error" => "奖品发放成功", "add_time" => date("Y-m-d H:i:s")]);
                                $this->success("OK");
                            } catch (Exception $e) {
                                \Think\Db::rollback();
                                $this->error("添加错误" . var_export($e, true));
                            }
                            break;
                        case "优惠券":
                            $code = $this->createNonceStr(10);
                            $promo_code = ["type" => $prize_setting["type"], "value" => $prize_setting["value"], "recurring" => 0, "start_time" => time(), "max_times" => 1, "one_time" => 1, "once_per_client" => 1, "notes" => "【" . $User . "】" . $gzhx_activity_user["msg"], "code" => $code];
                            if (intval($prize_setting["time_out"]) == 1) {
                                $promo_code["expiration_time"] = strtotime("+" . $prize_setting["time_out_day"] . " day", time());
                            } else {
                                $promo_code["expiration_time"] = strtotime($prize_setting["time_out_date"] . ":00");
                            }
                            if (!empty($prize_setting["product_id"])) {
                                $promo_code["appliesto"] = $prize_setting["product_id"];
                            }
                            try {
                                \Think\Db::name("promo_code")->insert($promo_code);
                                \Think\Db::name("gzhx_activity_user")->where("id", "=", $gzhx_activity_user["id"])->update(["error" => "奖品发放成功" . (empty($prize_setting["product_id"]) ? "" : "【产品ID：" . $prize_setting["product_id"] . "】") . "", "code" => $code, "add_time" => date("Y-m-d H:i:s")]);
                                $this->success("OK");
                            } catch (Exception $e) {
                                \Think\Db::rollback();
                                $this->error("添加错误" . var_export($e, true));
                            }
                            break;
                        default:
                            $this->error("奖品设置出错，请联系管理人员");
                    }
                    break;
                default:
                    $this->error("参数不存在");
            }
        }
        $ClientGroups = \Think\Db::name("client_groups")->alias("a")->field("a.*,b.type,b.bates")->join("user_product_bates b", "b.user=a.id")->order("b.bates asc,id asc")->select()->toArray();
        $ClientGroups = array_column($ClientGroups, NULL, "id");
        $ClientGroups[0] = ["bates" => 100];
        $Activity = \Think\Db::name("gzhx_activity")->where("plugin", "=", $this->PluginName)->where("status", "=", 2)->where("start_time", "<=", date("Y-m-d"))->where("end_time", ">", date("Y-m-d", strtotime("+1 day", time())))->select()->toArray();
        foreach ($Activity as $k => $item) {
            $setting = unserialize($item["setting"]);
            if (!(empty($setting) || empty($setting["activity_type"]) || empty($setting["activity_prize"]))) {
                $prize = \Think\Db::name("gzhx_activity_prize_setting")->where("plugin", "=", $this->PluginName . "_" . $item["id"])->order("winning asc,id asc")->select()->toArray();
                if (!empty($prize)) {
                    if ($setting["activity_type"] == "实名认证") {
                        $vv = $prize[0];
                        $checkVerified = \Think\Db::name("gzhx_activity_user")->where("uid", "=", $User)->where("type", "=", "verified")->where("plugin", "=", $this->PluginName)->where("aid", "=", $vv["id"])->find();
                        if (empty($checkVerified)) {
                            $certifi_person = \Think\Db::name("certifi_person")->where("auth_user_id", "=", $User)->where("status", "=", 1)->find();
                            if (empty($certifi_person)) {
                                $certifi_person = \Think\Db::name("certifi_company")->where("auth_user_id", "=", $User)->where("status", "=", 1)->find();
                            }
                            if ($certifi_person) {
                                $prize_setting = unserialize($vv["setting"]);
                                if (!empty($prize_setting)) {
                                    $text = "";
                                    switch ($setting["activity_prize"]) {
                                        case "现金红包":
                                            $text = "实名认证赠送" . $setting["activity_prize"];
                                            break;
                                        case "优惠券":
                                            if ($prize_setting["type"] == "fixed") {
                                                $text = $prize_setting["value"] . "元" . $setting["activity_prize"];
                                            } else {
                                                $text = $prize_setting["value"] . "元" . $setting["activity_prize"];
                                            }
                                            break;
                                        case "代理级别":
                                            $text = "实名认证赠送";
                                            break;
                                        default:
                                            $text = "";
                                            if (!empty($text)) {
                                                if ($setting["activity_prize"] == "代理级别") {
                                                    if (intval($prize_setting["value"]) != intval($Clients["groupid"]) && floatval($ClientGroups[$prize_setting["value"]]["bates"]) < floatval($ClientGroups[$Clients["groupid"]]["bates"])) {
                                                        try {
                                                            if (!empty($prize_setting["value"])) {
                                                                \Think\Db::name("clients")->where("id", "=", $User)->update(["groupid" => $prize_setting["value"]]);
                                                                \Think\Db::name("gzhx_activity_user")->insert(["uid" => $User, "type" => "verified", "plugin" => $this->PluginName, "aid" => $vv["id"], "error" => "升级成功", "add_time" => date("Y-m-d H:i:s"), "msg" => "实名认证赠送升级为" . $ClientGroups[$prize_setting["value"]]["group_name"]]);
                                                                \Think\Db::commit();
                                                            }
                                                        } catch (Exception $e) {
                                                            \Think\Db::rollback();
                                                        }
                                                    }
                                                } else {
                                                    \Think\Db::name("gzhx_activity_user")->insert(["uid" => $User, "type" => "verified", "plugin" => $this->PluginName, "aid" => $vv["id"], "msg" => "实名认证赠送" . $text]);
                                                }
                                            }
                                    }
                                }
                            }
                        }
                    }
                    if ($setting["activity_type"] == "单笔充值") {
                        $prizes = [];
                        foreach ($prize as $kk => $vv) {
                            $prizes[$vv["id"]] = $vv["winning"];
                        }
                        $prizes_list = array_column($prize, NULL, "id");
                        arsort($prizes);
                        $MinMoney = end($prizes);
                        $invoices = \Think\Db::name("invoices")->where("type", "=", "recharge")->where("payment_status", "=", "Paid")->where("paid_time", ">=", strtotime($item["start_time"]))->where("total", ">=", $MinMoney)->where("uid", "=", $User)->select()->toArray();
                        foreach ($invoices as $kkk => $vvv) {
                            if (!strstr($vvv["notes"], $this->PluginName . "抽奖")) {
                                foreach ($prizes as $kk => $vv) {
                                    $prizes_info = $prizes_list[$kk];
                                    if (!empty($prizes_info)) {
                                        $prize_setting = unserialize($prizes_list[$kk]["setting"]);
                                        if (!empty($prize_setting)) {
                                            $text = "";
                                            switch ($setting["activity_prize"]) {
                                                case "现金红包":
                                                    $text = $prize_setting["value"] . "元" . $setting["activity_prize"];
                                                    break;
                                                case "优惠券":
                                                    if ($prize_setting["type"] == "fixed") {
                                                        $text = $prize_setting["value"] . "元" . $setting["activity_prize"];
                                                    } else {
                                                        $text = $prize_setting["value"] . "%折扣" . $setting["activity_prize"];
                                                    }
                                                    break;
                                                case "代理级别":
                                                    $text = "代理";
                                                    break;
                                                default:
                                                    $text = "";
                                                    if (!empty($text)) {
                                                        if ($prizes_info["winning"] <= floatval($vvv["total"])) {
                                                            $checkInvoices = \Think\Db::name("gzhx_activity_user")->where("uid", "=", $User)->where("type", "=", "onepay#" . $vvv["id"])->where("plugin", "=", $this->PluginName)->where("aid", "=", $prizes_info["id"])->find();
                                                            if (empty($checkInvoices)) {
                                                                if ($setting["activity_prize"] == "代理级别") {
                                                                    if (intval($prize_setting["value"]) != intval($Clients["groupid"]) && floatval($ClientGroups[$prize_setting["value"]]["bates"]) < floatval($ClientGroups[$Clients["groupid"]]["bates"])) {
                                                                        try {
                                                                            if (!empty($prize_setting["value"])) {
                                                                                \Think\Db::name("clients")->where("id", "=", $User)->update(["groupid" => $prize_setting["value"]]);
                                                                                \Think\Db::name("gzhx_activity_user")->insert(["uid" => $User, "type" => "onepay#" . $vvv["id"], "plugin" => $this->PluginName, "aid" => $prizes_info["id"], "error" => "升级成功", "add_time" => date("Y-m-d H:i:s"), "msg" => "单笔充值满" . $prizes_info["winning"] . "元升级为" . $ClientGroups[$prize_setting["value"]]["group_name"]]);
                                                                                \Think\Db::commit();
                                                                            }
                                                                        } catch (Exception $e) {
                                                                            \Think\Db::rollback();
                                                                        }
                                                                    }
                                                                } else {
                                                                    \Think\Db::name("gzhx_activity_user")->insert(["uid" => $User, "type" => "onepay#" . $vvv["id"], "plugin" => $this->PluginName, "aid" => $prizes_info["id"], "msg" => "单笔充值满" . $prizes_info["winning"] . "元获得" . $text]);
                                                                }
                                                            }
                                                        }
                                                    }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } else {
                        if ($setting["activity_type"] == "累积充值") {
                            $invoices = \Think\Db::name("invoices")->where("type", "=", "recharge")->where("uid", "=", $User)->where("payment_status", "=", "Paid")->where("paid_time", ">=", strtotime($item["start_time"]))->sum("total");
                            foreach ($prize as $kk => $vv) {
                                $prize_setting = unserialize($vv["setting"]);
                                if (!empty($prize_setting)) {
                                    $text = "";
                                    switch ($setting["activity_prize"]) {
                                        case "现金红包":
                                            $text = $prize_setting["value"] . "元" . $setting["activity_prize"];
                                            break;
                                        case "优惠券":
                                            if ($prize_setting["type"] == "fixed") {
                                                $text = $prize_setting["value"] . "元" . $setting["activity_prize"];
                                            } else {
                                                $text = $prize_setting["value"] . "%折扣" . $setting["activity_prize"];
                                            }
                                            break;
                                        case "代理级别":
                                            $text = "代理";
                                            break;
                                        default:
                                            $text = "";
                                            if (!empty($text)) {
                                                if (floatval($vv["winning"]) <= $invoices) {
                                                    $checkInvoices = \Think\Db::name("gzhx_activity_user")->where("uid", "=", $User)->where("type", "=", "totalonpay#" . $vv["id"])->where("plugin", "=", $this->PluginName)->where("aid", "=", $vv["id"])->find();
                                                    if (empty($checkInvoices)) {
                                                        if ($setting["activity_prize"] == "代理级别") {
                                                            if (intval($prize_setting["value"]) != intval($Clients["groupid"]) && floatval($ClientGroups[$prize_setting["value"]]["bates"]) < floatval($ClientGroups[$Clients["groupid"]]["bates"])) {
                                                                try {
                                                                    if (!empty($prize_setting["value"])) {
                                                                        \Think\Db::name("clients")->where("id", "=", $User)->update(["groupid" => $prize_setting["value"]]);
                                                                        \Think\Db::name("gzhx_activity_user")->insert(["uid" => $User, "type" => "totalonpay#" . $vv["id"], "plugin" => $this->PluginName, "aid" => $vv["id"], "error" => "升级成功", "add_time" => date("Y-m-d H:i:s"), "msg" => "单笔充值满" . $vv["winning"] . "元升级为" . $ClientGroups[$prize_setting["value"]]["group_name"]]);
                                                                        \Think\Db::commit();
                                                                    }
                                                                } catch (Exception $e) {
                                                                    \Think\Db::rollback();
                                                                }
                                                            }
                                                        } else {
                                                            \Think\Db::name("gzhx_activity_user")->insert(["uid" => $User, "type" => "totalonpay#" . $vv["id"], "plugin" => $this->PluginName, "aid" => $vv["id"], "msg" => "累计充值满" . $vv["winning"] . "元获得" . $text]);
                                                        }
                                                    }
                                                }
                                            }
                                    }
                                }
                            }
                        } else {
                            if ($setting["activity_type"] == "累积消费") {
                                $invoicesCredit = \Think\Db::name("invoices")->where("type", "in", ["product", "upgrade", "renew"])->where("payment_status", "=", "Paid")->where("uid", "=", $User)->where("paid_time", ">=", strtotime($item["start_time"]))->sum("credit");
                                foreach ($prize as $kk => $vv) {
                                    $prize_setting = unserialize($vv["setting"]);
                                    if (!empty($prize_setting)) {
                                        $text = "";
                                        switch ($setting["activity_prize"]) {
                                            case "现金红包":
                                                $text = $prize_setting["value"] . "元" . $setting["activity_prize"];
                                                break;
                                            case "优惠券":
                                                if ($prize_setting["type"] == "fixed") {
                                                    $text = $prize_setting["value"] . "元" . $setting["activity_prize"];
                                                } else {
                                                    $text = $prize_setting["value"] . "%折扣" . $setting["activity_prize"];
                                                }
                                                break;
                                            default:
                                                if (floatval($vv["winning"]) <= $invoicesCredit) {
                                                    $checkInvoices = \Think\Db::name("gzhx_activity_user")->where("uid", "=", $User)->where("type", "=", "oneonconsumption#" . $vv["id"])->where("plugin", "=", $this->PluginName)->where("aid", "=", $vv["id"])->find();
                                                    if (empty($checkInvoices)) {
                                                        if ($setting["activity_prize"] == "代理级别") {
                                                            if (intval($prize_setting["value"]) != intval($Clients["groupid"]) && floatval($ClientGroups[$prize_setting["value"]]["bates"]) < floatval($ClientGroups[$Clients["groupid"]]["bates"])) {
                                                                try {
                                                                    if (!empty($prize_setting["value"])) {
                                                                        \Think\Db::name("clients")->where("id", "=", $User)->update(["groupid" => $prize_setting["value"]]);
                                                                        \Think\Db::name("gzhx_activity_user")->insert(["uid" => $User, "type" => "oneonconsumption#" . $vv["id"], "plugin" => $this->PluginName, "aid" => $vv["id"], "error" => "升级成功", "add_time" => date("Y-m-d H:i:s"), "msg" => "累积消费满" . $vv["winning"] . "元升级为" . $ClientGroups[$prize_setting["value"]]["group_name"]]);
                                                                        \Think\Db::commit();
                                                                    }
                                                                } catch (Exception $e) {
                                                                    \Think\Db::rollback();
                                                                }
                                                            }
                                                        } else {
                                                            \Think\Db::name("gzhx_activity_user")->insert(["uid" => $User, "type" => "oneonconsumption#" . $vv["id"], "plugin" => $this->PluginName, "aid" => $vv["id"], "msg" => "累积消费满" . $vv["winning"] . "元获得" . $text]);
                                                        }
                                                    }
                                                }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        $page = !intval($_GET["page"]) ? 1 : intval($_GET["page"]);
        if ($page < 1) {
            $page = 1;
        }
        $limit = 10;
        $count = \Think\Db::name("gzhx_activity_user")->alias("a")->leftJoin("gzhx_activity_prize_setting c", "a.aid=c.id")->leftJoin("gzhx_activity b", "CONCAT('" . $this->PluginName . "_',b.id)=c.plugin")->where("a.uid", "=", $User)->where("a.plugin", "=", $this->PluginName)->count();
        $list = \Think\Db::name("gzhx_activity_user")->alias("a")->field("a.*,b.title,b.end_time as activity_end_time")->leftJoin("gzhx_activity_prize_setting c", "a.aid=c.id")->leftJoin("gzhx_activity b", "CONCAT('" . $this->PluginName . "_',b.id)=c.plugin")->where("a.plugin", "=", $this->PluginName)->where("a.uid", "=", $User)->page($page . "," . $limit)->order("a.id desc")->select()->toArray();
        foreach ($list as $k => $v) {
            if (strtotime($v["activity_end_time"]) < time() && empty($v["error"])) {
                $list[$k]["error"] = "活动过期";
            }
        }
        $this->assign("DomainList", $list);
        $this->assign("count", $count);
        $this->assign("Page", $page);
        $this->assign("Title", "奖品领取");
        return $this->fetchTemplete("/index");
    }
}

?>