<?php

namespace app\model;

use think\Db;
use think\Model;

class Users extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'u_users';

    public function selectUser($userId, $fields = 'id,user_phone')
    {
        $param["status"] = array( "eq", 0 );
        $data = $this->field($fields)
            ->where($param)
            ->find($userId);

        if (isset($data->user_pic)) {
            $data->user_pic = HEADERIMGURL.$data->user_pic;
        }
        return $data;
    }
    
    /**
     * 查询用户和经纪人
     * 
     * @param type $pageNo
     * @param type $pageSize
     * @param type $order_
     * @param type $fields
     * @param type $params
     * @return type
     */
    public function getUserAgent($pageNo = 1, $pageSize = 15, $order_ = 'a.id desc', $fields = '*', $params = '') {
        $result = $this->field($fields)          
                ->where($params)
                ->order($order_)
                ->limit($pageSize)
                ->page($pageNo)
                ->select();
        
        $agents = new Agents();
        foreach ($result as $k=>$v) {
            $data[$k] = $v->getData();
            $data[$k]['user_pic'] = CURRENT_URL.'static/head_portrait/'.$data[$k]['user_pic'];
            $agent_data = $agents->field('realname,phone')->where('id',$data[$k]['referrer_id'])->find();
            $data[$k]['realname'] = $agent_data['realname'];
            $data[$k]['phone']    = $agent_data['phone'];
        }
        return $data; 
    }

    /**
     * 获取查询用户和经纪人总数
     *
     * @param $params
     * @return mixed
     */
    public function getUserAgentTotal($params) {
        $result = $this->where($params)->count();
        return $result;
    }


    /**
     * 删除用户
     *
     * @param $id
     * @param int $status
     * @return array
     */
    public function delete_user($id, $status = 1) {
        $arr = array(
            "id" => $id,
            "status" => $status,
            "update_time" => date("Y-m-d H:i:s")
        );
        Db::startTrans();
        try {
            $id = $this->update($arr);
            Db::commit();
            return [ "code" => "200", "msg" => '删除成功', 'data'=>$id];
        } catch (\Exception $e) {
            Db::rollback();
            return [ "code" => "101", "msg" => "没有该用户", 'data'=>''];
        }
    }
}
