<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2018-4-3
 */

namespace app\admin\controller;

use think\Db;
use think\Page;
use think\Cache;

class LinksGroup extends Base
{
    public function index()
    {
        $list = array();
        $keywords = input('keywords/s');

        $condition = array();
        if (!empty($keywords)) {
            $condition['group_name'] = array('LIKE', "%{$keywords}%");
        }

        $linksgroupsM =  Db::name('links_group');
        $count = $linksgroupsM->where($condition)->count('id');// 查询满足要求的总记录数
        $Page = $pager = new Page($count, config('paginate.list_rows'));// 实例化分页类 传入总记录数和每页显示的记录数
        $list = $linksgroupsM->where($condition)->order('sort_order asc, id asc')->limit($Page->firstRow.','.$Page->listRows)->select();
        $min_group_id = 0;
        foreach ($list as $key => $val) {
            if ($min_group_id > $val['id'] || empty($min_group_id)) {
                $min_group_id = $val['id'];
            }
        }
        $this->assign('min_group_id',$min_group_id);

        $show = $Page->show();// 分页显示输出
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('list',$list);// 赋值数据集
        $this->assign('pager',$pager);// 赋值分页对象
        return $this->fetch();
    }

    /**
     * 保存友情链接分组
     */
    public function linksgroup_save()
    {
        if (IS_AJAX_POST) {
            $post = input('post.');

            if (empty($post['group_name'])) {
                $this->error('至少新增一个链接分组！');
            } else {
                $is_empty = true;
                foreach ($post['group_name'] as $key => $val) {
                    $val = trim($val);
                    if (!empty($val)) {
                        $is_empty = false;
                        break;
                    }
                }
                if (true === $is_empty) {
                    $this->error('分组名称不能为空！');
                }
            }

            // 数据拼装
            $now_time = getTime();
            $addData = $editData = [];
            foreach ($post['group_name'] as $key => $val) {
                $group_name  = trim($val);
                if (!empty($group_name)) {
                    if (empty($post['id'][$key])) {
                        $addData[] = [
                            'group_name' => $group_name,
                            'sort_order' => $post['sort_order'][$key] ? :100,
                            'add_time' => $now_time,
                            'update_time' => $now_time,
                        ];
                    } else {
                        $id = intval($post['id'][$key]);
                        $editData[] = [
                            'id' => $id,
                            'group_name' => $group_name,
                            'sort_order' => $post['sort_order'][$key] ? :100,
                            'update_time' => $now_time,
                        ];
                    }
                }
            }

            if (!empty($addData)) {
                $rdata = model('LinksGroup')->saveAll($addData);
            }

            $r = true;
            if (!empty($editData)) {
                $r = model('LinksGroup')->saveAll($editData);
            }

            if ($r !== false) {
                Cache::clear('links');
                Cache::clear('links_group');
                adminLog('保存链接分组：'.implode(',', $post['group_name']));
                $this->success('操作成功');
            }
        }
        $this->error('操作失败');
    }
    
    /**
     * 删除友情链接分组
     */
    public function del()
    {
        $id_arr = input('del_id/a');
        $id_arr = eyIntval($id_arr);
        if(IS_POST && !empty($id_arr)){
            $linksGroupRow = Db::name('links_group')->order('id asc')->column('id');
            if (!empty($linksGroupRow)) {
                if (1 < count($linksGroupRow)) {
                    $firstRow = current($linksGroupRow);
                    $min_group_id = empty($firstRow['id']) ? 0 : $firstRow['id'];
                    if (in_array($min_group_id, $id_arr)) {
                        $this->error('禁止删除默认分组');
                    }
                } else {
                    $this->error('至少保留一个分组');
                }
            }

            $group_name_list = Db::name('links_group')->where([
                    'id'    => ['IN', $id_arr],
                ])->column('group_name');

            $r = Db::name('links_group')->where([
                    'id'    => ['IN', $id_arr],
                ])->delete();
            if ($r !== false) {
                Db::name('links')->where([
                    'groupid'    => ['IN', $id_arr],
                ])->delete();

                Cache::clear('links');
                Cache::clear('links_group');
                adminLog('删除友情链接分组：'.implode(',', $group_name_list));
                $this->success('删除成功');
            }
        }
        $this->error('删除失败');
    }
}