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

namespace app\admin\model;

use think\Db;
use think\Page;
use think\Model;
use app\common\logic\DecorationLogic;

/**
 * 模型
 */
load_trait('controller/Jump');

class Decoration extends Model
{
    use \traits\controller\Jump;

    private $terminal = '';
    public function __construct($terminal = '') {
        if (!empty($terminal)) $this->terminal = $terminal;
        parent::__construct();
    }

    //初始化
    protected function initialize()
    {
        // 需要调用`Model`的`initialize`方法
        parent::initialize();
        // 当前时间戳
        $this->times = getTime();
        // 逻辑层
        $this->decorationLogic = new DecorationLogic;
        // 广告链接
        $this->ad_link_db = Db::name('applets_ad_link');
        // 底部导航
        $this->bottom_nav_db = Db::name('applets_bottom_nav');
        // 页面路由
        $this->page_paths_db = Db::name('applets_page_paths');
        // 广告内容
        $this->ad_content_db = Db::name('applets_ad_content');
        // 广告位
        $this->ad_position_db = Db::name('applets_ad_position');
        // 插件配置信息
        $this->weappInfo = [];
//        $this->weappInfo = model('ShopPublicHandle')->getWeappInfo('Suibian');
    }

    // 获取广告位列表
    public function getAdPositionList()
    {
        // 查询条件
        $where = [];
        // 小程序调用则执行
        if (!empty($this->terminal) && 'applets' == $this->terminal) $where['status'] = 1;

        // 分页查询
        $count = $this->ad_position_db->alias('a')->where($where)->count('position_id');
        $pages = new Page($count, config('paginate.list_rows'));

        // 列表查询
        $list = $this->ad_position_db->where($where)->limit($pages->firstRow.','.$pages->listRows)->order('sort_order asc,add_time asc, position_id asc')->select();

        // 小程序调用则执行
        if (!empty($this->terminal) && 'applets' == $this->terminal) {
            $where = [
                'position_id' => ['IN', get_arr_column($list, 'position_id')],
            ];
            $content = $this->ad_content_db->where($where)->order('sort_order desc, content_id desc')->select();
            // 广告处理
            foreach ($content as $key => $value) {
                $value['content_images'] = handle_subdir_pic($value['content_images'], 'img', true);
                $content[$key] = $value;
                if (empty($value['content_title']) || empty($value['content_images'])) unset($content[$key]);
            }
            $content = $this->decorationLogic->getAdContentLinkNames($content, $this->terminal);
            $content = !empty($content) ? group_same_key($content, 'position_id') : [];
            // 如果金刚位广告存在数据则执行
            if (!empty($content[2])) {
                // 数组进行升序排序
                sort($content[2]);
                foreach ($content[2] as $key => $value) {
                    $content[2][$key]['fur_index'] = $key;
                }
            }
            // 广告处理
            foreach ($list as $key => $value) {
                $value['content'] = !empty($content[$value['position_id']]) ? $content[$value['position_id']] : [];
                $list[$key] = $value;
            }
        }

        // 返回数据
        return [
            'list' => $list,
            'pages' => $pages,
            'show' => $pages->show(),
        ];
    }

    // 获取指定广告位的广告内容列表
    public function getAdContentList($position_id = 0)
    {
        if (empty($position_id)) $position_id = input('param.position_id/d', 0);
        // 查询条件
        $where = [
            'position_id' => intval($position_id),
        ];
        // 广告位信息
        $field = $this->ad_position_db->where($where)->find();

        // 广告内容信息
        $order = 'sort_order asc, content_id asc';
        $list = $this->ad_content_db->where($where)->order($order)->select();
        // 获取链接名称
        $list = $this->decorationLogic->getAdContentLinkNames($list);

        // 小程序调用则执行
        if (!empty($this->terminal) && 'applets' == $this->terminal) {
            foreach ($list as $key => $value) {
                if (empty($value['content_title']) || empty($value['content_images'])) unset($list[$key]);
            }
            $list = array_merge($list);
            foreach ($list as $key => $value) {
                $value['fur_index'] = $key;
                $value['content_images'] = handle_subdir_pic($value['content_images'], 'img', true);
                $list[$key] = $value;
            }
            // 返回数据
            $field['content'] = $list;
            return [
                'list' => [$field],
            ];
        } else {
            foreach ($list as $key => $value) {
                $value['content_images'] = handle_subdir_pic($value['content_images'], 'img');
                $list[$key] = $value;
            }
            // 最大 content_id
            $maxContentID = $this->ad_content_db->max('content_id');
            // 返回数据
            return [
                'list' => $list,
                'field' => $field,
                'maxContentID' => $maxContentID,
            ];
        }
    }

