<?php
// +----------------------------------------------------------------------
// | Wendasns [ 开源问答社区系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020~2021 http://wendasns.com All rights reserved.
// +----------------------------------------------------------------------
namespace app\wendasns\admin;

//use app\admin\AdminBaseController;
use app\wendasns\model\Frlink as byFrlink;
use app\wendasns\model\FrlinkType;
use app\wendasns\model\FrlinkRelations;

class Frlink
{
	
    public function index()
    {
    	$limit = input('get.limit',1,'intval');

    	$dm = byFrlink::paginate($limit);
        $data = $dm->toArray();
		return view('index', ['data'=>$data['data']]);
    }

    public function add()
    {
		$name = $this->request->post('name','','');
		$link = $this->request->post('link','','');
		$logo = $this->request->post('logo','','');
		$category = $this->request->post('category','','');
		$sort = $this->request->post('sort','','');
		
    	$dm = byFrlink::create([
			'name' =>  $name,
			'link' =>  $link,
			'logo' =>  $logo,
			'sort' =>  $sort
		]);
		if($dm->id){
			$list = [];
			foreach($category as $v){
				$list[] = ['type_id'=>$v];
			}
			$dm->relations()->saveAll($list);
			$this->showMessage('添加成功');
		}
		$this->showError('添加失败');
    }
    
	public function edit()
	{
		$id = $this->request->post('id',0,'');
		$name = $this->request->post('name','','');
		$link = $this->request->post('link','','');
		$logo = $this->request->post('logo','','');
		$category = $this->request->post('category',[],'');
		$sort = $this->request->post('sort','','');
		
    	$dm = byFrlink::find($id);
    	if(!$dm){
    		$this->showError('友情链接不存在');
    	}

		$dm->name = $name;
		$dm->link = $link;
		$dm->logo = $logo;
		$dm->sort = $sort;
		$dm->save();
		
		$ft = FrlinkType::where('frlink_id',$id)->where('type_id','in',$category)->select();
		if($ft){
			$row = $ft->toArray();
			foreach($row as $v){
				$k = array_search($v['type_id'], $category);
				if($k!==false){
					$list_add[] = ['frlink_id'=>$id,'type_id'=>$v['type_id']];
					unset($category[$k]);
				}
			}
		}
		$this->showMessage('操作成功');
    }

    public function del()
    {
		$id = $this->request->post('id','','');
		if(is_array($id)){
			byFrlink::destroy($id);
		}
		$this->showMessage('操作成功');
    }
    
    public function category()
    {
    	$dm = FrlinkType::select();
    	$this->showMessage('',$dm);
    }
}
