afa 9 сар өмнө
parent
commit
38f61e0dde

+ 6 - 1
application/admin/controller/Ajax.php

@@ -302,9 +302,11 @@ class Ajax extends Backend
         if (!empty($params)) {
             $province = isset($params['province']) ? $params['province'] : null;
             $city = isset($params['city']) ? $params['city'] : null;
+            $area = isset($params['area']) ? $params['area'] : null;
         } else {
             $province = $this->request->get('province');
             $city = $this->request->get('city');
+            $area = $this->request->get('area');
         }
         $where = ['parent_id' => 0, 'level' => 1];
         $provincelist = null;
@@ -315,8 +317,11 @@ class Ajax extends Backend
                 $where['parent_id'] = $city;
                 $where['level'] = 3;
             }
+            if ($area !== null) {
+                $where['parent_id'] = $area;
+                $where['level'] = 4;
+            }
         }
-        //dump($where);die;
         $provincelist = Db::name('region')->where($where)->field('id as value,name')->select();
         $this->success('', '', $provincelist);
     }

+ 208 - 0
application/admin/controller/product/Areas.php

@@ -0,0 +1,208 @@
+<?php
+
+namespace app\admin\controller\product;
+
+use app\common\controller\Backend;
+use Exception;
+use think\Db;
+use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
+use PhpOffice\PhpSpreadsheet\Reader\Xls;
+use app\admin\model\Importregion;
+use app\admin\model\Importlog;
+use think\exception\DbException;
+use think\exception\PDOException;
+use think\exception\ValidateException;
+/**
+ * 商品地区
+ *
+ * @icon fa fa-circle-o
+ */
+class Areas extends Backend
+{
+
+    /**
+     * Areas模型对象
+     * @var \app\common\model\ProductArea
+     */
+    protected $model = null;
+
+    public function _initialize()
+    {
+        parent::_initialize();
+        $this->model = new \app\common\model\ProductArea;
+        $this->assignconfig('ids', $this->request->param('ids'));
+    }
+
+
+
+    /**
+     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
+     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
+     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
+     */
+    public function index()
+    {
+        //设置过滤方法
+        $this->request->filter(['strip_tags', 'trim']);
+        if (false === $this->request->isAjax()) {
+            return $this->view->fetch();
+        }
+        //如果发送的来源是 Selectpage,则转发到 Selectpage
+        if ($this->request->request('keyField')) {
+            return $this->selectpage();
+        }
+        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
+        $product_id = $this->request->param('ids');
+        $list = $this->model//->with('products')
+            ->where($where)->where('product_id', $product_id)
+            ->order($sort, $order)
+            ->paginate($limit);
+        $result = ['total' => $list->total(), 'rows' => $list->items()];
+        return json($result);
+    }
+
+        
+    /**
+     * 添加
+     *
+     * @return string
+     * @throws \think\Exception
+     */
+    public function add()
+    {
+        if (false === $this->request->isPost()) {
+            return $this->view->fetch();
+        }
+        $params = $this->request->post('row/a');
+        if (empty($params) || empty($params['province'])) {
+            $this->error(__('Parameter %s can not be empty', ''));
+        }
+        $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()->validate($validate);
+            }
+            $params['product_id'] = $this->request->param('ids');
+            if($this->model::where('product_id', $params['product_id'])->where('address', $params['address'])->count() > 0) throw new ValidateException('商品关联区域已存在');
+            $result = $this->model->allowField(true)->save($params);
+            Db::commit();
+        } catch (ValidateException|PDOException|Exception $e) {
+            Db::rollback();
+            $this->error($e->getMessage());
+        }
+        if ($result === false) {
+            $this->error(__('No rows were inserted'));
+        }
+        $this->success();
+    }
+
+
+    /**
+     * 导入产品地区
+     * @param $ids
+     * @return string
+     * @throws DbException
+     * @throws \think\Exception
+     */
+    public function exports(Importregion $importregion, Importlog $Importlog){
+        if (false === $this->request->isPost()) { 
+            $this->assignconfig('areaData', []);
+            return $this->view->fetch();
+        }
+        $params = $this->request->post('row/a');
+        if (empty($params)) {
+            $this->error(__('Parameter %s can not be empty', ''));
+        }
+        $params = $this->preExcludeFields($params);
+        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
+            $params[$this->dataLimitField] = $this->auth->id;
+        }
+        $params['product_id'] = $this->request->param('ids');
+        $file = $params['export'];
+        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
+        if (!is_file($filePath)) {
+            $this->error(__('No results were found'));
+        }
+        //实例化reader
+        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
+        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
+            $this->error(__('Unknown data format'));
+        }
+        $reader = ($ext === 'xls')? new Xls(): new Xlsx();
+        $result = false;
+        Db::startTrans();
+        try {
+            if (!$PHPExcel = $reader->load($filePath)) {
+                $this->error(__('Unknown data format'));
+            }
+            $PHPExcel = $reader->load($filePath);
+            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
+            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
+            //读取第二行字段名
+            $data = [];
+            $fields = [];
+            $k = 0;
+            $i = 0;
+            $time = time();
+            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
+                $values = [];
+                //列字段
+                for ($currentColumn = 2999; $currentColumn <= 5; $currentColumn++) {
+                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
+                    $values[] = is_null($val) ? '' : $val;
+                }
+                if(empty($values[0])) continue;
+                $field =  implode('-', $values);
+                $row = $importregion::where('name', $field)->find();
+                if(!empty($row)){
+                        if($this->model::where('product_id',$params['product_id'])->where('address',$row['name'])->count() > 0) continue;
+                        $data = self::importData($data, $k, $params['product_id'], $row->com_id, $time);
+                        $data[$k]['address']     = $row['name'];
+                        $k +=1;
+                }else{
+                        $fields = self::importData($fields, $i, $params['product_id'], $field, $time);
+                        $i += 1;
+                }
+            }
+            if(!empty($data)) $result= $this->model::insertAll($data);
+            //错误日志
+            if(!empty($fields)) $Importlog::insertAll($fields);
+            Db::commit();
+        } catch (ValidateException|PDOException|Exception $e) {
+            Db::rollback();
+            $this->error($e->getMessage());
+        }
+        if ($result === false) {
+            $this->error(__('No rows were inserted'));
+        }
+        $this->success();
+
+    }
+
+
+
+     /**
+     * 导入数据
+     * @return array
+     */
+    private static function importData(array $data, int $k, int $product_id, string $ids,  $time): array
+    {   
+        //$data = array();
+        $arr = explode('-', $ids); //分割ID
+        $data[$k]['product_id']  = $product_id;
+        $data[$k]['province']    = $arr[0]??0;
+        $data[$k]['city']        = $arr[1]??0 ; 
+        $data[$k]['area']        = $arr[2]??0;
+        $data[$k]['county']      = $arr[3]??0;
+        $data[$k]['create_time'] = $time;
+        return $data;
+    }
+}

