<?php

namespace App\Community\Actions\Vaccine;

use App\Models\Order;
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;
        $sn = $this->row->order_sn;
        $openid = $this->row->orderUser->openid;
//        $openid = 'oYmUA5A1OIqtpA1XSrw35tbjtv1w';
        if(empty($openid)) return true;
        $time = $this->row->created_at;
        $price = (intval($this->row->total_amount) / 100);
        $pantient = $this->row->orderPatient->name;
        $organization = $this->row->organization->name;
        $paystatus = Order::getPayStatus()[$this->row->payment_status];

        DB::beginTransaction();
        try {
            //退还余额
            $res = Order::orderCancel($id,'社区取消');
            $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){
            dd($e->getMessage());
            DB::rollBack();
            return $this->response()->error('操作失败!');
        }

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

}
