<?php

namespace app\admin\controller;

use app\BaseController;

use app\admin\model\Banner as BannerModel;
use Exception;
use think\facade\Db;

class Banner extends BaseController
{

    /**
     * 删除轮播
     */
    function delete()
    {
        Db::startTrans();
        try {
            $id = $this->request->param('id');
            $banner = BannerModel::findOrFail($id);
            $banner->delete();
            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }
        return $this->success();
    }

    /**
     * 编辑轮播
     */
    function update()
    {
        $errors = [];
        Db::startTrans();
        try {
            $params = $this->request->param();
            $params['id'] = $this->request->param('id', 0);
            $id = $params['id'];
            unset($params['id']);
            $params['link'] = isset($params['link']) ? $params['link'] : '';
            $params['remarks'] = isset($params['remarks']) ? $params['remarks'] : '';
            $params['img_url'] = replacePartInUrl($params['img_url']);
            if ($id > 0) {
                BannerModel::where('id', $id)->update($params);
            } else {
                BannerModel::create($params);
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollBack();
            return $this->error($e->getMessage(), $errors);
        }
        return $this->success();
    }

    /**
     * 首页轮播
     */
    public function index()
    {
        try {
            $page = $this->request->param('page', 1);
            $limit = $this->request->param('limit', 15);
            $count = BannerModel::count();
            $list = BannerModel::limit($limit)
                ->page($page)
                ->order('sort','asc')
                ->select()->toArray();

        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success(['count' => $count, 'list' => $list]);
    }
}