+ 17 - 117
application/admin/controller/product/Lists.php

@@ -5,15 +5,9 @@ namespace app\admin\controller\product;
 use app\common\controller\Backend;
 use Exception;
 use think\Db;
-use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
-use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
-use PhpOffice\PhpSpreadsheet\Reader\Xls;
-use PhpOffice\PhpSpreadsheet\Reader\Csv;
 use app\common\model\ProductArea;
 use think\exception\DbException;
 use think\exception\PDOException;
-use app\admin\model\Importregion;
-use app\admin\model\Importlog;
 use think\exception\ValidateException;
 
 /**
@@ -102,13 +96,15 @@ class Lists extends Backend
                 $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                 $this->model->validateFailException()->validate($validate);
             }
-            $areaArr    = json_decode($params['product_area'], true);
-            $areaArrTxt = json_decode($params['product_area_txt'], true);
-            if(empty($areaArr) || empty($areaArrTxt)) throw new ValidateException('请添加商品关联地区');
+            if(!empty($params['is_area'])){
+                $areaArr    = json_decode($params['product_area'], true);
+                $areaArrTxt = json_decode($params['product_area_txt'], true);
+                if(empty($areaArr) || empty($areaArrTxt)) throw new ValidateException('请添加商品关联区域');
+            }
             unset($params['product_area'], $params['product_area_txt']);
             //商品
-            $add   = $this->model->create($params);
-            $result= self::setEqualArea($add->id, $areaArr, $areaArrTxt, 0);
+            $result   = $this->model->create($params);
+            if(!empty($params['is_area'])) $result= self::setEqualArea($result->id, $areaArr, $areaArrTxt, 0);
             Db::commit();
         } catch (ValidateException|PDOException|Exception $e) {
             Db::rollback();
@@ -162,9 +158,9 @@ class Lists extends Backend
                 $areaTxt[]  = [$item->address];
             }
             $this->assignconfig('areaData', json_encode($areaData));
-            $this->view->assign('row', $row);
             $this->view->assign('areaTxt', json_encode($areaTxt, JSON_UNESCAPED_UNICODE));
             $this->view->assign('areaCode', json_encode($areaCode));
+            $this->view->assign('row', $row);
             return $this->view->fetch();
         }
         $params = $this->request->post('row/a');
@@ -181,14 +177,15 @@ class Lists extends Backend
                 $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                 $row->validateFailException()->validate($validate);
             }
-            
-            $areaArr    = json_decode($params['product_area'], true);
-            $areaArrTxt = json_decode($params['product_area_txt'], true);
-            if(empty($areaArr) || empty($areaArrTxt)) throw new ValidateException('请添加商品关联地区');
+            if(!empty($params['is_area'])){
+                $areaArr    = json_decode($params['product_area'], true);
+                $areaArrTxt = json_decode($params['product_area_txt'], true);
+                if(empty($areaArr) || empty($areaArrTxt)) throw new ValidateException('请添加商品关联区域');
+            }
             unset($params['product_area'], $params['product_area_txt']);
-            $row->allowField(true)->save($params);
-            //$this->productArea::where('product_id', $ids)->where('status', 1)->delete();
-            $result= self::setEqualArea($ids, $areaArr, $areaArrTxt, 1);
+            $result=$row->allowField(true)->save($params);
+            //更新地区
+            if(!empty($params['is_area'])) $result= self::setEqualArea($ids, $areaArr, $areaArrTxt, 1);
             Db::commit();
         } catch (ValidateException|PDOException|Exception $e) {
             Db::rollback();
@@ -200,104 +197,7 @@ class Lists extends Backend
         $this->success();
     }
 
-    /**
-     * 导入产品地区
-     * @param $ids
-     * @return string
-     * @throws DbException
-     * @throws \think\Exception
-     */
-    public function exports(Importregion $importregion, Importlog $Importlog){
-        if (false === $this->request->isPost()) { 
-            $this->assignconfig('areaData', []);
-            return $this->view->fetch();
-        }
-        $params = $this->request->post('row/a');
-        if (empty($params)) {
-            $this->error(__('Parameter %s can not be empty', ''));
-        }
-        $params = $this->preExcludeFields($params);
-        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
-            $params[$this->dataLimitField] = $this->auth->id;
-        }
-        $file = $params['export'];
-        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
-        if (!is_file($filePath)) {
-            $this->error(__('No results were found'));
-        }
-        //实例化reader
-        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
-        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
-            $this->error(__('Unknown data format'));
-        }
-        $reader = ($ext === 'xls')? new Xls(): new Xlsx();
-        $result = false;
-        Db::startTrans();
-        try {
-            if (!$PHPExcel = $reader->load($filePath)) {
-                $this->error(__('Unknown data format'));
-            }
-            $PHPExcel = $reader->load($filePath);
-            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
-            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
-            //读取第二行字段名
-            $data = [];
-            $fields = [];
-            $k = 0;
-            $i = 0;
-            $time = time();
-            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
-                $values = [];
-                //列字段
-                for ($currentColumn = 2; $currentColumn <= 5; $currentColumn++) {
-                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
-                    $values[] = is_null($val) ? '' : $val;
-                }
-                if(empty(array_filter($values))) continue;
-                $field =  implode('-', $values);
-                $row = $importregion::where('name', $field)->find();
-                if(!empty($row)){
-                        if($this->productArea::where('product_id',$params['product_id'])->where('address',$row['name'])->count() > 0) continue;
-                        $data = self::importData($data, $k, $params['product_id'], $row->com_id, $time);
-                        $data[$k]['address']     = $row['name'];
-                        $k +=1;
-                }else{
-                        $fields = self::importData($fields, $i, $params['product_id'], $field, $time);
-                        $i += 1;
-                }
-            }
-            if(!empty($data)) $result= $this->productArea::insertAll($data);
-            //错误日志
-            if(!empty($fields)) $Importlog::insertAll($fields);
-            Db::commit();
-        } catch (ValidateException|PDOException|Exception $e) {
-            Db::rollback();
-            $this->error($e->getMessage());
-        }
-        if ($result === false) {
-            $this->error(__('No rows were inserted'));
-        }
-        $this->success();
-
-    }
-
-
-     /**
-     * 导入数据
-     * @return array
-     */
-    private static function importData(array $data, int $k, int $product_id, string $ids,  $time): array
-    {   
-        //$data = array();
-        $arr = explode('-', $ids); //分割ID
-        $data[$k]['product_id']  = $product_id;
-        $data[$k]['province']    = $arr[0]??0;
-        $data[$k]['city']        = $arr[1]??0 ; 
-        $data[$k]['area']        = $arr[2]??0;
-        $data[$k]['county']      = $arr[3]??0;
-        $data[$k]['create_time'] = $time;
-        return $data;
-    }
+ 
 
 
     //判断是否存在相同元素

