<?php

namespace app\system\controller\v1;

use app\BaseController;
use app\model\system\ProductRule as ProductRuleModel;
use library\services\UtilService;
use think\Request;

/**
 * 规则管理
 * Class ProductRule
 * @package app\system\controller\v1
 */
class ProductRule extends BaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $where = UtilService::getMore([
            ['page', 1],
            ['limit', 15],
            ['rule_name','']
        ]);
//        if($this->merId){
//            $where['mer_id'] = $this->merId;
//        }
        $list = ProductRuleModel::sysPage($where);
        return app('json')->success($list);
    }

    /**
     * 保存新建的资源
     *
     * @param \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request,$id)
    {
        $data = UtilService::getMore([
            ['rule_name',''],
            ['spec',[]]
        ]);
        //$data['mer_id'] = $this->merId ?: '';
        if ($data['rule_name'] == '') return app('json')->fail('请输入规则名称');
        if (!$data['spec']) return app('json')->fail('缺少规则值');
        $data['rule_value'] = json_encode($data['spec']);
        unset($data['spec']);
        if ($id){
            $rule = ProductRuleModel::get($id);
            if (!$rule) return app('json')->fail('数据不存在');
            ProductRuleModel::edit($data, $id);
            return app('json')->success('编辑成功!');
        }else{
            ProductRuleModel::create($data);
            return app('json')->success('规则添加成功!');
        }
    }

    /**
     * 显示指定的资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function read($id)
    {
        $info = ProductRuleModel::sysInfo($id);
        return app('json')->success($info);
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function delete()
    {
        $data = UtilService::getMore([
            ['ids','']
        ]);
        if ($data['ids']=='') return app('json')->fail('请至少选择一条数据');
        $ids = strval($data['ids']);
        $res = ProductRuleModel::whereIn('id',$ids)->delete();
        if (!$res)
            return app('json')->fail(ProductRuleModel::getErrorInfo('删除失败,请稍候再试!'));
        else
            return app('json')->success('删除成功!');
    }
}
