<?php

namespace app\admin\controller\device;

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

class DeviceController extends Curd
{
    public function __construct()
    {
        $this->model = new Device();
        $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');
        $type = $request->get('type', '');
        $field = $field ?? 'device_addtimes';
        if ($type == 'bind') {
            $where['device_status'] = 'ACTIVED';
        }
        $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->with([
            'ledger' => function ($query) {
                $query->select('device_ledger_id', 'device_ledger_name');
            }
        ]);
        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 afterQuery($items)
    {
        foreach ($items as &$item) {
            $deviceConfigJson = json_decode($item['device_config_json'], true);
            $item['dept_name'] = $deviceConfigJson['dept_name'] ?? '';
        }

        return $items;
    }

    /* 设备列表（下拉选项）*/
    public function selectList()
    {
        $class = get_class($this->model);
        $data = $class::whereIn('device_status', ['PROCESSING', 'PENDING'])
            ->select('device_id', 'device_name', 'device_src_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);
            dump($data);
            $this->doInsert($data);
        } catch (BusinessException $customException) {
            return json_fail($customException->getMessage());
        } catch (\Exception $e) {
            dump($e->getMessage());
            return json_fail('数据写入失败');
        }

        _syslog("添加设备", "设备名称【" . $request->post('device_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('device_name') . '】');

        return json_success('success');
    }

    protected function insertInput(Request $request): array
    {
        $data = $this->inputFilter($request->post());
        $data['device_id'] = $this->generateDeviceId();
        return $data;
    }

    /**
     * @Desc 生成设备ID
     * @Author Gorden
     * @Date 2024/3/26 13:32
     *
     * @return string
     * @throws \support\exception\BusinessException
     */
    private function generateDeviceId()
    {
        $id = SysSerial::getSerial();

        return "DE" . str_pad($id, 16, '0', STR_PAD_LEFT) . random_string(6, 'up');
    }

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

        if (Device::whereIn('device_id', $ids)->where('device_status', '<>', 'WAITING')->exists()) {
            return json_fail('只有库存状态的设备可以删除');
        }

        $devices = Device::whereIn('device_id', $ids)->get()->toArray();

        $this->doDelete($ids);

        _syslog("删除设备", "删除的设备ID【" . implode(',', $ids) . '】', $devices);

        return json_success('success');
    }

    /**
     * @Desc 获取所有的打印机
     * @Author Gorden
     * @Date 2024/12/18 15:19
     *
     * @return Response
     */
    public function getAllPrinter()
    {
        $printers = Device::where('device_type', 'PRINTER')
            ->where('device_status', 'ACTIVED')
            ->select('device_id', 'device_name', 'device_config_json')
            ->get()
            ->toArray();
        $data = [];
        foreach ($printers as $printer) {
            if (empty($printer['device_config_json'])) {
                continue;
            }
            $deviceConfigJson = json_decode($printer['device_config_json'], true);
            $data[] = [
                'device_id' => $printer['device_id'],
                'device_name' => (isset($deviceConfigJson['dept_name']) ? $deviceConfigJson['dept_name'] . '-' : '') . $printer['device_name']
            ];
        }

        return json_success('success', $data);
    }
}