<?php

namespace app\admin\controller;

use think\App;
use app\model\project\AdvertCate as AdvertCateModel;
use think\facade\Validate;

class AdvertCate extends AdminBase
{
    protected $advertcate;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->advertcate = new AdvertCateModel();
    }

    //广告列表
    public function index(string $do = '')
    {
        $limit = 10;
        if ($do == 'json') {

            $post = input();
            $post['limit'] = isset($post['limit']) ? $post['limit'] : $limit;
            $map[] = ['is_del', '=', 0];
            if (isset($post['kw']) && !empty($post['kw'])) {
                $map[] = ['name', 'like', '%' . $post['kw'] . '%'];
            }

            $list = $this->advertcate->where($map)->paginate($post['limit']);
            return $this->returnMsg($list);
        }

        $this->assign('limit', $limit);
        return $this->fetch('', '', false);
    }

    //快速编辑
    public function editup()
    {
        $post = input();
        $result = $this->advertcate->update([$post['af'] => $post['av']], [['id', '=', $post['id']]]);
        if ($result) {
            return $this->returnMsg('修改成功', 1);
        } else {
            return $this->returnMsg('修改失败');
        }
    }
    //编辑新增广告
    public function edit()
    {
        $post = input();
        if ($this->request->isPost()) {

            $validate = Validate::rule([
                'name'  => 'require'
            ])->message([
                'name.require' => '名称不能为空',
            ]);

            if(!$validate->check($post)) {
                return $this->returnMsg($validate->getError(), 0);
            }
            try {
                if ($post['id'] > 0) {
                    $msg = '更新成功';
                    $this->advertcate->update($post, ['id' => $post['id']]);
                } else {
                    $post['create_time'] = time();
                    unset($post['id']);
                    $msg = '添加成功';
                    $this->advertcate->save($post);
                }
            } catch (\Exception $e) {

                return $this->returnMsg($e->getMessage(), 0);
            }
            return $this->returnMsg($msg, 1);

        }
        $data = $this->advertcate->find($post['id']);

        $this->assign('data', $data);
        return $this->fetch('', '', false);
    }

    public function del()
    {
        $post = input();
        $ids = is_array($post['id']) ? implode(',', $post['id']) : $post['id'];
        if ($this->advertcate->where("id IN(" . $ids . ")")->update(['is_del' => 1])) {
            return $this->returnMsg("删除成功", 1);
        } else {
            return $this->returnMsg("删除失败");
        }
    }


}