<?php
/**
 * Created by PhpStorm.
 * User: zilongs
 * Date: 20-9-30
 * Time: 下午10:56
 */

namespace App\Models;

class Order extends BaseModel
{
    protected $appends = ['is_evaluate', 'consult_duration', 'callback_phone'];

    CONST UNPAID = 1, NOTACCEPT = 2, ISING = 3, FINISHED = 4,CANCELED=5,ISOUT=6; //订单状态(1.未支付 2.进行中 3.已完成 4.已取消)
    public static  $_order_status = [
        self::UNPAID=>'未支付',
        self::NOTACCEPT=>'待支付',
        self::ISING=>'进行中',
        self::FINISHED=>'已完成',
        self::CANCELED=>'已取消',
        self::ISOUT=>'已超时'
    ];

    //获取订单状态
    public static  function getStatus()
    {
        return self::$_order_status;
    }

    public function docter()
    {
        return $this->belongsTo(Docter::class);
    }

    public function calllog()
    {
        return $this->hasMany(CallLog::class);
    }
    /**
     * 用户医生关注表
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     * @author Liu-Yh
     * Create By 2020/11/18 11:06
     */
    public function userDocter(){
        return $this->hasOne(UserDocter::class,'user_id','user_id')->select(['id', 'remark']);
    }

    public function patients(){
        return $this->belongsTo(Patient::class);
    }
    public function orderPatient()
    {
        return $this->hasOne(OrderPatient::class);
    }

    public function orderPack()
    {
        return $this->hasOne(OrderPack::class);
    }

    public function orderNurse()
    {
        return $this->hasMany(OrderNurse::class);
    }

    public function orderVaccine()
    {
        return $this->hasOne(OrderVaccine::class);
    }

    public function orderUser()
    {
        return $this->hasOne(User::class,'id','user_id');
    }

