<?php

namespace App\Admin\Actions\Wo;

use Encore\Admin\Actions\RowAction;
use Illuminate\Database\Eloquent\Model;
use Wo;

class Unsubscribe extends RowAction
{
    public $name = '退订';

    public function handle(Model $model)
    {
        $postData = [
            'logNo' => $model->logNo,
        ];
        //查询状态
        $res = Wo::ticketQuery($postData, $model->user_id);
        if (is_string($res)) {
            return $this->response()->error($res)->refresh();
        }

        $ConfigTicketState     = config('wo.ticketState');
        $ConfigTicketStateText = config('wo.ticketStateText');
        $ticketState           = $res['ticketState'];

        if (!in_array($ticketState, ['A', 'U'])) {
            $msg = (array_key_exists($ticketState, $ConfigTicketStateText)) ? $ConfigTicketStateText[$ticketState] : '未知状态';
            return $this->response()->error($msg)->refresh();
        }

        //判断数组中是否存在下标
        if (!array_key_exists($ticketState, $ConfigTicketState)) {
            return $this->response()->error('未知状态')->refresh();
        }

        $postData['service'] = $ConfigTicketState[$ticketState];
        $postData['ologNo']  = $postData['logNo'];

        //退业务
        $res = Wo::ticketBack($postData, $model->user);

        if (is_string($res)) {
            return $this->response()->error($res)->refresh();
        }

        return $this->response()->success($res)->refresh();
    }

    public function dialog()
    {
        $this->confirm('确定要退订吗？');
    }
}
