<?php

namespace App\Services\marketing;


use App\Exception\custom\MarketingException;
use App\Models\marketing\mysql\ColonelDistributorInviteOrderNum;
use App\Models\marketing\mysql\Marketing;
use App\Models\marketing\mysql\ColonelDistributorConfig;

class PindanActivityColonelConfigService
{
    // 活动默认时间范围点
    const ACTIVITY_DEFAULT_HOUR = 12;

    /**
     * 编辑团长分销活动配置
     * @param array $params
     * @return bool
     * @throws MarketingException
     */
    public static function editColonelConfig($params = [])
    {
        $date = $params["date"];
        $today = date("Y-m-d");
        $hour = date("H");
        if ($date < $today || ($date == $today && $hour >= 12)) {
            throw new MarketingException(['cus' => MarketingException::COLONEL_DATE_ERROR]);
        }

        $type = empty($params["type"]) ? ColonelDistributorConfig::TYPE_COLONEL : $params["type"];
        $configList = $params["config"];
        $marketingId = $params["marketing_id"];

        if (empty($configList)) {
            throw new MarketingException(['cus' => MarketingException::COLONEL_CONFIG_NULL]);
        }

        if (count($configList) > 6) {
            throw new MarketingException(['cus' => MarketingException::COLONEL_LEVEL_SIX]);
        }

        $idRes = ColonelDistributorConfig::getRecordMaster(["date" => $date, "type" => $type, "marketing_id" => $marketingId], ["colonel_config_id"]);
        if (!empty($idRes[0]["colonel_config_id"])) {
            ColonelDistributorConfig::save([
                "marketing_id" => $marketingId,
                "date" => $date,
                "type" => $type,
                "data" => $configList,
            ], ["colonel_config_id" => $idRes[0]["colonel_config_id"]]);
        } else {
            ColonelDistributorConfig::save([
                "marketing_id" => $marketingId,
                "date" => $date,
                "type" => $type,
                "data" => $configList,
            ]);
        }

        return true;
    }

    /**
     * 团长分销活动配置
     * @param array $params
     * @return array
     */
    public static function colonelConfig($params = [])
    {
        $day = $params["date"];
        $type = empty($params["type"]) ? ColonelDistributorConfig::TYPE_COLONEL : $params["type"];
        if(empty($day)) {
            //默认取最近更新的一条配置
            $config = ColonelDistributorConfig::getRecord([
               "type" => $type,"ORDER" => ["update_time" => "DESC"], "LIMIT" => 1
            ]);
        }else {
            $config = ColonelDistributorConfig::getRecord(["date" => $day, "type" => $type]);
        }
        if (empty($config)) {
            $config = ColonelDistributorConfig::getRecord([
                "date[<=]" => $day,
                "ORDER" => ["date" => "DESC"],
                "LIMIT" => 1
            ]);
        }

        $data = [];
        if (!empty($config)) {
            $configData = json_decode($config["data"], true);
            foreach ($configData as $key => $item) {
                $data[$key]["marketing_id"] = $config["marketing_id"];
                $data[$key]["date"] = $config["date"];
                $data[$key]["level"] = $item["level"];
                $data[$key]["assess_order_num"] = $item["assess_order_num"];
                $data[$key]["reward_amount"] = $item["reward_amount"];
            }
            $sortKeys = array_column($data, "level");
            array_multisort($sortKeys, SORT_ASC, $data);
        }
        return $data;
    }

    /**
     * 团长分销活动任务中心列表
     * @param array $params
     * @return array
     */
    public static function getTaskData($params = [])
    {
        $timeRange = self::getActivityTimeRange();
        $date = date("Y-m-d", strtotime($timeRange["start_time"]));

        $configList = self::colonelConfig(["date" => $date, "type" => ColonelDistributorConfig::TYPE_COLONEL]);
        $marketingId = empty($configList[0]["marketing_id"]) ? 0 : $configList[0]["marketing_id"];
        if (!Marketing::isGoing($marketingId)) {
            return ["number" => 0, 'list' => []];
        }

        $num = 0;
        if (!empty($params["user_id"])) {
            $inviteOrderNumRes = ColonelDistributorInviteOrderNum::getRecord([
                "colonel_user_id" => $params["user_id"],
                "date" => $date,
            ]);
            $num = empty($inviteOrderNumRes["num"]) ? 0 : $inviteOrderNumRes["num"];
        }

        if (!empty($configList)) {
            foreach ($configList as $key => $config) {
                $configList[$key]["is_finish"] = 0;
                if ($config["assess_order_num"] <= $num) {
                    $configList[$key]["is_finish"] = 1;
                }
            }
        }
        return ["number" => $num, 'list' => $configList];
    }


    /**
     * Notes: 获取活动时间范围
     * User: pengfei@yidian-inc.com
     * Date: 2021/9/3 2:50 下午
     * @return string[]
     */
    public static function getActivityTimeRange() : array
    {
        // 获取活动时间范围   例如活动时间（2021-09-03） --- 2021-09-03:12:00:00 - 2021-09-04:12:00:00
        $hour = ' '.self::ACTIVITY_DEFAULT_HOUR . ':00:00';
        if (date('H') >= self::ACTIVITY_DEFAULT_HOUR) {
            $startTime = date('Y-m-d').$hour;
            $endTime = date('Y-m-d', strtotime('+1 day')).$hour;
        } else {
            $startTime = date('Y-m-d', strtotime('-1 day')).$hour;
            $endTime = date('Y-m-d').$hour;
        }
        return [
            'start_time' => $startTime,
            'end_time' => $endTime,
            'date' => date('Y-m-d', strtotime($startTime))
        ];
    }

    /**
     * Notes: 获取结算时间范围
     * User: pengfei@yidian-inc.com
     * Date: 2021/9/3 2:50 下午
     * @return string[]
     */
    public static function getSettlementTimeRange() : array
    {
        // 获取活动时间范围   例如当前时间（2021-09-03 12:00:00） 应结算时间为 2021-08-31-:12:00:00 - 2021-09-01:12:00:00
        $hour = ' '.self::ACTIVITY_DEFAULT_HOUR . ':00:00';
        $startTime = date('Y-m-d', strtotime('-3 day')).$hour;
        $endTime   = date('Y-m-d', strtotime('-2 day')).$hour;
        return [
            'start_time' => $startTime,
            'end_time' => $endTime,
            'date' => date('Y-m-d', strtotime($startTime))
        ];
    }

}