    public function organization()
    {
        return $this->belongsTo(Organization::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }
    public function evaluate()
    {
        return $this->hasOne(Evaluate::class);
    }
    //支付完成的处理方法
    public static function payCompletedHandle($order_id)
    {
        $order = Order::select(['user_id', 'docter_id', 'product_type', 'total_amount', 'payment_type', 'payment_amount', 'order_sn', 'pay_order_pack_id', 'organization_id'])->where('id', $order_id)->first();
        //发送下单消息
        if ($order['product_type'] < 6) {
            $product_type_text = config('config.product_type_map')[$order['product_type']];
            UserMessage::saveMessage($order['user_id'], 4, $order_id, [$product_type_text]);
        }
        elseif ($order['product_type'] == 6) {
            $orderPack = OrderPack::select(['pack_name', 'end_time'])->where('order_id', $order_id)->first();
            UserMessage::saveMessage($order['user_id'], 5, $order_id, [$orderPack['pack_name'], date('Y-m-d', $orderPack['end_time'])]);
            //更新用户为服务包用户
            User::where('id', $order['user_id'])->update(['is_pack' => 1]);
        }
        elseif ($order['product_type'] == 7) {
            $user = User::select(['balance'])->where('id', $order['user_id'])->first();
            UserMessage::saveMessage($order['user_id'], 7, $order_id, [round($order['total_amount']/100, 2), round($user['balance']/100, 2)]);
        }
        //发送余额付款成功消息
        if ($order['payment_type'] == 2) {
            $user = User::select(['balance'])->where('id', $order['user_id'])->first();
            UserMessage::saveMessage($order['user_id'], 8, $order_id, [round($order['payment_amount']/100, 2), round($user['balance']/100, 2)]);
        }
        //发送医生端消息
        DocterMessage::saveMessage($order['docter_id'], $order['user_id'], 1, $order_id, [$order['order_sn']]);

        //如果是服务包支付的，就扣服务包的次数
        if ($order['payment_type'] == 3) {
            OrderPack::deductPackData($order['pay_order_pack_id'], $order['product_type'], $order['payment_amount']);
        }

       /* if (!empty($order['docter_id'])) {
            //更新医生的服务人数
            Docter::where('id', $order['docter_id'])->increment('service_persons');
        }*/

        //如果是门诊预约，预约时间段的订单数要加1
        if ($order['product_type'] == 3) {
            $orderPatient = OrderPatient::select(['time_period_id', 'appoint_start_time'])->where('order_id', $order_id)->first();
            $schedule_date = date('Y-m-d', $orderPatient['appoint_start_time']);
            SchedulePeriod::where('docter_id', $order['docter_id'])->where('organization_id', $order['organization_id'])->where('schedule_type', 1)->where('time_period_id', $orderPatient['time_period_id'])->where('schedule_date', $schedule_date)->increment('order_num');
        }
        //如果是儿保和疫苗预约，预约时间段的订单数要加1
        if (in_array($order['product_type'], [4,5])) {
            $orderPatient = OrderPatient::select(['time_period_id', 'appoint_start_time'])->where('order_id', $order_id)->first();
            $schedule_date = date('Y-m-d', $orderPatient['appoint_start_time']);
            $schedule_type = $order['product_type'] == 4 ? 2 : 3;
            SchedulePeriod::where('organization_id', $order['organization_id'])->where('schedule_type', $schedule_type)->where('time_period_id', $orderPatient['time_period_id'])->where('schedule_date', $schedule_date)->increment('order_num');
        }

        //如果是疫苗就减少疫苗库存
        if ($order['product_type'] == 4) {
            $orderVaccine = OrderVaccine::where('order_id', $order_id)->first();
            OrganizationVaccine::where('org_id', $order['organization_id'])->where('vaccine_id', $orderVaccine['vaccine_id'])->decrement('stock');
        }

        return true;
    }

    public function suggest()
    {
        return $this->hasOne(Suggest::class)->select(['id', 'order_id']);
    }

    public function getIsEvaluateAttribute()
    {
        $is_evaluate = 0;
        $user = User::getUserByToken(false);
        if (!empty($user)) {
            if (Evaluate::where('order_id', $this->id)->where('user_id', $user['id'])->exists()) {
                $is_evaluate = 1;
            }
        }

        return $is_evaluate;
    }

    //取消订单，建议是在事务里面去调用
    public static function orderCancel($order_id)
    {
        $order = Order::with(['orderPatient'])->where('id', $order_id)->first();
        //改变订单状态
        Order::where('id', $order_id)->update(['order_status' => 5]);
        //退钱到余额
        if (!empty($order['payment_amount'])) {
            User::changeBalance($order_id, $order['payment_amount'], 4, $order['id'], '取消订单退款');
        }
        //如果距离预约时间还有半个小时以上，那么预约时间段的订单数减1
        if ($order['order_patient']['appoint_start_time'] - 1800 > time()) {
            $schedule_date = date('Y-m-d', $order['order_patient']['appoint_start_time']);
            SchedulePeriod::where('docter_id', $order['docter_id'])->where('organization_id', $order['organization_id'])->where('time_period_id', $order['order_patient']['time_period_id'])->where('schedule_date', $schedule_date)->decrement('order_num');
        }
        //更新医生的服务人数
        Docter::where('id', $order['docter_id'])->decrement('service_persons');

        return true;
    }

    public function getConsultDurationAttribute()
    {
        $duration = 0;
        if ($this->product_type == 1) {
            $duration = CallLog::where('order_id', $this->id)->where('talk_time', '<>', null)->sum('talk_time');
            $duration = !empty($duration) ? $duration : 0;
        }
        elseif ($this->product_type == 2) {
            $duration = $this->end_time - $this->receiving_time;
        }

        return $duration > 0 ? $duration : 0;
    }

    public function getCallbackPhoneAttribute()
    {
        $secret_no = '';
        if ($this->product_type == 1) {
            $secret_no = CallLog::where('order_id', $this->id)->orderBy('id', 'desc')->value('secret_no');
        }

        return !empty($secret_no) ? $secret_no : '';
    }
}
