<?php

namespace App\Services\marketing;

use App\Exception\custom\MarketingException;
use App\Models\marketing\mysql\ColonelDistributorColonel;
use App\Models\marketing\mysql\ColonelDistributorInviteOrder;
use App\Models\marketing\mysql\ColonelDistributorInviteOrderNum;
use App\Models\marketing\mysql\ColonelDistributorPayInfo;
use App\Services\user\UserService;

class PindanActivityInviteOrderService
{
    /**
     * 团长分销下单逻辑
     * @param array $params
     * @return bool
     * @throws MarketingException
     */
    public static function placeOrder($params = [])
    {
        $num = empty($params["num"]) ? 1 : $params["num"];
        $inviteOrderData = [
            "colonel_user_id" => $params["colonel_user_id"],
            "user_id" => $params["user_id"],
            "order_id" => $params["order_id"],
            "refund_time" => null,
        ];

        $inviteOrder = ColonelDistributorInviteOrder::selectMaster("*", $inviteOrderData, []);
        if (!empty($inviteOrder)) {
            return true;
        }

        $hour = date("H");
        if ($hour < 10 && $hour > 0) {
            $date = date("Y-m-d", strtotime("-1 day"));
        } elseif ($hour > 16) {
            $date = date("Y-m-d");
        } else {
            $date = date("Y-m-d");
        }

        $inviteOrderNumData = [
            "colonel_user_id" => $params["colonel_user_id"],
            "date" => $date,
        ];
        $inviteOrderNum = ColonelDistributorInviteOrderNum::selectMaster("*", $inviteOrderNumData, []);

        ColonelDistributorInviteOrder::beginTransaction();
        $addInviteOrderRes = ColonelDistributorInviteOrder::save($inviteOrderData);

        if (!empty($inviteOrderNum)) {
            $addInviteOrderNumRes = ColonelDistributorInviteOrderNum::save(["num[+]" => $num], ["invite_order_num_id" => $inviteOrderNum[0]["invite_order_num_id"]]);
        } else {
            $inviteOrderNumData["num"] = $num;
            $addInviteOrderNumRes = ColonelDistributorInviteOrderNum::save($inviteOrderNumData);
        }

        if (empty($addInviteOrderRes) || empty($addInviteOrderNumRes) || !ColonelDistributorInviteOrder::commit()) {
            ColonelDistributorInviteOrder::rollback();
            throw new MarketingException(["cus" => MarketingException::COMMIT_ERROR]);
        }
        return true;
    }

    /**
     * 团长分销退单逻辑
     * @param array $params
     * @return bool
     * @throws MarketingException
     */
    public static function refundOrder($params = [])
    {
        $orderId = $params["order_id"];

        $inviteOrder = ColonelDistributorInviteOrder::selectMaster("*", ["order_id" => $orderId], []);
        if (!empty($inviteOrder) && $inviteOrder[0]["is_refund"] == ColonelDistributorInviteOrder::IS_REFUND_NO) {
            $inviteOrderData = [
                "colonel_user_id" => $inviteOrder[0]["colonel_user_id"],
                "user_id" => $inviteOrder[0]["user_id"],
                "order_id" => $orderId,
            ];

            $hour = date("H");
            if ($hour < 10 && $hour > 0) {
                $date = date("Y-m-d", strtotime("-1 day"));
            } elseif ($hour > 16) {
                $date = date("Y-m-d");
            } else {
                $date = date("Y-m-d");
            }
            $inviteOrderNumData = [
                "colonel_user_id" => $inviteOrder[0]["colonel_user_id"],
                "date" => $date,
            ];

            ColonelDistributorInviteOrder::beginTransaction();
            $addInviteOrderRes = ColonelDistributorInviteOrder::save([
                "is_refund" => ColonelDistributorInviteOrder::IS_REFUND_YES,
                "refund_time" => date("y-m-d H:i:s")
            ], $inviteOrderData);

            $addInviteOrderNumRes = ColonelDistributorInviteOrderNum::save(["num[-]" => 1], $inviteOrderNumData);

            if (empty($addInviteOrderRes) || empty($addInviteOrderNumRes) || !ColonelDistributorInviteOrder::commit()) {
                ColonelDistributorInviteOrder::rollback();
                throw new MarketingException(["cus" => MarketingException::COMMIT_ERROR]);
            }
        }
        return true;
    }

    /**
     * 团长分销，昨日收入，总收入
     * @param array $params
     * @return array
     */
    public static function incomeStatistics($params = [])
    {
        $userIds = $params["user_ids"];
        $yesterday = date("Y-m-d", strtotime("-1 day"));

        $yesterdayRewards = ColonelDistributorPayInfo::select(["colonel_user_id", "reward"], ["date" => $yesterday, "colonel_user_id" => $userIds], []);
        $yesterdayData = [];
        if (!empty($yesterdayRewards)) {
            foreach ($yesterdayRewards as $item) {
                $yesterdayData[$item["colonel_user_id"]][] = $item["reward"];
            }
        }

        $allRewards = ColonelDistributorPayInfo::select(["colonel_user_id", "reward"], ["colonel_user_id" => $userIds], []);
        $allData = [];
        if (!empty($allRewards)) {
            foreach ($allRewards as $item) {
                $allData[$item["colonel_user_id"]][] = $item["reward"];
            }
        }

        $data = [];
        foreach ($userIds as $userId) {
            $data[$userId]["yesterday_reward"] = 0;
            $data[$userId]["all_reward"] = 0;
            if (!empty($yesterdayData[$userId])) {
                $data[$userId]["yesterday_reward"] = sprintf("%.2f", array_sum($yesterdayData[$userId]) / 100);
            }
            if (!empty($allData[$userId])) {
                $data[$userId]["all_reward"] = sprintf("%.2f", array_sum($allData[$userId]) / 100);
            }
        }

        return $data;
    }

