<?php

namespace Modules\Operation\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\Common\Services\CommonConfigService;
use Modules\User\Http\Controllers\UserTrait;

class FirstPageController extends CatchController
{
    use ValidatesRequests;
    use UserTrait;

    /**
     *  首页列表
     */
    public function list(Request $request) {
        $firstPageListTypeMap = CommonConfigService::getFirstPageListTypeMap();
        $miniprogramTypeMap = CommonConfigService::getMiniprogramTypeMap();
        $miniprogramType = $request->input('miniprogram_type');
        $firstPageListType = $request->input('type');
        $result = DB::table('first_pages')
            ->where('is_enabled', 1)
            ->when($miniprogramType, function ($query, $miniprogramType){
                return $query->where('miniprogram_type', $miniprogramType);
            })->when($firstPageListType, function ($query, $firstPageListType){
                return $query->where('type', $firstPageListType);
            })->orderBy('status', 'desc')
            ->orderBy('id', 'desc')
            ->paginate($request->input('limit', 15));
        foreach ($result as $item) {
            $item->type_str = $firstPageListTypeMap[$item->type]['label'] ?? '';
            $item->duanjus = collect(\json_decode($item->duanjus, true))->sortBy('sort')->values();
            $item->miniprogram_type_str = $miniprogramTypeMap[$item->miniprogram_type]['label'] ?? '';
        }
        return $result;
    }

    /**
     * 添加配置
     * @param Request $request
     * @return string
     * @throws \Illuminate\Validation\ValidationException
     */
    public function add(Request $request) {
        $this->validate($request, [
            'type' => 'required|in:1,2',
            'status' => 'required|in:0,1',
            'miniprogram_type' => 'required|in:1,2'
        ]);

        $now = date('Y-m-d H:i:s');
        if(1 == $request->input('status')) {
            DB::table('first_pages')
                ->where([
                    'type' => $request->input('type'),
                    'miniprogram_type' => $request->input('miniprogram_type')
                ])
                ->update(['status' => 0, 'updated_at' => $now]);
        }

        DB::table('first_pages')
            ->insert([
                'type' => $request->input('type'),
                'status' => $request->input('status'),
                'miniprogram_type' => $request->input('miniprogram_type'),
                'created_at' => $now,
                'updated_at' => $now,
            ]);
        return 'ok';
    }

    /**
     * 开启配置,一个列表类型中只允许一个配置开启
     * @param Request $request
     * @return string
     * @throws \Illuminate\Validation\ValidationException
     */
    public function enableStatus(Request $request) {
        $this->validate($request, ['id' => 'required']);
        $info = DB::table('first_pages')
            ->where('id', $request->input('id'))
            ->first();
        if(!$info) {
            CommonBusinessException::throwError(Errors::OPERATION_FIRST_PAGE_LIST_NOT_EXISTS);
        }

        $now = date('Y-m-d H:i:s');
        DB::table('first_pages')
            ->where([
                'type' => $info->type,
                'miniprogram_type' => $info->miniprogram_type,
            ])
            ->update(['status' => 0, 'updated_at' => $now]);
        DB::table('first_pages')
            ->where('id', $request->input('id'))
            ->update(['status' => 1, 'updated_at' => $now]);
        return 'ok';
    }

    /**
     * 配置剧集
     * @param Request $request
     * @return string
     * @throws \Illuminate\Validation\ValidationException
     */
    public function setConfig(Request $request) {
        $this->validate($request, [
            'id' => 'required',
            'duanjus' => 'nullable|array',
        ]);

        $now = date('Y-m-d H:i:s');
        DB::table('first_pages')
            ->where('id', $request->input('id'))
            ->update(['duanjus' => \json_encode($request->input('duanjus', [])),
                'updated_at' => $now]);

        return 'ok';
    }

    /**
     * 删除
     * @param Request $request
     * @return string
     * @throws \Illuminate\Validation\ValidationException
     */
    public function delete(Request $request) {
        $this->validate($request, [
            'id' => 'required',
        ]);
        $now = date('Y-m-d H:i:s');
        DB::table('first_pages')
            ->where('id', $request->input('id'))
            ->where('is_enabled', 1)
            ->update(['is_enabled' => 0,
                'updated_at' => $now]);

        return 'ok';
    }
}

