<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Home extends CI_Controller
{
	public $data;

	public function __construct()
    {
        parent::__construct();

        /** 检查是否已登录，未登录执行登录步骤 */
        $this->userm->check_login(2, FALSE);

        $this->data['base_url']   = base_url();
        $this->data['web_name']   = $this->config->item('web_name');
        $this->data['UserInfo']   = $this->userm->UserInfo;
        $this->data['Currency']   = $this->config->item('CalculateMoney');
        $this->data['new_notify'] = $this->basem->new_notify();
        
        $this->load->model('reward/rewardm');
    }

	public function index()
	{
        if(isset($_GET['inajax'])) unset($_GET['inajax']);
        $limit      = 15;
        $keyword    = trim($this->input->get('keyword', true));

        /** 获取 URI 字符串 @Author Bob */
        $this->data['uris']	= explode('/', $this->uri->uri_string());

        /** @var 处理URL参数 $uri */
        $page = intval($this->input->get('page', true))<1?1:intval($this->input->get('page', true));
        $offset = ($page-1)*$limit;
        
        $this->data['page']=$offset;
        $order = intval($this->input->get('order', true))??0;
        $cat_id = intval($this->input->get('cat_id', true))??0;
        $min = intval($this->input->get('min', true));
		$max = intval($this->input->get('max', true));
        /** 获取分类CODE */
        $cat_code = '';
        if ($cat_id === 0 && count($this->data['uris']) >= 2)
        {
            $cat_code = $this->data['uris'][1];
        }

        /** 获取分类信息 */
        $this->data['category'] = [];
        $this->load->model('categorym');
        if ($cat_id || $cat_code)
        {
            $cat_where = ['is_del' => 0, 'is_show' => 1, 'cat_type' => 1];
            if ($cat_id) $cat_where['cat_id'] = $cat_id;
            elseif ($cat_code) $cat_where['cat_code'] = $cat_code;
            $this->data['category'] = $this->categorym->get([
                'where' => $cat_where,
                'field' => 'cat_id,cat_type,cat_code,cat_name,cat_title,cat_keyword,cat_desc',
            ]);
            if($this->data['category'])
            {
                $this->data['category']['cat_title'] = $this->data['category']['cat_title']?:NULL;
                $this->data['category']['cat_keyword'] = $this->data['category']['cat_keyword']?:NULL;
                $this->data['category']['cat_desc'] = $this->data['category']['cat_desc']?:NULL;
            }
        }

        /** 排序开始 @Author Bob */
        $orders  = [
            0 => ['field' => 'r.is_top DESC,r.add_time DESC, r.last_update DESC', 'icon' => ''],
            1 => ['field' => 'r.is_top DESC,r.add_time DESC', 'icon' => 'falling'],
            2 => ['field' => 'r.is_top DESC,r.top_add_time DESC', 'icon' => 'falling'],
            3 => ['field' => 'r.is_top DESC,r.apply_price DESC', 'icon' => 'falling'],
            4 => ['field' => 'r.is_top DESC,r.apply_price ASC', 'icon' => 'ascend'],
        ];

        $order_by = $orders[$order]['field'];
        $order_url = '';
        $this->data['order'] = [];
        $this->data['current_order'] = 'default';
       /* foreach ($orders AS $ok => $ov)
        {
            if ($ok)
            {
                @list($field, $sort) = explode(' ', $ov['field']);
                if($ok == $order)
                {
                    $new_order = ( $field . ' ' . ( $sort == 'ASC' ? 'DESC' : 'ASC' ) );
                    foreach ($orders AS $k => $o)
                    {
                        if($o['field'] == $new_order)
                        {
                            $nk = $k;
                            break;
                        }
                    }
                    $order_url = "/o{$ok}";
                    $this->data['current_order'] = $field;
                    $this->data['order'][$field] = $ov['icon'];
                    $this->data['order'][$field.'_url'] = site_url(implode('/', $this->data['uris']) . "/o{$nk}");
                }
                elseif ( ! isset($this->data['order'][$field]) && $sort == 'DESC')
                {
                    $this->data['order'][$field] = 'falling';
                    $this->data['order'][$field.'_url'] = site_url(implode('/', $this->data['uris']) . "/o{$ok}");
                }
            }
        }*/

	    $where = ['r.is_del' => 0, 'r.status' => 1];

	    /** 分类 */
        if ($this->data['category']) $where['r.cat_id'] = $this->data['category']['cat_id'];

        /** 搜索 */
        if($keyword)
        {
        	if(is_numeric($keyword))
        	{
        		 $where['r.reward_id like'] = "%{$keyword}%";
        	}
        	else
        	{
        		 $where['r.reward_title like'] = "%{$keyword}%";
        	}
        }
       
        
        /** 金额 */
        if($min) $where['r.apply_price >'] = $min;
        
        if($max) $where['r.apply_price <='] = $max;

        /** 统计数量 */
        $this->data['num_rows'] = $this->rewardm->count(['where' => $where]);

        /** 分页 */
        /*$this->load->helper('page');
        $this->data['pagehtml']	= pagination(implode('/', $this->data['uris']).$order_url, $this->data['num_rows'], $limit);*/
		
		/** VIP信息 */
        // $this->load->model('user/user_vipm');
        // $this->data['user_vip'] = $this->user_vipm->vip_info($this->data['UserInfo']['user_id']);
		
        /** 任务列表 */
        
        if(!empty($_GET['k'])){
            $limit=$_GET['k']+'15';
        }
        $this->data['list'] = $this->rewardm->all([
	        'where'     => $where,
            'join'      => ['user', 'category', 'reward_extra', 'reward_browse'],
            'field'     => 'r.*,u.phone,u.avatar,u.nickname,c.cat_id,c.cat_type,c.cat_code,c.cat_name,rb.id as reward_browse_id,re.id as reward_extra_id',
            //'order_by'  =>'r.top_add_time','RANDOM',
            'order_by'  =>$order_by,
            'offset'	=> $offset,
            'limit'		=> $limit,
        ]);
        
       //  'order_by'  => 'r.is_top DESC, r.top_add_time DESC, ' . $order_by,
		$this->data['list'];
        /** @var 获取列表中的任务用户是否可接 $reward_ids */
    	//var_dump($this->data['list']);die();
        if ($this->data['list'] && $this->data['UserInfo'])
        {
            $reward_ids = implode(',', array_column($this->data['list'], 'reward_id'));
            $this->load->model('reward/applym');
            $applys = $this->applym->all( [
                'where' => [
                    'a.apply_user_id' => $this->data['UserInfo']['user_id'],
                    'a.reward_id IN (' . $reward_ids . ')' => NULL,
                ],
                'field' => 'a.reward_id',
            ] );
            $order_ids = $applys ? array_column($applys, 'reward_id') : [];
            
            
            $caina = $this->applym->all( [
                'where' => [
                    'a.apply_user_id' => $this->data['UserInfo']['user_id'],
                    'a.reward_id IN (' . $reward_ids . ')' => NULL,
                    'a.acception_status' => 1,
                ],
                'field' => 'a.reward_id',
            ] );

            $cainaids = $caina ? array_column($caina, 'reward_id') : [];
            $this->data['cainaids']=$cainaids;
        }
        

        /** 数据处理 */
        foreach ($this->data['list'] AS & $item)
        {
            /** 判断是否可接单 */
            if ($this->data['UserInfo'])
            {
                $item['order_state'] = (
                    ( $item['user_id'] != $this->data['UserInfo']['user_id'] && $item['status'] == 1 ) ?
                    ( in_array($item['reward_id'], $order_ids) ? 1 : 2 )
                    : 0
                );
            }
            else
            {
                $item['order_state'] = $item['status'] == 1 ? 2 : 0;
            }

            /** 没有设置昵称的用隐藏手机号 */
            $item['nickname'] = $item['nickname'] ?: hide_phone($item['phone']);
            unset($item['phone']);
        }


        
        $this->load->model('reward/Rewardm');
        $toutiao = $this->Rewardm->get_jingpai_all_zs();

        foreach($toutiao as $k=>$v){
            $v['reward']=$this->Rewardm->get(['where'=>['reward_id'=>$v['rid']]]);
            $toutiao[$k]=$v;
        }
        $this->data['toutiao']=$toutiao;

        /** 电脑端才获取 */
        if (IN_MOBILE === FALSE)
        {
            /** 最新任务 */
            $this->data['new_list'] = $this->rewardm->all([
                'where'     => ['r.is_del' => 0, 'r.status' => 1, 'r.surplus_votes > ' => 0],
                'field'     => 'r.reward_id,r.reward_title,r.apply_price',
                'order_by'  => 'r.add_time DESC',
                'limit'		=> 10,
            ]);

            /** 热门任务 */
            $this->data['hot_list'] = $this->rewardm->all([
                'where'     => ['r.is_del' => 0, 'r.status' => 1, 'r.surplus_votes > ' => 0],
                'field'     => 'r.reward_id,r.reward_title,r.apply_price',
                'order_by'  => 'r.views DESC, r.add_time DESC',
                'limit'		=> 10,
            ]);
        }

        /** AJAX请求返回json数据 */
        if ($this->input->is_ajax_request())
        {
            $data = [
                /*'page' => $this->data['pagehtml'],*/
                'html' => $this->load->view( "reward/list", $this->data, TRUE),
            ];
            ShowMsg('获取成功', 'javascript:;', 1, $data);
        }
        else
        {
            /** 分类列表 */
            $this->data['categorys'] = $this->categorym->all([
                'where'     => ['is_del' => 0, 'is_show' => 1, 'cat_type' => 1],
                'field'     => 'cat_id,cat_type,cat_code,cat_name',
                'transform' => TRUE,
            ]);
            /*if ($order_url)
            {
                foreach ($this->data['categorys'] AS & $item)
                {
                    $item['cat_url'] = site_url($item['cat_uri'].$order_url);
                }
            }*/

            $this->load->config('reward', TRUE);
            /*$this->data['order_url']       = $order_url;*/
            $this->data['this_nav']        = 'reward';
            $this->data['web_title']       = ( ( $this->data['category'] ? (
                                                    $this->data['category']['cat_title']??
                                                    $this->data['category']['cat_name']
                                                ) : NULL ) ??
                                                $this->config->item( 'seo_title', 'reward' )
                                            );
            $this->data['web_keywords']    = ( ( $this->data['category'] ?
                                                $this->data['category']['cat_keyword'] : NULL ) ??
                                                $this->config->item( 'seo_keyword', 'reward' )
                                            );
            $this->data['web_description'] = ( ( $this->data['category'] ?
                                            $this->data['category']['cat_desc'] : NULL ) ??
                                            $this->config->item( 'seo_description', 'reward' )
                                        );

            $this->load->view( 'reward/home', $this->data );
        }
	}
}
