<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace app\model;

/**
 * 分类模型
 */
class Record extends \think\Model {

	protected $type = [
		'new_data' => 'json',
		'old_data' => 'json',
		'order_num'    => 'float'
	];

	public function getDataList($request) {
		$map   = [];
		$order = "id desc";
		$param = $request->param();

		if (isset($param['name']) && $param['name'] != '') {
			$map[] = ['data_name', 'LIKE', '%' . $param['name'] . '%'];
		}
		if (isset($param['nickname']) && $param['nickname'] != '') {
			$searchUser = db('Member')->where('nickname', $param['nickname'])->field('uid,department')->find();
			if ($searchUser) {
				$map[] = ['uid', '=', $searchUser['uid']];
			}
		}
		if (isset($param['data']) && count($param['data']) == 2 && $param['data'][0] && $param['data'][1]) {
			$data  = [strtotime($param['data'][0]), strtotime($param['data'][1])];
			$map[] = ['create_time', 'between time', $data];
		}
		//数据权限
		if ($request->user['role']['data_auth'] == 1) {
			// 部门数据...
			$user = Db::name('Member')->field('uid')
				->where('department', $request->user['department'])
				->buildSql();
			$map[] = ["uid", "EXP", "in " . $user];
		} elseif ($request->user['role']['data_auth'] == 2) {
			// 个人数据...
			$map[] = ['uid', '=', $request->user['uid']];
		}

		$list = self::with(['member'])->where($map)
			->order($order)->paginate($request->pageConfig);
		return $list;
	}

	/**
	 * title : 添加记录
	 * param : old 旧数据，new 新数据 type 类型
	 */
	public function adds($old = array(), $new = array(), $type = 'customer') {
		$edit = array(); //修改过的字段
		foreach ($new as $key => $value) {
			if (isset($old[$key]) && $value != $old[$key]) {
				$edit[] = $key;
			}
		}
		if (!empty($edit)) {
			$data['data_id']     = $old['id'];
			$data['data_name']   = $old['name'];
			$data['type']        = $type;
			$data['uid']         = session('user_auth.uid');
			$data['old_data']    = json_encode($old);
			$data['new_data']    = json_encode($new);
			$data['fields']      = json_encode($edit);
			$data['create_time'] = time();
			return $this->insert($data);
		}
	}

	public function member() {
		return $this->hasOne('Member', 'uid', 'uid')->field('uid,username,nickname');
	}
}