<?php

namespace app\admin\controller\bbfxshop\merchant;

use app\admin\controller\bbfxshop\Base;
use think\Db;
use app\common\model\bbfxshop\Goods as GoodsModel;


class MerchantCategory extends Base
{
    public function getList(){
        $params = $this->param();
        $pindex = max(1, intval($params["page"]));
        $psize = intval($params["limit"])?intval($params["limit"]):20;
        $mid = $this->param("mid/d");
        $keyword = $this->param("keyword/s");
        
        $where = ['uniacid'=>UNIACID];
        if(!empty($keyword)){
            $where['name'] = ['like','%'.$keyword.'%'];
        }
        
        $list = Db::name("bbfx_merchant_category")->where($where)->order("sort desc")->limit(($pindex-1)*$psize,$psize)->select();
        
        foreach ($list as $key => &$val){
            $val['image'] = cdnurl($val['image']);
        }
        unset($val);
        
        $total = Db::name("bbfx_merchant_category")->where($where)->count();
        
        __success("操作成功",['list'=>$list,'total'=>$total]);
    }
    
    public function all(){
        $params = $this->param();
        $where = ['uniacid'=>UNIACID];
        
        $list = Db::name("bbfx_merchant_category")->where($where)->order("sort desc")->select();
        
        foreach ($list as $key => &$val){
            $val['image'] = cdnurl($val['image']);
        }
        unset($val);
        
        
        __success("操作成功",['list'=>$list]);
    }
    
    public function detail(){
        $id = $this->param("id/d");
        $item = Db::name("bbfx_merchant_category")->where(['id'=>$id])->find();
        if(empty($item)){
            __error("数据不存在");
        }
        
        $item['image'] = cdnurl($item['image']);
        
        __success("操作成功",['info'=>$item]);
    }
    
    public function post(){
        $params = $this->param(['name/s','image/s','sort/d']);
        $id = $this->param("id/d");
        
        if(empty($params['name'])){
            __error("请输入分类名称");
        }
        if(empty($params['image'])){
            __error("请上传分类图片");
        }
        
        $item = Db::name("bbfx_merchant_category")->where(['id'=>$id])->find();
        
        $data = [
            "uniacid"=>UNIACID,
            "name"=>$params['name'],
            "image"=>replaceSiteroot($params['image']),
            "sort"=>$params['sort'],
        ];
        
        if(empty($item)){
            $res = Db::name("bbfx_merchant_category")->insert($data);
        }
        else{
            $res = Db::name("bbfx_merchant_category")->where(['id'=>$item['id']])->update($data);
        }
        
        if($res){
            __success("操作成功");
        }
        else{
            __error("操作失败");
        }
    }
    
    public function delete(){
        $this->commonDelete("bbfx_merchant_category");
    }
}