<?php

namespace app\api\controller\script;

use app\admin\model\Device;
use app\common\controller\Api;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }

    // 保存编号
    public function saveNumber()
    {
        try {
            if ($this->request->isPost()) {
                $number = $this->request->post('number');
                $row = Device::where('number', $number)->find();
                if ($row) {
                    $this->error('编号已存在');
                } else {
                    $data['number'] = $number;
                    $data['createtime'] = time();
                    $data['updatetime'] = time();
                    $res = Device::insertGetId($data);
                }
                if ($res) {
                    $this->success('保存成功', ['id' => $res]);
                } else {
                    $this->error('保存失败');
                }
            }
        } catch (ValidateException $e) {
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            $this->error($e->getMessage());
        }
    }

    // 获取任务状态
    public function getTaskStatus()
    {
        try {
            $number = $this->request->post('number');
            if (!$number) $this->error('编号不能为空');
            $row = Device::where('number', $number)->find();
            if ($row) {
                $this->success('获取成功', ['status' => $row['status']]);
            }
            $this->error('获取失败');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }
}
