<?php
namespace app\worker\controller;

use think\facade\Session;
use app\worker\BaseController;
use app\common\model\User as UserModel;
use app\common\model\UserAuths as UserAuthsModel;
use app\common\model\UserFollow as UserFollowModel;
use app\common\model\UserGroups as UserGroupsModel;
use app\common\model\Agent as AgentModel;
use app\common\model\Broker as BrokerModel;

use app\common\validate\User as UserValidate;
use think\exception\ValidateException;

use PHPExcel_IOFactory;
use PHPExcel;

class User extends BaseController
{
	
	// 用户跟进记录
	public function follow()
	{
		$userid = input('userid/d');
		$user = UserModel::findOrEmpty($userid);
		$followlist = UserFollowModel::where('userid',$userid)->order('id','desc')->limit(100)->select();
		return view('user/follow',[
			'user'			=> $user,
			'followlist'	=> $followlist
		]);
	}
	
	public function editFollow()
	{
		$userid = input('userid/d', 0);
		$user = UserModel::findOrEmpty($userid);
		if ($user->isEmpty()){
			exit(json_encode(array(
				'code' 	=> 1,
				'msg'	=> "用户信息不存在。"
			)));
		}
		$worker = $this->access_worker;
		$broker = BrokerModel::where('workerid','=',$worker['id'])->findOrEmpty($user->brokerid);
		if ($broker->isEmpty()){
			exit(json_encode(array(
				'code' 	=> 1,
				'msg'	=> "你无权限上报该用户跟进记录。"
			)));
		}
		UserFollowModel::create([
			'userid'		=> $userid,
			'ftype'			=> input('ftype/s', ""),
			'remark'		=> input('remark/s', ""),
			'createtime'	=> time()
		]);
		$followstatus = input('followstatus/d', 1);
		$user->save([
			'followstatus' => $followstatus
		]);
		exit(json_encode(array(
			'code' 	=> 0
		)));
	}
	
		
	// 用户授权
	public function authsList()
	{
		$userid = input('userid/d');
		return view('user/authslist',[
			'userid'	=> $userid
		]);
	}
	
	public function listAuths()
	{
		$userid = input('userid/d');
		$list = UserAuthsModel::where('userid',$userid)->order('id','asc')->append(['identitytype_text'])->select();
		$count = UserAuthsModel::where('userid',$userid)->count();
		if ($count==0){
			exit(json_encode(array(
				'code' 	=> 1,
				'msg'	=> "未查询到数据"
			)));
		}
		exit(json_encode(array(
			'code' 	=> 0,
			'msg'	=> "",
			'count' => $count,
			'data'  => $list
		)));
	}
	
	public function delAuths()
	{
		$id = input('id/d');
		$auths = UserAuthsModel::find($id);
		if ($auths->identitytype == 'mobile'){
			exit(json_encode(array(
				'code' 	=> 1,
				'msg'	=> "手机号授权方式不允许删除"
			)));
		}
		$result = $auths->delete();
		if ($result){
			exit(json_encode(array(
				'code' 	=> 0
			)));
		}
		exit(json_encode(array(
			'code' 	=> 1,
			'msg'	=> "删除失败，请稍后重试"
		)));
	}
	
	// 用户
	public function userList()
	{
		$workerid = $this->access_worker['id'];
		$groupslist = UserGroupsModel::order(['isdefault'=>'desc','id'=>'asc'])->select();
		$agentlist = AgentModel::with('broker')->where('workerid', '=', $workerid)->order(['id'=>'desc'])->select();
		return view('user/userlist',[
			'groupslist'	=> $groupslist,
			'agentlist'		=> $agentlist
		]);
	}

	
	public function fieldUser()
	{
		$workerid = $this->access_worker['id'];
		$id = input('id/d',0); 
		$user = UserModel::where('workerid', '=', $workerid)->findOrEmpty($id);
		if ($user->isEmpty()){
			exit(json_encode(array(
				'code' 	=> 1,
				'msg'	=> "信息不存在"
			)));
		}else{
			$user->save([
				input('field/s')  => input('value')
			]);
		}
		exit(json_encode(array(
			'code' 	=> 0
		)));
	}
	