+ 13 - 0
application/admin/lang/zh-cn/product/areas.php

@@ -0,0 +1,13 @@
+<?php
+
+return [
+    'Product_id'  => '产品Id',
+    'Province'    => '省份Id',
+    'City'        => '城市Id',
+    'Area'        => '区域Id',
+    'County'      => '街道Id',
+    'Status'      => '状态',
+    'Address'     => '地址描述',
+    'Create_time' => '创建时间',
+    'Update_time' => '更新时间'
+];

+ 25 - 0
application/admin/view/product/areas/add.html

@@ -0,0 +1,25 @@
+<form id="add-form"  role="form" data-toggle="validator" method="POST" action="">
+    <div class="form-horizontal">
+    <br/>
+    <div class="form-group">
+        <label class="control-label col-xs-12 col-sm-3">{:__('关联区域')}:</label>
+        <div class="col-xs-12 col-sm-8">
+            <div class="form-inline" data-toggle="cxselect" data-selects="province,city,area,county">
+                <select class="province form-control" name="row[province]" data-url="ajax/area"></select>
+                <select class="city form-control" name="row[city]" data-url="ajax/area"></select>
+                <select class="area form-control" name="row[area]" data-url="ajax/area"></select>
+                <select class="county form-control" name="row[county]" data-url="ajax/area"></select>
+                <input type="hidden"  id="c-address" name="row[address]" class="form-control" value="1" > 
+            </div>
+        </div>
+    </div>
+
+    <div class="form-group layer-footer">
+        <label class="control-label col-xs-12 col-sm-2"></label>
+        <div class="col-xs-12 col-sm-8">
+            <button type="submit" class="btn btn-primary btn-embossed disabled">{:__('OK')}</button>
+            <button type="reset" class="btn btn-default btn-embossed">{:__('Reset')}</button>
+        </div>
+    </div>
+</div>
+</form>

+ 64 - 0
application/admin/view/product/areas/edit.html

