<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
/**
 * 订单
 */
class Order extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    //支付状态:0=待付款,1=待出行,2=已完成,10=已取消,21=售后中,22=已退款
    protected $order_status = [
        0 => '待付款',
        1 => '待出行',
        2 => '已完成',
        10 => '已取消',//未付取消
        21 => '售后中',//已付取消
        22 => '已退款',//已付已退
    ];

    //订单列表
    public function lists()
    {
        $showstatus = input('showstatus',1); //1=全部，2=待付款，3=待出行，4=售后

        $map = [
            'order.user_id' => $this->auth->id,
        ];
        if($showstatus == 2){
            $map['order.status'] = 0;
        }
        if($showstatus == 3){
            $map['order.status'] = 1;
        }
        if($showstatus == 4){
            $map['order.status'] = 21;
        }

        $order = Db::name('order')
            ->field('order.id,order.order_no,order.pay_fee,order.ticket_str,order.status,
        p.image,p.name')
            ->join('product p','order.product_id = product.id','LEFT')
            ->order('order.id desc')->where($map)->autopage()->select();

        $order = list_domain_image($order,['image']);

        foreach($order as $key => &$val){
            $val['status_text'] = isset($this->order_status[$val['status']]) ? $this->order_status[$val['status']] : '';
        }

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

    //订单取消
    public function apply_cancel(){
        $order_id = input('order_id',0);

        Db::startTrans();
        $order = Db::name('order')->where('user_id',$this->auth->id)->where('id',$order_id)->lock(true)->find();
        if(empty($order)){
            Db::rollback();
            $this->error('不存在的订单');
        }

        if($order['status'] != 0){
            Db::rollback();
            $this->error('当前订单的状态不能取消');
        }

        //修改订单状态
        $update = [
            'status' => 10,//已取消
            'cancle_time' => time(),
        ];
        $order = Db::name('order')->where('id',$order_id)->update($update);
        if($order === false){
            Db::rollback();
            $this->error('请稍后重试');
        }

        //车票还回去
        $order_road = Db::name('order_road')->where('order_id',$order_id)->lock(true)->select();
        foreach($order_road as $key => $road){
            $chufabanci = Db::name('product_chufabanci')->where('id',$road['chufabanci_id'])->lock(true)->find();
            $update = [
                'ticket_remain' => $chufabanci['ticket_remain'] + $road['ticket_number'],
            ];
            $rs_ticket = Db::name('product_chufabanci')->where('id',$road['chufabanci_id'])->update($update);
            if($rs_ticket === false){
                Db::rollback();
                $this->error('请稍后重试');
            }
        }

        Db::commit();

        $this->success('取消成功');
    }

    //订单申请退款
    public function apply_refund(){
        $order_id = input('order_id',0);
        $reason = input('reason','','trim');

        Db::startTrans();
        $order = Db::name('order')->where('user_id',$this->auth->id)->where('id',$order_id)->lock(true)->find();
        if(empty($order)){
            Db::rollback();
            $this->error('不存在的订单');
        }

        if($order['status'] != 1){
            Db::rollback();
            $this->error('当前订单的状态不能申请退款');
        }

        $order_road = Db::name('order_road')->where('order_id',$order['id'])->order('roadtype asc')->lock(true)->select();
        foreach($order_road as $key => $road){
            if($road['hexiao_status'] == 1){
                Db::rollback();
                $this->error($order_road['roadname'].'已经核销，不能申请退款');
            }

            if($key == 0){//第一个班次
                $applyrefund_early_minute = config('site.applyrefund_early_minute') ?: 10;//提前量
                if((time() + ($applyrefund_early_minute * 60)) >= $road['chufatime'] ){
                    Db::rollback();
                    $this->error('距离发车时间不足'.$applyrefund_early_minute.'分钟，您已错过申请');
                }
            }
        }

        $update = [
            'refund_reason' => $reason,
            'status' => 21,//售后中
        ];
        $order_rs = Db::name('order')->where('id',$order_id)->update($update);
        if($order_rs === false){
            Db::rollback();
            $this->error('请稍后重试');
        }

        Db::commit();
        $this->success('申请成功,请等待审核');
    }

    //生成我的视频海报
    //生成邀请码二维码图片
    private function inviteimage($text) {
        $params['text'] = $text;
        $qrcode_service = \addons\qrcode\library\Service::qrcode($params);
//        $mimetype = 'image/png';
//        $response = Response::create()->header("Content-Type", $mimetype);

        // 直接显示二维码
//        header('Content-Type: ' . $qrcode_service->getContentType());
//        $response->content($qrcode_service->writeString());
        $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/';
        if (!is_dir($qrcodePath)) {
            @mkdir($qrcodePath);
        }
        if (is_really_writable($qrcodePath)) {
            $filename = md5(implode('', $params)) . '.png';
            $filePath = $qrcodePath . $filename;
            $qrcode_service->writeFile($filePath);
        }

        return '/uploads/qrcode/' . $filename;
    }

    //某个订单的核销码
    public function order_qrcode(){
        $order_id = input('order_id',0);

        $order = Db::name('order')->where('user_id',$this->auth->id)->where('id',$order_id)->find();
        if(empty($order)){
            $this->error('不存在的订单');
        }

        $order_road   = Db::name('order_road')->alias('road')
            ->field('road.*,
            car.chepaihao,
            coach.mobile as sijimobile
            ')
            ->join('product_chufabanci bc','road.chufabanci_id = bc.id','LEFT')
            ->join('car','bc.car_id = car.id','LEFT')
            ->join('coach','bc.coach_id = coach.id','LEFT')
            ->where('road.order_id',$order_id)->order('road.roadtype asc')->select();
        foreach($order_road as $key => &$road){
            $road['chufatime_text'] = date('Y-m-d H:i',$road['chufatime']);
            $road['ticket_str'] = $order['ticket_str'];
            $road['realname'] = $order['realname'];

            $road['qrcode'] = config('pay_notify_url').$this->inviteimage($road['hexiao_no']);
        }

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

    //待核销//已核销
    public function hexiao_list(){
        $hexiao_status = input('hexiao_status',1);

        $map = [
            'order.user_id' => $this->auth->id,
        ];
        if($hexiao_status == 1){
            $map['order.status'] = 1;
        }else{
            $map['order.status'] = 2;
        }

        $order = Db::name('order')
            ->field('order.id,order.order_no,order.pay_fee,order.ticket_str,order.status,
        p.image,p.name')
            ->join('product p','order.product_id = product.id','LEFT')
            ->order('order.id desc')->where($map)->autopage()->select();

        $order = list_domain_image($order,['image']);

        foreach($order as $key => &$val){
            $val['status_text'] = isset($this->order_status[$val['status']]) ? $this->order_status[$val['status']] : '';
        }

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

    //扫码核销信息
    public function get_hexiao_info(){
        $this->error('请前往司机端');
        if($this->auth->group_id !=2){
            $this->error('您无权限核销');
        }

        $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->error('请前往司机端');
        if($this->auth->group_id !=2){
            $this->error('无权限核销');
        }

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

        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('此核销码已核销');
        }

        $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);
        }


        //
        $update = [
            'hexiao_status' => 1,
            'hexiao_uid' => $this->auth->id,
        ];
        $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('核销成功');
    }


}
