<?php

namespace app\admin\controller\device;

use app\admin\validate\device\LedgerValidate;
use app\controller\Curd;
use app\model\DeviceLedger;
use support\exception\BusinessException;
use support\Request;
use support\Response;

class LedgerController extends Curd
{
    public function __construct()
    {
        $this->model = new DeviceLedger();
        $this->validate = true;
        $this->validateClass = new LedgerValidate();
    }

    /**
     * @Desc 列表
     * @Author Gorden
     * @Date 2024/3/26 11:17
     *
     * @param Request $request
     * @return Response
     * @throws \support\exception\BusinessException
     */
    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $order = $request->get('order', 'desc');
        $field = $field ?? 'device_ledger_addtimes';
        $query = $this->doSelect($where, $field, $order);
        return $this->doFormat($query, $format, $limit);
    }

    public function selectList()
    {
        $class = get_class($this->model);
        $data = $class::where('device_ledger_status', 'ACTIVED')
            ->select('device_ledger_id', 'device_ledger_name')
            ->get()
            ->toArray();

        return json_success('', $data);
    }

    protected function afterQuery($items)
    {
        foreach ($items as &$item){
            if (!empty($item->device_ledger_metadata_json)){
                $item->meta_data = json_decode($item->device_ledger_metadata_json);
            }
        }

        return $items;
    }

    protected function insertInput(Request $request): array
    {
        $data = $this->inputFilter($request->post());

        $data['device_ledger_metadata_json'] = $request->post('meta_data','[]');

        return $data;
    }

    protected function updateInput(Request $request): array
    {
        //meta_data
        $primary_key = $this->model->getKeyName();
        $id = $request->post($primary_key);
        $data = $this->inputFilter($request->post());
        $data['device_ledger_metadata_json'] = $request->post('meta_data','[]');
        $model = $this->model->find($id);
        if (!$model) {
            throw new BusinessException('记录不存在', 2);
        }
        unset($data[$primary_key]);
        return [$id, $data];
    }
}