<?php

namespace app\model;


use think\Db;

class GHouses extends BaseModel
{
    protected $table = 'g_houses';

    /**
     * 通过id获取商铺详情
     *
     * @param $id
     * @return array|false|\PDOStatement|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getHouseById($id) {
        $fields = 'a.*,b.fee_rule,internal_item_advantage,external_item_advantage,tiny_brochure_url,auditorium,traffic,
                   enter_num,do_business_date,start_business_date,singn_rule,landlord_phone';
        $select_data = $this->alias('a')->field($fields)
            ->join('g_houses_ext b','a.id = b.house_id', 'left')
            ->where('a.id',$id)
            ->find();
        $data = $select_data->getData();
        $img = new GHousesImgs();
        $img_data = $img->field('id,img_type,img_name')
            ->where('img_status = 0 AND house_id = '.$id)
            ->select();
        $area = explode('##',$data['code']);
        $data['province_code'] = $area['0'];
        $data['city_code'] = $area['1'];
        $data['disc_code'] = $area['2'];
        foreach ($img_data as $k=>$v) {
            switch ($v->img_type) {
                case 1 :
                    $data['cover'] = $v;break;
                case  2 :
                    $data['slide_show'][$k] = $v;break;
                default :
                    $data['plan'][$k] = $v;
            }
        }
        return $data;
    }

    /**
     * 楼盘列表
     *
     * @param int $pageNo
     * @param int $pageSize
     * @param string $order_
     * @param string $field
     * @param string $params
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getHouseList($pageNo = 1, $pageSize = 15, $order_ = 'id desc', $field = '', $params = '') {
        $data = $this->field($field)
            ->where($params)
            ->order($order_)
            ->limit($pageSize)
            ->page($pageNo)
            ->select();
        $house_id = array();
        foreach ($data as $k => $v) {
            $house_id[$k] = $v['id'];
            $v->create_time = date('Y-m-d',strtotime($v->create_time));
        }

        $result = array();
        if (empty($house_id)) {
            $result = $data;
        } else {
            /*案场权限人和盘方*/
            $house_agents = Db::table('g_houses_to_agents')->alias('a')
                ->field('a.houses_id,b.id,b.name,b.phone,a.type')
                ->join('a_agents b', 'a.agents_id=b.id','left')
                ->where('a.houses_id','IN', implode(',',$house_id))
                ->select();

