<?php

namespace app\api\controller\coach;

use app\common\controller\Apic;
use app\common\library\Sms;
use think\Exception;
use think\Validate;

use think\Db;

/**
 * 首页
 */
class Index extends Apic
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';


    //首页
    public function index(){
        //先判断是否有进行中的，不论日期，防止有跨夜班车
        $map = [
            'fache_status|fache_ready' => 1,
            'coach_id' => $this->auth->id,
        ];
        $check = Db::name('product_chufabanci')->where($map)->find();

        if($check){
            //取详情
            $info = $this->banci_info($check['id']);

            $result = ['datetype'=>'info','info'=>$info,'list'=>[]];
            $this->success(1,$result);
        }else{
            //取今日列表，最靠前的一个
            $list = $this->index_old();

            $result = ['datetype'=>'list','info'=>(object)[],'list'=>$list];
            $this->success(1,$result);
        }

    }
    //原首页
    private function index_old(){
        $starttime = strtotime(date('Y-m-d'));
        $endtime   = $starttime + 86399;

        //我的 今天未发车班次
        $map = [
            'bc.fache_status' => 0,
            'bc.fache_ready'  => 0,
            'bc.coach_id' => $this->auth->id,
            'bc.chufatime' => ['BETWEEN',[$starttime,$endtime]],
        ];
        $list = Db::name('product_chufabanci')->alias('bc')
            ->field('bc.*,
            road.roadname,
            coach.mobile as sijimobile
            ')
            ->join('product_road road','bc.road_id = road.id','LEFT')
            ->join('coach','bc.coach_id = coach.id','LEFT')
            ->where($map)->order('chufatime asc')
            ->limit(1)->select();

        if(!empty($list)){
            foreach($list as $key => &$val){
                //起始点默认值
                $val['startname'] = $val['roadname'];
                $val['endname'] = $val['roadname'];

                //起始点分割,临时用这个,客户说不重要
                $jieduan = mb_strpos($val['roadname'],'-');
                if($jieduan !== false){
                    $val['startname'] = mb_substr($val['roadname'],0,$jieduan);
                    $val['endname']   = mb_substr($val['roadname'],$jieduan+1);
                }

                //售票数量。一个司机一天最多2班车，这里不影响
                $shou_num = Db::name('order_road')->alias('road')
                    ->join('order','road.order_id = order.id','LEFT')
                    ->where('road.chufabanci_id',$val['id'])
//                    ->where('road.hexiao_status',0)
                    ->where('order.status','IN',[1,2])
                    ->sum('ticket_number');

                $val['shou_num'] = $shou_num;

                //验票数量
                $yan_num = Db::name('order_road')->alias('road')
                    ->join('order','road.order_id = order.id','LEFT')
                    ->where('road.chufabanci_id',$val['id'])
                    ->where('road.hexiao_status',1)
                    ->where('order.status','IN',[1,2])
                    ->sum('ticket_number');

                $val['yan_num']  = $yan_num;
            }
        }

        return $list;
    }

    //班次列表，和上面首页接口一样的，多了接参
    public function banci_list(){
        //日期
        $today = date('Y-m-d');
        $startdate = input('date',$today);
        if(empty($startdate)){
            $startdate = $today;
        }

        $starttime = strtotime($startdate);
        $endtime   = $starttime + 86399;

        //状态
        $fache_status = input('fache_status',1);
        if($fache_status == 1){
            $status_map = ['IN',[0,1]];
        }else{
            $status_map = 2;
        }

        $map = [
            'bc.fache_status' => $status_map,
            'bc.coach_id' => $this->auth->id,
            'bc.chufatime' => ['BETWEEN',[$starttime,$endtime]],
        ];
        $list = Db::name('product_chufabanci')->alias('bc')
            ->field('bc.*,
            road.roadname,
            coach.mobile as sijimobile
            ')
            ->join('product_road road','bc.road_id = road.id','LEFT')
            ->join('coach','bc.coach_id = coach.id','LEFT')
            ->where($map)->order('chufatime asc')
            ->select();

        if(!empty($list)){
            $have_ready = 0;
            foreach($list as $key => &$val){
                //起始点默认值
                $val['startname'] = $val['roadname'];
                $val['endname'] = $val['roadname'];

                //起始点分割,临时用这个,客户说不重要
                $jieduan = mb_strpos($val['roadname'],'-');
                if($jieduan !== false){
                    $val['startname'] = mb_substr($val['roadname'],0,$jieduan);
                    $val['endname']   = mb_substr($val['roadname'],$jieduan+1);
                }

                //售票数量。一个司机一天最多2班车，这里不影响
                $shou_num = Db::name('order_road')->alias('road')
                    ->join('order','road.order_id = order.id','LEFT')
                    ->where('road.chufabanci_id',$val['id'])
//                    ->where('road.hexiao_status',0)
                    ->where('order.status','IN',[1,2])
                    ->sum('ticket_number');

                $val['shou_num'] = $shou_num;

                //验票数量
                $yan_num = Db::name('order_road')->alias('road')
                    ->join('order','road.order_id = order.id','LEFT')
                    ->where('road.chufabanci_id',$val['id'])
                    ->where('road.hexiao_status',1)
                    ->where('order.status','IN',[1,2])
                    ->sum('ticket_number');

                $val['yan_num']  = $yan_num;

                //是否有人准备或服务中
                if($val['fache_ready'] == 1 || $val['fache_status'] == 1){
                    $have_ready = 1;
                }
            }

            //是否能点准备与继续服务
            $today_start = strtotime(date('Y-m-d'));
            $today_end   = $today_start + 86399;
            foreach($list as $keynew => $valnew){
                if($valnew['chufatime'] < $today_start || $valnew['chufatime'] > $today_end){
                    //不是今天，没按钮
                    $valnew['fuwu_button'] = 0;
                }else{
                    if($have_ready == 1){
                        //默认不能点
                        $valnew['fuwu_button'] = 0;

                        //已经发车的能点
                        if($valnew['fache_ready'] == 1 || $valnew['fache_status'] == 1){
                            $valnew['fuwu_button'] = 2;
                        }
                    }else{
                        //默认能点,按钮为发车
                        $valnew['fuwu_button'] = 1;

                        //到站的不能点
                        if($valnew['fache_status'] == 2){
                            $valnew['fuwu_button'] = 0;
                        }
                    }
                }

                $list[$keynew] = $valnew;
            }

        }

        $this->success(1,$list);
    }

    //班次详情
    public function banci_info($banci_id_return = false){
        $banci_id = input('banci_id',0);

        if($banci_id_return !== false){
            $banci_id = $banci_id_return;
        }

        $map = [
            'bc.id' => $banci_id,
        ];
        $val = Db::name('product_chufabanci')->alias('bc')
            ->field('bc.*,
            road.roadname,
            coach.mobile as sijimobile,
            car.chepaihao
            ')
            ->join('product_road road','bc.road_id = road.id','LEFT')
            ->join('coach','bc.coach_id = coach.id','LEFT')
            ->join('car','bc.car_id = car.id','LEFT')
            ->where($map)->find();

        //起始点默认值
        $val['startname'] = $val['roadname'];
        $val['endname'] = $val['roadname'];

        //起始点分割,临时用这个,客户说不重要
        $jieduan = mb_strpos($val['roadname'],'-');
        if($jieduan !== false){
            $val['startname'] = mb_substr($val['roadname'],0,$jieduan);
            $val['endname']   = mb_substr($val['roadname'],$jieduan+1);
        }

        //售票数量。一个司机一天最多2班车，这里不影响
        $shou_num = Db::name('order_road')->alias('road')
            ->join('order','road.order_id = order.id','LEFT')
            ->where('road.chufabanci_id',$val['id'])
//            ->where('road.hexiao_status',0)
            ->where('order.status','IN',[1,2])
            ->sum('ticket_number');

        $val['shou_num'] = $shou_num;

        //验票数量
        $yan_num = Db::name('order_road')->alias('road')
            ->join('order','road.order_id = order.id','LEFT')
            ->where('road.chufabanci_id',$val['id'])
            ->where('road.hexiao_status',1)
            ->where('order.status','IN',[1,2])
            ->sum('ticket_number');

        $val['yan_num']  = $yan_num;

        //售验票情况
        $val['shouyan_list'] = $this->shouyan_list($banci_id);

        if($banci_id_return !== false){
            return $val;
        }
        $this->success(1,$val);
    }

    //售验票列表
    private function shouyan_list($banci_id){
        $order_road = Db::name('order_road')->alias('road')
            ->field('road.id as road_id,road.chufaname,road.hexiao_no,road.ticket_number,road.hexiao_status,
            order.realname,order.mobile')
            ->join('order','road.order_id = order.id','LEFT')
            ->where('road.chufabanci_id',$banci_id)
            ->where('order.status','IN',[1,2])                    //付完款和已完成的
            ->order('road.hexiao_status desc,road.id asc')
            ->select();

        if(empty($order_road)){
            return [];
        }

        return $order_road;
    }

    //发出准备 提交
    public function banci_ready(){
        $this->apiLimit();

        //检查其他准备中的
        $check = Db::name('product_chufabanci')->where('coach_id',$this->auth->id)->where('fache_ready = 1 or fache_status = 1')->find();
        if(!empty($check)){
            $this->error('您已经有其他班次在服务中');
        }

        //开始
        $banci_id = input('banci_id',0);

        $info = Db::name('product_chufabanci')->where('id',$banci_id)->find();
        if(empty($info)){
            $this->error('不存在的班次');
        }

        if($info['fache_status'] != 0){
            $this->error('该班次发车状态有误，请刷新列表重试');
        }
        if($info['fache_ready'] != 0){
            $this->error('该班次准备状态有误，请刷新列表重试');
        }

        $update = [
            'fache_ready'=>1,
        ];
        $rs = Db::name('product_chufabanci')->where('id',$banci_id)->update($update);
        if($rs === false){
            $this->error('准备失败');
        }

        $this->success('准备成功');
    }

    //发车提交
    public function banci_fache(){
        $this->apiLimit();

        $banci_id = input('banci_id',0);

        $info = Db::name('product_chufabanci')->where('id',$banci_id)->find();
        if(empty($info)){
            $this->error('不存在的班次');
        }

        if($info['fache_status'] != 0){
            $this->error('该班次发车状态有误，请刷新列表重试');
        }

        if($info['fache_ready'] != 1){
            $this->error('该班次尚未准备，请刷新列表重试');
        }

        $update = [
            'fache_status'=>1,
            'fache_time'=>time(),
        ];
        $rs = Db::name('product_chufabanci')->where('id',$banci_id)->update($update);
        if($rs === false){
            $this->error('发车失败');
        }

        $this->success('发车成功');
    }

    //到站提交
    public function banci_daozhan(){
        $this->apiLimit();

        $banci_id = input('banci_id',0);

        $info = Db::name('product_chufabanci')->where('id',$banci_id)->find();
        if(empty($info)){
            $this->error('不存在的班次');
        }

        if($info['fache_status'] != 1){
            $this->error('该班次发车状态有误，请刷新列表重试');
        }

        if($info['fache_ready'] != 1){
            $this->error('该班次尚未准备，请刷新列表重试');
        }

        $update = [
            'fache_ready'=>0,//解锁
            'fache_status'=>2,
            'daozhan_time'=>time(),
        ];
        $rs = Db::name('product_chufabanci')->where('id',$banci_id)->update($update);
        if($rs === false){
            $this->error('到站失败');
        }

        $this->success('到站成功');
    }

    //扫码核销信息
    public function get_hexiao_info(){

        $hexiao_no = input('hexiao_no','','trim');

        $order_road = Db::name('order_road')->where('hexiao_no',$hexiao_no)->find();
        if(empty($order_road)){
            $this->error('无效核销码');
        }

        $order = Db::name('order')->where('id',$order_road['order_id'])->find();
        if($order['status'] != 1 && $order['status'] != 2){
            $error = '无法核销的码';
            if($order['status'] == 0){
                $error = '订单未支付';
            }
            if($order['status'] == 10){
                $error = '订单已取消';
            }
            if($order['status'] > 20){
                $error = '订单已售后';
            }
            $this->error($error);
        }

        //辅助
        $roadtype_arr = [
            1 => '单程票',
            2 => '单程票',
            3 => '往返票',
        ];
        $order_roadtype_text = isset($roadtype_arr[$order['roadtype']]) ? $roadtype_arr[$order['roadtype']] : '';

        $roadtype_arr = [
            1 => '去程',
            2 => '返程',
        ];
        $road_roadtype_text = isset($roadtype_arr[$order_road['roadtype']]) ? $roadtype_arr[$order_road['roadtype']] : '';

        //结果
        $result = [
            'product_name' => $order['product_name'],
            'roadname' => $order_roadtype_text.' '.$order_road['roadname'].' '.$road_roadtype_text,
            'chufatime' => date('Y-m-d H:i',$order_road['chufatime']),
            'ticket_str' => $order['ticket_str'],
            'realname' => $order['realname'],
            'mobile' => $order['mobile'],
            'hexiao_no' => $hexiao_no,
            'hexiao_status' => $order_road['hexiao_status'],
        ];

        $this->success(1,$result);
    }

    //核销提交
    public function hexiao_submit(){
        $this->apiLimit();


        $hexiao_no = input('hexiao_no','','trim');
        $banci_id  = input('banci_id',0,'intval');

        Db::startTrans();

        $order_road = Db::name('order_road')->where('hexiao_no',$hexiao_no)->lock(true)->find();
        if(empty($order_road)){
            Db::rollback();
            $this->error('无效核销码');
        }
        if($order_road['hexiao_status'] != 0){
            Db::rollback();
            $this->error('此核销码已核销');
        }
        if($order_road['chufabanci_id'] != $banci_id){
            Db::rollback();
            $this->error('此码与班次不符');
        }

        $order = Db::name('order')->where('id',$order_road['order_id'])->lock(true)->find();
        if($order['status'] != 1){
            $error = '无法核销的码';
            if($order['status'] == 0){
                $error = '订单未支付';
            }
            if($order['status'] == 2){
                $error = '订单已核销';
            }
            if($order['status'] == 10){
                $error = '订单已取消';
            }
            if($order['status'] > 20){
                $error = '订单已售后';
            }
            Db::rollback();
            $this->error($error);
        }

        //
        $banci_info = Db::name('product_chufabanci')->where('id',$banci_id)->find();
        if($banci_info['coach_id'] != $this->auth->id){
            Db::rollback();
            $this->error('班次与司机不符');
        }
        if($banci_info['fache_status'] != 0){
            /*Db::rollback();
            $this->error('该班次已发车不能继续验票');*/
        }

        //
        $update = [
            'hexiao_status' => 1,
            'hexiao_coachid' => $this->auth->id,
            'hexiao_time' => time(),
        ];
        $rs1 = Db::name('order_road')->where('id',$order_road['id'])->update($update);
        if($rs1 === false){
            Db::rollback();
            $this->error('核销失败');
        }

        //找到没核销的
        $road_find = Db::name('order_road')->where('order_id',$order_road['order_id'])->where('hexiao_status',0)->count();
        if($road_find == 0){
            //如果都核销了，修改订单状态
            $update = [
                'finishtime' => time(),
                'status'=>2
            ];
            $rs2 = Db::name('order')->where('id',$order_road['order_id'])->update($update);
            if($rs1 === false){
                Db::rollback();
                $this->error('核销失败,请稍后再试');
            }
        }

        Db::commit();

        $this->success('核销成功');
    }

    //验票记录
    public function yanpiao_history(){
        $date = input('date',date('Y-m-d'));
        if(empty($date)){
            $date = date('Y-m-d');
        }

        $starttime = strtotime($date);
        $endtime   = $starttime + 86399;

        $order_road = Db::name('order_road')->alias('road')
            ->field('road.id as road_id,road.chufaname,road.hexiao_no,road.ticket_number,road.hexiao_status,
            order.realname,order.mobile')
            ->join('order','road.order_id = order.id','LEFT')
            ->where('road.hexiao_time','BETWEEN',[$starttime,$endtime])
            ->where('road.hexiao_status',1)
            ->where('road.hexiao_coachid',$this->auth->id)
            ->order('road.hexiao_time desc')
            ->select();

        $ticket = array_column($order_road,'ticket_number');
        $result = [
            'count' => array_sum($ticket),
            'list' => $order_road,
        ];

        $this->success(1,$result);
    }

    //班线-日历
    public function slot_index()
    {
        //本周一
        $this_monday = date('Y-m-d',strtotime('monday this week'));

        //获取本周一
        $monday = input('date',$this_monday);
        if(empty($monday)){
            $monday = $this_monday;
        }

        //确定周一转移量
        $type = input('type',0);//0本周，1往前翻，2往后翻

        $time_zhuanyi = 0;
        if($type == 1){
            $time_zhuanyi = -86400*7;
        }
        if($type == 2){
            $time_zhuanyi = 86400*7;
        }

        //最终的周一
        $monday_time = strtotime($monday) + $time_zhuanyi;


        $result = [];
        $week_arr = [
            1 => '周一',
            2 => '周二',
            3 => '周三',
            4 => '周四',
            5 => '周五',
            6 => '周六',
            7 => '周日',
        ];
        $today = date('Y-m-d');

        for($i=0;$i<7;$i++){
            $time = $monday_time + ($i * 86400);
            $newone = [
                'time'        => $time,
                'date'        => date('Y-m-d',$time),
                'simple_date' => date('m/d',$time),
                'week'        => date('N',$time),
                'is_today'    => 0,
            ];
            $newone['week_text'] = $week_arr[$newone['week']];

            if($newone['date'] == $today){
                $newone['is_today'] = 1;
                $newone['week_text'] = '今天';
            }

            $result[] = $newone;
        }

        $this->success(1,$result);
    }





}
