<?php

namespace app\admin\controller;

use app\common\controller\Api;
use think\Cache;
use think\Db;
use app\common\controller\Backend;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 预约列管理
 *
 * @icon fa fa-circle-o
 */
class Sun extends Backend
{

    /**
     * Sun模型对象
     * @var \app\admin\model\Sun
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Sun;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        $filter = input('filter');
        if ($filter == '{}' || $filter = null || $filter == '') {
            $time = strtotime(date('Y-m-d')) - 1;
            $map['sun.createtime'] = ['GT', $time];
        } else {
            $map = [];
        }
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage,则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['time', 'user', 'plane'])
                ->where($map)
                ->where($where)
                ->order('sun.createtime desc,plane.base_id,plane.id,time.id desc')
                ->paginate($limit);
            foreach ($list as $row) {

                $row->getRelation('time')->visible(['title']);
                $row->getRelation('user')->visible(['avatar', 'nickname']);
                $row->getRelation('plane')->visible(['title']);
                $row['base_title'] = Db::name('base')->where('id', Db::name('plane')->where('id', $row['plane_id'])->value('base_id'))->value('title');
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /*自定义批量修改*/
    public function updateing()
    {

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $Item = Cache::get('temp');
            Db::name('sun')->where('id', 'IN', $Item)->update(['status' => $params['status']]);
            Cache::clear();
            $this->success('操作成功');
        }
        return $this->view->fetch();
    }

    public function Cache()
    {
        $Ids = input('temp');
        Cache::set('temp', $Ids, 3600);
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    //查询未更改前数据
                    $User_id = Db::name('sun')->where('id', $ids)->value('user_id');

                    /*新增预约*/
                    if ($params['status'] == 3) {
                        if ($params['user_id'] == '') {
                            $this->error('请选择预约人');
                        }
                        if ($User_id != $params['user_id']) {
                            if ($User_id == '') {
                                //新增预约
                                $this->Ding($ids, $params['user_id']);
                            } else {
                                $this->Ding($ids, $params['user_id']);
                                $this->Kill($ids, Db::name('sun')->where('id', $ids)->value('user_id'));
                            }
                        }
                    }
                    /*可预约*/
                    if ($params['status'] == 1) {
                        if ($User_id != '') {
                            $params['user_id'] = '';
                            $this->Kill($ids, Db::name('sun')->where('id', $ids)->value('user_id'));
                        }
                    }
                    /*不可预约*/
                    if ($params['status'] == 2) {
                        if ($User_id != '') {
                            $params['user_id'] = '';
                            $this->Kill($ids, Db::name('sun')->where('id', $ids)->value('user_id'));
                        }
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /*新增预约单*/
    public function Ding($SunId, $UserID)
    {
        /*超过最大次数拦截*/
        $this->CountNum($UserID, $SunId);
        /*更改预约列表状态/新增预约单*/
        $this->YuYue($UserID, $SunId);
    }

    /*取消预约*/
    public function Kill($SunId, $UserId)
    {
        $IsKill = Db::name('sun')->where('user_id', $UserId)->where('id', $SunId)->find();
        if (empty($IsKill)) $this->error('预约不存在', 0);
        $kill = Db::name('yuyue')->where('sun_id', $IsKill['id'])->where('user_id', $UserId)->find();
        if ($kill['status'] != 0) $this->error('预约单已使用不可取消');
        /*取消预约限制拦截*/
//        $this->KillGroup($SunId);
        /*减少待扣除飞行时间*/
        $GoodsAfter = Db::name('goods_after')->where('plane_type_id', Db::name('plane')->where('id', $IsKill['plane_id'])->value('plane_type_id'))->where('user_id', $UserId)->find();
        if (empty($GoodsAfter)) $this->error('您还没有购买该产品', 0);
        Db::name('goods_after')->where('plane_type_id', Db::name('plane')->where('id', $IsKill['plane_id'])->value('plane_type_id'))->where('user_id', $UserId)->update(['AfterMinutes' => $GoodsAfter['AfterMinutes'] - 60]);
        Db::name('sun')->where('user_id', $UserId)->where('id', $SunId)->update(['user_id' => '', 'status' => 1]);
        Db::name('yuyue')->where('id', $kill['id'])->delete();
    }

    public function CountNum($UserId, $Id)
    {
        $createtime = Db::name('sun')->where(['id' => $Id])->value('createtime');
        //没明白为啥要用between
//        $map['sun_createtime'] = ['BETWEEN', [$createtime - 2, $createtime + 5]];

        $map['sun_createtime'] = $createtime;
        $map['status'] = ['NEQ', 2];
        $count = Db::name('yuyue')->where(['user_id' => $UserId])->where($map)->count();
        if ($count > 1) $this->error('超过最大可预约次数', 0);
    }


    public function YuYue($UserID, $ID)
    {
        if (Db::name('sun')->where('id', $ID)->value('status') == 3) $this->error('您选择的时间中含已被其他人预约的时间,请重新选择预约', 0);
        /*预约列表信息*/
        $Info = Db::name('sun')->where('id', $ID)->find();
        /*查询教练*/
        $TeacherId = Db::name('teacher_work')->where('plane_id', $Info['plane_id'])->where('time', strtotime(date('Y-m-d', Db::name('sun')->where('id', $ID)->value('createtime'))))->value('teacher_id');
        if (empty($TeacherId)) $this->error('该飞机类型暂无教练', 0);
        /*增加待扣除飞行时间*/
        $GoodsAfter = Db::name('goods_after')->where('plane_type_id', Db::name('plane')->where('id', $Info['plane_id'])->value('plane_type_id'))->where('user_id', $UserID)->find();
        if (empty($GoodsAfter)) $this->error('您还没有购买该产品', 0);
        Db::name('goods_after')->where('plane_type_id', Db::name('plane')->where('id', $Info['plane_id'])->value('plane_type_id'))->where('user_id', $UserID)->update(['AfterMinutes' => $GoodsAfter['AfterMinutes'] + 60]);
        /*更改预约列表状态*/
        Db::name('sun')->where('id', $ID)->update(['status' => 3, 'user_id' => $UserID, 'updatetime' => time()]);
        /*新增预约信息*/
        $Insert = [
            'user_id' => $UserID,
            'sun_id' => $ID,
            'sun_createtime' => $Info['createtime'],
            'plane_id' => $Info['plane_id'],
            'teacher_id' => $TeacherId,
            'status' => 0,
            'type' => 0,
            'no_price_type' => 0,
            'no_price' => 0,
            'FlyMinutes' => 0,
            'createtime' => time(),
            'updatetime' => time()
        ];
        $Res = Db::name('yuyue')->insert($Insert);
        if (!$Res) $this->error('新增预约失败');
    }


    public function KillGroup($id)
    {
        $Info = Db::name('sun')->where('id', $id)->find();
        $Date = date('Y-m-d', $Info['createtime']);
        if ($Info['time_id'] == 11) $Time = strtotime(date("$Date" . ' ' . '8:00'));
        if ($Info['time_id'] == 10) $Time = strtotime(date("$Date" . ' ' . '9:00'));
        if ($Info['time_id'] == 9) $Time = strtotime(date("$Date" . ' ' . '10:00'));
        if ($Info['time_id'] == 8) $Time = strtotime(date("$Date" . ' ' . '11:00'));
        if ($Info['time_id'] == 7) $Time = strtotime(date("$Date" . ' ' . '12:00'));
        if ($Info['time_id'] == 6) $Time = strtotime(date("$Date" . ' ' . '13:00'));
        if ($Info['time_id'] == 5) $Time = strtotime(date("$Date" . ' ' . '14:00'));
        if ($Info['time_id'] == 4) $Time = strtotime(date("$Date" . ' ' . '15:00'));
        if ($Info['time_id'] == 3) $Time = strtotime(date("$Date" . ' ' . '16:00'));
        if ($Info['time_id'] == 2) $Time = strtotime(date("$Date" . ' ' . '17:00'));
        if ($Info['time_id'] == 1) $Time = strtotime(date("$Date" . ' ' . '18:00'));
        if ($Time < time() + 86400) $this->error('您的会员等级不能取消超过24小时的预约', 0);
    }
}