<?php
/**
 * 公众号菜单
 * @file:WechatMenuService.php
 * @Date: 2023/7/11
 * @Time: 10:53
 */


namespace Modules\WechatPlatform\Services;

use Illuminate\Support\Facades\DB;
use Modules\Channel\Services\WechatOpenPlatform\WechatOpenPlatformService;
use Modules\Common\Services\BaseService;
use Modules\WechatPlatform\Models\WechatAccountMenuDetail;
use Modules\WechatPlatform\Models\WechatMenu;
use function PHPUnit\Framework\isNan;

class WechatMenuService extends BaseService
{


    /**
     *  添加菜单
     * name: addMenu
     * @param $param
     * date 2023/07/11 11:38
     */
    public static function addMenu($param)
    {
        $res = WechatMenu::create($param);
        if ($res) {
            return ['msg' => '操作成功'];
        }
        self::throwErrMsg('操作失败');
    }

    /**
     *  更新菜单
     * name: updateMenu
     * @param $id
     * @param $param
     * @return string[]
     * date 2023/07/12 07:17
     */
    public static function updateMenu($id, $param)
    {
        $info = WechatMenu::where('id', $id)->where('is_del', 0)->first();
        if (is_empty($info)) {
            self::throwErrMsg('该菜单不存在或已删除');
        }
        WechatMenu::where('id', $id)->update($param);
        $data = [
            'type' => $param['type'],
            'content' => $param['content'],
            'msg_content' => $param['msg_content']
        ];
        WechatAccountMenuDetail::where('menu_id', $id)->update($data);
        // 更新公众号菜单
        $appIds = WechatAccountMenuDetail::where(['status' => 1, 'menu_id' => $info->id])->pluck('wechat_authorization_info_id')->toArray();
        self::createWechatMenus($appIds,$id);
        return ['msg' => '操作成功'];
    }

    /**
     * 创建微信菜单
     * name: createWechatMenus
     * @param array $appIds
     * @param $menuId
     * @return bool
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * date 2023/07/12 14:29
     */
    private static function createWechatMenus(array $appIds,$menuId)
    {
        if (empty($appIds)) {
            return true;
        }
        $info = WechatAccountMenuDetail::query()->whereIn('wechat_authorization_info_id', $appIds)->where('menu_id',$menuId)->get();
        foreach ($info as $val) {
            $app = self::getofficialAccount($val->wechat_authorization_info_id);
            if ($val->wx_menuid) {
                // 有菜单则删除菜单
                $app->menu->delete($val->wx_menuid);
            }
            $matchRule = [
                "client_platform_type" => $val->type == "ios" ? "1" : "2",
            ];
            $res = $app->menu->create($val->content, $matchRule);
            // myLog('wx-meun')->info(['res' => $res]);

            $errcode = getProp($res,'errcode',"");
            if (intval($errcode) ==  65303){
                $res = $app->menu->create($val->content);
            }
            // myLog('wx-meun')->info(['res' => $res]);
            $wxMenuId = getProp($res, 'menuid', "");
            $res = $app->menu->create($val->content, $matchRule);
            myLog('wx-meun')->info(['res' => $res,'mid' => $wxMenuId]);
            if ($wxMenuId) {
                WechatAccountMenuDetail::query()->where('id', $val->id)->update(['wx_menuid' => $wxMenuId]);
            }
        }
        return true;
    }

    public static function getofficialAccount($id)
    {
        $info = WechatOpenPlatformService::getAppInfoById($id);
        $componentInfo = WechatOpenPlatformService::getComponentInfoByAppid($info->component_appid);
        $openPlatform = WechatOpenPlatformService::buildApplication($componentInfo);
        $app = $openPlatform->officialAccount($info->authorizer_appid, getProp($info, 'authorizer_refresh_token'));
        unset($appInfo);
        return $app;
    }


    /**
     * 菜单详情
     * name: detail
     * @param $id
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * date 2023/07/12 07:17
     */
    public static function detail($id)
    {
        return WechatMenu::query()->where('id', $id)->first();
    }

