<?php

namespace App\Community\Actions\Nurse;

use App\Models\Order;
use App\Models\Organization;
use App\Models\User;
use Encore\Admin\Actions\RowAction;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class OrderCance extends RowAction
{
    public $name = '取消订单';

    public function handle(Model $model)
    {
        $id = $this->row->id;
        $order = Order::where(['id'=>$id])->with('orderUser')->first();
        $sn = $order->order_sn;

//        $openid = 'oYmUA5A1OIqtpA1XSrw35tbjtv1w';
        $time = $this->row->created_at;
        $price = ($this->row->total_amount / 100);

        $pantient = $this->row->orderPatient->name;
        $organization = Organization::where(['id'=>$this->row->organization_id])->value('name');
        $paystatus = Order::getPayStatus()[$this->row->payment_status];

        DB::beginTransaction();
        try {
            //退还余额
            $res = Order::orderCancel($id,'社区取消');
            if(empty($order->orderUser) || empty($order->orderUser->openid) ) {
                DB::commit();
                return $this->response()->success('操作成功!')->refresh();
            }
            $openid = $order->orderUser->openid;
            $msg = [
                $openid,$sn,'儿保预约',$price,$time,$pantient,$organization,'社区取消',$paystatus
            ];
            $miniMsg = [
                $openid,$sn,'社区取消','儿保预约',$paystatus
            ];
            //用户和医生都要发
//            $ret = admin_send_wechat_message(1,$msg,$miniMsg);
            DB::commit();
        } catch ( \Exception $e){
            dump($e->getMessage());
            DB::rollBack();
            return $this->response()->error('操作失败!');
        }

        if($res){
            return $this->response()->success('操作成功!')->refresh();
        }
        return $this->response()->error('操作失败!');
    }

}
