<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Powerless < wzxaini9@gmail.com>
// +----------------------------------------------------------------------
namespace app\user\controller;

use app\user\model\CommentModel;
use cmf\controller\UserBaseController;
use app\user\model\UserModel;
use think\Db;
use think\Request;
use app\portal\controller\ToolController as tool;


class YuyueController extends UserBaseController
{

    /*按时间预约*/

    //step1:时间选择
    public function index()
    {
        return $this->fetch('yu_studycar');
    }

    //step2:预约时间提交
    public function yueyue_do(Request $re)
    {
        $day   = $re->param('day');
        $begin = $re->param('begin');
        $end   = $re->param('end');
        $week  = $re->param('week');

        session('yuyue_pre.day', $day);
        session('yuyue_pre.week', $week);
        session('yuyue_pre.begin', $begin);
        session('yuyue_pre.end', $end);
        return json(['code' => '1', 'msg' => 'ok']);
    }

    //step3:选择响应时间教练
    public function coach_list()
    {
        if (!session('yuyue_pre.day')) {
            echo '非法请求';
        }
        //获取选择的时间时段
        $bbegin = session('yuyue_pre.begin');
        $eend   = session('yuyue_pre.end');

        //获取当前已被预约的教练
        $rr = Db::name('yuyue')
            ->where(['yuyue_day' => session('yuyue_pre.day')])
            ->select()->toArray();

        //获取当前时段已被预约的教练
        $ex = '';
        foreach ($rr as $v) {
            $day_find = [];
            for ($i = $v['yuyue_begin']; $i <= $v['yuyue_end']; $i++) {
                $day_find[] = $i;
            }
            $f1 = array_search($bbegin, $day_find);
            $f2 = array_search($eend, $day_find);
            $ac = count($day_find) - 1;

            if (($f2 && $f2 > '0') || ($f1 && $f1 < $ac) || ($f1 && $f2)) {
                $ex .= $v['teach_id'] . ',';
            }
        }

        //获取当前时段有时间的教练
        $where['user_type'] = 3;
        $where['id']        = array('not in', $ex);
        $rree               = Db::name('user')->where($where)->select();

        //赋值已经选择的时间段
        $data['day1']       = session('yuyue_pre.day');
        $data['hour1']      = session('yuyue_pre.begin') . ':00 - ' . session('yuyue_pre.end') . ':00';
        $data['week']       = session('yuyue_pre.week');

        $this->assign("data", $data);
        $this->assign("data1", $rree);
        return $this->fetch();
    }

    //step4:教练信息查看
    public function coach_introduce(Request $re)
    {
        $tech_id = $re->param('id');
        $ddata   = session('yuyue_pre.day');
        $id      = $re->param('id');
        $rr      = Db::name('user')->where(['id' => $id])->find();
        $rre     = Db::name('commente')->where(['teach_id' => $id])->find();
        $rree    = Db::name('commente_tag')->where(['id' => ['in', $rre['comment_tag']]])->field('name')->select()->toArray();
        //获取标签
        $rre   = Db::name('commente')
            ->alias('c')
            ->join('qnb_user u', 'u.id = c.uid')
            ->where(['teach_id' => $id])
            ->field('c.*,u.user_nickname')
            ->select()
            ->toarray();
        $cm_tg = '';
        foreach ($rre as $v) {
            $cm_tg .= $v['comment_tag'];
        }
        $cm_td_ar = explode(',', $cm_tg);
        $aaa      = array_unique($cm_td_ar);
        $bbb      = implode(',', $aaa);
        $rree     = Db::name('commente_tag')->where(['id' => ['in', $bbb]])->field('name')->select()->toArray();

        $this->assign("ddata", $ddata);
        $this->assign("data", $rr);
        $this->assign("cdata", $rre);
        $this->assign("ctdata", $rree);
        $this->assign("tech_id", $tech_id);
        $this->assign("shijian_data", session('yuyue_pre.hour1'));
        return $this->fetch();
    }