            foreach ($data as $k=>$v) {
                $result[$k] = $v->toArray();
                $dish_name = '';
                $result[$k]['dish_name'] = '';
                foreach ($house_agents as $k2 => $v2) {
                    if ($v->id == $v2['houses_id']) {
                        if ($v2['type'] == 2) {
                            $dish_name .=  $v2['name'].',';
                            $result[$k]['dish_name'] = rtrim($dish_name,',');
                        } else {
                            $result[$k]['dish_name'] = '';
                        }
                    }
                }
            }
        }

        return $result;
    }

    /**
     * 查询属于盘方的商铺列表
     *
     * @param int $pageNo
     * @param int $pageSize
     * @param string $order_
     * @param string $field
     * @param string $params
     * @return array|false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getHouseListDish($pageNo = 1, $pageSize = 15, $order_ = 'id desc', $field = '', $params = '') {
        $data = $this->field($field)->alias('a')
            ->join('g_houses_to_agents b', 'a.id=b.houses_id','left')
            ->join('a_agents c','b.agents_id=c.id','left')
            ->where($params)
            ->order($order_)
            ->limit($pageSize)
            ->page($pageNo)
            ->select();
        $house_id = array();
        foreach ($data as $k => $v) {
            $house_id[$k] = $v['id'];
        }

        $result = array();
        if (empty($house_id)) {
            $result = $data;
        } else {
            /*案场权限人和盘方*/
            $house_agents = Db::table('g_houses_to_agents')->alias('a')
                ->field('a.houses_id,b.id,b.name,b.phone,a.type')
                ->join('a_agents b', 'a.agents_id=b.id','left')
                ->where('a.houses_id','IN', implode(',',$house_id))
                ->select();

            foreach ($data as $k=>$v) {
                $result[$k] = $v->toArray();
                $dish_name = '';
                $result[$k]['dish_name'] = '';
                foreach ($house_agents as $k2 => $v2) {
                    if ($v->id == $v2['houses_id']) {
                        if ($v2['type'] == 2) {
                            $dish_name .=  $v2['name'].',';
                            $result[$k]['dish_name'] = rtrim($dish_name,',');
                        } else {
                            $result[$k]['dish_name'] = '';
                        }
                    }
                }
            }
        }
        return $result;
    }

    /**
     * 查询属于盘方的商铺列表总记录数
     *
     * @param string $params
     * @return int|string
     */
    public function getHouseListDishTotal($params = '') {
        $data = $this->alias('a')
            ->join('g_houses_to_agents b', 'a.id=b.houses_id','left')
            ->join('a_agents c','b.agents_id=c.id','left')
            ->where($params)
            ->count();
        return $data;
    }

    /**
     * 添加和编辑商铺
     *
     * @param $params
     * @return mixed
     * @throws \Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add($params) {
        $date = date('Y-m-d H:i:s');

        if ($params['id']) {
            $params['update_time'] = $date;
        } else {
            $params['create_time'] = $date;
            $params['update_time'] = $date;
        }

        $case = new ACase();
        $case_id = $case->addCase($params['phone']);
        $params['case_id'] = $case_id;

        $regions = new Regions();
        $province = $regions->getRegions($params['province_code']);
        $city = $regions->getRegions($params['city_code']);
        $disc = $regions->getRegions($params['disc_code']);
        $params['province'] = $province['name'];
        $params['city'] = $city['name'];
        $params['disc'] = $disc['name'];
        $params['code'] = $params['province_code'].'##'.$params['city_code'].'##'.$params['disc_code'];

        //新增或编辑
        if ($params['id'] == '') {
            $this->allowField(true)->save($params);
            $house_id = $this->id;
        } else {
            $this->allowField(true)->isUpdate(true)->save($params, ['id' => $params['id']]);
            $house_id = $this->id;
        }
        $params['house_id'] = $house_id;

        if ($params['start_business_date']) {
            $params['start_business_date'] = date('Y-m-d H:i:s' , strtotime($params['start_business_date']));
        }

        $houses_ext = new GHousesExt();
        //新增或编辑根据id
        if ($params['id'] == '') {
            $houses_ext->allowField(true)->save($params);
        } else {
            $house_ext_data = $houses_ext->field('id')->where('house_id',$params['id'])->find();
            $houses_ext->allowField(true)->isUpdate(true)->save($params, ['id' => $house_ext_data['id']]);
        }

        /***保存图片 hujun 2018.1.19 start***/
        $house_img = new GHousesImgs();
        if ($params['id'] == '') {
            $house_img->add($params, $house_id);
        } else {
            $house_img->edit($params, $house_id);
        }
        /***保存图片 hujun 2018.1.19 end***/

        $agents = new GHousesToAgents();
        //权限人
        $agents->addAgents($params['agent_data'], $house_id,1);
        //盘方
        $agents->addAgents($params['agent_dish'], $house_id,2);
        //独家方
        $agents->addAgents($params['exclusive_ids'], $house_id,3);
        return $house_id;
    }

    /**
     * 商铺列表独家编辑
     *
     * @param $data
     * @param $house_id
     * @return bool
     * @throws \Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function exclusive($data, $house_id) {
        $this->startTrans();
        $result = $this->save([
            'is_exclusive_type' => $data['is_exclusive_type'],
            'update_time'       => date('Y-m-d H:i:s')
        ],['id'=>$house_id]);

        if ($result) {
            $ext = new GHousesExt();
            $update_data['agent_start_time'] = $data['agent_start_time'];
            $update_data['agent_end_time'] = $data['agent_end_time'];
            $ext_result = $ext->save($update_data,['house_id'=>$data['houses_id']]);

            $house_img = new GHousesImgs();
            $house_img->edit($data, $house_id);

            $agents = new GHousesToAgents();
            $agents->addAgents($data['exclusive_id'], $house_id,3);
        }

        if ($result == 1 || $ext_result == 1) {
            $this->commit();
            $return = true;
        } else {
            $this->rollback();
            $return = false;
        }
        return $return;
    }

    /**
     * 获取独家方信息
     *
     * @param $houses_id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getExclusive($houses_id) {
        $result = $this->field('id,is_exclusive_type')->where('id',$houses_id)->where('status','<>',3)->find();
        if ($result->id) {
            $house_ext = $this->table('g_houses_ext')->where('house_id',$houses_id)->field('agent_start_time,agent_end_time')->find();
            $agents = $this->table('g_houses_to_agents')->field('b.id,b.name,b.phone')->alias('a')
                ->join('a_agents b', 'a.agents_id=b.id','left')
                ->where('a.is_del','<>',1)
                ->where('b.status',0)->find();

            $img = $this->table('g_houses_imgs')
                ->field('img_name')
                ->where('house_id',$houses_id)
                ->where('img_status',0)->select();

            $return['id'] = $agents->id;
            $return['name'] = $agents['name'].'-'.$agents['phone'];
            $return['agent_start_time'] = $house_ext['agent_start_time'];
            $return['agent_end_time']   = $house_ext['agent_end_time'];
            $return['exclusive_img']    = $img;
            $return['is_exclusive_type'] = $result->is_exclusive_type;
        } else {
            $return = false;
        }
        return $return;
    }
}