    /**
     * 团长分销，昨日转化单数，总转化单数
     * @param array $params
     * @return array
     */
    public static function inviteOrderNumberStatistics($params = [])
    {
        $userIds = $params["user_ids"];
        $yesterday = date("Y-m-d", strtotime("-1 day"));

        $yesterdayNums = ColonelDistributorInviteOrderNum::select(["colonel_user_id", "num"],
            ["date" => $yesterday, "colonel_user_id" => $userIds], []);
        $yesterdayData = array_column($yesterdayNums, null, "colonel_user_id");

        $allNums = ColonelDistributorInviteOrderNum::select(["colonel_user_id", "num"], ["colonel_user_id" => $userIds], []);
        $allData = array_column($allNums, null, "colonel_user_id");

        $data = [];
        foreach ($userIds as $userId) {
            $data[$userId]["yesterday_order_num"] = 0;
            $data[$userId]["all_order_num"] = 0;
            if (!empty($yesterdayData[$userId])) {
                $data[$userId]["yesterday_order_num"] = $yesterdayData[$userId]["num"];
            }
            if (!empty($allData[$userId])) {
                $data[$userId]["all_order_num"] = $allData[$userId]["num"];
            }
        }
        return $data;
    }

    /**
     *  团长分销，账单详情
     * @param array $params
     * @return array
     */
    public static function getPayInfoList($params = [])
    {
        $weekDay = date("Y-m-d", strtotime("-7 day"));
        $userId = $params["user_id"];
        if (empty($userId)) {
            return [];
        }

        $payList = ColonelDistributorPayInfo::select("*", [
            "colonel_user_id" => $userId,
            "date[>=]" => $weekDay,
            "ORDER" => ["date" => "DESC"]
        ], []);
        $data = $res = [];
        if (!empty($payList)) {
            foreach ($payList as $item) {
                $tempItem = [];
                $tempItem["type"] = $item["type"];
                $tempItem["type_desc"] = ColonelDistributorPayInfo::$typeDesc[$item["type"]];
                $tempItem["invite_user_id"] = $item["invite_user_id"];
                $tempItem["invite_user_nick"] = $item["invite_user_nick"];
                $tempItem["reward"] = $item["reward"];
                $tempItem["finish_num"] = $item["finish_num"];
                $tempItem["status"] = $item["status"];
                $data[$item["date"]][] = $tempItem;
            }

            foreach ($data as $key => $item) {
                $rewards = array_column($item, "reward");
                $total = array_sum($rewards);

                $res[$key]["total"] = $total / 100;
                $res[$key]["date"] = $key;
                $res[$key]["data"] = $item;
                foreach ($item as $k => $v) {
                    $res[$key]["data"][$k]["reward"] = $v["reward"] / 100;
                }
            }
        }
        return array_values($res);
    }

    /**
     * 团长分销，下单记录
     * @param array $params
     * @return array
     */
    public static function getInviteOrderRecord($params = [])
    {
        $userId = $params["user_id"];
        $lastId = empty($params["last_id"]) ? "" : $params["last_id"];
        $limit = empty($params["page_size"]) ? 10 : $params["page_size"];

        $hour = date("H");
        if ($hour < 10 && $hour > 0) {
            $date = date("Y-m-d", strtotime("-1 day"));
        } elseif ($hour > 16) {
            $date = date("Y-m-d");
        } else {
            $date = date("Y-m-d");
        }

        $secondDay = date("Y-m-d", strtotime("$date +1 day"));
        $startTime = $date." 16:00:00";
        $endTime = $secondDay." 10:00:00";

        $where = [];
        $where["colonel_user_id"] = $userId;
        $where["create_time[>]"] = $startTime;
        $where["create_time[<]"] = $endTime;
        $where["LIMIT"] = $limit;
        $where["ORDER"] = ["invite_order_id" => "DESC"];

        if (!empty($lastId)) {
            $where["invite_order_id[<]"] = $lastId;
        }

        $list = ColonelDistributorInviteOrder::select(["invite_order_id", "user_id", "is_refund"], $where, []);
        if (!empty($list)) {
            $userIds = array_unique(array_column($list, "user_id"));
            $userList = UserService::userWechatBind(["user_id"=>$userIds]);
            if (!empty($userList)) {
                $userList = array_column($userList, null, "user_id");
            }

            $count = count($list);
            foreach ($list as $key => $item) {
                if (!empty($userList[$item["user_id"]])) {
                    $list[$key]["user_nick"] = $userList[$item["user_id"]]["user_nick"];
                    $list[$key]["user_avatar"] = $userList[$item["user_id"]]["user_avatar"];
                } else {
                    $list[$key]["user_nick"] = "";
                    $list[$key]["user_avatar"] = "";
                }
                $lastId = $item["invite_order_id"];
            }
            if ($count < $limit) {
                $lastId = "-1";
            }
        } else {
            $lastId = "-1";
        }
        return ["list" => $list, "last_id" => $lastId];
    }
}