    //step5:提交预约信息
    public function yuyue_time_do(Request $re, tool $tool)
    {

        $tech_id = $re->param('id');
        if (!$tech_id) {
            return json(['code' => '0', 'msg' => '抱歉,数据错误']);
        } else {
            $data['teach_id'] = intval($tech_id);
            $data['uid']      = session('user.id');

            //预约订单完成后才可以再次预约
            $rr               = Db::name('yuyue')->where($data)->order('create_time', 'desc')->find();
            $ytime = strtotime($rr['yuyue_day'].''.$rr['yuyue_end'].':00');
            $tt = time();
            if ( $ytime >$tt) {
                return json(['code' => '0', 'msg' => '您好,您有待学车预约']);
            }

            $data['yuyue_day']   = session('yuyue_pre.day');
            $data['yuyue_week']  = session('yuyue_pre.week');
            $data['yuyue_end']   = session('yuyue_pre.end');
            $data['yuyue_begin'] = session('yuyue_pre.begin');

            $ress = Db::name('yuyue')->where($data)->find();
            if($ress){
                return json(['code'=>'0','msg'=>'抱歉,您已经预约过']);
            }
            $data['status']      = '1';
            $data['create_time'] = time();

            $res = Db::name('yuyue')->insert($data);
            if ($res) {
                $stu_info = Db::name('user')->where(['id' => $data['uid']])->find();
                $tea_info = Db::name('user')->where(['id' => $data['teach_id']])->find();
                $msg      = "您好!您已成功预约:{$data['yuyue_day']} {$data['yuyue_begin']}:00 - {$data['yuyue_end']}:00 时间段{$tea_info['user_nickname']}的课程,请按时上课,教练电话:{$tea_info['mobile']},如有问题可直接与教练或您的学车顾问进行联系。【悠乐驾】";
                $tool->get_sms_code_p($stu_info['mobile'], $msg);
                $msg1 = "您好!您的:{$data['yuyue_day']} {$data['yuyue_begin']}:00 - {$data['yuyue_end']}:00 时间段课程已被{$stu_info['user_nickname']}学员预约,请按时上课,学员电话:{$stu_info['mobile']}【悠乐驾】";
                $tool->get_sms_code_p($tea_info['mobile'], $msg1);
                $param1 = [
                    'touser'      => $stu_info['openid'],
                    'topcolor'    => '#7B68EE',
                    'url'         => 'http://wx.youlj.cn/user/yuyue/my_yuyue',
                    'template_id' => 'OPENTM401874855',
                    'data'        => array(
                        'first'    => array('value' => '您的预约成功啦'),
                        'keyword1' => array('value' => $stu_info['user_nickname'], 'color' => '#0099FF'),
                        'keyword2' => array('value' => $stu_info['mobile']),
                        'keyword3' => array('value' => "{$data['yuyue_day']} {$data['yuyue_begin']}:00 - {$data['yuyue_end']}:00 ", 'color' => '#333366'),
                        'keyword4' => array('value' => $tea_info['user_nickname']),
                        'remark'   => array('value' => "点击查看预约")
                    )
                ];
                $param2 = [
                    'touser'      => $tea_info['openid'],
                    'topcolor'    => '#7B68EE',
                    'url'         => 'http://wx.youlj.cn/user/yuyue/my_yuyue',
                    'template_id' => 'OPENTM401874855',
                    'data'        => array(
                        'first'    => array('value' => '有新的学员预约啦'),
                        'keyword1' => array('value' => $stu_info['user_nickname'], 'color' => '#0099FF'),
                        'keyword2' => array('value' => $stu_info['mobile']),
                        'keyword3' => array('value' => "{$data['yuyue_day']} {$data['yuyue_begin']}:00 - {$data['yuyue_end']}:00 ", 'color' => '#333366'),
                        'keyword4' => array('value' => "点击查看预约并确认预约")
                    )
                ];

                $res = $tool->wxtemsg_send($param1);
                $res = $tool->wxtemsg_send($param2);


                return json(['code' => '1', 'msg' => '预约成功']);
            } else {
                return json(['code' => '0', 'msg' => '抱歉,预约失败']);
            }
        }

    }


    /*按教练预约*/

    //step1:教练选择
    public function yu_coach()
    {
        $rr = Db::name('user')->where(['user_type' => 3])->select();
        $this->assign("data", $rr);
        return $this->fetch('yu_coach');
    }

    //step2:教练信息查看
    public function coach_introduce_2(Request $re)
    {

        $ddata = date('Y-m-d', strtotime(session('yuyue_pre.day')));
        $id    = $re->param('id');
        $rr    = Db::name('user')->where(['id' => $id])->find();

        //获取标签
        $rre   = Db::name('commente')
            ->alias('c')
            ->join('qnb_user u', 'u.id = c.uid')
            ->where(['teach_id' => $id])
            ->field('c.*,u.user_nickname')
            ->select()
            ->toarray();
        $cm_tg = '';
        foreach ($rre as $v) {
            $cm_tg .= $v['comment_tag'];
        }
        $cm_td_ar = explode(',', $cm_tg);
        $aaa      = array_unique($cm_td_ar);
        $bbb      = implode(',', $aaa);
        $rree     = Db::name('commente_tag')->where(['id' => ['in', $bbb]])->field('name')->select()->toArray();


        $this->assign("ddata", $ddata);
        $this->assign("data", $rr);
        $this->assign("cdata", $rre);
        $this->assign("ctdata", $rree);
        $this->assign("id", $id);
        return $this->fetch();
    }

