<?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;

class Decoration extends Base {

    /**
     * 构造方法
     */
    public function __construct() {
        parent::__construct();
        $this->decorationModel = model('Decoration');
        $this->bottom_nav = Db::name('applets_bottom_nav');
        $this->ad_link = Db::name('applets_ad_link');
        $this->ad_content = Db::name('applets_ad_content');
    }

    // 页面路径
    public function page_paths()
    {
        $list = array();
        $param = input('param.');
        $keywords = input('keywords/s');
        $keywords = trim($keywords);
        $condition = [];
        // 应用搜索条件
        foreach (['keywords'] as $key) {
            if (isset($param[$key]) && $param[$key] !== '') {
                if ($key == 'keywords') {
                    $condition['a.title|a.paths'] = array('LIKE', "%{$keywords}%");
                } else {
                    $condition['a.'.$key] = array('eq', trim($param[$key]));
                }
            }
        }
        $condition['a.status'] = 1;
        if ($this->php_servicemeal < 2) {
            $condition['a.id'] = ['notin', [14,15,17,18,19,21,22,23,24,25,26,27,28,29,30,31,32,33]];
        }
        $count = Db::name('applets_page_paths')->alias("a")->where($condition)->count('a.id');// 查询满足要求的总记录数
        $Page = $pager = new Page($count, config('paginate.list_rows'));// 实例化分页类 传入总记录数和每页显示的记录数
        $list = Db::name('applets_page_paths')->alias("a")->where($condition)->order('a.sort_order asc, a.id asc')->limit($Page->firstRow.','.$Page->listRows)->select();

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

        return $this->fetch();
    }


    // 页面管理
    public function index()
    {
        // 获取指定广告位的广告内容列表
        $ad_list[2] = $this->decorationModel->getAdContentList(2);
        $ad_list[3] = $this->decorationModel->getAdContentList(3);
        // 获取底部导航信息
        $bottom_list = $this->decorationModel->getBottomNavList();
        $ret = [
            'ad_list_2' => $ad_list[2]['list'],
            'ad_list_3' => $ad_list[3]['list'],
            'bottom_list' => $bottom_list['list'],
        ];
        $this->assign($ret);
        return $this->fetch();
    }

    //广告保存
    public function save_ad()
    {
        if (IS_AJAX_POST){
            $post = input('param.');
            $position_id = $post['position_id'];
            if (!empty($post['data'])){
                $sort_order = 1;
                foreach ($post['data'] as $k => $v){
                    $v['update_time'] = getTime();
                    $v['sort_order'] = $sort_order;
                    $sort_order++;
                    if (empty($v['content_id'])){
                        $v['add_time'] = getTime();
                        $v['position_id'] = $position_id;
                        $this->ad_content->insert($v);
                    }else{
                        $content_id = $v['content_id'];
                        unset($v['content_id']);
                        $this->ad_content->where('content_id',$content_id)->update($v);
                    }
                }
                $this->success('保存成功!');
            }
        }
        $this->error('操作失败');
    }

    //广告删除
    public function del_ad(){
        if (IS_AJAX_POST) {
            $content_id = input('content_id/d');
            if (!empty($content_id)){
                $res = $this->ad_content->where('content_id',$content_id)->delete();
                if (false !== $res){
                    $this->success('删除成功');
                }
            }
            $this->error('删除失败');
        }
        $this->error('请求错误');
    }

    // 更新保存底部导航信息
    public function save_bottom()
    {
        if (IS_AJAX_POST){
            $post = input('post.');
            if (!empty($post['data'])){
                $sort_order = 1;
                foreach ($post['data'] as $k => $v){
                    $v['update_time'] = getTime();
                    $v['sort_order'] = $sort_order;
                    $sort_order++;
                    if (empty($v['nav_id'])){
                        $v['add_time'] = getTime();
                        $this->bottom_nav->insert($v);
                    }else{
                        $nav_id = $v['nav_id'];
                        unset($v['nav_id']);
                        $this->bottom_nav->where('nav_id',$nav_id)->update($v);
                    }
                }
                $this->success('保存成功!');
            }
        }
        $this->error('操作失败');
    }

    //底部导航删除
    public function del_bottom(){
        if (IS_AJAX_POST) {
            $nav_id = input('nav_id/d');
            if (!empty($nav_id)){
                $res = $this->bottom_nav->where('nav_id',$nav_id)->delete();
                if (false !== $res){
                    $this->success('删除成功');
                }
            }
            $this->error('删除失败');
        }
        $this->error('请求错误');
    }

