<?php

namespace app\index\controller;

use think\Controller;
use think\Db;
use think\Cache;
use app\common\model\Wenzhenorder;

class Plantask extends Controller
{
    //未支付订单，下单N分钟后，自动取消
    public function auto_cancel_nopay_order(){
        $nowtime  = time();
        $second   = config('site.nopay_order_autocancel_minute') * 60;
        $lasttime = $nowtime - $second;

        //dump(datetime($lasttime));exit;
        $rs = Db::name('wenzhen_order')->where('status',0)->where('createtime','lt',$lasttime)->update([
            'status'        => 3,
            'cancel_time'   => $nowtime,
            'cancel_reason' => '超时未支付',
            'finish_time'   => $nowtime,
        ]);
        echo $rs;

    }

    //待接诊订单，医生不操作，支付N分钟后，自动退诊，即时视频订单除外
    public function auto_tuizhen_noaccept_order(){
        $nowtime  = time();
        $second   = config('site.payorder_noaccept_autotuizhen_minute') * 60;
        $lasttime = $nowtime - $second;

        //dump(datetime($lasttime));exit;
        Db::startTrans();

        $wenzhen_order = Db::name('wenzhen_order')->where('status',10)->where('video_mode','NEQ',2)->where('pay_time','lt',$lasttime)->order('id asc')->lock(true)->find();
        if(empty($order_list)){
            Db::rollback();
            echo 'empty';
            exit;
        }

        $order_id = $wenzhen_order['id'];

        //修改订单
        $update = [
            'status'        => 16,
            'cancel_time'   => $nowtime,
            'cancel_reason' => '超时未接诊',
            'finish_time'   => $nowtime,
        ];

        //余额支付的直接退款
        if($wenzhen_order['pay_type'] == 'wallet'){

            //用户加钱
            $logtype = $wenzhen_order['ordertype'] == 1 ? 13 : 14;
            $rs_wallet = model('wallet')->lockChangeAccountRemain($wenzhen_order['user_id'],'money',$wenzhen_order['total_fee'],$logtype,$remark='超时未接诊','wenzhen_order',$order_id);
            if($rs_wallet['status'] === false){
                Db::rollback();
                echo $rs_wallet['msg'];
                exit;
            }

            //订单退款参数
            $update['refund_price']  = $wenzhen_order['total_fee'];
            $update['refund_status'] = 3;
        }else{
            $update['refund_status'] = 1; //待退款

            //发起退款
            $Wenzhenorder_model = new Wenzhenorder;
            $refund_rs = $Wenzhenorder_model->old_refund($wenzhen_order,$wenzhen_order['total_fee']);
            if($refund_rs === true){
                $update['refund_status'] = 3; //退款完成
            }
        }

        $update_rs = Db::name('wenzhen_order')->where('id',$order_id)->update($update);
        if(!$update_rs){
            Db::rollback();
            echo '退诊失败';
            exit;
        }


        Db::commit();
        echo '退诊成功'.$order_id.'结束';
        exit;


    }

    //app视频订单，已拨打，通话N分钟后，自动结束
    public function auto_finish_firstvideo_videoorder(){
        $nowtime  = time();
        $second   = config('site.firstvideo_videoorder_autofinish_minute') * 60;
        $lasttime = $nowtime - $second;

        $list = Db::name('wenzhen_order')->where('status',25)->where('ordertype',2)->where('comefrom',1)->where('video_time','lt',$lasttime)->limit(10)->select();

        if(empty($list)){
            echo 'empty';exit;
        }

        foreach($list as $key => $order){
            echo $order['id'].':'.$this->finish($order['id']);
        }
    }

    //TV视频订单，已拨打，通话N分钟后，自动结束
    public function auto_finish_firstvideo_videoorder_tv(){
        $nowtime  = time();
        $second   = config('site.tv_firstvideo_videoorder_autofinish_minute') * 60;
        $lasttime = $nowtime - $second;

        $list = Db::name('wenzhen_order')->where('status',25)->where('ordertype',2)->where('comefrom',2)->where('video_time','lt',$lasttime)->limit(10)->select();

        if(empty($list)){
            echo 'empty';exit;
        }

        foreach($list as $key => $order){
            echo $order['id'].':'.$this->finish($order['id']);
        }
    }