	public function listUser()
	{
		$workerid = $this->access_worker['id'];
		$limit = input('limit');
		$page = input('page');
		$map = array();
		$brokeridarr = BrokerModel::where('workerid','=',$workerid)->column('id');
		$map[] = ['brokerid', 'in', $brokeridarr];
		$map[] = ['brokerid', '<>', 0];
		$keywords = input('keywords/s');
		if (!empty($keywords)){
			$map[] =['nickname|realname', 'like', '%'.$keywords.'%', 'or'];
		}
		$agentbrokerarr = explode(",", input('agentbroker/s'));
		$agentid = isset($agentbrokerarr[0]) ? $agentbrokerarr[0] : 0;
		if (!empty($agentid)){
			$brokeridarr = BrokerModel::where('agentid','=',$agentid)->column('id');
			$map[] = ['brokerid', 'in', $brokeridarr];
		}
		$brokerid = isset($agentbrokerarr[1]) ? $agentbrokerarr[1] : 0;
		if (!empty($brokerid)){
			$map[] = ['brokerid', '=', $brokerid];
		}
		$status = input('status/d');
		if (!empty($status)){
			$map[] = ['status', '=', $status];
		}
		$list = UserModel::with(['userGroups','broker'=>['agent','worker']])->where($map)->order('id','desc')->limit($limit)->page($page)->append(['status_text','isvip_text','authstatus_text','followstatus_text'])->select();
		$count = UserModel::where($map)->count();
		if ($count==0){
			exit(json_encode(array(
				'code' 	=> 1,
				'msg'	=> "未查询到数据"
			)));
		}
		exit(json_encode(array(
			'code' 	=> 0,
			'msg'	=> "",
			'count' => $count,
			'data'  => $list
		)));
	}
	
	
	public function exportUser()
	{
		$workerid = $this->access_worker['id'];
		$map = array();
		$brokeridarr = BrokerModel::where('workerid','=',$workerid)->column('id');
		$map[] = ['brokerid', 'in', $brokeridarr];
		$map[] = ['brokerid', '<>', 0];
		$keywords = input('keywords/s');
		if (!empty($keywords)){
			$map[] =['nickname|realname', 'like', '%'.$keywords.'%', 'or'];
		}
		$agentbrokerarr = explode(",", input('agentbroker/s'));
		$agentid = isset($agentbrokerarr[0]) ? $agentbrokerarr[0] : 0;
		if (!empty($agentid)){
			$brokeridarr = BrokerModel::where('agentid','=',$agentid)->column('id');
			$map[] = ['brokerid', 'in', $brokeridarr];
		}
		$brokerid = isset($agentbrokerarr[1]) ? $agentbrokerarr[1] : 0;
		if (!empty($brokerid)){
			$map[] = ['brokerid', '=', $brokerid];
		}
		$status = input('status/d');
		if (!empty($status)){
			$map[] = ['status', '=', $status];
		}
		$authstatus = input('authstatus/d');
		if (!empty($authstatus)){
			$map[] = ['authstatus', '=', $authstatus];
		}
		$followstatus = input('followstatus/d');
		if (!empty($followstatus)){
			$map[] = ['followstatus', '=', $followstatus];
		}
		$xlsData = UserModel::with(['userGroups','broker'=>['agent','worker']])->where($map)->order('id','desc')->select()->append(['status_text','isvip_text','authstatus_text','followstatus_text'])->toArray();
		$xlsCell = array(
			array('id','表ID'),
			array('nickname','昵称'),
			array('realname','姓名'),
			array('mobile','手机号'),
			array('integral','可用积分'),
			array('inttotal','累计积分'),
			array('status_text','状态'),
			array('isvip_text','是否VIP'),
			array('authstatus_text','是否实名认证'),
			array('idcard','身份证号'),
			array('gender','性别',array(1=>'男',2=>'女')),
			array('birthday','出生日期'),
			array('address','现居住地'),
			array('education','学历'),
			array('bankcard.openbank','开户行'),
			array('bankcard.account','账户名'),
			array('bankcard.number','账户号'),
			array('followstatus_text','跟进状态'),
			array('userGroups.title','用户组'),
			array('broker.agent.title','代理门店'),
			array('broker.title','职业顾问'),
			array('createtime','注册时间'),
		);
		export_excel("系统用户",$xlsCell,$xlsData);
	}
	