    /**
     *  公众号列表
     * name: authList
     * @param $id
     * @param $userId
     * @return mixed
     * date 2023/07/12 07:16
     */
    public static function authList($id, $userId)
    {
        $list = DB::table('wechat_authorization_infos')
            ->where('user_id', $userId)
            ->select('id', 'nick_name', 'is_enabled')->get();
        $authList = WechatAccountMenuDetail::where('menu_id', $id)->where('status' , 1)->distinct('appid')->get();
        if (!$list->isEmpty()) {
            foreach ($list as $val) {
                $val->is_auth = 0;
                $info = $authList->where('wechat_authorization_info_id', $val->id)->first();
                if (getProp($info, 'status') == 1) {
                    $val->is_auth = 1;
                }
                if ($val->is_enabled != 1) {
                    $val->nick_name .= "(取消授权)";
                }
                unset($val->is_enabled);
            }
        }
        return $list;
    }

    /**
     *   删除
     * name: del
     * @param $ids
     * @return string[]
     * date 2023/07/12 07:14
     */
    public static function del($ids)
    {
        WechatMenu::whereIn('id', $ids)->update(['is_del' => 1, 'del_at' => get_date()]);
        $applyIds = WechatAccountMenuDetail::query()->whereIn('menu_id', $ids)->where('status', 1)->pluck('id')->toArray();
        if ($applyIds) {
            WechatAccountMenuDetail::whereIn('menu_id', $ids)->update(['status' => 0]);
            // 删除菜单
            self::delWechatAccountMenu($applyIds);
        }
        return ['msg' => "操作成功"];

    }

    private static function delWechatAccountMenu(array $applyIds)
    {
        $info = WechatAccountMenuDetail::query()->whereIn('id', $applyIds)->get();
        foreach ($info as $val) {

            if ($val->wx_menuid) {
                // 有菜单则删除菜单
                $app = self::getofficialAccount($val->wechat_authorization_info_id);
                $app->menu->delete($info->wx_menuid);
            }

            WechatAccountMenuDetail::query()->where('wechat_authorization_info_id', $val->id)->update(['wx_menuid' => ""]);
        }
        return "操作成功";
    }

    /**
     *  分配公众号
     * name: allocation
     * @param $id
     * @param array $wxAuthIds
     * date 2023/07/12 07:20
     */
    public static function allocation($id, $wxAuthIds)
    {
        $info = WechatMenu::query()->where('id', $id)->where('is_del', 0)->first();
        if (is_empty($info)) {
            self::throwErrMsg('该菜单不存在或已删除');
        }
        // 已分配的
        $appIds = WechatAccountMenuDetail::where(['status' => 1, 'menu_id' => $info->id])->pluck('wechat_authorization_info_id')->toArray();
        $list = [];
        $delAppId = [];
        $createAddIp = [];

        if (empty($wxAuthIds)) {
            $data['wechat_accounts'] = [];
            $delAppId = $appIds;
        } else {
            $wechatAccountInfos = DB::table('wechat_authorization_infos')
                ->whereIn('id', $wxAuthIds)
                ->where('is_enabled', 1)
                ->where('user_id', $info->user_id)
                ->get();
            if ($wechatAccountInfos->isEmpty()) {
                self::throwErrMsg("优化师对提交的公众号没有使用权限");
            }

            $canNotUsed = $wechatAccountInfos->pluck('id')->toArray();
            $canNotUsed = array_diff($wxAuthIds, $canNotUsed);
            if (count($canNotUsed) > 0) {
                self::throwErrMsg("优化师对id:为:" . implode(',', $canNotUsed) . "的公众号没有使用权限");
            }
            foreach ($appIds as $val) {
                if (!in_array($val, $wxAuthIds)) {
                    $delAppId[] = $val;
                }
            }
            // $allSet = WechatAccountMenuDetail::query()->where('user_id', $info->user_id)->get();
            $appIds = [];
            foreach ($wechatAccountInfos as $val) {
                $data['wechat_accounts'][] = [
                    'id' => $val->id,
                    'appid' => $val->authorizer_appid,
                    'nick_name' => $val->nick_name,
                    'component_appid' => $val->component_appid
                ];
                $appIds[] = $val->authorizer_appid;
                $list[] = [
                    'menu_id' => $info->id,
                    'user_id' => $info->user_id,
                    'puser_id' => $info->puser_id,
                    'miniprogram_id' => $info->miniprogram_id,
                    'appid' => $val->authorizer_appid,
                    'wechat_authorization_info_id' => $val->id,
                    'nick_name' => $val->nick_name,
                    'content' => $info->content,
                    'msg_content' => $info->msg_content,
                    'status' => 1,
                ];
            }
            unset($wechatAccountInfos, $appIds, $val, $canNotUsed);
        }
        DB::beginTransaction();
        try {
            if (!empty($list)) {
                foreach ($list as $val) {
                    WechatAccountMenuDetail::updateOrCreate(
                        [
                            'menu_id' => $val['menu_id'],
                            'miniprogram_id' => $val['miniprogram_id'],
                            'wechat_authorization_info_id' => $val['wechat_authorization_info_id']
                        ], $val);

                }
            } else {
                WechatAccountMenuDetail::where('menu_id', $id)->update(['status' => 0]);
            }
            if (!empty($delAppId)) {
                WechatAccountMenuDetail::whereIn('id', $delAppId)->update(['status' => 0]);
            }
            WechatMenu::query()->where('id', $id)->update($data);
            DB::commit();
        } catch (\Exception $exception) {
            self::throwErrMsg('操作失败');
        }
        $createAddIp = WechatAccountMenuDetail::where(['status' => 1, 'menu_id' => $info->id])->pluck('wechat_authorization_info_id')->toArray();
        myLog('wx-meun')->info(['c' => $createAddIp,'del' => $delAppId]);
        if (!empty($createAddIp)) {
            self::createWechatMenus($createAddIp,$id);
        }
        if (!empty($delAppId)) {
            self::delWechatAccountMenuByMeunId($delAppId,$id);
        }
        return ['msg' => "操作成功"];
    }