    //step3:教练时间列表
    public function yu_studycar_2(Request $re)
    {
        $id    = $re->param('id');
        $ddata = date('Y-m-d', strtotime(session('yuyue_pre.day')));
        $id    = $re->param('id');
        $rr    = Db::name('user')->where(['id' => $id])->find();
        $rre   = Db::name('commente')->where(['teach_id' => $id])->find();
        $rree  = Db::name('commente_tag')->where(['id' => ['in', $rre['comment_tag']]])->field('name')->select()->toArray();

        $this->assign("ddata", $ddata);
        $this->assign("data", $rr);
        $this->assign("cdata", $rre);
        $this->assign("ctdata", $rree);
        $this->assign("id", $id);
        return $this->fetch();
    }

    //step4:提交预约信息
    public function yuyue_coach_do(Request $re, tool $tool)
    {

        $day     = $re->param('day');
        $begin    = $re->param('begin');
        $end    = $re->param('end');
        $week    = $re->param('week');
        $tech_id = $re->param('id');

        if (!$tech_id) {
            return json(['code' => '0', 'msg' => '抱歉,数据错误']);
        } else {
            $data['teach_id']    = intval($tech_id);
            $data['uid']         = session('user.id');
            $data['yuyue_day']   = $day;
            $data['yuyue_begin']  = $begin;
            $data['yuyue_end']  = $end;
            $data['yuyue_week']  = $week;
            $ress = Db::name('yuyue')->where($data)->find();
            if($ress){
                return json(['code'=>'0','msg'=>'抱歉,您已经预约过']);
            }
            $data['status']      = 1;
            $data['create_time'] = time();

            $res = Db::name('yuyue')->insert($data);
            if ($res) {

                $stu_info = Db::name('user')->where(['id' => $data['uid']])->find();
                $tea_info = Db::name('user')->where(['id' => $data['teach_id']])->find();
                $msg      = "您好!您已成功预约:{$data['yuyue_day']} {$data['yuyue_begin']}:00 - {$data['yuyue_end']}:00 时间段{$tea_info['user_nickname']}的课程,请按时上课,教练电话:{$tea_info['mobile']},如有问题可直接与教练或您的学车顾问进行联系。【悠乐驾】";
                $tool->get_sms_code_p($stu_info['mobile'], $msg);
                $msg1 = "您好!您的:{$data['yuyue_day']} {$data['yuyue_begin']}:00 - {$data['yuyue_end']}:00 时间段课程已被{$stu_info['user_nickname']}学员预约,请按时上课,学员电话:{$stu_info['mobile']}【悠乐驾】";
                $tool->get_sms_code_p($tea_info['mobile'], $msg1);
                $param1 = [
                    'touser'      => $stu_info['openid'],
                    'topcolor'    => '#7B68EE',
                    'url'         => 'http://wx.youlj.cn/user/yuyue/my_yuyue',
                    'template_id' => 'kmRG7k7OOLd3m5a3sTvvMknbIySIifBtptFPxs3lgUo',
                    'data'        => array(
                        'first'    => array('value' => '学车预约通知'),
                        'keyword1' => array('value' => "{$data['yuyue_day']} {$data['yuyue_begin']}:00 - {$data['yuyue_end']}:00 ", 'color' => '#333366'),
                        'keyword2' => array('value' => $stu_info['kemu'], 'color' => '#0099FF'),
                        'keyword3' => array('value' => $tea_info['user_nickname'], 'color' => '#0099FF'),
                        'keyword4' => array('value' => $tea_info['mobile']),
                        'keyword5' => array('value' => '无', 'color' => '#0099FF')
                    )
                ];
                $param2 = [
                    'touser'      => $tea_info['openid'],
                    'topcolor'    => '#7B68EE',
                    'url'         => 'http://wx.youlj.cn/user/yuyue/my_yuyue',
                    'template_id' => 'kmRG7k7OOLd3m5a3sTvvMknbIySIifBtptFPxs3lgUo',
                    'data'        => array(
                        'first'    => array('value' => '学车预约通知'),
                        'keyword1' => array('value' => "{$data['yuyue_day']} {$data['yuyue_begin']}:00 - {$data['yuyue_end']}:00 ", 'color' => '#333366'),
                        'keyword2' => array('value' => $stu_info['kemu'], 'color' => '#0099FF'),
                        'keyword3' => array('value' => $stu_info['user_nickname'], 'color' => '#0099FF'),
                        'keyword4' => array('value' => $stu_info['mobile']),
                        'keyword5' => array('value' => '无', 'color' => '#0099FF')
                    )
                ];

                $res = $tool->wxtemsg_send($param1);
                $res = $tool->wxtemsg_send($param2);




                return json(['code' => '1', 'msg' => '预约成功']);
            } else {
                return json(['code' => '0', 'msg' => '抱歉,预约失败']);
            }
        }


    }

