<?php

namespace Modules\Callback\Services;

use Illuminate\Support\Facades\DB;
use Modules\Permissions\Middlewares\PermissionGate;

/**
 * 巨量2.0事件-微信小程序
 */
class JLEventService
{
    /**
     * 判断回传配置的金额项
     * @param $chargeMoneyMap
     * <pre>
     * [
     *      [
     *          'min_money' => 1, // 最小金额
     *          'max_money' => 2, // 最大金额(不包含)
     *          'callback_type' => 1, // 回传参数,类型:1-全部回传,2-全部不回传,3-自定义
     *          'callback_param' => '1:1', // callback_type == 3 时, 自定义,传几卡几
     *      ]
     * ]
     * </pre>
     */
    public static function judgeChargeMoneyOk($chargeMoneyMap) {
        $len = count($chargeMoneyMap);
        for($i = 0; $i < $len; $i++) {
            for($j = $i+1; $j < $len ; $j ++) {
                if($chargeMoneyMap[$i]['min_money'] >= $chargeMoneyMap[$j]['max_money'] ||
                    $chargeMoneyMap[$i]['max_money'] <= $chargeMoneyMap[$j]['min_money']) {
                    continue;
                } else {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 金额项的卡比例选项
     * @return array
     */
    public static function listCustomCallBackRate() {
        $arr = explode(',', config('callback.jlEvent.customRate'));
        $result = [];
        foreach ($arr as $item) {
            $temp = explode(':', $item);
            $result[$item] = '传'.$temp[0].'卡'.$temp[1];
        }
        return $result;
    }

    /**
     * 回传配置的金额项的比例配置信息
     * @param $userId 优化师id
     * @param $configId 回传配置id
     * @param $chargeMoneyMap
     * <pre>
     * [
     *      [
     *          'min_money' => 1, // 最小金额
     *          'max_money' => 2, // 最大金额(不包含)
     *          'callback_type' => 1, // 回传参数,类型:1-全部回传,2-全部不回传,3-自定义
     *          'callback_param' => '1:1', // callback_type == 3 时, 自定义,传几卡几
     *      ]
     * ]
     * </pre>
     */
    public static function saveRateConfigLog($userId, $configId, $chargeMoneyMap){
        $now = date('Y-m-d H:i:s');
        DB::table('jl_event_rate_config_log')
            ->where([
                'user_id' => $userId, 'config_id' => $configId,
                'is_enabled' => 1,
            ])->update([
                'is_enabled' => 0, 'updated_at' => $now,
            ]);

        $insertData = [];
        foreach ($chargeMoneyMap as $item) {
            if(3 == $item['callback_type']) {
                $insertData[] = [
                    'user_id' => $userId,
                    'config_id' => $configId,
                    'rate_str' => $item['callback_param'],
                    'created_at' => $now, 'updated_at' => $now,
                    'min_money' => $item['min_money'],
                    'max_money' => $item['max_money']
                ];
            }
        }
        if(count($insertData)) {
            DB::table('jl_event_rate_config_log')
                ->insert($insertData);
        }
    }
}