@@ -0,0 +1,64 @@
+<form id="edit-form" class="form-horizontal" role="form" data-toggle="validator" method="POST" action="">
+
+    <div class="form-group">
+        <label class="control-label col-xs-12 col-sm-2">{:__('Product_id')}:</label>
+        <div class="col-xs-12 col-sm-8">
+            <input id="c-product_id" data-rule="required" data-source="product/index" class="form-control selectpage" name="row[product_id]" type="text" value="{$row.product_id|htmlentities}">
+        </div>
+    </div>
+    <div class="form-group">
+        <label class="control-label col-xs-12 col-sm-2">{:__('Province')}:</label>
+        <div class="col-xs-12 col-sm-8">
+            <input id="c-province" data-rule="required" class="form-control" name="row[province]" type="number" value="{$row.province|htmlentities}">
+        </div>
+    </div>
+    <div class="form-group">
+        <label class="control-label col-xs-12 col-sm-2">{:__('City')}:</label>
+        <div class="col-xs-12 col-sm-8">
+            <input id="c-city" data-rule="required" class="form-control" name="row[city]" type="number" value="{$row.city|htmlentities}">
+        </div>
+    </div>
+    <div class="form-group">
+        <label class="control-label col-xs-12 col-sm-2">{:__('Area')}:</label>
+        <div class="col-xs-12 col-sm-8">
+            <input id="c-area" data-rule="required" class="form-control" name="row[area]" type="number" value="{$row.area|htmlentities}">
+        </div>
+    </div>
+    <div class="form-group">
+        <label class="control-label col-xs-12 col-sm-2">{:__('County')}:</label>
+        <div class="col-xs-12 col-sm-8">
+            <input id="c-county" data-rule="required" class="form-control" name="row[county]" type="number" value="{$row.county|htmlentities}">
+        </div>
+    </div>
+    <div class="form-group">
+        <label class="control-label col-xs-12 col-sm-2">{:__('Status')}:</label>
+        <div class="col-xs-12 col-sm-8">
+            <input id="c-status" data-rule="required" class="form-control" name="row[status]" type="number" value="{$row.status|htmlentities}">
+        </div>
+    </div>
+    <div class="form-group">
+        <label class="control-label col-xs-12 col-sm-2">{:__('Address')}:</label>
+        <div class="col-xs-12 col-sm-8">
+            <input id="c-address" class="form-control" name="row[address]" type="text" value="{$row.address|htmlentities}">
+        </div>
+    </div>
+    <div class="form-group">
+        <label class="control-label col-xs-12 col-sm-2">{:__('Create_time')}:</label>
+        <div class="col-xs-12 col-sm-8">
+            <input id="c-create_time" data-rule="required" class="form-control datetimepicker" data-date-format="YYYY-MM-DD HH:mm:ss" data-use-current="true" name="row[create_time]" type="text" value="{:$row.create_time?datetime($row.create_time):''}">
+        </div>
+    </div>
+    <div class="form-group">
+        <label class="control-label col-xs-12 col-sm-2">{:__('Update_time')}:</label>
+        <div class="col-xs-12 col-sm-8">
+            <input id="c-update_time" data-rule="required" class="form-control datetimepicker" data-date-format="YYYY-MM-DD HH:mm:ss" data-use-current="true" name="row[update_time]" type="text" value="{:$row.update_time?datetime($row.update_time):''}">
+        </div>
+    </div>
+    <div class="form-group layer-footer">
+        <label class="control-label col-xs-12 col-sm-2"></label>
+        <div class="col-xs-12 col-sm-8">
+            <button type="submit" class="btn btn-primary btn-embossed disabled">{:__('OK')}</button>
+            <button type="reset" class="btn btn-default btn-embossed">{:__('Reset')}</button>
+        </div>
+    </div>
+</form>

+ 2 - 8
application/admin/view/product/lists/exports.html → application/admin/view/product/areas/exports.html

@@ -1,13 +1,7 @@
 <form id="edit-form" role="form" data-toggle="validator" method="POST" action="">
 
-    <div class="form-horizontal">
-    <div class="form-group">
-        <label class="control-label col-xs-12 col-sm-2">{:__('产品')}:</label>
-        <div class="col-xs-12 col-sm-8">
-            <input id="c-product_id" data-rule="required" data-source="product/lists/index" data-field="zh_name" class="form-control selectpage" name="row[product_id]" type="text" value="{$row.product_id|htmlentities}">
-        </div>
-    </div>
-   
+
+    <div class="form-horizontal">   
     <div class="form-group">
         <label class="control-label col-xs-12 col-sm-2">{:__('导入文件')}:</label>
         <div class="col-xs-12 col-sm-8">

+ 26 - 0
application/admin/view/product/areas/index.html