    /*我的预约*/

    //我的预约 学员
    public function my_yuyue()
    {
        $id     = session("user.id");
        $p_info = Db::name('user')->where(['id' => $id])->find();
        if($p_info['user_type']=='3'){
            return $this->redirect('my_yuyue_coach');
        }

        $gname = Db::name('order')
            ->alias('o')
            ->join('__GOODS__ g', 'o.gid = g.id')
            ->join('__USER__ u', 'u.id = o.uid')
            ->where(['uid' => session('user.id'), 'o.status' => '1'])
            ->field('o.*,g.name,g.price')
            ->value('name');

        $data = Db::name('yuyue')
            ->alias('yy')
            ->join('qnb_user u', 'u.id=yy.teach_id')
            ->where(['uid' => $id])
            ->field('yy.*,u.user_nickname,u.headimgurl,u.id as tech_id')
            ->order('create_time desc')
            ->select()
            ->toArray();
        foreach ($data as $k => $v) {
            if ($v['status'] == '3' && $v['pingjia_jiaolian'] != '1') {
                $data[$k]['status'] = '2';
            }
        }
        $dxdata = Db::name('yuyue')
            ->alias('yy')
            ->join('qnb_user u', 'u.id=yy.teach_id')
            ->where(['uid' => $id, 'status' => 1])
            ->field('yy.*,u.user_nickname,u.headimgurl,u.id as tech_id')
            ->order('create_time desc')
            ->select()
            ->toArray();
        $dpdata = Db::name('yuyue')
            ->alias('yy')
            ->join('qnb_user u', 'u.id=yy.teach_id')
            ->where(['uid' => $id, 'status' => 2])
            ->field('yy.*,u.user_nickname,u.headimgurl,u.id as tech_id')
            ->order('create_time desc')
            ->select()
            ->toArray();
        $ypdata = Db::name('yuyue')
            ->alias('yy')
            ->join('qnb_user u', 'u.id=yy.teach_id')
            ->where(['uid' => $id, 'status' => 5])
            ->field('yy.*,u.user_nickname,u.headimgurl,u.id as tech_id')
            ->order('create_time desc')
            ->select()
            ->toArray();

        $yyxs = Db::name('yuyue')
            ->where(['uid' => $id, 'status' => 3])
            ->count();
        $yyxs = $yyxs ? $yyxs : 0;

        $this->assign("data", $data);
        $this->assign("yyxs", $yyxs);
        $this->assign("p_info", $p_info);
        $this->assign("dxdata", $dxdata);
        $this->assign("dpdata", $dpdata);
        $this->assign("ypdata", $ypdata);
        $this->assign("gname", $gname);
        return $this->fetch();
    }