	public function delUser()
	{
		$workerid = $this->access_worker['id'];
		$brokeridarr = BrokerModel::where('workerid','=',$workerid)->column('id');
		$idarr = input('idarr/a');
		UserModel::whereIn('brokerid',$brokeridarr)->where('brokerid','<>', 0)->whereIn('id',$idarr)->delete();
		exit(json_encode(array(
			'code' 	=> 0,
			'msg'	=> ""
		)));
	}
	
	public function editUser()
	{
		$id = input('id/d');
		$mobile = input('mobile/s');
		$vdata = array(
			'id'		=> $id,
			'mobile'    => $mobile
		);
		try {
			validate(UserValidate::class)->check($vdata);
		} catch (ValidateException $e) {
			exit(json_encode(array(
				'code' 	=> 1,
				'msg'	=> $e->getError()
			)));
		}
		$agentbrokerarr = explode(",", input('agentbroker/s'));
		$brokerid = isset($agentbrokerarr[1]) ? $agentbrokerarr[1] : 0;
		$data = array(
			'groupsid'			=> input('groupsid/d', 0),
			'brokerid'			=> $brokerid,
			'nickname'			=> input('nickname/s', ""),
			'avatar'			=> input('avatar/s', ""),
			'realname'			=> input('realname/s', ""),
			'mobile'			=> $mobile,
			'status'			=> input('status/d', 1),
			'isvip'				=> input('isvip/d', 1),
			'authstatus'		=> input('authstatus/d', 1),
			'authremark'		=> input('authremark/s', ""),
			'idcardzpic'		=> input('idcardzpic/s', ""),
			'idcardfpic'		=> input('idcardfpic/s', ""),
			'idcard'			=> input('idcard/s', ""),
			'gender'			=> input('gender/d', 1),
			'birthday'			=> input('birthday/s', ""),
			'address'			=> input('address/s', ""),
			'education'			=> input('education/s', ""),
			'jobintention'		=> input('jobintention/s', ""),
			'workexperience'	=> input('workexperience/s', ""),
			'eduexperience'		=> input('eduexperience/s', ""),
			'followstatus'		=> input('followstatus/d', 1),
			'bankcard'			=> input('bankcard/a', array()),
		);
		$password = input('password/s');
		if (empty($id)){
			$data['integral'] = 0;
			$data['inttotal'] = 0;
			$data['createtime'] = time();
			$user = UserModel::create($data);
			$auths = UserAuthsModel::create([
				'userid'		=> $user->id,
				'identitytype'	=> "mobile",
				'identifier'	=> $mobile,
				'password'		=> empty($password) ? md5("123456789") : md5($password),
				'logintime'		=> time(),
				'loginip'		=> $_SERVER['SERVER_ADDR'],
				'wxampcode'		=> ""
			]);
		}else{
			$data['id'] = $id;
			$user = UserModel::update($data);
			$adata = ['identifier'=>$mobile];
			if (!empty($password)){
				$adata['password'] =  md5($password);
			}
			UserAuthsModel::update($adata, ['userid'=>$id,'identitytype'=>'mobile']);
		}
		exit(json_encode(array(
			'code' 	=> 0
		)));
	}
	


}