<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/20
 * Time: 10:52
 */

namespace app\api\controller;

use app\common\model\Catalogs as CatalogsModel;
use app\common\model\Citys as CitysModel;
use app\common\model\Guide as GuideModel;
use app\common\model\Project as ProjectModel;
use app\common\model\UserCollection;
use app\common\model\UserCollection as UserCollectionModel;
use app\common\model\Tags as TagsModel;
use app\common\model\User as UserModel;
use app\common\model\Reservations as ReservationsModel;
use think\Validate;

class Project extends Base
{

    /**
     * 搜索分页列表
     * @url /api/project/index
     * @param p int 当前页
     * @param page int 每页条数
     * @param type int 类型
     * @param catalog_id int 分类
     * @param city int 城市
     * @param tags array 标签
     * @return json
     */
    public function index()
    {
        //当前页
        $p = input('?post.p') ? input('post.p') : 1;
        //一页显示几条
        $page = input('?post.page') ? input('post.page') : 8;

        $map = [];
        //根据标题
        if (input('?post.title')) $map['title'] = ['like', '%' . input('post.title') . '%'];
        //根据项目
        if (input('?post.type')) $map['type'] = input('post.type/d');
        //根据分类
        if (input('?post.catalog_id')) $map['catalog_id'] = input('post.catalog_id');
        //根据地区分类/国内国外
        if (input('post.region_type')) {
            $map['region_type'] = input('post.region_type');
        } else {
            if (input('?post.city')) $map['city'] = input('post.city');
        }
        //根据标签划分
        if (input('?post.tags')) {
            $tags     = [];
            $tagArray = json_decode(input('post.tags'), true);
            if ($tagArray) {
                if (count($tagArray) == 1) {

                    $map['tags'] = ['like', "%|{$tagArray[0]}|%"];

                } else {
                    foreach ($tagArray as $v) {
                        $tags[] = ['like', "%|{$v}|%"];
                    }
                    $map['tags'] = $tags;
                }

//                halt($map);
            }
        }
        $project = ProjectModel::all(function ($query) use ($map, $p, $page) {
            $query->where($map)
                ->order('sort', 'desc')
                ->page($p, $page);
        });

        $project = $project ? collection($project)->visible(['id', 'title', 'poster', 'sign_limits', 'night_num', 'tags', 'price', 'vip_price', 'type', 'location', 'latitude', 'longitude'])->append(['sign_endtime_str'])->toArray() : [];
        if (!$project) return ['code' => 1, 'msg' => '没有更多'];
        return ['code' => 0, 'msg' => 'success', 'data' => $project];
    }

    /**
     * 首页获取最新活动最新活动/爆款专区/酒店预订/美行攻略
     * @url /api/Project/homeAll
     * return json
     */
    public function homeAll()
    {
        //最新活动-只显示3个
        $newProjects = ProjectModel::all(function ($query) {
            $query->where('type', 1)
                ->order('sort', 'desc')
                ->order('id', 'desc')
                ->limit(6);
        });
        $newProjects = $newProjects ? collection($newProjects)->visible(['id', 'title', 'poster', 'night_num', 'price', 'vip_price'])->toArray() : [];

        //爆款专区-只显示3个
        $heatProjects = ProjectModel::all(function ($query) {
            $query->where('type', 2)
                ->where('heat', 'neq', 0)
                ->order('sort', 'desc')
                ->order('id', 'desc')
                ->limit(6);
        });
        $heatProjects = $heatProjects ? collection($heatProjects)->visible(['id', 'title', 'poster', 'night_num', 'price', 'vip_price'])->toArray() : [];

        // 酒店预订
        $businessProjects = ProjectModel::all(function ($query) {
            $query->where('catalog_id', 5)
                ->where('type', 2)
                ->order('sort', 'desc')
                ->order('id', 'desc')
                ->limit(8);
        });
        $businessProjects = $businessProjects ? collection($businessProjects)->visible(['id', 'title', 'poster', 'night_num', 'price', 'vip_price'])->toArray() : [];

        //美行攻略
        $guides = GuideModel::all(function ($query) {
            $query->order('id', 'desc')
                ->limit(6);
        });
        $guides = $guides ? collection($guides)->toArray() : [];

        $data = compact('newProjects', 'heatProjects', 'businessProjects', 'guides');
        if (!$data) return ['code' => 1, 'msg' => '没有更多'];
        return ['code' => 0, 'msg' => 'success', 'data' => $data];
    }

