<?php

namespace app\model;

use think\Model;

class GHousesToAgents extends BaseModel
{
    protected $table = 'g_houses_to_agents';
    protected $date  = '';

    public function __construct()
    {
        $this->date = date('Y-m-d H:i:s');
    }

    /**
     * @param $agents_id
     * @param $houses_id
     * @param $type 案场权限人:0,盘方:1,独家:2
     * @return array|false
     * @throws \Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addAgents($agents_id, $houses_id, $type){
        $agent_arr   = array();
        $date        = date('Y-m-d H:i:s');
        $agents_id   = array_unique(explode(',',$agents_id));

        $where['type']      = $type;
        $where['houses_id'] = $houses_id;
        $where['is_del']    = 0;
        //为空全部伪删除
        if (empty($agents_id[0])) {
            $res = $this->where($where)->setField('is_del',1);
        } else {
            $houses_data = $this->where($where)->select();
            $key = 0;
            foreach ($houses_data as $k=>$v) {
                if (!in_array($v['agents_id'], $agents_id) && $type == $v['type']) {
                    $agent_arr[$key]['id'] = $v['id'];
                    $agent_arr[$key]['is_del'] = 1;
                    $agent_arr[$key]['update_time'] = $date;
                    $key++;
                }
            }

            foreach ($agents_id as $k=>$v) {
                $check = $this->where([
                    'houses_id' => $houses_id,
                    'agents_id' => $v,
                    'is_del'    => 0 ,
                    'type'      => $type
                ])->find();
                if ($check) {
                    continue;
                }
                $agent_arr[$key]['agents_id'] = $v;
                $agent_arr[$key]['houses_id'] = $houses_id;
                $agent_arr[$key]['type'] = $type;
                $agent_arr[$key]['create_time'] = $this->date;
                $agent_arr[$key]['update_time'] = $this->date;
                $key++;
            }
            $res = $this->saveAll($agent_arr);
        }

        return $res;
    }

    /**
     * 解除经纪人和楼盘关系
     *
     * @param $id
     * @return bool|false|int
     */
    public function del($id, $houses_id) {
        if ($id) {
            $res = $this->save(['is_del' => 1],['agents_id'=>$id,'houses_id'=>$houses_id]);
        } else {
            $res = false;
        }

        return $res;
    }

    public function getAgentsHousesList($pageNo = 1, $pageSize = 15, $order_ = 'id desc', $field = '', $params = '') {
        return $this->field($field)
            ->alias('a')
            ->join('a_agents b', 'a.agents_id = b.id','left')
            ->where($params)
            ->order($order_)
            ->limit($pageSize)
            ->page($pageNo)
            ->select();
    }
}
