<?php

namespace Modules\Tuiguang\Http\Controllers;

use Catch\Base\CatchController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\Common\Errors\Errors;
use Modules\Common\Exceptions\CommonBusinessException;
use Modules\User\Http\Controllers\UserTrait;

class RanseConfigController extends CatchController
{
    use UserTrait;
    use ValidatesRequests;
    /**
     * 设置染色时间
     * @param Request $request
     */
    public function setRanseDuration(Request $request) {
        $this->validate($request, [
            'no_charge_user_duration' => 'required|integer|min:0',
            'charge_user_duration' => 'required|integer|gte:no_charge_user_duration',
        ]);
        $uid = $this->getOptimizerUid();
        if(!$uid) {
            CommonBusinessException::throwError(Errors::NO_OPERATE_PERMISSION);
        }
        $now = date('Y-m-d H:i:s');
        DB::table('ranse_config')->where('user_id', $uid)
            ->where('is_enabled', 1)
            ->update(['is_enabled' => 0, 'updated_at' => $now]);
        DB::table('ranse_config')
            ->insert([
                'user_id' => $uid, 'is_enabled' => 1,
                'no_charge_user_duration' => $request->input('no_charge_user_duration'),
                'charge_user_duration' => $request->input('charge_user_duration'),
                'created_at' => $now, 'updated_at' => $now,
            ]);

        return 'ok';
    }

    /**
     * 获取染色时间
     * @param Request $request
     * @return array
     */
    public function getRanseDuration(Request $request) {
        $uid = $this->getOptimizerUid();
        if(!$uid) {
            CommonBusinessException::throwError(Errors::NO_OPERATE_PERMISSION);
        }

        $config = DB::table('ranse_config')->where('user_id', $uid)
            ->where('is_enabled', 1)
            ->first();
        if(!$config) {
            $config = DB::table('ranse_config')
                ->where([
                    'user_id' => 0, 'miniprogram_id' => 0, 'is_enabled' =>1
                ])->first();
        }

        return [
            'charge_user_duration' => $config->charge_user_duration,
            'no_charge_user_duration' => $config->no_charge_user_duration,
        ];
    }
}