    //图文订单，已接诊，接诊N分钟后，自动结束
    public function auto_finish_accept_textorder(){
        $nowtime  = time();
        $second   = config('site.accept_textorder_autofinish_minute') * 60;
        $lasttime = $nowtime - $second;

        $list = Db::name('wenzhen_order')->where('status',20)->where('ordertype',1)->where('accept_time','lt',$lasttime)->limit(10)->select();
        if(empty($list)){
            echo 'empty';exit;
        }

        foreach($list as $key => $order){
            echo $order['id'].':'.$this->finish($order['id']);
        }
    }

    public function finish($order_id){

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

        if($wenzhen_order['ordertype'] == 1){
            if($wenzhen_order['status'] != 20){
                Db::rollback();
                //$this->error('已接诊订单才能完成');
                return '已接诊订单才能完成';
            }

            $old_status = 20;
        }
        if($wenzhen_order['ordertype'] == 2){
            if($wenzhen_order['status'] != 25){
                Db::rollback();
                //$this->error('尚未发起视频，不能结束');
                return '尚未发起视频，不能结束';
            }

            $old_status = 25;
        }

        //修改订单
        $nowtime = time();
        $update = [
            'status' => 30,
            'finish_time' => $nowtime,
        ];

        //给医生结算钱
        $logtype = $wenzhen_order['ordertype'] == 1 ? 111 : 112;
        if($wenzhen_order['comefrom'] == 1 && $wenzhen_order['total_fee'] > 0){
            $rs_wallet = model('walletdoctor')->lockChangeAccountRemain($wenzhen_order['doctor_id'],'money',$wenzhen_order['total_fee'],$logtype,$remark='问诊订单','wenzhen_order',$order_id);
            if($rs_wallet['status'] === false){
                Db::rollback();
                //$this->error($rs_wallet['msg']);
                return $rs_wallet['msg'];
            }
        }

        //订单状态
        $update_rs = Db::name('wenzhen_order')->where('id',$order_id)->where('status',$old_status)->update($update);
        if(!$update_rs){
            Db::rollback();
            //$this->error('操作失败');
            return '操作失败';
        }

        //医生接诊量
        Db::name('doctor')->where('id',$wenzhen_order['doctor_id'])->setInc('ordernum');

        Db::commit();

        //发送im消息给用户，让他不能再输入
        /*if($wenzhen_order['ordertype'] == 1){
            $tenim = new Tenim();
            $message = [
                'businessID' => 'order_status_doctor_type',
                'name' => '',
                'status' => '30',
                'id' => (string)$order_id,
                'content' => '',
            ];
            $rs = $tenim->sendCustomMessageToUser('user'.$wenzhen_order['user_id'],'doctor'.$wenzhen_order['doctor_id'],$message);
        }*/


        //$this->success('操作成功');
        return '操作成功';
    }

/////////////////////////////////////////////////////////////////////////

    //定时跑用户活跃，改成离线
    public function auto_user_active(){
        $actitime = time() - 7200;

        $sql = 'update `mt_user` set is_active = 0 where is_active = 1 and id in (select user_id from mt_user_active where requesttime < '.$actitime.')';
        db()->query($sql);
    }

    //vip过期的，三个隐私设置改成0
    //vip过期的，更新用户表is_vip
    public function auto_vipend(){
//        $sql = 'update `mt_user_power` set yinsi = 0,yinshen = 0,wuhen = 0 where user_id in (select user_id from mt_user_wallet where vip_endtime > 0 and vip_endtime < '.time().')';
//        db()->query($sql);

        /*$sql2 = 'update `mt_user` set is_vip = 0 where is_vip = 1 and user_id in (select user_id from mt_user_wallet where vip_endtime > 0 and vip_endtime < '.time().')';
        db()->query($sql2);*/
    }




}