    // 选择链接
    public function link()
    {
        $assign_data = [];
        $assign_data['ad_host_id'] = input('param.ad_host_id/d', 1);
        $assign_data['ad_link_id'] = input('param.ad_link_id/d', 0);
        // 链接详情
        $where = [
            'link_id' => $assign_data['ad_link_id'],
        ];
        $assign_data['linkInfo'] = $this->ad_link->where($where)->find();
        // 链接分组
        $where = [
            'status' => 1,
        ];
        $field = 'link_id, host_id, host_title';
        $assign_data['linkGroup'] = $this->ad_link->field($field)->where($where)->group('host_id')->order('host_id asc')->getAllWithIndex('host_id');

        // 查询类型
        $link_type = input('link_type/d', 0);

        // 商品列表
        if (3 === intval($assign_data['ad_host_id'])) {
            // 默认查询条件
            $condition = [
                'a.channel' => 2,
                'a.is_del' => 0,
                'a.merchant_id' => 0,
            ];

            // 获取到所有GET参数
            $param = input('param.');

            // 应用搜索条件
            foreach (['keywords'] as $key) {
                $param[$key] = addslashes(trim($param[$key]));
                if (isset($param[$key]) && $param[$key] !== '') {
                    if ($key == 'keywords') {
                        $condition['a.title'] = array('LIKE', "%{$param[$key]}%");
                    } else {
                        $condition['a.'.$key] = array('eq', trim($param[$key]));
                    }
                }
            }

            // 权限控制 by 小虎哥
            $admin_info = session('admin_info');
            if (0 < intval($admin_info['role_id'])) {
                $auth_role_info = $admin_info['auth_role_info'];
                if (!empty($auth_role_info) && isset($auth_role_info['only_oneself']) && 1 == $auth_role_info['only_oneself']) {
                    $condition['a.admin_id'] = $admin_info['admin_id'];
                }
            }

            // 自定义排序
            $orderby = input('param.orderby/s');
            $orderway = input('param.orderway/s');
            if (!empty($orderby) && !empty($orderway)) {
                $orderby = "a.{$orderby} {$orderway}, a.aid desc";
            } else {
                $orderby = "a.aid desc";
            }

            $count = Db::name('archives')->alias("a")->where($condition)->count('a.aid');
            $Page = $pager = new Page($count, config('paginate.list_rows'));
            $list = Db::name('archives')->alias("a")->field('a.*')->where($condition)->order($orderby)->limit($Page->firstRow.','.$Page->listRows)->select();
            foreach ($list as $key => $val) {
                $val['litpic'] = get_default_pic($val['litpic']);
                $list[$key] = $val;
            }
            $assign_data['param'] = $param;
            $assign_data['page'] = $Page->show();
            $assign_data['list'] = $list;
            $assign_data['pager'] = $Page;
        }
        // 分类管理
        else if (4 === intval($assign_data['ad_host_id'])) {
           // 目录列表
           $where = [
               'is_del' => 0,
               'current_channel' => 2,
           ];
           $arctypeLogic = new \app\common\logic\ArctypeLogic;
           $assign_data['arctype_list'] = $arctypeLogic->arctype_list(0, 0, false, 0, $where, false);

           // 获取所有有子栏目的栏目id
           $where = [
               'is_del' => 0,
               'parent_id' => ['gt', 0],
           ];
           $parent_ids = Db::name('arctype')->where($where)->group('parent_id')->cache(true, EYOUCMS_CACHE_TIME, 'arctype')->column('parent_id');
           $cookied_treeclicked =  json_decode(cookie('admin-treeLinkClicked-Arr'));
           empty($cookied_treeclicked) && $cookied_treeclicked = [];
           $all_treeclicked = cookie('admin-treeLinkClicked_All');
           empty($all_treeclicked) && $all_treeclicked = [];
           $tree = [
               'has_children'=>!empty($parent_ids) ? 1 : 0,
               'parent_ids'=>json_encode($parent_ids),
               'all_treeclicked'=>$all_treeclicked,
               'cookied_treeclicked'=>$cookied_treeclicked,
               'cookied_treeclicked_arr'=>json_encode($cookied_treeclicked),
           ];
           $assign_data['tree'] = $tree;
        }
        // 基础链接、会员中心
        else {
            // 指定分组的链接列表
            $where = [
                'status' => 1,
            ];
            if ($this->php_servicemeal < 2) {
                $where['link_id'] = ['NOTIN', [4,5,14,15,16]];
            }
            // 查询类型
            if (0 === intval($link_type)) {
                $where['link_type'] = ['IN', [1, 2]];
            } else if (3 === intval($link_type)) {
                $where['link_type'] = ['IN', [1, 3]];
            }
            $linkList = $this->ad_link->where($where)->order('sort_order asc, link_id asc')->select();
            $assign_data['linkList'] = group_same_key($linkList, 'host_id');
        }

        $assign_data['link_type'] = intval($link_type);
        $this->assign($assign_data);

        return $this->fetch('link');
    }
}