Goods.php 11.2 KB
<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;

/**
 * 商品管理
 *
 * @icon fa fa-circle-o
 */
class Goods extends Backend
{
    
    /**
     * Goods模型对象
     * @var \app\admin\model\Goods
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Goods;
        $this->view->assign("issaleList", $this->model->getIssaleList());
        $this->view->assign("ismemberList", $this->model->getIsmemberList());
        $this->view->assign("ishotList", $this->model->getIshotList());
        $this->view->assign("ismakeList", $this->model->getIsmakeList());
        $this->view->assign("specTypeList", $this->model->getSpecTypeList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage,则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','goods_images','goods_name','issale','ismember','ishot','ismake','spec_type','updatetime','weigh']);
                
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    // 添加规格数据
                    $goods_spec = new \app\admin\model\GoodsSpec;
                    if ($params['spec_type'] == '1') {
                        // 单规格
                        $this->model->spec()->save($params['spec']);
                    } else if ($params['spec_type'] == '2') {
                        $spec_many = json_decode($params['spec_many'],true);
                        // 添加商品与规格关系记录
                        $goods_spec->addGoodsSpecRel($this->model['id'], $spec_many['spec_attr']);
                        // 添加商品sku
                        $goods_spec->addSkuList($this->model['id'], $spec_many['goods_spec_list']);
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    // 更新模式: 先删除所有规格
                    $goods_spec = new \app\admin\model\GoodsSpec;
                    $goods_spec->removeAll($row['id']);
                    // 添加规格数据
                    if ($params['spec_type'] == '1') {
                        // 单规格
                        $row->spec()->save($params['spec']);
                    } else if ($params['spec_type'] == '2') {
                        $spec_many = json_decode($params['spec_many'],true);
                        // 添加商品与规格关系记录
                        $goods_spec->addGoodsSpecRel($row['id'], $spec_many['spec_attr']);
                        // 添加商品sku
                        $goods_spec->addSkuList($row['id'], $spec_many['goods_spec_list']);
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        $this->assignconfig('specData', $row['spec_type'] == '2' ? $row->getManySpecData($row['spec_rel'], $row['spec']) : null);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    (new \app\admin\model\GoodsSpec)->removeAll($v['id']);
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 模特款
     */
    public function style($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $goods_style = new \app\common\model\GoodsStyle;
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if(empty($params['goods_style'])){
                    $this->error(__('该模板下无规格选项,请在【规格模板管理】里为其添加规格'));
                }
                $params['goods_style'] = json_encode($params['goods_style']);
                $params['goods_id'] = $ids;
                try {
                    $goods_style->where(['goods_id'=>$ids])->delete();
                    $result = $goods_style->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $style_template_list = \app\admin\model\StyleTemplate::where('type','style')->field('id,name')->select();
        $goods_style = $goods_style->get(['goods_id'=>$ids]);
        $this->view->assign('style_template_list',$style_template_list);
        $this->view->assign('goods_style',$goods_style);
        $this->assignconfig('goods_style',!empty($goods_style['goods_style']) ? json_decode($goods_style['goods_style'],true) : []);
        return $this->view->fetch();
    }

    /**
     * 正常显示规格
     */
    public function styleList()
    {
        $style_template_id = $this->request->request('style_template_id');
        $list = \app\common\model\Style::styleList($style_template_id);
        $this->success(__('成功'),null,compact('list'));
    }
}