<?php

namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\Models\ArticleType;
use Illuminate\Http\Request as Req;

class AriticleTypeController extends Controller
{
    /***
     * @param Req $req
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Req $req)
    {
        $request['title'] = isset($req->title) ? trim($req->title) : null;
        $request['type'] = isset($req->type) ? trim($req->type) : null;

        $acticle_type = new ArticleType();
        $selectdata = $acticle_type->type();
        $type = $this->getTree($selectdata);
        $dt = \App\Lib\DataTable\DataTable::init();
        $dt->setDataSource('/admin/System/getArticleType');
        $dt->setLang('ariticle');
        // $dt->addColsFields('id');
        $dt->addColsFields('id');
        // $dt->addColsFields('content');
        $dt->addColsFields('cate_name');
        $dt->addColsFields('parent_path');//层级
        $dt->addColsFields('sort');
        $dt->addColsFields('create_time');
        $dt->enableCheckBox();
        if (checkRriv('/admin/Notice/Edit')) {
            $arr[] = 'edit';
        }
        $dt->setToolBar($arr, array('width' => 140));

        $request["classtype"]    =   $type;

        return view('admin.systemSet/ariticleTypelist', $dt->render($request));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function add(Req $req)
    {
        //分类下拉框
        $acticle_type = new ArticleType();
        $selectdata = $acticle_type->type();
        if (!$req->isMethod('post')) {
            return view('admin.systemSet/articleType', ['select' => null, "selectdata" => $this->getTree($selectdata)]);
        } else {
            $pid = $req->input("type");
            $pid = $pid ? $pid : 0;
            $grade  =   $acticle_type->getGrade($pid);
            //返回所有的父级
          //  $from   =  $this->getFrom($selectdata,$pid,0);

            $type_data = [
                "parent_id" => $pid,
                "cate_name" => $req->input("title"),

                "parent_path" => $grade,

                "sort" => $req->input("sort"),
                "create_time" => date("Y-m-d H:i:s"),
            ];
            $addType = $acticle_type->addType($type_data);
            $type_log = [
                session('adminInfo.admin_name'),
                $req['title']];
            OperationLog(session('adminInfo.admin_id'), 'add_notice_type', $type_log);

            return responseToJson(1);
        }
    }


    public function edit(Req $req)
    {
        $id = $req->id;

        if (empty($id)) {
            abort(404);
        }
        $db = new ArticleType();
        if (!$req->isMethod('post')) {
            $data = $db->getIdData($id, 1);

            $selectdata = $db->type();
            return view('admin.systemSet/articleType', ['select' => $data["parent_id"], "selectdata" => $this->getTree($selectdata), 'data' => $data,]);
        } else {
            $pid = $req->input("type");
            $grade  =   $db->getGrade($pid);
            $type_data = [
                "parent_id" => $pid ? $pid : 0,
                "cate_name" => $req->input("title"),
                "parent_path" =>$grade,
                "sort" => $req->input("sort"),
                "create_time" => date("Y-m-d H:i:s"),
            ];

            $addType = $db->updateIdData(intval($id), $type_data);
            $type_log = [
                session('adminInfo.admin_name'),
                $req['title'] ];
            OperationLog(session('adminInfo.admin_id'), 'edit_notice_type', $type_log);

            return responseToJson(1);
        }
    }


    public function delete(Req $req)
    {
        $forbid_ids =   [1,2,3,10,11,20,55];

      //  return responseToJson("0","分类禁止删除");
        $id = $req->input('id');
        if (empty($id)) {
            return responseToJson(-2001); //id����Ϊ��
        }
        $ids = explode(',', $id);
        if (!is_array($ids) && intval($ids) < 0) {
            return responseToJson(-2002); //id����
        }
        if (is_array($ids) && count($ids) > 0) {
            foreach ($ids as $k => $v) {

                if (intval($v) < 1||in_array($v,$forbid_ids)) {
                    unset($ids[$k]);
                }
            }
        }


        $rows = \App\Models\ArticleType::whereIn('id', $ids)->delete();
        if (!$rows) {
            return responseToJson(-2003); //id����
        }
        $type_log = [
            session('adminInfo.admin_name'),
            $req['id']];
       // OperationLog(session('adminInfo.admin_id'), 'del_notice_type', $type_log);
        return responseToJson(1); //id����
    }


    private function getTree($array, $pid = 0, $cen = 0)
    {
        $arr = array();
        $cen = ++$cen;
        $str = "";
        foreach ($array as $k => $v) {
            if ($v['parent_id'] == $pid) {
                $str = str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;", $cen - 1);
                $arr[] = ["id" => $v["id"], "name" => ($cen - 1 ? $str . "└" . $v["cate_name"] : $v["cate_name"])];
                unset($array[$k]);
                $arr = array_merge($arr, $this->getTree($array, $v['id'], $cen));
            }
        }
        return $arr;
    }

    private function getFrom($array,$pid,$cen){
        $from   =   [];
        $cen    = ++ $cen ;
        foreach ($array as $k=>$v){
            if($pid==$v["id"]){
                unset($array[$k]);
                $from[$cen]= $v["cate_name"];
                $a =    $this->getFrom($array,$v["parent_id"],$cen);
                $from   =   array_merge($a,$from);
            }
        }
        return $from;
    }

    function view(Req $req)
    {
        return $this->Edit($req);
    }
}
