<?php

# 需求核心类，数据获取类

namespace Demand\Lib;

use Dever;

class Demand
{
	private $table_info = 'demand/info';
	private $table_attr = 'demand/info_attr';
    /**
     * instance
     *
     * @var string
     */
    protected static $instance;

    /**
     * init
     *
     * @return mixed
     */
    public static function init($top_category = false)
    {
        if (empty(self::$instance[$top_category])) {
            self::$instance[$top_category] = new self($top_category);
        }

        return self::$instance[$top_category];
    }

	public function __construct($top_category = false)
	{
		$this->top_category = $top_category;

        # 必有有分类才能进入到需求中
        if (!$this->top_category) {
            Dever::alert('错误的分类信息');
        }
	}

    private function setAttr($cate, $order = 'list_reorder')
    {
        if ($order != 'list_reorder') {
            Dever::config('base')->attrOrder = $order;
        }
        
        Dever::setInput('search_option_category', $cate);
        $attr = Dever::db($this->table_attr, array(), $cate);
        return $attr;
    }

    public function getAttr($cate)
    {
        return Dever::load('attr/api')->getAttrByCate($cate, 'list');
    }

    # 根据分类获取需求列表数据
    public function getData($cate = false, $limit = '0,10', $page = false, $attr = true)
    {
        if (!$limit) {
            $limit = '0,10';
        }
        $where = $data = array();
        if (!$cate) {
            if ($this->top_category > 0) {
                $where['top_category_id'] = $this->top_category;
            }
        } elseif (strstr($cate, ',')) {
            $where['category'] = $this->top_category . ',' . $cate;
        } else {
            $where['second_category_id'] = $cate;
        }
        
        if ($page) {
            $method = 'getPageAll';
        } else {
            $where['limit'] = $limit;
            $method = 'getAll';
        }
        $name = Dever::input('name');
        if ($name) {
            $where['name'] = $name;
        }
        $data = Dever::db($this->table_info)->$method($where);
        if ($data && $attr) {
            foreach ($data as $k => $v) {
                $data[$k] = $this->info($v, 'list_reorder');
            }
        }

        return $data;
    }

    # 获取某个用户的需求列表
    public function getDataByUid($uid)
    {
        $where['poster_uid'] = $uid;
        
        if ($where) {
            $data = Dever::db($this->table_info)->getPageAll($where);
            if ($data) {
                foreach ($data as $k => $v) {
                    $data[$k] = $this->info($v, 'list_reorder');
                }
            }
        }

        return $data;
    }

    # 根据属性获取需求列表数据 这里带有检索属性的功能 此处还需优化
    public function getDataByAttr($cate = false, $where = array())
    {
        if (!$cate) {
            Dever::alert('错误的分类信息');
        }
        $where_sql = array();
        $name = Dever::input('name');
        if ($name) {
            //$where['name'] = $name;
            $where_sql[] = ' t_2.name = "'.$name.'"';
        }

        $attr = $this->setAttr($this->top_category . ',' . $cate);
        //print_r($attr->config['attr']);

        $where_sql = Dever::load('attr/api')->getSql($attr->config['attr'], $where, $where_sql);
        if (!$where_sql) {
            return array();
        }
        # 这里用pdo的数据绑定，字符串字段的区间查询就是有问题。。。只能用sql了
        //$data = $attr->getPageAll($where);

        $page['template'] = 'list';
        $page['num'] = 10;
        $where_sql = implode(' and ', $where_sql);

        $sql = 'SELECT t_2.* FROM `info_demand_'.$attr->config['name'].'` as t_1 Left Join `info_demand_info` AS t_2 ON t_1.`info_id`=t_2.`id` WHERE '.$where_sql.' order by t_2.`reorder` desc,t_2.`id` desc';

        $data = $attr->fetchAll($sql, array(), $page);

        if ($data) {
            foreach ($data as $k => $v) {
                $data[$k] = $this->info($v, 'list_reorder');
            }
        }

        return $data;
    }

	# 获取列表页的搜索条件
    public function getSearch($cate = false)
    {
    	# 获取搜索条件
        if (!$cate) {
            $search_cate = $cate = $this->top_category;
        } else {
            $search_cate = $this->top_category . ',' . $cate;
        }
        # 1是当前用户所在的城市，暂时写死
        # 获取搜索条件
        $search = Dever::load('attr/api')->getSearch($search_cate, true, 1, false, 3);
        # 下级分类
        $search['cate'] = Dever::load('category/api')->getList($cate);

        # 上级分类
        $search['parent_cate'] = Dever::load('category/api')->getList($this->top_category);
        return $search;
    }

    public function getPayState($uid, $id, $category)
    {
        $pay_where['category'] = $category;
        $pay = Dever::db('demand/pay')->one($pay_where);
        $pay_state = 0;
        if ($pay && $pay['num'] > 0) {
            $pay_state = $pay['num'];
        } elseif (strstr($category, ',')) {
            $category = explode(',', $category);
            $category = array_pop($category);
            $pay_state = $this->getPayState($uid, $id, $category);
        }

        //$update['where_id'] = $id;
        //$update['poster_pay_type'] = $pay_state;
        //Dever::db($this->table_info)->update($update);

        return $pay_state;
    }