@@ -0,0 +1,26 @@
+<div class="panel panel-default panel-intro">
+    {:build_heading()}
+
+    <div class="panel-body">
+        <div id="myTabContent" class="tab-content">
+            <div class="tab-pane fade active in" id="one">
+                <div class="widget-body no-padding">
+                    <div id="toolbar" class="toolbar">
+                        <a href="javascript:;" class="btn btn-primary btn-refresh" title="{:__('Refresh')}" ><i class="fa fa-refresh"></i> </a>
+                        <a href="javascript:;" class="btn btn-success btn-add {:$auth->check('product/areas/add')?'':'hide'}" title="{:__('Add')}" ><i class="fa fa-plus"></i> {:__('Add')}</a>
+                        <a href="javascript:;" class="btn btn-danger btn-del btn-disabled disabled {:$auth->check('product/areas/del')?'':'hide'}" title="{:__('Delete')}" ><i class="fa fa-trash"></i> {:__('Delete')}</a>
+                        <a href="javascript:;" class="btn btn-info btn-exports {:$auth->check('product/areas/exports')?'':'hide'}" title="{:__('import')}" id="btn-export-file"><i class="fa fa-download"></i> {:__('import')}</a>
+
+                        
+                    </div>
+                    <table id="table" class="table table-striped table-bordered table-hover table-nowrap"
+                           data-operate-edit="{:$auth->check('product/areas/edit')}"
+                           data-operate-del="{:$auth->check('product/areas/del')}"
+                           width="100%">
+                    </table>
+                </div>
+            </div>
+
+        </div>
+    </div>
+</div>

+ 11 - 7
application/admin/view/product/lists/add.html

@@ -1,16 +1,20 @@
 <form id="add-form"  role="form" data-toggle="validator" method="POST" action="">
-    <div class="form-horizontal"> 
+    <div class="form-horizontal">
+
     <div class="form-group">
         <label class="control-label col-xs-12 col-sm-2">{:__('Type_id')}:</label>
-        <div class="col-xs-12 col-sm-3">
+        <div class="col-xs-12 col-sm-2">
             <input id="c-type_id" data-rule="required" data-source="product/products/index" data-field="zh_title" class="form-control selectpage" name="row[type_id]" type="text" value="">
         </div>
-        <label class="control-label col-xs-12 col-sm-2">{:__('Weigh')}:</label>
-        <div class="col-xs-12 col-sm-3">
+        <label class="control-label col-xs-12 col-sm-1">{:__('关联区域')}:</label>
+        <div class="col-xs-12 col-sm-2">
+            {:build_radios('row[is_area]', ['0'=>__('否'), '1'=>__('关联')])}
+        </div>
+        <label class="control-label col-xs-12 col-sm-1">{:__('Weigh')}:</label>
+        <div class="col-xs-12 col-sm-2">
             <input id="c-weigh" data-rule="required" class="form-control" name="row[weigh]" type="number" value="0">
         </div>
     </div>
-
     <div class="form-group">
         <label class="control-label col-xs-12 col-sm-2">{:__('Zh_name')}:</label>
         <div class="col-xs-12 col-sm-3">
@@ -53,7 +57,7 @@
    
 
     <div class="form-group" id="app">
-        <label class="control-label col-xs-12 col-sm-2">{:__('关联区')}:</label>
+        <label class="control-label col-xs-12 col-sm-2">{:__('关联区')}:</label>
         <div class="col-xs-12 col-sm-8">
             <div class="block">
             <treeselect
@@ -63,7 +67,7 @@
             :flat="true"
             :default-expand-level="1"
             :sort-value-by="sortValueBy"
-            placeholder="选择关联区"
+            placeholder="选择关联区"
             v-model="data"
             @input="handleChange"
             ref="treeselect"/>

+ 9 - 5
application/admin/view/product/lists/edit.html

@@ -3,11 +3,15 @@
     <div class="form-horizontal">
     <div class="form-group">
         <label class="control-label col-xs-12 col-sm-2">{:__('Type_id')}:</label>
-        <div class="col-xs-12 col-sm-3">
+        <div class="col-xs-12 col-sm-2">
             <input id="c-type_id" data-rule="required" data-source="product/products/index" class="form-control selectpage" data-field="zh_title" name="row[type_id]" type="text" value="{$row.type_id|htmlentities}">
         </div>
-        <label class="control-label col-xs-12 col-sm-2">{:__('Weigh')}:</label>
-        <div class="col-xs-12 col-sm-3">
+        <label class="control-label col-xs-12 col-sm-1">{:__('关联区域')}:</label>
+        <div class="col-xs-12 col-sm-2">
+            {:build_radios('row[is_area]', ['0'=>__('否'), '1'=>__('关联')], $row['is_area'])}
+        </div>
+        <label class="control-label col-xs-12 col-sm-1">{:__('Weigh')}:</label>
+        <div class="col-xs-12 col-sm-2">
             <input id="c-weigh" data-rule="required" class="form-control" name="row[weigh]" type="number" value="{$row.weigh|htmlentities}">
         </div>
     </div>
@@ -52,7 +56,7 @@
         </div>
     </div>
     <div class="form-group" id="app">
-        <label class="control-label col-xs-12 col-sm-2">{:__('关联区')}:</label>
+        <label class="control-label col-xs-12 col-sm-2">{:__('关联区')}:</label>
         <div class="col-xs-12 col-sm-8">
             <div class="block">
                 <treeselect
@@ -62,7 +66,7 @@
                 :flat="true"
                 :default-expand-level="1"
                 :sort-value-by="sortValueBy"
-                placeholder="选择关联区"
+                placeholder="选择关联区"
                 v-model="data"
                 @input="handleChange"
                 :clearable='false'

+ 0 - 3
application/admin/view/product/lists/index.html

