<?php
namespace Smi\Controller;

use Think\Controller;

header("Content-Type:text/html;CharSet=UTF-8");
class ShareController extends BaseController
{		
	protected $business_id;

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

		$this->business_id = session('admin_id');
	}

	/**
	 * 分享设置
	 */
	public function index()
	{	
		$data = I('post.');

		$config = M('share_config')->where(array('admin_id' => $this->business_id))->find();

		if (empty($config)) {
			M('share_config')->add(array(
					'admin_id' => $this->business_id,
					'create_time' => time()
				));
			$config = M('share_config')->where(array('admin_id' => $this->business_id))->find();
		}

		if (!empty($data)) {
			$save = array(
						'num' => $data['num'],
						'acc' => $data['acc'],
						'status' => $data['status'],
						'update_time' => time()
					);

			$result = M('share_config')->where(array('admin_id' => $this->business_id))->save($save);

			if ($result) {
				$this->success('Successfully Saved');die;
			} else {
				$this->error('Save failed');die;
			}
		}

		$this->assign('config', $config);
		$this->display();
	}

	/**
	 * 被分享者列表
	 */
	public function shared($search = '')
	{	
		$where = 'uu.admin_id = '.$this->business_id.' AND us.admin_id = '.$this->business_id;

		if (!empty($search)) {
			$where .= ' AND uu.nickname LIKE "%'.$search.'%"';
		}

		$field = 'uu.id user_id, uu.nickname unickname, uu.avatarurl uavatarurl, us.id share_id, us.nickname snickname, us.avatarurl savatarurl, am_share.int, am_share.create_time';

		$count = M('share')
				->join('am_users AS uu ON uu.id = am_share.user_id')
				->join('am_users AS us ON us.id = am_share.share_id')
				->field($field)
				->where($where)
				->count();


		$Page = new \Think\Page($count, 15);
		$show = $Page->show();
		$limit = $Page->firstRow.', '.$Page->listRows;


		$list = M('share')
				->join('am_users AS uu ON uu.id = am_share.user_id')
				->join('am_users AS us ON us.id = am_share.share_id')
				->field($field)
				->where($where)
				->order('am_share.create_time DESC')
				->limit($limit)
				->select();


		$this->assign('page', $show);
		$this->assign('search', $search);
		$this->assign('list', $list);
		$this->display();
	}
}