<?php
namespace app\worker\controller;

use app\worker\BaseController;
use app\common\model\Worker as WorkerModel;
use app\common\model\Agent as AgentModel;
use app\common\model\Broker as BrokerModel;
use app\common\model\User as UserModel;

use app\common\validate\Agent as AgentValidate;
use think\exception\ValidateException;

use think\facade\Session;
use think\facade\Db;
use think\facade\Request;

class Agent extends BaseController
{
	
	public function agentList()
	{
		return view('agent/agentlist');
	}
	
	public function agentForm()
	{
		$workerid = $this->access_worker['id'];
		$id = input('id/d, 0');
		$agent = AgentModel::where('workerid','=',$workerid)->findOrEmpty($id);
		return view('agent/agentform',[
			'agent'		=> $agent,
			'worker'	=> $this->access_worker
		]);
	}
	
	public function editAgent()
	{
		$workerid = $this->access_worker['id'];
		$id = input('id/d');
		$vdata = array(
			'id'			=> $id,
			'loginname'		=> input('loginname/s', ""),
			'idnumber'		=> input('idnumber/s', "")
		);
		try {
			validate(AgentValidate::class)->check($vdata);
		} catch (ValidateException $e) {
			exit(json_encode(array(
				'code' 	=> 1,
				'msg'	=> $e->getError()
			)));
		}
		$muser = UserModel::where(['mobile'=>input('musermobile/s', '')])->findOrEmpty();
		if ($muser->isEmpty()){
			exit(json_encode(array(
				'code' 	=> 1,
				'msg'	=> "关联的用户不存在。"
			)));
		}
		$data = [
			'userid'		=> $muser->id,
			'workerid'		=> $workerid,
			'loginname'  	=> input('loginname/s', ""),
			'idnumber'  	=> input('idnumber/s', ""),
			'title'			=> input('title/s', ""),
			'tilpic'		=> input('tilpic/s', ""),
			'picall'		=> input('picall/a', array()),
			'realname'  	=> input('realname/s', ""),
			'mobile'    	=> input('mobile/s', ""),
			'telephone'		=> input('telephone/s', ""),
			'latitude'		=> input('latitude/f', 0.00),
			'longitude'		=> input('longitude/f', 0.00),
			'province'		=> input('province/s', ""),
			'city'			=> input('city/s', ""),
			'district'		=> input('district/s', ""),
			'address'		=> input('address/s', ""),
			'details'		=> input('details/s', ""),
			'priority'		=> input('priority/d', 0),
			'remark'		=> input('remark/s', ""),
			'status'		=> input('status/d', 0)
		];
		$password = input('password/s', "");
		if (empty($id)){
			$data['password'] = empty($password) ? md5("123456789") : md5($password);
			$data['createtime'] = time();
			$agent = AgentModel::create($data);
		}else{
			if (!empty($password)){
				$data['password'] = md5($password);
			}
			$agent = AgentModel::find($id);
			$agent->save($data);
		}
		BrokerModel::update([
			'workerid' => $workerid
		],['agentid'=>$agent->id]);
		exit(json_encode(array(
			'code' 	=> 0
		)));
	}

	public function agent_join()
    {
        if(Request::isAjax()){
            $data['realname'] = trim(input('post.realname/s'));
            $data['mobile'] = trim(input('post.mobile/s'));
            $data['address'] = trim(input('post.province/s')).trim(input('post.city/s')).trim(input('post.district/s')).trim(input('post.address/s'));
            $data['idcard'] = trim(input('post.idcard/s'));
            $data['recommender'] = trim(input('post.recommender/s'));
            $data['createtime'] = time();
            $data['status'] = (int)1;

            $res = Db::name('agent_form')->insert($data);

            if($res){
                $rtn['code'] = 0;
                $rtn['msg'] = '您的申请已提交，请静心等待';
            }else{
                $rtn['code'] = 1;
                $rtn['msg'] = '对不起，您的申请失败，请重新申请';
            }
            return  $rtn;
        }else{
            return view('agent/agent_join');
        }

    }
	
	public function fieldAgent()
	{
		$workerid = $this->access_worker['id'];
		$id = input('id/d',0); 
		$agent = AgentModel::where('workerid','=',$workerid)->findOrEmpty($id);
		if ($agent->isEmpty()){
			exit(json_encode(array(
				'code' 	=> 1,
				'msg'	=> "信息不存在"
			)));
		}else{
			$agent->save([
				input('field/s')  => input('value')
			]);
		}
		exit(json_encode(array(
			'code' 	=> 0
		)));
	}
	
	public function delAgent()
	{
		$workerid = $this->access_worker['id'];
		$password = input('password');
		if ( $this->access_worker['password'] !== md5($password) ){
			exit(json_encode(array(
				'code' 	=> 1,
				'msg'	=> "操作密码验证失败"
			)));
		}
		$idarr = input('idarr/a');
		$agent = AgentModel::where('workerid','=',$workerid)->whereIn('id',$idarr)->select();
		$result = $agent->delete();
		if ($result){
			exit(json_encode(array(
				'code' 	=> 0,
				'msg'	=> ""
			)));
		}
		exit(json_encode(array(
			'code' 	=> 1,
			'msg'	=> "删除失败，请稍后重试"
		)));
	}
	
	public function listAgent()
	{
		$workerid = $this->access_worker['id'];
		$limit = input('limit');
		$page = input('page');
		$map = array();
		$map[] = ['workerid', '=', $workerid];
		$keywords = input('keywords/s');
		if (!empty($keywords)){
			$map[] =['idnumber', 'like', '%'.$keywords.'%'];
		}
		$status = input('status/d');
		if (!empty($status)){
			$map[] = ['status', '=', $status];
		}
		$list = AgentModel::with(['muser'])->where($map)->order(['priority'=>'DESC','id'=>'DESC'])->limit($limit)->page($page)->append(['status_text'])->select();
		$count = AgentModel::where($map)->count();
		if ($count==0){
			exit(json_encode(array(
				'code' 	=> 1,
				'msg'	=> "未查询到数据"
			)));
		}
		exit(json_encode(array(
			'code' 	=> 0,
			'msg'	=> "",
			'count' => $count,
			'data'  => $list
		)));
	}
	

}