    // 获取页面路径列表
    public function getPagePahtsList()
    {
        // 查询条件
        $where = [
            'status' => 1,
        ];
        
        // 列表查询
        $list = $this->page_paths_db->where($where)->order('add_time asc, id asc')->select();

        // 返回数据
        return [
            'list' => $list,
        ];
    }

    // 获取广告链接列表
    public function getAdLinkList()
    {
        $ad_host_id = input('param.ad_host_id/d', 1);
        $ad_link_id = input('param.ad_link_id/d', 0);

        // 查询条件
        $where = [
            'status' => 1,
        ];
        // 如果未开启积分商城插件则执行
        $pointsShop = model('ShopPublicHandle')->getWeappInfo('PointsShop');
        if (empty($pointsShop['status']) || 1 !== intval($pointsShop['status']) || empty($pointsShop['data']['openPoints'])) {
            $where['link_id'] = ['NOTIN', [5, 15]];
        }
        // 列表查询
        $linkList = $this->ad_link_db->where($where)->order('sort_order asc,add_time asc, link_id asc')->select();
        // 获取指定的单个链接
        $linkFind = [];
        if (!empty($ad_link_id)) {
            foreach ($linkList as $key => $value) {
                if (intval($ad_link_id) === intval($value['link_id'])) {
                    $linkFind = $value;
                    break;
                }
            }
        }
        // 获取每个host_id组的第一条内容数据
        $linkGroup = [];
        foreach ($linkList as $key => $value) {
            if (empty($linkGroup[$value['host_id']])) {
                $linkGroup[$value['host_id']] = [
                    'link_id' => $value['link_id'],
                    'host_id' => $value['host_id'],
                    'host_title' => $value['host_title'],
                ];
            }
        }
        // 以host_id分组
        $linkList = group_same_key($linkList, 'host_id');

        // 查询商品列表
        if (3 === intval($ad_host_id)) {
            // 默认查询条件
            $where = [
                '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') {
                        $where['a.title'] = array('LIKE', "%{$param[$key]}%");
                    } else {
                        $where['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']) {
                    $where['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($where)->count('a.aid');
            $Page = $pager = new Page($count, config('paginate.list_rows'));
            $list = Db::name('archives')->alias("a")->field('a.*')->where($where)->order($orderby)->limit($Page->firstRow.','.$Page->listRows)->select();
            foreach ($list as $key => $val) {
                $val['litpic'] = get_default_pic($val['litpic']);
                $val['title_new'] = @msubstr(checkStrHtml($val['title']), 0, 12, true);
                $list[$key] = $val;
            }
            // 返回数据
            $assign = [
                'param' => $param,
                'page' => $Page->show(),
                'list' => $list,
                'pager' => $Page,
            ];
        }
        // 查询商品分类
        else if (4 === intval($ad_host_id)) {
            // 目录列表
            $where = [
                'current_channel' => 2,
                'is_del' => 0,
            ];
            $arctypeLogic = new \app\common\logic\ArctypeLogic;
            $arctype_list = $arctypeLogic->arctype_list(0, 0, false, 0, $where, false);

            // 获取所有有子栏目的栏目id
            $where = [
                'parent_id' => ['gt', 0],
                'is_del' => 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 = [
                'tree' => $tree,
                'arctype_list' => $arctype_list,
            ];
        }

        // 返回数据
        $result = [
            'linkFind' => $linkFind,
            'linkList' => $linkList,
            'linkGroup' => $linkGroup,
            'ad_link_id' => $ad_link_id,
            'ad_host_id' => $ad_host_id,
        ];
        return !empty($assign) ? array_merge($result, $assign) : $result;
    }

    // 获取底部导航列表
    public function getBottomNavList()
    {
        // 底部导航列表信息
        $where = [
            'status' => 1,
        ];
        $list = $this->bottom_nav_db->where($where)->order('sort_order asc, add_time asc, nav_id asc')->select();
        foreach ($list as $key => $value) {
            $value['default_pic'] = handle_subdir_pic($value['default_pic'], 'img', true);
            $value['selected_pic'] = handle_subdir_pic($value['selected_pic'], 'img', true);
            $list[$key] = $value;
            if (!empty($this->terminal) && 'applets' == $this->terminal) {
                if (empty($value['link_id']) && empty($value['nav_title']) && empty($value['default_pic']) && empty($value['selected_pic'])) {
                    unset($list[$key]);
                }
            }
        }
        // 获取链接名称
        $list = $this->decorationLogic->getAdContentLinkNames($list, $this->terminal);

        // 返回数据
        return [
            'list' => $list,
        ];
    }

}