<?php

namespace App\Modules\OfficialAccount\Models;

use Illuminate\Database\Eloquent\Model;

class SelfDefinedMenu extends Model
{
    protected $table = 'self_defined_menu';

    protected $fillable = ['distribution_channel_id','menu','status','is_generate'];

    public static function getMenu($distribution_channel_id,$filter=[]){
        $obj =  self::where('distribution_channel_id',$distribution_channel_id);
        if(isset($filter['status']) && $filter['status']) {
            $obj->where('status',$filter['status']);
        }
        $menu =  $obj->first();
        \Log::info('getMenu:');\Log::info($menu);
        if(!empty($menu)){
            $menu->menu = json_decode($menu->menu);
        }
        \Log::info('getMenu2:');\Log::info($menu);
        return $menu;
    }

    public static function getMenuFormated($distribution_channel_id,$filter=[]) {
        $res = self::getMenu($distribution_channel_id,$filter);
        if($res){
            $menus_raw=$res->menu;
            $menus_raw = json_decode($menus_raw,true);
            \Log::info($menus_raw);
            $menus_raw = $menus_raw['buttons'];
            foreach ($menus_raw as $key =>$menu) {
                //如果有子菜单 则遍历子菜单
                if(isset($menu['sub_button']) && is_array($menu['sub_button']) && count($menu['sub_button'])>0) {
                    foreach ($menu['sub_button'] as $k=> $each) {
                        if($each['type'] == 'link' || $each['type']=='custom') {
                            $menus_raw[$key]['sub_button'][$k]['url'] = trim($menus_raw[$key]['sub_button'][$k]['url']);
                            $menus_raw[$key]['sub_button'][$k]['type'] = 'view';
                            if(empty($each['key'])) {
                                unset($menus_raw[$key]['sub_button'][$k]['key']);
                            }
                        }else{
                            $menus_raw[$key]['sub_button'][$k]['type'] = 'click';
                            if(isset($each['url'])){
                                unset($menus_raw[$key]['sub_button'][$k]['url']);
                            }
                        }
                    }

                }else {
                    if($menu['type'] == 'link' || $menu['type']=='custom') {
                        $menus_raw[$key]['type'] = 'view';
                        $menus_raw[$key]['url'] = trim($menus_raw[$key]['url']);
                        if(empty($each['key'])) {
                            unset($menus_raw[$key]['key']);
                        }
                    }else{
                        $menus_raw[$key]['type'] = 'click';
                        if(isset($menu['url'])){
                            unset($menus_raw[$key]['url']);
                        }
                    }
                }
            }
            return $menus_raw;
        }
        return false;
    }
}