@@ -9,13 +9,10 @@
                         <a href="javascript:;" class="btn btn-primary btn-refresh" title="{:__('Refresh')}" ><i class="fa fa-refresh"></i> </a>
                         <a href="javascript:;" class="btn btn-success btn-add {:$auth->check('product/lists/add')?'':'hide'}" title="{:__('Add')}" ><i class="fa fa-plus"></i> {:__('Add')}</a>
                         <a href="javascript:;" class="btn btn-danger btn-del btn-disabled disabled {:$auth->check('product/lists/del')?'':'hide'}" title="{:__('Delete')}" ><i class="fa fa-trash"></i> {:__('Delete')}</a>
-                        <a href="javascript:;" class="btn btn-info btn-exports {:$auth->check('product/lists/exports')?'':'hide'}" title="{:__('import')}" id="btn-export-file"><i class="fa fa-download"></i> {:__('import')}</a>
-
                     </div>
                     <table id="table" class="table table-striped table-bordered table-hover table-nowrap"
                            data-operate-edit="{:$auth->check('product/lists/edit')}"
                            data-operate-del="{:$auth->check('product/lists/del')}"
-                           data-operate-del="{:$auth->check('product/lists/exports')}"
                            width="100%">
                     </table>
                 </div>

+ 11 - 14
application/api/controller/Order.php

@@ -33,8 +33,8 @@ class Order extends Api
         if(!$validate->scene('add')->check($params)) $this->error($validate->getError());
         $order_info = $productPopular->where('id', $params['order_id'])->find();
         if(empty($order_info)) $this->error(__("参数有误,无可用产品"));
-        $areaArr = explode(',', $params['area_id']);
-        $areaNum = count($areaArr);
+        $areaArr = ($params['type'] == 1)? explode(',', $params['area_id']): '';
+        $areaNum = ($params['type'] == 1)? count($areaArr): $params['num'];
         if(($order_info->num +$order_info->init_num+ $areaNum) > $order_info->stock) $this->error(__("库存不足"));
     
         // 启动事务
@@ -46,17 +46,14 @@ class Order extends Api
             if(bccomp($totalPrice, $amount, 2) > 0) throw new Exception(__("余额不足请前往充值"), 15001);
             if($order_info->start_time > time()) throw new Exception(__("抢购未开始"));
             if($order_info->stock == 0 || time() >= $order_info->end_time) throw new Exception(__("抢购已结束"));
-            //批量地区添加
-            foreach ($areaArr as $item) {
-                // 生成订单
-                $order_arr['price'] = $order_info->price;
-                $order_arr['product_id']= $params['product_id'];
-                $order_arr['area_id']   = $item;
-                $productOrder::setCreateOrder($params['order_id'], $order_arr, $productOrder::Popular, $this->auth->id, 0, getOrderSN('R'), 0, $order_info->price);
-                //修改区域状态
-                $productArea->where('id', $item)->setField('status', ProductLists::STOP);
-            }
-    
+
+            //批量地区添加 1选择地区 2未选择地区
+            if($params['type'] == 1)
+                $productOrder::setPopularAreaOrder($areaArr, $params['order_id'], $order_info->price, $params['product_id'], $this->auth->id);
+            else
+                $productOrder::setPopularNoAreaOrder($areaNum, $params['order_id'], $order_info->price, $params['product_id'], $this->auth->id);
+            
+
             //余额记录
             $ledgerWalletModel->changeWalletAccount($this->auth->id, Asset::TOKEN, -$totalPrice, $ledgerWalletModel::Popular, $this->auth->id);
 