    /**
     * 最新活动
     * @url /api/project/newProjects
     * @param int $p 默认1 表示第几页
     * @param int $page 默认8 每页显示条数
     * @param int $type 1是最新活动  爆款专区
     * @return json
     */
    public function newProjects($p = 1, $page = 8)
    {
        $type = input('post.type') ? input('post.type') : 1;
        if ($type == 1) {
            $newProjects = ProjectModel::all(function ($query) use ($p, $page) {
                $query->where('type', 1)
                    ->order('sort', 'desc')
                    ->order('id', 'desc')
                    ->page($p, $page);
            });
        } elseif ($type == 2) {
            $newProjects = ProjectModel::all(function ($query) use ($p, $page) {
                $query->where('type', 2)
                    ->where('heat', 'neq', 0)
                    ->order('sort', 'desc')
                    ->order('id', 'desc')
                    ->page($p, $page);
            });
        }

        $newProjects = $newProjects ? collection($newProjects)->visible(['id', 'title', 'poster', 'sign_limits', 'night_num', 'tags', 'price', 'vip_price', 'type', 'location', 'latitude', 'longitude'])->append(['sign_endtime_str'])->toArray() : [];
        if (!$newProjects) return ['code' => 1, 'msg' => '没有更多'];

        return ['code' => 0, 'msg' => 'success', 'data' => $newProjects];
    }

    /**
     * 爆款专区
     * @url /api/project/heatProjects
     * @param int $p 默认1 表示第几页
     * @param int $page 默认8 每页显示条数
     * @return json
     */
//    public function heatProjects($p = 1, $page = 8)
//    {
//        $heatProjects = ProjectModel::all(function ($query) use ($p, $page) {
//            $query->where('type', 1)
//                ->where('heat', 'neq', 0)
//                ->order('heat', 'desc')
//                ->order('id', 'desc')
//                ->page($p, $page);
//        });
//        $heatProjects = $heatProjects ? collection($heatProjects)->visible(['id', 'title', 'poster', 'night_num', 'price'])->toArray() : [];
//        if (!$heatProjects) return ['code' => 1, 'msg' => '没有更多'];
//        return ['code' => 0, 'msg' => 'success', 'data' => $heatProjects];
//    }

    /**
     * 酒店预订
     * @url /api/project/businessProjects
     * @param int $p 默认1 表示第几页
     * @param int $page 默认8 每页显示条数
     * @return json
     */
    public function businessProjects($p = 1, $page = 8)
    {
        $businessProjects = ProjectModel::all(function ($query) use ($p, $page) {
            $query->where('catalog_id', 5)
                ->where('type', 2)
                ->order('sort', 'desc')
                ->order('id', 'desc')
                ->page($p, $page);
        });
        $businessProjects = $businessProjects ? collection($businessProjects)->visible(['id', 'title', 'poster', 'night_num', 'price'])->toArray() : [];
        if (!$businessProjects) return ['code' => 1, 'msg' => '没有更多'];
        return ['code' => 0, 'msg' => 'success', 'data' => $businessProjects];
    }

    /**
     * 美行攻略
     * @url /api/project/guides
     * @param int $p 默认1 表示第几页
     * @param int $page 默认8 每页显示条数
     * @return json
     */
    public function guides($p = 1, $page = 8)
    {
        $guides = GuideModel::all(function ($query) use ($p, $page) {
            $query->order('id', 'desc')
                ->page($p, $page);
        });
        $guides = $guides ? collection($guides)->toArray() : [];
        if (!$guides) return ['code' => 1, 'msg' => '没有更多'];
        return ['code' => 0, 'msg' => 'success', 'data' => $guides];
    }

    /**
     * 收藏/取消收藏
     * @url /api/project/collect
     * @param int pid 活动/商家id
     * @return json
     */
    public function collect($pid = 0)
    {
        if (empty($pid)) return ['code' => 1, 'msg' => '缺少参数pid'];
        $uid     = $this->userinfo[0];
        $data    = UserCollectionModel::get(['uid' => $uid, 'pid' => $pid]);
        $project = ProjectModel::get($pid);
        if (!$project) return ['code' => 1, 'msg' => '活动或该商家不存在'];
        if ($data) {
            //已经收藏->取消收藏
            if ($data->delete(true)) {
                $project->collect_num--;
                $project->save();
                return ['code' => 0, 'msg' => '取消收藏成功!', 'collect' => 'remove'];
            } else {
                return ['code' => 1, 'msg' => '取消收藏失败,请重试!'];
            }
        } else {
            //未收藏,收藏
            $result = UserCollectionModel::create([
                'pid' => $pid,
                'uid' => $uid
            ]);
            if ($result) {
                $project->collect_num++;
                $project->save();
                return ['code' => 0, 'msg' => '收藏成功!', 'collect' => 'add'];
            } else {
                return ['code' => 1, 'msg' => '收藏失败,请重试!'];
            }
        }
    }

