<?php
/**
 * @package merchant
 *
 * @author xaboy
 * @day 2020-03-26
 *
 * 
 */

namespace app\common\repositories\system\config;


use app\common\dao\system\config\SystemContributionDao;
use app\common\repositories\BaseRepository;
use FormBuilder\Exception\FormBuilderException;
use FormBuilder\Factory\Elm;
use FormBuilder\Form;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Route;

/**
 * Class ConfigContributionRepository
 * @package crmeb\repositories\system\config
 * @mixin SystemContributionDao
 */
class ConfigContributionRepository extends BaseRepository
{

    /**
     * ConfigContributionRepository constructor.
     * @param SystemContributionDao $dao
     */
    public function __construct(SystemContributionDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author xaboy
     * @day 2020-03-31
     */
    public function lst()
    {
        $list = $this->dao->all();
        $count = $this->dao->count();

        return compact('list', 'count');
    }


    /**
     * @param int|null $id
     * @param array $formData
     * @return Form
     * @throws FormBuilderException
     * @author xaboy
     * @day 2020-03-31
     */
    public function form(?int $id = null, array $formData = []): Form
    {
        $form = Elm::createForm(is_null($id) ? Route::buildUrl('configContributionCreate')->build() : Route::buildUrl('configContributionUpdate', ['id' => $id])->build());
        $form->setRule([
            Elm::input('title', '范围名称')->required(),
            Elm::number('start', '范围开始')->required(),
            Elm::number('end', '范围结束')->required(),
            Elm::input('type', '类型')->required(),
            Elm::number('jd', '京豆')->required(),
            Elm::number('value', '贡献值')->required(),
        ]);

        return $form->setTitle(is_null($id) ? '添加' : '编辑')->formData($formData);
    }

    /**
     * @return Form
     * @throws FormBuilderException
     * @author xaboy
     * @day 2020-03-30
     */
    public function createForm()
    {
        return $this->form();
    }


    /**
     * @param $id
     * @return Form
     * @throws DataNotFoundException
     * @throws DbException
     * @throws FormBuilderException
     * @throws ModelNotFoundException
     * @author xaboy
     * @day 2020-03-31
     */
    public function updateForm($id)
    {
        return $this->form($id, $this->dao->get($id)->toArray());
    }
}