<?php

namespace app\controller\admin\system;

use app\BaseController;
use app\entity\SysDictionary;
use app\entity\SysDictionaryData;
use app\service\CurdService;
use think\db\exception\DbException;
use think\response\Json;

class DictionaryDataController extends BaseController
{
    public function add()
    {
        $data = $this->request->post([
            'dictId' => null,
            'dictDataCode' => null,
            'dictDataName' => null,
            'sortNumber' => 100,
            'comments' => ''
        ]);
        $sysDictionary = new SysDictionaryData();
        $sysDictionary->save([
            'dict_id' => $data['dictId'],
            'dict_data_code' => $data['dictDataCode'],
            'dict_data_name' => $data['dictDataName'],
            'sort_number' => $data['sortNumber'],
            'comments' => $data['comments']
        ]);
        return $this->writeSuccess('添加成功');
    }

    public function update()
    {
        $data = $this->request->put([
            'dictDataId' => 0,
            'dictId' => null,
            'dictDataCode' => null,
            'dictDataName' => null,
            'sortNumber' => 100,
            'comments' => ''
        ]);
        SysDictionaryData::findOrFail($data['dictDataId'])->save([
            'dict_id' => $data['dictId'],
            'dict_data_code' => $data['dictDataCode'],
            'dict_data_name' => $data['dictDataName'],
            'sort_number' => $data['sortNumber'],
            'comments' => $data['comments']
        ]);
        return $this->writeSuccess('修改成功');
    }

    public function batchRemove()
    {
        $data = $this->request->delete();
        SysDictionaryData::destroy($data);
        return $this->writeSuccess('删除成功');
    }

    public function lists(): Json
    {
        $dictCode = $this->request->param('dictCode/s', '');

        $data = SysDictionary::dictCodeData($dictCode);

        return $this->writeSuccess('success', $data);
    }

    /**
     * 查询字典集列表
     * @return Json
     * @throws DbException
     */
    public function page(): Json
    {
        $paginate = CurdService::getPaginate($this->request, SysDictionaryData::withSearch(['dictId', 'dictDataName', 'dictDataCode'], [
            'dictId'       => $this->request->get('dictId/d', 0),
            'dictDataName' => $this->request->get('dictDataName/s', ''),
            'dictDataCode' => $this->request->get('dictDataCode/s', ''),
        ]));

        return $this->writeSuccess('success', $paginate);
    }
}