    /**
     * 搜索条件列表
     * @url api/Project/searchCondition
     * @return json
     */
    public function searchCondition()
    {
        $data['type']       = [['id' => 1, 'name' => '活动'], ['id' => 2, 'name' => '商家']];
        $data['catalog_id'] = collection(CatalogsModel::order('sort', 'desc')->select())->visible(['id', 'name'])->toArray();
        $data['city']       = collection(CitysModel::order('sort', 'desc')->select())->visible(['id', 'name'])->toArray();
        $data['tags']       = collection(TagsModel::order('sort', 'desc')->select())->visible(['id', 'name'])->toArray();
        if (!$data) return ['code' => 1, 'msg' => '没有更多'];
        array_unshift($data['type'], ['id' => '0', 'name' => "全部项目"]);
        array_unshift($data['catalog_id'], ['id' => '0', 'name' => "全部分类"]);
        array_unshift($data['city'], ['id' => '2', 'name' => "国外"]);
        array_unshift($data['city'], ['id' => '1', 'name' => "国内"]);
        array_unshift($data['city'], ['id' => '0', 'name' => "全部地区"]);
        return ['code' => 0, 'msg' => 'success', 'data' => $data];
    }

    /**
     * 活动/商家详情
     * @url api/Project/detail
     * @param id int 活动id
     * @return json
     */
    public function detail()
    {
        if (!input('post.id')) {
            return ['code' => 1, 'msg' => '缺少参数ID'];
        }
        $project = ProjectModel::get(input('post.id'));
        if (!$project) {
            return ['code' => 1, 'msg' => '该活动或商家不存在!'];
        }
        // 是否过期
        $endTime = strtotime($project['sign_endtime']);
        // 正常
        $project['status']      = 0;
        $project['status_text'] = '立即报名';
        if (strtotime($project['sign_endtime']) < time()) {
            // 已过期
            $project['status']      = 1;
            $project['status_text'] = '预约下次';
        } else {
            if (intval($project['sign_limits']) <= intval($project['sign_num'])) {
                // 已售罄
                $project['status']      = 2;
                $project['status_text'] = '已售罄';
            }
        }
        // 是否收藏了本活动
        $project['is_collect'] = UserCollectionModel::get(['uid' => $this->userinfo[0], 'pid' => input('post.id')]) ? true : false;

        return ['code' => 0, 'msg' => 'success', 'data' => $project];
    }

    /**
     * 活动用户信息
     * @param id int 要报名的活动id
     * @return json
     */
    public function getEnrollInfo()
    {
        if (!input('post.id')) {
            return ['code' => 1, 'msg' => '缺少参数ID'];
        }
        $project = ProjectModel::get(input('post.id'));
        if (!$project) {
            return ['code' => 1, 'msg' => '商家不存在!'];
        }
        $user = UserModel::get($this->userinfo[0]);
        $data = [
            'project_id' => $project->id,
            'title'      => $project->title,
            'poster'     => $project->poster,
            'vip_price'  => $project->vip_price,
            'price'      => $project->price,
            'nickname'   => $user->nickname,
            'phone'      => $user->phone,
            'is_vip'     => $user->is_vip
        ];
        return ['code' => 0, 'msg' => 'success', 'data' => $data];
    }

    /**
     * 预约下一次
     * @url /api/Project/reservations
     * @param nickname
     * @param phone
     * @param pid
     * @param expectation_time
     * @return json
     */
    public function reservations()
    {
        $validate = Validate::make([
            'nickname'         => 'require',
            'phone'            => 'require',
            'pid'              => 'require',
            'expectation_time' => 'require',
        ]);
        $res      = $validate->check(input('post.'));
        if (!$res) return ['code' => 1, 'msg' => $validate->getError()];
        if (!ProjectModel::get(input('post.pid'))) {
            return ['code' => 1, 'msg' => '该活动不存在'];
        }
        ReservationsModel::create([
            'nickname'         => input('post.nickname'),
            'phone'            => input('post.phone'),
            'pid'              => input('post.pid'),
            'expectation_time' => input('post.expectation_time'),
            'remark'           => input('post.remark'),
            'uid'              => $this->userinfo[0]
        ]);
        return ['code' => 0, 'msg' => '预约成功'];
    }
}