    /**
     * 列表
     * name: list
     * @param array $param
     * date 2023/07/12 07:43
     */
    public static function list(array $param)
    {
        $sql = self::getQuery($param)->orderBy('id', 'desc');
        $isAll = getProp($param, 'is_all', false);
        if ($isAll) {
            $list = $sql->get();
        } else {
            $list = $sql->paginate(getProp($param, 'limit', 10));
        }
        foreach ($list as $val){
            $val->wechat_accounts =  WechatAccountMenuDetail::query()->where(
                ['menu_id' => $val->id,
                    'status' => 1
                ])->distinct('appid')->select('wechat_authorization_info_id as id',"appid",'nick_name')->get();
        }
        return $list;
    }

    private static function getQuery(array $param)
    {
        $sql = WechatMenu::query()->where('is_del', 0);
        if (getProp($param, 'puser_id')) {
            $sql->where('puser_id', $param['puser_id']);
        }
        if (getProp($param, 'user_id')) {
            $sql->where('user_id', $param['user_id']);
        }
        if (getProp($param, 'title')) {
            $sql->where('title', "like", "%" . $param['title'] . "%");
        }
        if (getProp($param, 'type')) {
            $sql->where('user_id', $param['type']);
        }
        if (getProp($param, 'miniprogram_id')) {
            $sql->where('miniprogram_id', $param['miniprogram_id']);
        }
        if (getProp($param, 'wechat_authorization_info_id')) {
            $ids = WechatAccountMenuDetail::query()->where([
                'wechat_authorization_info_id' => $param['wechat_authorization_info_id'],
                'status' => 1,
            ])->distinct('menu_id')->pluck('menu_id')->toArray();
            $sql->whereIn('id',$ids);
        }
        return $sql;
    }

    private static function delWechatAccountMenuByMeunId(array $delAppId, $menuId)
    {
        $info = WechatAccountMenuDetail::query()->whereIn('wechat_authorization_info_id', $delAppId)->where('menu_id',$menuId)->get();

        foreach ($info as $val) {

            if ($val->wx_menuid) {
                // 有菜单则删除菜单
                $app = self::getofficialAccount($info->wechat_authorization_info_id);
                $app->menu->delete($val->wx_menuid);
            }

            WechatAccountMenuDetail::query()->where('wechat_authorization_info_id', $val->id)->update(['wx_menuid' => ""]);
        }
        return "操作成功";
    }

    /**
     *  点击事件回复
     * name: getClickInfoContent
     * @param $wechatInfoId
     * date 2023/07/12 16:37
     */
    public static function getClickInfoContent($wechatAppId,$key)
    {
        $info = WechatAccountMenuDetail::query()->where([
            'status' => 1,
            'wechat_authorization_info_id' => $wechatAppId,
        ])->first();
        if (is_empty($info)){
            return "";
        }
        $content  = $info->msg_content;
        if (empty($content)){
            return  "";
        }
        foreach ($content as  $val){

            if (isset($val[$key])){
               $content  =  $val[$key];
               break ;
            }
        }
        return  $content ?: "";
    }

}