<?php
/**
 * 微信公众号关键词回复设置
 * @file:WechatKeywordsController.php
 * @Date: 2023/7/5
 * @Time: 15:00
 */


namespace Modules\WechatPlatform\Http\Controllers;

use Catch\Base\CatchController;
use Catch\Exceptions\FailedException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\Manage\Enmus\MiniprogramType;
use Modules\User\Http\Controllers\UserTrait;
use Modules\WechatPlatform\Http\Requests\WechatKeywordsRequest;
use Modules\WechatPlatform\Services\WechatKeywordsService;

class WechatKeywordsController extends CatchController
{
    use UserTrait;
    /**
     *  关键词列表
     * name: List
     * @param Request $request
     * date 2023/07/05 15:10
     */
    public function List(Request $request)
    {

    }

    /**
     *  添加
     * name: add
     * @param WechatKeywordsRequest $request
     * date 2023/07/05 15:36
     */
    public function add(WechatKeywordsRequest $request)
    {
        $param = $request->validated();
        $param = $this->WechatKeywordsParam($param);
        $userContext = $this->getUserContext(null);
        $param['user_id'] = $userContext['loginUser']->id;
        $param['puser_id'] = $userContext['loginUser']->pid;
        return WechatKeywordsService::addKeyword($param);
    }

    private function WechatKeywordsParam(mixed $param)
    {
        if (getProp($param,'type') != 'miniprogram'){
            return $param;
        }
        $info = DB::table('miniprogram')->where('id',$param['miniprogram_id'])->first();
        if(empty($info)){
            throw  new  FailedException("小程序不正确");
        }
        if($info->status != 1){
            throw  new  FailedException("此小程序暂不提供使用");
        }
        if ($info->type != MiniprogramType::WEIXIN->value()){
            throw  new  FailedException("关键词回复设置仅支持微信小程序");
        }
        $param['miniprogram_appid'] = $info->appid;
        $info = DB::table('user_has_miniprograms')->where('uid',$this->getLoginUserId())->where('miniprogram_id',$param['miniprogram_id'])->where('is_enabled',1)->value('id');
        if(empty($info)){
            throw  new  FailedException("没有此小程序的使用权限");
        }
        return  $param;
    }
    /**
     *  编辑
     * name: edit
     * @param $id
     * @param WechatKeywordsRequest $request
     * date 2023/07/05 15:36
     */
    public function edit($id, WechatKeywordsRequest $request)
    {

    }

    /**
     *  详情
     * name: detail
     * @param $id
     * date 2023/07/05 15:36
     */
    public function detail($id)
    {

    }

    /**
     *  分配
     * name: allocation
     * @param $id
     * @param Request $request
     * date 2023/07/05 16:03
     */
    public function allocation($id,Request $request)
    {

    }

    /**
     *  删除
     * name: del
     * @param $id
     * date 2023/07/05 15:47
     */
    public function del($id)
    {

    }


}