    # 更新需求
    public function update($top, $cate, $data, $id, $uid)
    {
        if ($cate) {
            $category = $top . ',' . $cate;
        } else {
            $category = $top;
        }
        $attr = $this->setAttr($category);

        $attr_update = Dever::preInput('attr_');
        if ($attr_update) {
            foreach ($attr_update as $k => $v) {
                if (strstr($k, '_s')) {
                    $k = str_replace('_s', '', $k);
                    $attr_update[$k] = $v;
                }
                if (strstr($k, '_e')) {
                    $k = str_replace('_e', '', $k);
                    $attr_update[$k] .= ',' . $v;
                }
            }
        }

        $update = array();
        $update['name'] = $data['name'];
        $update['category'] = $category;
        $update['pic'] = $data['pic'];
        //$update['pic_cover'] = $data['pic'];
        $update['poster_uid'] = $uid;
        if (isset($data['view_price']) && $data['view_price']) {
            $update['view_price'] = $data['view_price'];
        }
        if ($uid && $id) {
            # 此处要判断是用户自己的
            $info = Dever::db($this->table_info)->one($id);

            /*
            if ($uid == $info['poster_uid']) {
                Dever::alert('错误的用户参数');
            }
            */
            $update['where_id'] = $attr_update['where_id'] = $id;
            Dever::db($this->table_info)->update($update);
            Dever::db($this->table_attr)->update($attr_update);
            $pay = 0;
        } else {
            $id = Dever::db($this->table_info)->insert($update);
            $attr_update['category'] = $update['category'];
            $attr_update['info_id'] = $id;
            $attr_update['id'] = $id;
            Dever::db($this->table_attr)->insert($attr_update);

            # 验证是否需要支付，根据category判断
            $pay = false;
            //$pay = $this->getPayState($uid, $id, $category);

            $info = Dever::db($this->table_info)->one($id);
            $info = $this->getInfoLink($info);
        }
        return array('id' => $id, 'pay' => $pay, 'cate' => $category, 'top' => $top, 'info' => $info);
    }

    # 获取需求基本信息
    public function getInfo($id, $attr = true, $order = 'view_reorder')
    {
        $info = Dever::db($this->table_info)->one($id);

        if ($info && $attr) {
            $info = $this->info($info, $order);
        }

        if ($info['poster_uid'] < 0) {
            $info['poster_uid'] = 1;
        }

        if ($info['poster_uid'] > 0) {
            $info['user'] = Dever::db('passport/user')->one($info['poster_uid']);
            $sex = Dever::db('passport/user')->config['sex'];
            if ($info['user']['area']) {
                $info['user']['area'] = str_replace(',', '-', $info['user']['area']);
                $info['user']['area'] .= '-';
            }
            $info['user']['text'] = $info['user']['area'] . $sex[$info['user']['sex']];

            if (!$info['user']['avatar']) {
                $config = Dever::db('main/config')->one();
                $info['user']['avatar'] = $config['avatar'];
            }
        }

        $info['num_view_text'] = $info['num_view'] + $info['num_add_view'];

        $info['num_view_text'] .= '人浏览';

        if ($info['pic']) {
            $info['pic'] = explode(',', $info['pic']);
        }
        

        return $info;
    }

    # 获取需求基本信息
    public function info($info, $key = 'list_reorder')
    {
        $attr = $this->setAttr($info['category'], $key);
        $attr_data = $attr->one($info['id']);
        $info['category_array'] = Dever::load('category/api')->string($info['category']);

        $info['attr'] = array();

        if ($attr->config['attr']) {
            foreach ($attr->config['attr'] as $k => $v) {
                if (isset($v[$key]) && $v[$key] > 0) {
                    if (isset($attr_data['attr_' . $v['id']])) {
                        $v['value'] = $attr_data['attr_' . $v['id']];
                    } else {
                        continue;
                        $v['value'] = '';
                    }

                    $v['value_string'] = Dever::load('attr/api')->getValue($v);
                    
                    if ($v['ename'] == 'price') {
                        $info['price'] = $v['value_string'];
                    } else {
                        $v['bg'] = 'background-image: url('.$v['icon'].')';
                        $v['pic'] = '<img src="'.$v['icon'].'" width="18" />';
                        $info['attr'][] = $v;
                    }
                }
            }
        }
       
        if (isset($info['cdate']) && $info['cdate']) {
            $info['cdate_string'] = Dever::mdate($info['cdate'], 2);
        }

        $info = $this->getInfoLink($info);
        
    	return $info;
    }

    public function getInfoLink($info)
    {
        if (isset($this->view_path)) {
            $info['view_path'] = $this->view_path . '?top=' . $info['top_category_id'] . '&id=' . $info['id'];
            $info['view_link'] = Dever::url($info['view_path']);
        }

        return $info;
    }

    public function setViewPath($path)
    {
        $this->view_path = $path;
    }
}