<?php

namespace Code\Lib;

use Dever;

class Manage
{
	public function showCode($id)
	{
		$info = Dever::db('code/info')->one($id);

		if ($info['code']) {
			return $info['code'];
		}
		
		/*
		if ($info['create_uid'] > 0) {
			return Dever::load('code/lib/core')->view($info['id'], true);
			return '用户创建';
		}
		*/

		if ($info['product_id'] > 0) {
			return Dever::load('code/lib/core')->view($info['id'], true);
		}

		return 'T' . $id;
	}

	/**
	 * 显示用户信息
	 *
	 * @return mixed
	 */
	public function showUserInfo($create_uid, $uid, $ldate = false, $type = 1)
	{
		$table = array();
		if ($create_uid && $create_uid > 0) {
			$user = Dever::load('passport/user-one', $create_uid);
			$table['创建人'] = $user['username'] . '('.$create_uid.')';
		}
		if ($type == 3 && $uid && $uid > 0) {
			$user = Dever::load('passport/user-one', $uid);
			if ($user) {
				$table['领取人'] = $user['username'] . '('.$uid.')';
				$table['手机号'] = $user['mobile'];
				$table['领取时间'] = date('Y-m-d H:i:s', $ldate);
			}
		}

		return Dever::table($table);
	}

    /**
	 * 创建兑换码
	 *
	 * @return mixed
	 */
	public function create($id, $name, $param)
	{
		$code = Dever::param('num', $param);
		$score = Dever::param('score', $param);
		$product_num = Dever::param('product_num', $param);
		$product = Dever::param('product', $param);
		//$product_id = Dever::param('product_id', $param);
		$seller_id = Dever::param('seller_id', $param);

		$cate_id = $product_id = 0;
		if ($product && isset($product[0])) {
			$cate_id = $product[0];
			if (isset($product[1])) {
				$product_id = $product[1];
			}
			
			$product = implode(',', $product);
		}

		if ($cate_id <= 0){
			Dever::alert('生成失败，请选择分类');
		}


		//$total = Dever::db('code/info')->total(array('product_id' => $product_id, 'type' => 1));
		$total = 0;
		$core = Dever::load('code/lib/core');
		if ($code > 0 && $code > $total) {
			$num = $code - $total;

			$core->createCode($product, $cate_id, $product_id, $seller_id, $product_num, -1, false, $score, 1, $num);
		}
	}

	/**
	 * 作废
	 *
	 * @return mixed
	 */
	public function drop_api($id, $journal_id, $code)
	{
		if (!$code && $journal_id > 0) {
			Dever::setInput('set_product_id', $journal_id);
		}
		
		$update['where_id'] = $id;
		$update['type'] = 4;
		Dever::db('code/info')->update($update);
		return 'ok';
	}

	public function recovery_api($id, $journal_id, $code)
	{
		if (!$code && $journal_id > 0) {
			Dever::setInput('set_product_id', $journal_id);
		}

		$update['where_id'] = $id;
		$update['type'] = 1;
		Dever::db('code/info')->update($update);
		return 'ok';
	}
}