@@ -325,7 +322,7 @@ class Order extends Api
         Db::startTrans();
         try {
             //更新订单支付状态为 待确认
-            $order_update = OfflineRechargeRecordModel::create([
+            OfflineRechargeRecordModel::create([
                 'user_id'       => $this->auth->id,
                 'amount'        => $amount,
                 'status'        => OfflineRechargeRecordModel::StatusConfirm,

+ 9 - 5
application/api/validate/Order.php

@@ -10,11 +10,13 @@ class Order extends Validate
      * 验证规则
      */
     protected $rule = [
-   
+  
       'order_id'   => 'require',
       'product_id' => 'require',
-      'area_id'    => 'require',
+      'area_id'    => 'requireIf:type,1',
+      'num'        => 'requireIf:type,2',
       'name'       => 'require',
+      'type'       => 'require|in:1,2',
       'phone'      => 'require|mobile',
       'address'    => 'require',
       'price'      => 'require|number|gt:0',
@@ -23,11 +25,13 @@ class Order extends Validate
      * 提示消息
      */
     protected $message = [
-  
+
       'order_id.require'   => '订单ID有误',
       'product_id.require' => '产品ID有误', //
       'area_id.require'    => '位置ID有误',
-      'price.require'      => '转让金额有误',
+      'area_id.require'    => '位置ID有误',
+      'num.require'        => '数量有误',
+      'type.require'       => '参数有误',
       'price.gt'           => '转让金额有误',
       'name.require'       => '姓名不能为空',
       'phone.mobile'       => '手机号有误',
@@ -37,7 +41,7 @@ class Order extends Validate
      * 验证场景
      */
     protected $scene = [
-        'add'  => ['order_id', 'product_id', 'area_id'],
+        'add'  => ['order_id', 'product_id','type','area_id', 'num'],
         'pick' => ['order_id'],
         'tran' => ['price', 'order_id'],
         'out'  => ['order_id'],

+ 29 - 1
application/common/model/ProductOrder.php

@@ -49,6 +49,35 @@ class ProductOrder extends Model
         self::Closure           => '关闭',
     ];
 
+
+    //抢购下单:未选择地区购买
+    public static function setPopularNoAreaOrder($num, $order_id, $price, $product_id, $uid)
+    {
+        for ($i = 0; $i < $num; $i++) {
+            $order_arr['price']     = $price;
+            $order_arr['product_id']= $product_id;
+            $order_arr['area_id']   = 0;
+            self::setCreateOrder($order_id, $order_arr, self::Popular, $uid, 0, getOrderSN('R'), 0, $price);
+        }
+        return true;
+    }
+
+
+    //抢购下单:选择地区购买
+    public static function setPopularAreaOrder($areaArr, $order_id, $price, $product_id, $uid)
+    {
+        foreach ($areaArr as $item) {
+            // 生成订单
+            $order_arr['price']     = $price;
+            $order_arr['product_id']= $product_id;
+            $order_arr['area_id']   = $item;
+            self::setCreateOrder($order_id, $order_arr, self::Popular, $uid, 0, getOrderSN('R'), 0, $price);
+        }
+        //修改区域状态
+        return ProductArea::whereIn('id', $item)->setField('status', ProductLists::STOP);
+    }
+
+
     /**
      * @param int $orderId 订单id
      * @param array $orderInfo 订单详情
@@ -60,7 +89,6 @@ class ProductOrder extends Model
      */
     public static function setCreateOrder(int $orderId, $orderInfo, $typeId, $userId, $fromUser, string $orderNo, float $fees, float $price): object
     {   
-
         return self::create([
                 'order_id'   => $orderId,
                 'product_id' => $orderInfo['product_id'],

+ 2 - 2
application/common/model/ProductPopular.php

@@ -70,14 +70,14 @@ class ProductPopular extends Model
     {
         $info = self::alias('a')
             ->join("product_list b", "a.product_id = b.id", "left")
-            ->field('a.id,a.product_id,'.'b.'.$lan.'_name as name,b.images as img_url,price,cost_price,stock,(num+init_num) as num,start_time,end_time,b.details')
+            ->field('a.id,a.product_id,'.'b.'.$lan.'_name as name,b.images as img_url,price,cost_price,stock,(num+init_num) as num,start_time,end_time,b.is_area,b.details')
             ->where('a.product_id', $product_id)
             ->where('a.status', self::NORMAL)
             ->find();
         if (empty($info)) {
             $info = self::alias('a')
                 ->join("product_list b", "a.product_id = b.id", "left")
-                ->field('a.id,a.product_id,'.'b.'.$lan.'_name as name,b.images as img_url,price,cost_price,stock,(num+init_num) as num,start_time,end_time,b.details')
+                ->field('a.id,a.product_id,'.'b.'.$lan.'_name as name,b.images as img_url,price,cost_price,stock,(num+init_num) as num,start_time,end_time,b.is_area,b.details')
                 ->where('a.id', $ids)
                 ->order('a.weigh desc')
                 ->find();

+ 117 - 0
public/assets/js/backend/product/areas.js

@@ -0,0 +1,117 @@
+define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {
+
+    var Controller = {
+        index: function () {
+            // 初始化表格参数配置
+            Table.api.init({
+                extend: {
+                    index_url: 'product/areas/index' + location.search+'?ids='+Config.ids,
+                    add_url: 'product/areas/add'+'?ids='+Config.ids,
+                    del_url: 'product/areas/del',
+                    multi_url: 'product/areas/multi',
+                    import_url: 'product/areas/import',
+                    table: 'product_area',
+                }
+            });
+       
+            var table = $("#table");
+
+            // 初始化表格
+            table.bootstrapTable({
+                url: $.fn.bootstrapTable.defaults.extend.index_url,
+                pk: 'id',
+                sortName: 'id',
+                fixedColumns: true,
+                fixedRightNumber: 1,
+                columns: [
+                    [
+                        {checkbox: true},
+                        {field: 'id', title: __('Id'), operate: false},
+                        {field: 'product_id', title: __('Product_id'), operate: false},
+                        {field: 'province', title: __('Province'), operate: false},
+                        {field: 'city', title: __('City'), operate: false},
+                        {field: 'area', title: __('Area'), operate: false},
+                        {field: 'county', title: __('County'), operate: false},
+                        {field: 'address', title: __('Address'), operate: 'LIKE'},
+                        {field: 'status', title: __('状态'), searchList: { "1": __('正常'), "0": __('已出售')}, formatter: Table.api.formatter.status },
+                        {field: 'create_time', title: __('Create_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
+                        { field: 'operate', title: __('Operate'),
+                            buttons:[
+                                {
+                                   name:'importlog',//名称开始按钮 classname: 'btn btn-xs btn-primary btn-dialog',
+                                   text:'导入日志',//文本
+                                   classname:'btn btn-xs btn-info btn-primary btn-dialog',//按钮样式
+                                   icon:'fa fa-cog',//图标
+                                   url:'ledger/importlog/index',//请求的方法
+                                   extend:'data-area=["80%","85%"]',
+                                   refresh:true,//一开始界面需要刷新
+                                 },
+                              ],
+                            table: table, events: Table.api.events.operate,
+                            formatter: Table.api.formatter.operate 
+                        }
+
+                    ]
+                ]
+            });
+
+            // 为表格绑定事件
+            Table.api.bindevent(table);
+            $(".btn-add").data("area", ["60%", "50%"]);
+            //导入地区
+            $(document).on("click",".btn-exports",function(){
+                Fast.api.open('product/areas/exports?ids='+Config.ids, '导入地区',{
+                    //接收产品弹窗Fast.api.close传过来的参数
+                    callback:function(data){
+                    
+                    }
+                });
+            })
+        },
+        add: function () {
+            Controller.api.bindevent();
+            let obj = $('#c-address')
+            $(document).on('change','.province',function(){
+                let txt = $(this).find("option:selected").text();
+                obj.val(txt)
+            });
+            //城市
+            $(document).on('change','.city',function(){
+                let txt = $(this).find("option:selected").text();
+                var arr = obj.val().split("-");
+                arr.splice(1, 1);
+                if(txt != '请选择') arr[1] = txt
+                obj.val(arr.join('-'))
+            });
+            //地区
+            $(document).on('change','.area',function(){
+                let txt = $(this).find("option:selected").text();
+                var arr = obj.val().split("-");
+                arr.splice(2, 1);
+                if(txt != '请选择') arr[2] = txt
+                obj.val(arr.join('-'))
+            });
+            //乡镇
+            $(document).on('change','.county',function(){
+                let txt = $(this).find("option:selected").text();
+                var arr = obj.val().split("-");
+                arr.splice(3, 1);
+                if(txt != '请选择') arr[3] = txt
+                obj.val(arr.join('-'))
+            });
+        },
+        exports: function () {
+            Controller.api.bindevent();
+        },
+        importlog: function () {
+            Controller.api.bindevent();
+        },
+        api: {
+            bindevent: function () {
+                Form.api.bindevent($("form[role=form]"));
+                Form.api.bindevent($("form#cxselectform"));
+            }
+        }
+    };
+    return Controller;
+});

+ 13 - 23
public/assets/js/backend/product/lists.js

@@ -66,21 +66,23 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'area', 'vue', 'ELEME
                         { field: 'total_num', title: __('总设置数量'), operate: false },
                         { field: 'sell_num', title: __('已出售数量'), operate: false },
                         { field: 'thum', title: __('Thum'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.images },
-                        { field: 'weigh', title: __('Weigh'), operate: false },
                         { field: 'status', title: __('Status'), searchList: { "1": __('上架'), "0": __('下架') }, formatter: Table.api.formatter.toggle },
+                        { field: 'weigh', title: __('Weigh'), operate: false },
+                        { field: 'is_area', title: __('关联区域'), searchList: { "1": __('关联'), "0": __('否') }, formatter: Table.api.formatter.status },
                         { field: 'create_time', title: __('Create_time'), operate: 'RANGE', addclass: 'datetimerange', autocomplete: false, formatter: Table.api.formatter.datetime },
                         { field: 'update_time', title: __('Update_time'), operate: 'RANGE', addclass: 'datetimerange', autocomplete: false, formatter: Table.api.formatter.datetime },
-                        { field: 'importlog', title: __('Operate'),
+                        { field: 'operate', title: __('Operate'),
                             buttons:[
                                 {
-                                   name:'importlog',//名称开始按钮 classname: 'btn btn-xs btn-primary btn-dialog',
-                                   text:'导入日志',//文本
-                                   classname:'btn btn-xs btn-info btn-primary btn-dialog',//按钮样式
-                                   icon:'fa fa-play',//图标
-                                   url:'ledger/importlog/index',//请求的方法
-                                   extend:'data-area=["75%","85%"]',
-                                   refresh:true,//一开始界面需要刷新
-                                 },
+                                    icon: 'fa fa-cog',
+                                    classname: 'btn btn-xs btn-info',
+                                    name: '区域设置',
+                                    text: __('区域设置'),
+                                    title: __('区域设置'),
+                                    url: 'product/areas/index',
+                                    extend:'data-area=["80%","85%"]',
+                                    refresh:true,
+                                },
                               ],
                             table: table, events: Table.api.events.operate,
                             formatter: Table.api.formatter.operate 
@@ -96,15 +98,6 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'area', 'vue', 'ELEME
             table.on('post-body.bs.table', function () {
                 $('.btn-editone').data("area", ["100%", "100%"]);
             });
-            //导入地区
-            $(document).on("click",".btn-exports",function(){
-                Fast.api.open('product/lists/exports', '导入地区',{
-                    //接收产品弹窗Fast.api.close传过来的参数
-                    callback:function(data){
-                        
-                    }
-                });
-            })
         },
 
         add: function () {
@@ -113,10 +106,7 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'area', 'vue', 'ELEME
         edit: function () {
             Controller.api.bindevent();
         },
-        exports: function () {
-            Form.api.bindevent($("form[role=form]"));
-        },
-        importlog: function () {
+        setarea: function () {
 
             Form.api.bindevent($("form[role=form]"));
         },