<?php

namespace Modules\Callback\Http\Controllers\JLEvent;

use Catch\Base\CatchController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\Callback\Models\JLEventCallbackConfigModel;
use Modules\Callback\Services\CallbackConst;
use Modules\Callback\Services\JLEventService;
use Modules\Common\Errors\Errors;
use Modules\Common\Exceptions\CommonBusinessException;

/**
 * 巨量2.0事件-微信小程序
 */
class JLEventController extends CatchController
{
    use ValidatesRequests;
    /**
     * 回传配置列表
     * @param Request $request
     */
    public function list(Request $request) {
        $id = $request->input('id');
        $name = $request->input('name');
        $promotionId = $request->input('promotion_id');
        $unbind = $request->input('unbind', 0);

        $result =  DB::table('jl_event_callback_config as config')
            ->leftJoin('promotions', 'promotions.callback_config_id', '=', 'config.id')
            ->where([
                'user_id' => $this->getLoginUserId(),
            ])->when($id, function ($query, $id){
                return $query->where('config.id', $id);
            })->when($name, function ($query, $name){
                return $query->where('config.name', 'like', '%' .$name. '%');
            })->when($promotionId, function ($query, $promotionId){
                return $query->where('promotions.id', $promotionId)
                    ->where('promotions.callback_type' , CallbackConst::TYPE_JL_EVENT_20);
            })->when(1 == $unbind, function ($query){
                return $query->whereNull('promotions.id');
            })
            ->select('config.id', 'config.name', 'config.charge_type', 'config.updated_at',
                'promotions.name as promotion_name', 'promotions.id as promotion_id',
            'config.charge_money_map', 'config.is_roi')
            ->orderBy('id', 'desc')
            ->paginate($request->input('limit', 15));
        foreach ($result as $item){
            $item->charge_type_str = CallbackConst::CHARGE_TYPE_MAP[$item->charge_type] ?? '-';
            $item->charge_money_map = \json_decode($item->charge_money_map) ?? [];
        }
        return $result;
    }

    /**
     * 新增回传配置
     * @param Request $request
     */
    public function add(Request $request) {
        $this->validate($request, [
            'name' => 'required|string|max:64',
            // roi 全量上报:1-全量上报,2-不全量上报
            'is_roi' => 'required|integer|in:1,2',
            // 充值行为:1-首充,2-所有充值
            'charge_type' => 'required_if:is_roi,2|integer|in:1,2',
            // 金额项
            'charge_money_map'  => 'required_if:is_roi,2|array',
            'charge_money_map.*.min_money' => 'integer|min:0',
        ]);
        if(2 == $request->input('is_roi') &&
            (!JLEventService::judgeChargeMoneyOk($request->input('charge_money_map')))) {
            CommonBusinessException::throwError(Errors::CALLBACK_CHARGE_MONEY_MAP_ERROR);
        }
        $userId = $this->getLoginUserId();


        $model = JLEventCallbackConfigModel::create(array_merge($request->only('name', 'is_roi', 'charge_type'), [
            'charge_money_map' => \json_encode($request->input('charge_money_map')),
            'user_id' => $userId,
        ]));

        JLEventService::saveRateConfigLog($userId, $model->id, $request->input('charge_money_map', []));

        return 'ok';
    }

    /**
     * 更新回传配置
     * @param Request $request
     */
    public function update(Request $request) {
        $this->validate($request, [
            'ids' => 'required|array',
            'ids.*' => 'integer',
            // roi 全量上报:1-全量上报,2-不全量上报
            'is_roi' => 'required|integer|in:1,2',
            // 充值行为:1-首充,2-所有充值
            'charge_type' => 'required_if:is_roi,2|integer|in:1,2',
            // 金额项
            'charge_money_map'  => 'required_if:is_roi,2|array',
            'charge_money_map.*.min_money' => 'integer|min:0',
        ]);

        if(1 == count($request->input('ids'))) {
            $updateData = $request->only('is_roi', 'charge_type', 'name');
        } else {
            $updateData = $request->only('is_roi', 'charge_type');
        }
        $now = date('Y-m-d H:i:s');
        $userId = $this->getLoginUserId();
        $configIds = DB::table('jl_event_callback_config')
            ->whereIn('id', $request->input('ids'))
            ->where('user_id', $userId)
            ->select('id')->get()->pluck('id');
        DB::table('jl_event_callback_config')
            ->whereIn('id', $configIds)
            ->update(array_merge($updateData, [
                'charge_money_map' => \json_encode($request->input('charge_money_map', [])),
                'updated_at' => $now,
            ]));
        foreach ($configIds as $configId) {
            JLEventService::saveRateConfigLog($userId, $configId, $request->input('charge_money_map', []));
        }
        return 'ok';
    }
}
