<?php

namespace app\admin\controller\device;

use app\admin\validate\device\DeviceValidate;
use app\controller\Curd;
use app\model\Device;
use app\model\Metadata;
use app\model\SysSerial;
use support\exception\BusinessException;
use support\Request;
use support\Response;

class MetadataController extends Curd
{
    public function __construct()
    {
        $this->model = new Metadata();
//        $this->validate = true;
//        $this->validateClass = new DeviceValidate();
    }

    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $order = $request->get('order', 'desc');
        $field = $field ?? 'metadata_addtimes';
        $query = $this->doSelect($where, $field, $order);
        return $this->doFormat($query, $format, $limit);
    }

    protected function doSelect(array $where, string $field = null, string $order = 'desc')
    {
        $model = $this->model;
        foreach ($where as $column => $value) {
            if (is_array($value)) {
                if ($value[0] === 'like' || $value[0] === 'not like') {
                    $model = $model->where($column, $value[0], "%$value[1]%");
                } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
                    $model = $model->where($column, $value[0], $value[1]);
                } elseif ($value[0] == 'in' && !empty($value[1])) {
                    $valArr = $value[1];
                    if (is_string($value[1])) {
                        $valArr = explode(",", trim($value[1]));
                    }
                    $model = $model->whereIn($column, $valArr);
                } elseif ($value[0] == 'not in' && !empty($value[1])) {
                    $valArr = $value[1];
                    if (is_string($value[1])) {
                        $valArr = explode(",", trim($value[1]));
                    }
                    $model = $model->whereNotIn($column, $valArr);
                } elseif ($value[0] == 'null') {
                    $model = $model->whereNull($column);
                } elseif ($value[0] == 'not null') {
                    $model = $model->whereNotNull($column);
                } elseif ($value[0] !== '' || $value[1] !== '') {
                    $model = $model->whereBetween($column, $value);
                }
            } else {
                $model = $model->where($column, $value);
            }
        }
        if ($field) {
            $model = $model->orderBy($field, $order);
        }
        return $model;
    }

    /* 设备列表（下拉选项）*/
    public function selectList()
    {
        $class = get_class($this->model);
        $data = $class::select('metadata_id', 'metadata_name', 'metadata_key')
            ->get()
            ->toArray();

        return json_success('', $data);
    }

    public function insert(Request $request): Response
    {
        if ($this->validate && !$this->validateClass->scene('add')->check($request->post())) {
            return json_fail($this->validateClass->getError());
        }

        try {
            $data = $this->insertInput($request);
            $this->doInsert($data);
        } catch (BusinessException $customException) {
            return json_fail($customException->getMessage());
        } catch (\Exception $e) {
            dump($e->getMessage());
            return json_fail('数据写入失败');
        }

        _syslog("添加元数据", "元数据名称【" . $request->post('metadata_name') . '】');

        return json_success('success');
    }

    public function update(Request $request): Response
    {
        if ($this->validate && !$this->validateClass->scene('update')->check($request->post())) {
            return json_fail($this->validateClass->getError());
        }

        try {
            [$id, $data] = $this->updateInput($request);
            $this->doUpdate($id, $data);
        } catch (BusinessException $e) {
            return json_fail($e->getMessage());
        } catch (\Exception $e) {
            dump($e->getTrace());
            return json_fail('数据更新失败');
        }

        _syslog("编辑元数据", "元数据名称【" . $request->post('metadata_name') . '】');

        return json_success('success');
    }

    public function delete(Request $request): Response
    {
        $ids = $this->deleteInput($request);

        $metas = Metadata::whereIn('metadata_id', $ids)->get()->toArray();

        $this->doDelete($ids);

        _syslog("删除元数据", "删除的元数据ID【" . implode(',', $ids) . '】', $metas);

        return json_success('success');
    }
}