<?php
namespace Smi\Controller;

use Think\Controller;

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

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

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

	/*
	 * 积分商品列表
	 */
	public function index()
	{	
		$where = array('admin_id' => $this->business_id );

		$count = M('int_market')->where($where)->count();

		$Page = new \Think\Page($count, 15);
		$show = $Page->show();
		$limit = $Page->firstRow.','.$Page->listRows;
		$list = M('int_market')->where($where)->limit($limit)->order('create_time DESC')->select();

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

	/*
	 * 添加积分商品
	 */
	public function add_int()
	{	
		$data = I('post.');
		if (!empty($data)) {// 保存图片
			
			$add = array(
					'admin_id' => $this->business_id,
					'sort' => empty($data['sort']) ? 0 : $data['sort'],
					'name' => $data['name'],
					'int' => $data['int'],
					'status' => $data['status'] == 'on' ? 1 : 2,
					'create_time' => time()
				);
			
			if ($_FILES['img']['name']) {
				$upload_info = $this->upload('img', 'int_market', true);
				if (!empty($upload_info)) {
					$add['img'] = $upload_info['savepath'].$upload_info['savename'];
				}
			}
			$result = M('int_market')->add($add);
			if ($result) {
				$this->success('Successfully Saved');die;
			} else {
				$this->error('Add failure');die;
			}
		}

		$this->display();
	}

	/*
	 * 编辑积分商品
	 */
	public function edit($id = '')
	{	
		$data = I('post.');
		if (!empty($data)) {// 保存图片

			$save = array(
					'sort' => empty($data['sort']) ? 0 : $data['sort'],
					'name' => $data['name'],
					'int' => $data['int'],
					'status' => $data['status'] == 'on' ? 1 : 2,
					'update_time' => time()
				);

			if ($_FILES['img']['name']) {
				$upload_info = $this->upload('img', 'int_market', true);
				if (!empty($upload_info)) {
					$save['img'] = $upload_info['savepath'].$upload_info['savename'];
				}
			}
			
			$result = M('int_market')->where(array('id' => $data['id']))->save($save);
			if ($result) {
				$this->success('Successfully Edited');die;
			} else {
				$this->error('Update failed');die;
			}
		}
		$item  = M('int_market')->where(array('id' => $id))->limit(1)->select();
		$item[0]['img'] = __ROOT__.'/Uploads/'.$item[0]['img'];
		$this->assign('goods', $item[0]);
		$this->display('add_int');
	}

	/*
	 * 删除积分商品
	 */
	public function delete($id = '')
	{
		$goods = M('int_market')->where(array('id' => $id))->limit(1)->select();

		$result = M('int_market')->where(array('id' => $id))->delete();

		if ($result) {
			// 删除商品图片
			unlink(ROOT_PATH."/Uploads/".$goods[0]['img']);
			// 删除兑换记录
			M('exchange')->where(array('int_market_id' => $id))->delete();
			$this->success('Successfully Deleted');die;
		} else {
			$this->error('Delete failed');die;
		}
	}

	/*
	 * 积分商品兑换记录
	 */
	public function exchange()
	{	
		$data = I();
		
		$where = 'am_users.admin_id = '.$this->business_id;

		if (!empty($data['exchange_no'])) {
			$where .= ' AND exchange_no = '.$data['exchange_no'];
		}
		if (!empty($data['nickname'])) {
			$where .= ' AND nickname = '.$data['nickname'];
		}
		if (!empty($data['ctstar'])) {
			$ctstar = strtotime($data['ctstar']);
			$where .= ' AND am_exchange.create_time >= '.$ctstar;
		}
		if (!empty($data['ctend'])) {
			$ctend = strtotime($data['ctend']);
			$where .= ' AND am_exchange.create_time <= '.$ctend;
		}
		if (!empty($data['sts'])) {
			$where .= ' AND am_exchange.status = '.$data['sts'];
		}
		
		$count = M('exchange')
		->join('am_users ON am_users.id = am_exchange.user_id')
		->join('am_int_market ON am_int_market.id = am_exchange.int_market_id')
		->where($where)
		->count();

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

		$list = M('exchange')
		->join('am_users ON am_users.id = am_exchange.user_id')
		->join('am_int_market ON am_int_market.id = am_exchange.int_market_id')
		->where($where)
		->field('am_exchange.*, am_int_market.img, am_int_market.name iname')
		->limit($limit)
		->order('am_exchange.create_time DESC')
		->select();

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

	/*
	 * 兑换详情
	 */
	public function detail($id = '')
	{	
		$data  = I('post.');
		if (!empty($data) && !empty($data['id'])) {
			$result = M('exchange')->where(array('id' => $data['id']))->save(array('status' => 1));
			if ($result) {
				$this->ajaxReturn(['status' => 1, 'info' => 'Operation is successful']);die;
			} else {
				$this->ajaxReturn(['status' => -1, 'info' => 'The operation failure']);die;
			}
		}

		$item = M('exchange')
				->join('am_int_market ON am_exchange.int_market_id = am_int_market.id')
				->where(array('am_exchange.id' => $id))
				->field('am_exchange.*, am_int_market.name iname')
				->select();

		$this->assign('item', $item[0]);

		$this->display();
	}

	/**
	 * 入录物流单号
	 */
	public function logistics_no()
	{
		$data = I('post.');
		if (empty($data)) {
			$this->ajaxReturn(['status' => -1, 'msg' => 'Parameter is wrong']);die;	
		}

		$result = M('exchange')->where(array('exchange_no' => $data['exchange_no']))->save(array('logistics_no' => $data['logistics_no'], 'status' => 1));

		if ($result) {
			$this->ajaxReturn(['status' => 1, 'msg' => 'Recorded into success']);die;
		} else {
			$this->ajaxReturn(['status' => -1, 'msg' => 'The recorded failure']);die;
		}
	}

		/*
	 * 轮播图
	 */
	public function chart()
	{
		$list = M('int_chart')->where(array('admin_id' => $this->business_id))->select();
		$this->assign('list', $list);
		$this->display();
	}

	/*
	 * 添加轮播图
	 */
	public function add_chart()
	{
		$data = I('post.');

		if (!empty($data) && !empty($data['title'])) {
			$add = array(
					'admin_id' => $this->business_id,
					'title' => $data['title'],
					'status' => $data['status'],
					'create_time' => time(),
				);
			if (empty($_FILES['img']['name'])) {
				$this->error('Please Upload Slideshow Image');die;
			} else {
				$upload = ToolsController::upload('int_chart/');
				if ($upload['status'] == -1) {
					$this->error($upload['msg']);die;
				} else {
					$add['img'] = $upload['file_path'];
				}
			}

			$result = M('int_chart')->add($add);

			if ($result) {
				$this->success('Successfully Saved');die;
			} else {	
				unlink(ROOT_PATH.'/Uploads/'.$upload['file_path']);
				$this->error('Add failure');die;
			}
		}

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

	/*
	 * 编辑轮播图
	 */
	public function edit_chart($id)
	{
		$data = I('post.');

		if (!empty($data) && !empty($data['title'])) {

			$info = M('int_chart')->where(array('id' => $data['id']))->find();

			$save = array(
					'title' => $data['title'],
					'status' => $data['status'],
					'update_time' => time(),
				);

			if (!empty($_FILES['img']['name'])) {
				$upload = ToolsController::upload('int_chart/');
				if ($upload['status'] == -1) {
					$this->error($upload['msg']);die;
				} else {
					$save['img'] = $upload['file_path'];
				}
			}

			$result = M('int_chart')->where(array('id' => $data['id']))->save($save);

			if ($result) {
				if (!empty($_FILES['img']['name'])) {
					unlink(ROOT_PATH.'/Uploads/'.$info['img']);
				}
				
				$this->success('Successfully Edited');die;
			} else {
				unlink(ROOT_PATH.'/Uploads/'.$upload['file_path']);
				$this->error('Update failed');die;
			}
		}

		$info = M('int_chart')->where(array('id' => $id))->find();
		$info['img'] = __ROOT__.'/Uploads/'.$info['img'];

		$this->assign('info', $info);
		$this->assign('op', 'Edit');
		$this->display('add_chart');
	}	

	/*
	 * 删除轮播图
	 */
	public function delete_chart($id)
	{	
		$where = array('id' => $id);
		$chart_info = M('int_chart')->where($where)->find();

		if ($chart_info['admin_id'] != $this->business_id) {
			$this->error('Illegal operation');die;
		}

		$result = M('int_chart')->where($where)->delete();

		if ($result) {
			unlink(ROOT_PATH.'/Uploads/'.$chart_info['img']);
			$this->success('Successfully Deleted');die;
		} else {
			$this->error('Delete failed');die;
		}
	}

	/*
	 * 文件上传
	 */
	private function upload($name,$folder='',$datefolder=false){

        $upload = new \Think\Upload();

        $upload->maxSize  = 52428800 ;

        $upload->exts     = array('jpg', 'gif', 'png', 'jpeg');

        if($datefolder && $folder){

            $upload->rootPath = "./Uploads/";

            $upload->savePath = "{$folder}/";

        }else{

            $upload->rootPath = './Uploads/';

            //当subName未定义而autoSub为true时，自动以日期创建目录。

            $upload->subName  = $folder?$folder:$name;

        }

        $upload->autoSub  = true;

        $info = $upload->uploadOne($_FILES[$name]);

        if(!$info) $info = $upload->getError();

        return $info;

    }
}