    //我的预约 教练
    public function my_yuyue_coach()
    {
        $id     = session("user.id");
        $p_info = Db::name('user')->where(['id' => $id])->find();

        $data = Db::name('yuyue')
            ->alias('yy')
            ->join('qnb_user u', 'u.id=yy.uid')
            ->join('order o', 'o.uid=yy.uid')
            ->join('goods g', 'g.id=o.gid')
            ->where(['teach_id' => $id])
            ->field('yy.*,u.user_nickname,u.headimgurl,u.id as tech_id,g.name as gname')
            ->order('create_time desc')
            ->select()
            ->toArray();

        $data1 = Db::name('yuyue')
            ->alias('yy')
            ->join('qnb_user u', 'u.id=yy.uid')
            ->join('order o', 'o.uid=yy.uid')
            ->join('goods g', 'g.id=o.gid')
            ->where(['teach_id' => $id])
            ->where(['yy.status' => '1'])
            ->field('yy.*,u.user_nickname,u.headimgurl,u.id as tech_id,g.name as gname')
            ->order('create_time desc')
            ->select()
            ->toArray();
        $data2 = Db::name('yuyue')
            ->alias('yy')
            ->join('qnb_user u', 'u.id=yy.uid')
            ->join('order o', 'o.uid=yy.uid')
            ->join('goods g', 'g.id=o.gid')
            ->where(['teach_id' => $id])
            ->where(['yy.status' => '4'])
            ->field('yy.*,u.user_nickname,u.headimgurl,u.id as tech_id,g.name as gname')
            ->order('create_time desc')
            ->select()
            ->toArray();
        $data3 = Db::name('yuyue')
            ->alias('yy')
            ->join('qnb_user u', 'u.id=yy.uid')
            ->join('order o', 'o.uid=yy.uid')
            ->join('goods g', 'g.id=o.gid')
            ->where(['teach_id' => $id])
            ->where(['yy.status' => '2'])
            ->field('yy.*,u.user_nickname,u.headimgurl,u.id as tech_id,g.name as gname')
            ->order('create_time desc')
            ->select()
            ->toArray();
        $data4 = Db::name('yuyue')
            ->alias('yy')
            ->join('qnb_user u', 'u.id=yy.uid')
            ->join('order o', 'o.uid=yy.uid')
            ->join('goods g', 'g.id=o.gid')
            ->where(['teach_id' => $id])
            ->where(['yy.status' => '3'])
            ->field('yy.*,u.user_nickname,u.headimgurl,u.id as tech_id,g.name as gname')
            ->order('create_time desc')
            ->select()
            ->toArray();

        $yjxs = Db::name('yuyue')
            ->where(['teach_id' => $id, 'status' => 3])
            ->count();
        $yjxs = $yjxs ? $yjxs : 0;

        $this->assign("data", $data);
        $this->assign("data1", $data1);
        $this->assign("data2", $data2);
        $this->assign("data3", $data3);
        $this->assign("data4", $data4);
        $this->assign("yjxs", $yjxs);
        $this->assign("p_info", $p_info);
        return $this->fetch();
    }

    //取消预约
    public function redo(Request $re, tool $tool)
    {
        $id = $re->param('id');
        if (!$id) {
            return json(['code' => '0', 'msg' => '数据错误']);
        }
        $data = Db::name('yuyue')->where(['id' => $id])->find();
        if ($data) {
            $rdata = json_encode($data);
            $rree  = Db::name('recycle_bin')->insert(['name' => $rdata, 'create_time' => time()]);
            if ($rree) {
                $rres = Db::name('yuyue')->where(['id' => $id])->delete();

                if ($rres) {
                    $stu_info = Db::name('user')->where(['id' => $data['uid']])->find();
                    $tea_info = Db::name('user')->where(['id' => $data['teach_id']])->find();
                    $msg      = "您好!您已成功取消:{$data['yuyue_day1']}--{$data['yuyue_hour1']}时间段{$tea_info['user_nickname']}的课程,欢迎您再次预约。【悠乐驾】";
                    $tool->get_sms_code_p($stu_info['mobile'], $msg);
                    $msg1 = "您好!您的:{$data['yuyue_day1']}--{$data['yuyue_hour1']}时间段课程已被{$stu_info['user_nickname']}学员取消,该时间段将进入待预约状态。
【悠乐驾】";
                    $tool->get_sms_code_p($tea_info['mobile'], $msg1);
                    return json(['code' => '1', 'msg' => '删除成功']);
                } else {
                    return json(['code' => '0', 'msg' => '抱歉,删除失败']);
                }
            }
        }

    }

    //开始学车
    public function kaishi_xue(Request $re)
    {

        $id = $re->param('id');

        if (!$id) {
            return json(['code' => '0', 'msg' => '抱歉,数据错误']);
        } else {


            $res = Db::name('yuyue')->where(['id' => $id])->update(['status' => '4']);

            if ($res) {
                return json(['code' => '1', 'msg' => '学车开始']);
            } else {
                return json(['code' => '0', 'msg' => '抱歉,数据错误']);
            }
        }


    }

    //学车完毕
    public function wanbi_xue(Request $re)
    {

        $id = $re->param('id');

        if (!$id) {
            return json(['code' => '0', 'msg' => '抱歉,数据错误']);
        } else {


            $res = Db::name('yuyue')->where(['id' => $id])->update(['status' => '2']);
            if ($res) {
                return json(['code' => '1', 'msg' => '学车完毕']);
            } else {
                return json(['code' => '0', 'msg' => '抱歉,数据错误']);
            }
        }

    }


}