<?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,ISACCEPT=7;//订单状态(1.未支付 2.进行中 3.已完成 4.已取消)
    public static  $_order_status = [
        self::UNPAID=>'未支付',
        self::NOTACCEPT=>'待支付',
        self::ISING=>'进行中',
        self::FINISHED=>'已完成',
        self::CANCELED=>'已取消',
        self::ISOUT=>'已超时',
        self::ISACCEPT=>'已预约'
    ];


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

    // 支付状态(1.待付款 2.已付款 3.退款中 4.已退款  5.待退款)
    public static $_order_pay_status = [
        1=>'待支付',
        2=>'已付款',
        3=>'退款中',
        4=>'已退款',
        5=>'待退款',
    ];

    public static  function getPayStatus()
    {
        return self::$_order_pay_status;
    }

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

    public function calllog()
    {
        return $this->hasMany(CallLog::class);
    }
    /**
     * 用户医生关注表
     * @return
     * @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::with(['organization', 'orderVaccine', 'orderNurse', 'orderPack'])->where('id', $order_id)->first()->toArray();
        $orderPatient = OrderPatient::where('order_id', $order_id)->first();
        $user = User::where('id', $order['user_id'])->first();
        //更新订单
        $order_status = 2;
        if (in_array($order['product_type'], [3,4,5])) {
            $order_status = 7;
        }
        elseif ($order['product_type'] == 6) {
            $order_status = 3;
        }
        elseif ($order['product_type'] == 7) {
            $order_status = 4;
            //改变用户余额
            User::changeBalance($order['user_id'], $order['total_amount'], 2, $order['id'], '充值');
        }
        Order::where('id', $order_id)->update([
            'order_status' => $order_status,
            'payment_status' => 2,
            'payment_time' => time(),
        ]);
        //发送下单消息
        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) {
            UserMessage::saveMessage($order['user_id'], 7, $order_id, [round($order['total_amount']/100, 2), round($user['balance']/100, 2)]);
        }
        //发送余额付款成功消息
        if ($order['payment_type'] == 2) {
            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']);
        }

        //如果是门诊预约，预约时间段的订单数要加1
        if ($order['product_type'] == 3) {
            $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])) {
            $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();
            Vaccine::where('id', $orderVaccine['vaccine_id'])->decrement('stock');
        }

        //给用户发送微信消息
        $docter = Docter::where('id', $order['docter_id'])->first();
        if ($order['product_type'] == 1) {
            $official_arr = [$user['openid'], $docter['name'], date('Y-m-d H:i:s'), round($order['payment_amount']/100, 2)];
            $product_type_text = config('config.product_type_map')[$order['product_type']];
            $subscribe_arr = [$user['openid'], $product_type_text, $user['nickname'], date('Y-m-d H:i:s'), $product_type_text, round($order['payment_amount']/100, 2)];
            send_wechat_message(1, $official_arr, $subscribe_arr);
        }
        elseif ($order['product_type'] == 2) {
            $official_arr = [$user['openid'], $docter['name'], $orderPatient['name'], $orderPatient['symptoms'], date('Y-m-d H:i:s'), round($order['payment_amount']/100, 2)];
            $product_type_text = config('config.product_type_map')[$order['product_type']];
            $subscribe_arr = [$user['openid'], $product_type_text, $user['nickname'], date('Y-m-d H:i:s'), $product_type_text, round($order['payment_amount']/100, 2)];
            send_wechat_message(2, $official_arr, $subscribe_arr);
        }
        elseif ($order['product_type'] == 3) {
            $keyword2 = date('Y-m-d H:i', $orderPatient['appoint_start_time']).' - '.date('H:i', $orderPatient['appoint_end_time']);
            $official_arr = [$user['openid'], $docter['name'], $keyword2, $orderPatient['name'], $orderPatient['phone'], $order['organization']['name'], $order['organization']['address']];
            $subscribe_arr = [$user['openid'], $orderPatient['name'], $order['organization']['name'], $docter['name'], $keyword2];
            send_wechat_message(3, $official_arr, $subscribe_arr);
        }
        elseif ($order['product_type'] == 4) {
            $keyword2 = date('Y-m-d H:i', $orderPatient['appoint_start_time']).' - '.date('H:i', $orderPatient['appoint_end_time']);
            $official_arr = [$user['openid'], $order['organization']['name'], $order['order_vaccine']['vaccine_name'], $keyword2, $orderPatient['name'], $orderPatient['phone'], $order['organization']['name'], $order['organization']['address']];
            $subscribe_arr = [$user['openid'], $orderPatient['name'], $order['order_vaccine']['vaccine_name'], $order['organization']['name'], $keyword2];
            send_wechat_message(4, $official_arr, $subscribe_arr);
        }
        elseif ($order['product_type'] == 5) {
            $keyword2 = date('Y-m-d H:i', $orderPatient['appoint_start_time']).' - '.date('H:i', $orderPatient['appoint_end_time']);
            $official_arr = [$user['openid'], $order['organization']['name'], $order['order_nurse'][0]['nurse_name'], $keyword2, $orderPatient['name'], $orderPatient['phone'], $order['organization']['name'], $order['organization']['address']];
            $subscribe_arr = [$user['openid'], $orderPatient['name'], $order['order_nurse'][0]['nurse_name'], $order['organization']['name'], $keyword2];
            send_wechat_message(5, $official_arr, $subscribe_arr);
        }
        elseif ($order['product_type'] == 6) {
            $official_arr = [$user['openid'], $order['order_pack']['pack_name'], date('Y-m-d H:i:s', $order['order_pack']['start_time']), date('Y-m-d H:i:s', $order['order_pack']['end_time'])];
            $service_time = date('Y/m/d', $order['order_pack']['start_time']). ' - '. date('Y/m/d', $order['order_pack']['end_time']);
            $subscribe_arr = [$user['openid'], $order['order_pack']['pack_name'], $service_time, $user['nickname']];
            send_wechat_message(6, $official_arr, $subscribe_arr);
        }

        //给医生发送消息
        if (in_array($order['product_type'], [1,2])) {
            $official_arr = [$user['openid'], $order['order_sn'], config('config.product_type_map')[$order['product_type']], $orderPatient['name'], $orderPatient['phone']];
            send_wechat_message(10, $official_arr);
        }
        elseif ($order['product_type'] == 3) {
            $keyword4 = date('Y-m-d H:i', $orderPatient['appoint_start_time']).' - '.date('H:i', $orderPatient['appoint_end_time']);
            $official_arr = [$user['openid'], $orderPatient['name'], $orderPatient['phone'], $keyword4, $order['organization']['name'], $docter['name']];
            send_wechat_message(11, $official_arr);
        }

        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_notes = '')
    {
        $order = Order::with(['orderPatient'])->where('id', $order_id)->first()->toArray();
        //判断预约时间是否还剩1小时内
        $can_refund = true;
        if (in_array($order['product_type'], [3,4,5])) {
            $order_notes = '用户取消预约';
            if ($order['order_patient']['appoint_start_time'] - 3600 < time()) {
                $order_notes = '用户超时取消';
                $can_refund = false;
            }
        }
        //改变订单状态
        $updateOrder = ['order_status' => 5, 'order_notes' => $order_notes];
        if ($order['payment_status'] > 1) {
            //判断是余额支付还是服务包支付
            if ($order['payment_type'] == 3) {
                //退服务包的次数
                $map = [1 => 'phone_minutes', 2 => 'chat_num', 3 => 'appoint_num', 4 => 'vaccine_limit_amount', 5 => 'nurses_limit_amount'];
                OrderPack::where('id', $order['pay_order_pack_id'])->increment($map[$order['product_type']]);
                $updateOrder['cancel_time'] = time();
                $updateOrder['payment_status'] = 4;
                if ($order['product_type'] == 3 && !$can_refund) {
                    $updateOrder['payment_status'] = 2;
                }
            }
            else {
                //退钱到余额
                if (!empty($order['payment_amount']) && $can_refund && $order['product_type'] != 5) {
                    User::changeBalance($order['user_id'], $order['payment_amount'], 4, $order['id'], '取消订单退款');
                }
                $updateOrder['cancel_time'] = time();
                if ($can_refund) {
                    $updateOrder['payment_status'] = 4;
                }
                if ($order['product_type'] == 5) {
                    $updateOrder['payment_status'] = 5;
                }
                if ($order['product_type'] == 3 && !$can_refund) {
                    $updateOrder['payment_status'] = 2;
                }
            }
        }
        Order::where('id', $order_id)->update($updateOrder);

        //如果是门诊预约且距离预约时间还有1个小时以上，那么预约时间段的订单数减1
        if ($order['product_type'] == 3 && $can_refund) {
            $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)->where('order_num', '>', 0)->decrement('order_num');
        }

        //如果是疫苗儿保预约且距离预约时间还有1个小时以上，那么预约时间段的订单数减1
        if (in_array($order['product_type'], [4,5]) && $can_refund) {
            $schedule_type_map = [4 => 2, 5 => 3];
            $schedule_date = date('Y-m-d', $order['order_patient']['appoint_start_time']);
            SchedulePeriod::where('organization_id', $order['organization_id'])->where('time_period_id', $order['order_patient']['time_period_id'])->where('schedule_date', $schedule_date)->where('schedule_type', $schedule_type_map[$order['product_type']])->where('order_num', '>', 0)->decrement('order_num');
        }
        //如果是疫苗预约那么取消订单就增加疫苗库存
        if ($order['product_type'] == 4) {
            $orderVaccine = OrderVaccine::where('order_id', $order_id)->first();
            Vaccine::where('id', $orderVaccine['vaccine_id'])->increment('stock');
        }

        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 : '';
    }

    public static function checkOrder($order_id)
    {
        $order = Order::with(['orderPatient', 'orderVaccine'])->where('id', $order_id)->first()->toArray();
        $product_type = $order['product_type'];
        if (in_array($product_type, [1,2])) {
            //判断是否在服务时间内
            $now_line = (int)date('Hi');
            if (!DocterServiceTime::where('docter_id', $order['docter_id'])->where('type', $product_type)->where('start_time_line', '<=', $now_line)->where('end_time_line', '>', $now_line)->exists()) {
                exit_out(null, 10011, '当前不在医生服务时间内，不能下单');
            }

            //图文咨询订单未结束时不能针对同一医生再次下图文订单
            if ($product_type == 2 && Order::where('docter_id', $order['docter_id'])->where('product_type', 2)->where('user_id', $order['user_id'])->whereIn('order_status', [2,3])->exists()) {
                exit_out(null, 10012, '您已经下过该医生的图文订单了，并且订单还未完成');
            }
        }
        //检查号源
        elseif ($product_type == 3) {
            $schedule_date = date('Y-m-d', $order['order_patient']['appoint_start_time']);
            $schedulePeriod = SchedulePeriod::where('docter_id', $order['docter_id'])->where('time_period_id', $order['order_patient']['time_period_id'])->where('schedule_date', $schedule_date)->where('schedule_type', 1)->first();
            if (empty($schedulePeriod)) {
                exit_out(null, 10012, '医生无该时间段的排班');
            }
            $docterSettings = DocterSetting::select(['service_num'])->where('docter_id', $order['docter_id'])->where('type', 1)->first();
            if ($docterSettings['service_num'] <= $schedulePeriod['order_sn']) {
                exit_out(null, 10014, '医生该时间段已经预约满了');
            }
        }
        elseif (in_array($product_type, [4,5])) {
            if (Order::whereIn('product_type', [4,5])->where('user_id', $order['user_id'])->whereIn('order_status', [2,3])->exists()) {
                exit_out(null, 10012, '您已经下过'.config('config.product_type_map')[$product_type].'订单，并且订单还未完成');
            }

            $schedule_date = date('Y-m-d', $order['order_patient']['appoint_start_time']);
            $schedule_type_map = [4 => 2, 5 => 3];
            $schedulePeriod = SchedulePeriod::where('time_period_id', $order['order_patient']['time_period_id'])->where('schedule_date', $schedule_date)->where('organization_id', $order['organization_id'])->where('schedule_type', $schedule_type_map[$product_type])->first();
            if (empty($schedulePeriod)) {
                exit_out(null, 10013, '机构无该时间段的排班');
            }
            $docterSettings = DocterSetting::select(['service_num'])->where('org_id', $order['organization_id'])->where('type', $schedule_type_map[$product_type])->first();
            if ($docterSettings['service_num'] <= $schedulePeriod['order_sn']) {
                exit_out(null, 10015, '机构该时间段已经预约满了');
            }
        }

        //疫苗预约检查库存是否足够
        if ($product_type == 4) {
            $stock = Vaccine::where('id', $order['order_vaccine']['vaccine_id'])->value('stock');
            if ($stock <= 0) {
                exit_out(null, 10009, '该疫苗库存不足');
            }
        }

        if ($order['payment_type'] == 3) {
            OrderPack::checkUserServicePack($order['pay_order_pack_id'], $order['user_id'], $product_type);
        }

        return true;
    }
}
