<?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 PromotionController extends CatchController
{
    use UserTrait;
    use ValidatesRequests;
    public function list(Request $request) {
        $callbackTypeMap = [
            '0' => '无',
            '1' => '巨量账户级回传',
        ];
        $linkSourceMap = [
            '0' => '',
            '1' => 'tiktok'
        ];
        $name = $request->input('name');
        $isConfig = $request->input('is_config', 1);
        $id = $request->input('id');
        $videoName = $request->input('video_name');
        $starTime = $request->input('start_time');
        $endTime = $request->input('end_time');
        $miniprogramId = $request->input('miniprogram_id');
        $result = DB::table('promotions')
            ->leftJoin('videos', 'videos.id', '=', 'promotions.video_id')
            ->where(['promotions.is_enabled' => 1, 'promotions.uid' => $this->getLoginUserId()])
            ->when($miniprogramId, function ($query, $miniprogramId) {
                return $query->where('promotions.miniprogram_id', $miniprogramId);
            })
            ->when($isConfig, function ($query) {
                return $query->where('promotions.callback_config_id', '<>', 0);
            }, function ($query) {
                return $query->where('promotions.callback_config_id', 0);
            })->when($name, function ($query, $name){
                return $query->where('promotions.name', 'like', '%'. $name . '%');
            })->when($id, function ($query, $id) {
                return $query->where('promotions.id', $id);
            })->when($videoName, function ($query, $videoName) {
                return $query->where('videos.name', 'like', '%'. $videoName . '%');
            })->when($starTime, function ($query, $startTime) {
                return $query->where('promotions.created_at', '>=', $startTime);
            })->when($endTime, function ($query, $endTime){
                return $query->where('promotions.created_at', '<=', $endTime . ' 23:59:59');
            })->orderBy('created_at', 'desc')
            ->select('promotions.id', 'promotions.name', 'promotions.created_at',
            'videos.name as video_name', 'promotions.series_sequence', 'promotions.callback_type',
                'promotions.callback_config_id', 'promotions.video_id', 'promotions.remark', 'promotions.status',
            'promotions.first_charge_template_id', 'promotions.not_first_charge_template_id')
            ->paginate($request->input('limit', 15));
        $chargeTemplateIds = $result->pluck('first_charge_template_id')->merge($result->pluck('not_first_charge_template_id'))->unique();

        $payTemplates = DB::table('pay_templates')->whereIn('id', $chargeTemplateIds)
            ->select('id', 'name')
            ->get()->keyBy('id')->toArray();

        foreach ($result as $item) {
            $item->status_str = $item->status ? '启用':'禁用';
            $item->series_sequence_name = '第'. $item->series_sequence . '集';
            $item->callback_type_str = $callbackTypeMap[$item->callback_type] ?? '';
            $item->promotion_path = config('tuiguang.tuiguang.url') . DIRECTORY_SEPARATOR . 'api/promotion/index?ranse_id='. $item->id;
            $item->track_url = config('tuiguang.tuiguang.trackUrl') .
                '/track?dycallback=1&connection_id='.$item->id.
                '&link_source=' .( $linkSourceMap[$item->callback_type] ?? '') .
                '&adid=__AID__&cid=__CID__&imei=__IMEI__&oaid=__OAID__&mac=__MAC__&os=__OS__&ip=__IP__&androidid=__ANDROIDID__&ua=__UA__&timestamp=__TS__&callback_url=__CALLBACK_URL__&projectid=__PROJECT_ID__&promotionid=__PROMOTION_ID__&advertiser_id=__ADVERTISER_ID__&campaign_id=__CAMPAIGN_ID__';
            $item->first_charge_template_str = $payTemplates[$item->first_charge_template_id]->name ?? '';
            $item->not_first_charge_template_str = $payTemplates[$item->not_first_charge_template_id]->name ?? '';

        }
        return $result;

    }

    public function delete(Request $request) {
        $this->validate($request, ['id' => 'required']);

        DB::table('promotions')
            ->where(['id' => $request->input('id'), 'uid' => $this->getLoginUserId(), 'is_enabled' => 1])
            ->update(['is_enabled' => 0, 'updated_at' => date('Y-m-d H:i:s')]);

        return 'ok';
    }

    public function updateSeriesSequence(Request $request) {
        $this->validate($request, ['id' => 'required',
            'series_sequence' => 'required', 'remark' => 'nullable|string|max:140',
            'first_charge_template_id' => 'required',
            'not_first_charge_template_id' => 'required',]);

        DB::table('promotions')
            ->where(['id' => $request->input('id'), 'uid' => $this->getLoginUserId(), 'is_enabled' => 1])
            ->update(['series_sequence' => $request->input('series_sequence'),
                'remark' => $request->input('remark') ?? '',
                'first_charge_template_id' => $request->input('first_charge_template_id'),
                'not_first_charge_template_id' => $request->input('not_first_charge_template_id'),
                'updated_at' => date('Y-m-d H:i:s')]);

        return 'ok';
    }

    public function add(Request $request) {
        $this->validate($request, [
            'video_id' => 'required',
            'series_sequence' => 'required',
            'name' => 'required',
            'miniprogram_id' => 'required',
            'first_charge_template_id' => 'required',
            'not_first_charge_template_id' => 'required',
        ]);
        $now = date('Y-m-d H:i:s');
        $currentUser = $this->getCurrentUser();
        DB::table('promotions')
            ->insert([
                'uid' => $currentUser->id,
                'puid' => $currentUser->pid,
                'miniprogram_id' => $request->input('miniprogram_id'),
                'name' => $request->input('name'),
                'video_id' => $request->input('video_id'),
                'series_sequence' =>  $request->input('series_sequence'),
                'first_charge_template_id' =>  $request->input('first_charge_template_id'),
                'not_first_charge_template_id' =>  $request->input('not_first_charge_template_id'),
                'created_at' => $now,
                'updated_at' => $now,
            ]);
        return 'ok';
    }

    /**
     * 更新推广的回传配置
     * 1, 如果是巨量账户级,推广id和巨量账户唯一绑定
     * @param Request $request
     * @return string
     * @throws \Illuminate\Validation\ValidationException
     */
    public function updateCallbackConfig(Request $request) {
        $this->validate($request, [
            'id' => 'required',
            'callback_type' => 'required|in:1',
            'callback_config_id' => 'required',
            'remark' => 'nullable|string|max:140',
        ]);
        if(1 == $request->input('callback_type')) {
            $exist = DB::table('promotions')
                ->where(['is_enabled' => 1, 'callback_type' => $request->input('callback_type'),
                    'callback_config_id' => $request->input('callback_config_id'),
                    'status' => 1])
                ->first();
            if($exist && $exist->id != $request->input('id')) {
                CommonBusinessException::throwError(Errors::JULIANG_ACCOUNT_PROMOTION_UNIQUE);
            }
        }
        DB::table('promotions')
            ->where(['id' => $request->input('id'), 'uid' => $this->getLoginUserId(), 'is_enabled' => 1])
            ->update([
                'callback_type' => $request->input('callback_type'),
                'callback_config_id' => $request->input('callback_config_id'),
                'remark' => $request->input('remark', ''),
                'updated_at' => date('Y-m-d')
            ]);
        return 'ok';
    }
}
