<?php
/**
 *  微信公众号关注回复设置
 * @file:WechatSubscribeController.php
 * @Date: 2023/7/5
 * @Time: 15:02
 */


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\WechatSubscribeRequest;
use Modules\WechatPlatform\Services\WechatKeywordsService;
use Modules\WechatPlatform\Services\WechatSubscribeService;

class WechatSubscribeController extends CatchController
{

    use UserTrait;

    /**
     *  关注回复列表
     * name: list
     * @param Request $request
     * date 2023/07/10 09:29
     */
    public function list(Request $request)
    {
        $param  = $request->all();
        $userContext = $this->getUserContext(null);
        $param['user_id'] = $userContext['loginUser']->id;
        $param['puser_id'] = $userContext['loginUser']->pid;
        return WechatSubscribeService::list($param);
    }

    /**
     *  添加关注回复
     * name: add
     * @param WechatSubscribeRequest $request
     * @return string|void
     * date 2023/07/10 10:07
     */
    public function add(WechatSubscribeRequest $request)
    {
        $param = $request->validated();
        $param = $this->handelParam($param);
        $userContext = $this->getUserContext(null);
        $param['user_id'] = $userContext['loginUser']->id;
        $param['puser_id'] = $userContext['loginUser']->pid;
        $param['wechat_accounts'] = [];
        return WechatSubscribeService::addSubscribe($param);
    }

    /**
     *  编辑
     * name: edit
     * @param $id
     * @param WechatSubscribeRequest $request
     * date 2023/07/10 10:51
     */
    public function edit($id, WechatSubscribeRequest $request)
    {
        $param = $this->handelParam($request->validated());
        return WechatSubscribeService::updateSubscribe($id, $param);
    }

    /**
     *  详情
     * name: detail
     * @param $id
     * date 2023/07/10 10:07
     */
    public function detail($id)
    {
        return WechatSubscribeService::getDetail($id);
    }

    /**
     *  分配公众号
     * name: allocation
     * @param $id
     * @param Request $request
     * @return string
     * date 2023/07/10 10:22
     */
    public function allocation($id, Request $request)
    {
        if (!$request->has('wx_auth_ids')) {
            throw  new  FailedException("参数错误");
        }
        if (!empty($request->input('wx_auth_ids'))) {
            $wxAuthIds = explode(',', $request->input('wx_auth_ids'));
        } else {
            $wxAuthIds = [];
        }

        return WechatSubscribeService::allocation($id, $wxAuthIds);
    }

    /**
     *  公众号分配列表
     * name: authList
     * @param $id
     * date 2023/07/10 11:08
     */
    public function authList($id)
    {
        $userId  = $this->getLoginUserId();
        return WechatSubscribeService::WechaAccountAuthListInfo($id,$userId);
    }

    /**
     *  删除
     * name: del
     * @param Request $request
     * @return string
     * date 2023/07/10 11:08
     */
    public function del(Request $request)
    {
        $ids = $request->input('ids');
        if (empty($ids)) {
            throw  new  FailedException('要删除的数据参数错误');
        }

        $ids = explode(',', $ids);
        return WechatSubscribeService::del($ids);
    }

    /**
     * 获取设置
     * name: getConfig
     * @param $miniprogramId
     * @return int
     * date 2023/07/10 09:33
     */
    public function getConfig($miniprogramId)
    {

        $userContext = $this->getUserContext(null);
        $userId = $userContext['loginUser']->id;
        $puserId = $userContext['loginUser']->pid;
        return WechatSubscribeService:: getConfig($userId, $puserId, $miniprogramId);
    }

    /**
     * 更新设置
     * name: setConfig
     * @param $miniprogramId
     * @param Request $request
     * @return string
     * date 2023/07/10 09:33
     */
    public function setConfig($miniprogramId, Request $request)
    {
        if (!$request->has('value')) {
            throw  new FailedException("参数错误");
        }
        $param = $request->all(['value']);
        if (!in_array($param['value'], [0, 1])) {
            throw  new FailedException("参数错误");
        }
        $userContext = $this->getUserContext(null);
        $param['miniprogram_id'] = $miniprogramId;
        $param['user_id'] = $userContext['loginUser']->id;
        $param['puser_id'] = $userContext['loginUser']->pid;
        return WechatSubscribeService::setConfig($param);
    }

    private function handelParam(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("没有此小程序的使用权限");
        }
        $param['send_content'] = "";
        foreach ($param['content'] as & $val) {
            if (!is_array($val)) {
                throw  new  FailedException("回复内容格式不正确");
            }
            if (getProp($val, 'url')) {
                // 跳转小程序
                $val['content'] = "<a href=\"\" data-miniprogram-appid=\"{$param['miniprogram_appid']}\" data-miniprogram-path=\"{$val['url']}\">{$val['title']}</a>";
            } else {
                $val['content'] = $val['title'];
                $val['url'] = "";
            }
            $param['send_content'] .= $val['content'] . "\n";
        }
        rtrim($param['send_content'], "\n");
        return $param;
    }
}
