作者 Cool
1 个管道 的构建 通过 耗费 1 秒

Merge branch 'master' of http://114.215.101.231:8099/guosheng/community into liuzhen

# Conflicts:
#	public/api.html
<?php
namespace app\admin\controller;
use app\common\controller\Backend;
use app\admin\model\Housespec as SpecModel;
use app\admin\model\Housespecvalue as SpecValueModel;
/**
* 社区活动管理
*
* @icon fa fa-circle-o
*/
class HouseActivity extends Backend
{
/**
* HouseActivity模型对象
* @var \app\admin\model\HouseActivity
*/
protected $model = null;
public function _initialize()
{
parent::_initialize();
$this->SpecModel = new SpecModel;
$this->SpecValueModel = new SpecValueModel;
$this->model = new \app\admin\model\HouseActivity;
$this->view->assign("specTypeList", $this->model->getSpecTypeList());
}
/**
* 默认生成的控制器所继承的父类中有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','title','spec_type','start_time','end_time','updatetime']);
}
$list = collection($list)->toArray();
$result = array("total" => $total, "rows" => $list);
return json($result);
}
return $this->view->fetch();
}
public function addSpec($spec_name, $spec_value){
// 判断规格组是否存在
if (!$specId = $this->SpecModel->getSpecIdByName($spec_name)) {
// 新增规格组and规则值
if ($this->SpecModel->add($spec_name)
&& $this->SpecValueModel->add($this->SpecModel['id'], $spec_value))
return $this->success('', '', [
'spec_id' => (int)$this->SpecModel['id'],
'spec_value_id' => (int)$this->SpecValueModel['id'],
]);
return $this->error();
}
//return ;
// 判断规格值是否存在
if ($specValueId = $this->SpecValueModel->getSpecValueIdByName($specId, $spec_value)) {
return $this->success('', '', [
'spec_id' => (int)$specId,
'spec_value_id' => (int)$specValueId,
]);
}
// 添加规则值
if ($this->SpecValueModel->add($specId, $spec_value))
return $this->success('', '', [
'spec_id' => (int)$specId,
'spec_value_id' => (int)$this->SpecValueModel['id'],
]);
return $this->error();
}
/**
* 添加规格值
*/
public function addSpecValue($spec_id, $spec_value)
{
// 判断规格值是否存在
if ($specValueId = $this->SpecValueModel->getSpecValueIdByName($spec_id, $spec_value)) {
return $this->success('', '', [
'spec_value_id' => (int)$specValueId,
]);
}
// 添加规则值
if ($this->SpecValueModel->add($spec_id, $spec_value))
return $this->success('', '', [
'spec_value_id' => (int)$this->SpecValueModel['id'],
]);
return $this->error();
}
/**
* 添加
*/
public function add()
{
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
if ($params) {
if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
$params[$this->dataLimitField] = $this->auth->id;
}
try {
//是否采用模型验证
if ($this->modelValidate) {
$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
$this->model->validate($validate);
}
$result = $this->model->allowField(true)->save($params);
if ($result !== false) {
//成功之后 存储商品规格
$spec_many_params = $this->request->post("spec_many/a");
$this->model->addGoodsSpec($params,$spec_many_params,$this->request->post("spec/a"));
$this->success();
} else {
$this->error($this->model->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', ''));
}
return $this->view->fetch();
}
/**
* 删除
*/
public function del($ids = "")
{
if ($ids) {
$pk = $this->model->getPk();
$adminIds = $this->getDataLimitAdminIds();
if (is_array($adminIds)) {
$count = $this->model->where($this->dataLimitField, 'in', $adminIds);
}
$list = $this->model->where($pk, 'in', $ids)->select();
$count = 0;
foreach ($list as $k => $v) {
// 删除商品sku
$v->removesku();
$count += $v->delete();
}
if ($count) {
$this->success();
} else {
$this->error(__('No rows were deleted'));
}
}
$this->error(__('Parameter %s can not be empty', 'ids'));
}
/**
* 编辑
*/
public function edit($ids = NULL)
{
$row = $this->model->get($ids, ['specRel', 'spec', 'spec_rel.spec']);
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) {
try {
//是否采用模型验证
if ($this->modelValidate) {
$name = basename(str_replace('\\', '/', get_class($this->model)));
$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
$row->validate($validate);
}
$result = $row->allowField(true)->save($params);
if ($result !== false) {
//成功之后 存储商品规格
$spec_many_params = $this->request->post("spec_many/a");
$row->addGoodsSpec($params,$spec_many_params,$this->request->post("spec/a"), true);
$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', ''));
}
// 多规格信息
$specData = 'null';
if ($row['spec_type'] === '2'){
$specData = json_encode($this->model->getManySpecData($row['spec_rel'], $row['spec']));
}
$row['specData'] = $specData;
$this->view->assign("row", $row);
return $this->view->fetch();
}
}
... ...
<?php
return [
'Id' => 'ID',
'Title' => '活动标题',
'Content' => '描述详情',
'Spec_type' => '活动规格',
'Spec_type 0' => '无规格(免费)',
'Spec_type 1' => '单规格',
'Spec_type 2' => '多规格',
'House_ids' => '社区ID集合',
'Start_time' => '活动开始时间',
'End_time' => '活动结束时间',
'Createtime' => '创建时间',
'Updatetime' => '更新时间'
];
... ...
<?php
namespace app\admin\model;
use think\Model;
class HouseActivity extends Model
{
// 表名
protected $name = 'house_activity';
// 自动写入时间戳字段
protected $autoWriteTimestamp = 'int';
// 定义时间戳字段名
protected $createTime = 'createtime';
protected $updateTime = 'updatetime';
protected $deleteTime = false;
// 追加属性
protected $append = [
'spec_type_text',
'start_time_text',
'end_time_text'
];
public function getSpecTypeList()
{
return ['0' => __('Spec_type 0'), '1' => __('Spec_type 1'), '2' => __('Spec_type 2')];
}
public function getSpecTypeTextAttr($value, $data)
{
$value = $value ? $value : (isset($data['spec_type']) ? $data['spec_type'] : '');
$list = $this->getSpecTypeList();
return isset($list[$value]) ? $list[$value] : '';
}
public function getStartTimeTextAttr($value, $data)
{
$value = $value ? $value : (isset($data['start_time']) ? $data['start_time'] : '');
return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
}
public function getEndTimeTextAttr($value, $data)
{
$value = $value ? $value : (isset($data['end_time']) ? $data['end_time'] : '');
return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
}
protected function setStartTimeAttr($value)
{
return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
}
protected function setEndTimeAttr($value)
{
return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
}
/**
* 关联活动规格表
*/
public function spec()
{
return $this->hasMany('Houseactivityspec','house_activity_id','id');
}
/**
* 关联活动规格关系表
*/
public function specRel()
{
return $this->belongsToMany('Housespecvalue', 'house_activity_spec_rel','spec_value_id','house_activity_id');
}
/**
* 添加活动规格
* @param $data
* @param $isUpdate
* @throws \Exception
*/
public function addGoodsSpec(&$data,$params,$specparams,$isUpdate = false)
{
// 更新模式: 先删除所有规格
$model = new Houseactivityspec;
$isUpdate && $model->removeAll($this['id']);
// 添加规格数据
if ($data['spec_type'] === '1') {
// 单规格
$this->spec()->save($specparams);
} else if ($data['spec_type'] === '2') {
// 添加商品与规格关系记录
$model->addGoodsSpecRel($this['id'],$params['spec_attr']);
// 添加商品sku
$model->addSkuList($this['id'],$params['spec_list']);
}
}
public function removesku(){
// 删除活动sku
(new Houseactivityspec)->removeAll($this['id']);
}
/**
* 获取规格信息
*/
public function getManySpecData($spec_rel, $skuData)
{
// spec_attr
$specAttrData = [];
foreach ($spec_rel as $item) {
if (!isset($specAttrData[$item['spec_id']])) {
$specAttrData[$item['spec_id']] = [
'group_id' => $item['spec']['id'],
'group_name' => $item['spec']['spec_name'],
'spec_items' => [],
];
}
$specAttrData[$item['spec_id']]['spec_items'][] = [
'item_id' => $item['pivot']['spec_value_id'],
'spec_value' => $item['spec_value'],
];
}
// spec_list
$specListData = [];
foreach ($skuData as $item) {
$specListData[] = [
'id' => $item['id'],
'spec_sku_id' => $item['spec_sku_id'],
'rows' => [],
'form' => [
'price' => $item['price'],
],
];
}
return ['spec_attr' => array_values($specAttrData), 'spec_list' => $specListData];
}
}
... ...
<?php
namespace app\admin\model;
use think\Model;
class Houseactivityspec extends Model
{
// 表名
protected $name = 'house_activity_spec';
// 自动写入时间戳字段
protected $autoWriteTimestamp = 'int';
// 定义时间戳字段名
protected $createTime = 'create_time';
protected $updateTime = 'update_time';
/**
* 批量添加活动sku记录
* @param $house_activity_id
* @param $spec_list
* @return array|false
* @throws \Exception
*/
public function addSkuList($house_activity_id, $spec_list)
{
$data = [];
foreach ($spec_list as $item) {
$data[] = array_merge($item['form'], [
'spec_sku_id' => $item['spec_sku_id'],
'house_activity_id' => $house_activity_id,
]);
}
return $this->saveAll($data);
}
/**
* 添加商品活动关系记录
* @param $house_activity_id
* @param $spec_attr
* @return array|false
* @throws \Exception
*/
public function addGoodsSpecRel($house_activity_id, $spec_attr)
{
$data = [];
array_map(function ($val) use (&$data, $house_activity_id) {
array_map(function ($item) use (&$val, &$data, $house_activity_id) {
$data[] = [
'house_activity_id' => $house_activity_id,
'spec_id' => $val['group_id'],
'spec_value_id' => $item['item_id'],
];
}, $val['spec_items']);
}, $spec_attr);
$model = new Houseactivityspecrel;
return $model->saveAll($data);
}
/**
* 移除指定活动的所有sku
* @param $house_activity_id
* @return int
*/
public function removeAll($house_activity_id)
{
$model = new Houseactivityspecrel;
$model->where('house_activity_id','=', $house_activity_id)->delete();
return $this->where('house_activity_id','=', $house_activity_id)->delete();
}
}
... ...
<?php
namespace app\admin\model;
use think\Model;
class Houseactivityspecrel extends Model
{
// 表名
protected $name = 'house_activity_spec_rel';
// 自动写入时间戳字段
protected $autoWriteTimestamp = 'int';
// 定义时间戳字段名
protected $createTime = 'create_time';
protected $updateTime = '';
/**
* 关联规格组
* @return \think\model\relation\BelongsTo
*/
public function spec()
{
return $this->belongsTo('Housespec');
}
}
\ No newline at end of file
... ...
<?php
namespace app\admin\model;
use think\Model;
/**
* 规格/属性(组)模型
* Class Spec
* @package app\store\model
*/
class Housespec extends Model
{
// 表名
protected $name = 'house_spec';
// 自动写入时间戳字段
protected $autoWriteTimestamp = 'int';
// 定义时间戳字段名
protected $createTime = 'createtime';
protected $updateTime = '';
/**
* 根据规格组名称查询规格id
* @param $spec_name
* @return mixed
*/
public function getSpecIdByName($spec_name)
{
return self::where(compact('spec_name'))->value('id');
}
/**
* 新增规格组
* @param $spec_name
* @return false|int
*/
public function add($spec_name)
{
return $this->save(compact('spec_name'));
}
}
... ...
<?php
namespace app\admin\model;
use think\Model;
/**
* 规格/属性(组)模型
* Class Spec
* @package app\store\model
*/
class Housespecvalue extends Model
{
// 表名
protected $name = 'house_spec_value';
// 自动写入时间戳字段
protected $autoWriteTimestamp = 'int';
// 定义时间戳字段名
protected $createTime = 'createtime';
protected $updateTime = '';
/**
* 根据规格组名称查询规格id
* @param $spec_id
* @param $spec_value
* @return mixed
*/
public function getSpecValueIdByName($spec_id, $spec_value)
{
return self::where(compact('spec_id', 'spec_value'))->value('id');
}
/**
* 新增规格值
* @param $spec_id
* @param $spec_value
* @return false|int
*/
public function add($spec_id, $spec_value)
{
return $this->save(compact('spec_value', 'spec_id'));
}
/**
* 关联规格组表
* @return $this|\think\model\relation\BelongsTo
*/
public function spec()
{
return $this->belongsTo('Housespec','spec_id','id');
}
}
... ...
<?php
namespace app\admin\validate;
use think\Validate;
class HouseActivity extends Validate
{
/**
* 验证规则
*/
protected $rule = [
];
/**
* 提示消息
*/
protected $message = [
];
/**
* 验证场景
*/
protected $scene = [
'add' => [],
'edit' => [],
];
}
... ...
<form id="add-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">{:__('Title')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-title" data-rule="required" class="form-control" name="row[title]" type="text" value="">
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Content')}:</label>
<div class="col-xs-12 col-sm-8">
<textarea id="c-content" data-rule="required" class="form-control editor" rows="5" name="row[content]" cols="50"></textarea>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Spec_type')}:</label>
<div class="col-xs-12 col-sm-8">
<select id="c-spec_type" data-rule="required" class="form-control selectpicker" name="row[spec_type]">
{foreach name="specTypeList" item="vo"}
<option value="{$key}" {in name="key" value="0"}selected{/in}>{$vo}</option>
{/foreach}
</select>
</div>
</div>
<!-- 活动规格属性 start -->
<div class="goods-spec-many form-group">
<!-- <label class="control-label col-xs-12 col-sm-2"></label>-->
<div class="goods-spec-box col-xs-12 col-sm-11" style="background-color: white;">
<!-- 规格属性 -->
<div class="spec-attr"></div>
<!-- 添加规格:按钮 -->
<div class="spec-group-button">
<button type="button" class="btn-addSpecGroup btn btn-xs btn-success">添加规格</button>
</div>
<!-- 添加规格:表单 -->
<div class="spec-group-add">
<div class="spec-group-add-item form-group">
<label class="control-label form-require">规格名 </label>
<input type="text" class="input-specName tpl-form-input"
placeholder="请输入规格名称">
</div>
<div class="spec-group-add-item form-group">
<label class="control-label form-require">规格值 </label>
<input type="text" class="input-specValue tpl-form-input"
placeholder="请输入规格值">
</div>
<div class="spec-group-add-item margin-top">
<button type="button" class="btn-addSpecName btn btn-xs btn-success"> 确定
</button>
<button type="button" class="btn-cancleAddSpecName btn btn-xs btn-default"> 取消
</button>
</div>
</div>
<!-- 商品多规格sku信息 -->
<div class="goods-sku scrollable-horizontal">
<!-- 分割线 -->
<div class="goods-spec-line"></div>
<!-- sku 批量设置 -->
<div class="spec-batch form-inline">
<div class="form-group">
<label class="control-label">批量设置</label>
</div>
<div class="form-group">
<input type="number" data-type="price" placeholder="报名费用">
</div>
<div class="form-group">
<button type="button" class="btn-specBatchBtn btn btn-sm btn-secondary
radius">确定
</button>
</div>
</div>
<!-- sku table -->
<table class="spec-sku-tabel table table-bordered table-centered margin-bottom-xs text-nowrap"></table>
</div>
</div>
</div>
<div class="goods-spec-single">
<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-price" data-rule="required" class="form-control form-control" name="spec[price]" type="number" value="0">
</div>
</div>
</div>
<!-- 活动规格属性 end -->
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('House_ids')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-house_ids" data-rule="required" data-source="house/index" data-multiple="true" class="form-control selectpage" name="row[house_ids]" type="text" value="">
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Start_time')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-start_time" data-rule="required" class="form-control datetimepicker" data-date-format="YYYY-MM-DD HH:mm:ss" data-use-current="true" name="row[start_time]" type="text" value="{:date('Y-m-d H:i:s')}">
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('End_time')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-end_time" data-rule="required" class="form-control datetimepicker" data-date-format="YYYY-MM-DD HH:mm:ss" data-use-current="true" name="row[end_time]" type="text" value="{:date('Y-m-d H:i:s')}">
</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-success btn-embossed disabled">{:__('OK')}</button>
<button type="reset" class="btn btn-default btn-embossed">{:__('Reset')}</button>
</div>
</div>
</form>
{include file="house_activity/spec_many_template" /}
<link rel="stylesheet" href="__CDN__/assets/addons/litestore/css/litestoregoods.css">
\ No newline at end of file
... ...
<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">{:__('Title')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-title" data-rule="required" class="form-control" name="row[title]" type="text" value="{$row.title|htmlentities}">
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Content')}:</label>
<div class="col-xs-12 col-sm-8">
<textarea id="c-content" data-rule="required" class="form-control editor" rows="5" name="row[content]" cols="50">{$row.content|htmlentities}</textarea>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Spec_type')}:</label>
<div class="col-xs-12 col-sm-8">
<select id="c-spec_type" data-rule="required" class="form-control selectpicker" name="row[spec_type]">
{foreach name="specTypeList" item="vo"}
<option value="{$key}" {in name="key" value="$row.spec_type"}selected{/in}>{$vo}</option>
{/foreach}
</select>
</div>
</div>
<!-- 商品规格属性 start -->
<div class="goods-spec-many form-group">
<!-- <label class="control-label col-xs-12 col-sm-2"></label>-->
<div class="goods-spec-box col-xs-12 col-sm-11" style="background-color: white;">
<!-- 规格属性 -->
<div class="spec-attr"></div>
<!-- 添加规格:按钮 -->
<div class="spec-group-button">
<button type="button" class="btn-addSpecGroup btn btn-xs btn-success">添加规格</button>
</div>
<!-- 添加规格:表单 -->
<div class="spec-group-add">
<div class="spec-group-add-item form-group">
<label class="control-label form-require">规格名 </label>
<input type="text" class="input-specName tpl-form-input"
placeholder="请输入规格名称">
</div>
<div class="spec-group-add-item form-group">
<label class="control-label form-require">规格值 </label>
<input type="text" class="input-specValue tpl-form-input"
placeholder="请输入规格值">
</div>
<div class="spec-group-add-item margin-top">
<button type="button" class="btn-addSpecName btn btn-xs btn-success"> 确定
</button>
<button type="button" class="btn-cancleAddSpecName btn btn-xs btn-default"> 取消
</button>
</div>
</div>
<!-- 商品多规格sku信息 -->
<div class="goods-sku scrollable-horizontal">
<!-- 分割线 -->
<div class="goods-spec-line"></div>
<!-- sku 批量设置 -->
<div class="spec-batch form-inline">
<div class="form-group">
<label class="control-label">批量设置</label>
</div>
<div class="form-group">
<input type="number" data-type="price" placeholder="报名费用">
</div>
<div class="form-group">
<button type="button" class="btn-specBatchBtn btn btn-sm btn-secondary
radius">确定
</button>
</div>
</div>
<!-- sku table -->
<table class="spec-sku-tabel table table-bordered table-centered margin-bottom-xs text-nowrap"></table>
</div>
</div>
</div>
<div class="goods-spec-single">
<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-price" data-rule="required" class="form-control form-control" name="spec[price]" type="number" value="{$row.spec.0.price|default=0}">
</div>
</div>
</div>
<!-- 商品规格属性 end -->
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('House_ids')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-house_ids" data-rule="required" data-source="house/index" data-multiple="true" class="form-control selectpage" name="row[house_ids]" type="text" value="{$row.house_ids|htmlentities}">
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Start_time')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-start_time" data-rule="required" class="form-control datetimepicker" data-date-format="YYYY-MM-DD HH:mm:ss" data-use-current="true" name="row[start_time]" type="text" value="{:$row.start_time?datetime($row.start_time):''}">
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('End_time')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-end_time" data-rule="required" class="form-control datetimepicker" data-date-format="YYYY-MM-DD HH:mm:ss" data-use-current="true" name="row[end_time]" type="text" value="{:$row.end_time?datetime($row.end_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-success btn-embossed disabled">{:__('OK')}</button>
<button type="reset" class="btn btn-default btn-embossed">{:__('Reset')}</button>
</div>
</div>
</form>
{include file="house_activity/spec_many_template" /}
<link rel="stylesheet" href="__CDN__/assets/addons/litestore/css/litestoregoods.css">
<script type="text/javascript">
var from_specData = <?= $row['specData'] ?>;
</script>
... ...
<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('house_activity/add')?'':'hide'}" title="{:__('Add')}" ><i class="fa fa-plus"></i> {:__('Add')}</a>
<a href="javascript:;" class="btn btn-success btn-edit btn-disabled disabled {:$auth->check('house_activity/edit')?'':'hide'}" title="{:__('Edit')}" ><i class="fa fa-pencil"></i> {:__('Edit')}</a>
<a href="javascript:;" class="btn btn-danger btn-del btn-disabled disabled {:$auth->check('house_activity/del')?'':'hide'}" title="{:__('Delete')}" ><i class="fa fa-trash"></i> {:__('Delete')}</a>
<a href="javascript:;" class="btn btn-danger btn-import {:$auth->check('house_activity/import')?'':'hide'}" title="{:__('Import')}" id="btn-import-file" data-url="ajax/upload" data-mimetype="csv,xls,xlsx" data-multiple="false"><i class="fa fa-upload"></i> {:__('Import')}</a>
<div class="dropdown btn-group {:$auth->check('house_activity/multi')?'':'hide'}">
<a class="btn btn-primary btn-more dropdown-toggle btn-disabled disabled" data-toggle="dropdown"><i class="fa fa-cog"></i> {:__('More')}</a>
<ul class="dropdown-menu text-left" role="menu">
<li><a class="btn btn-link btn-multi btn-disabled disabled" href="javascript:;" data-params="status=normal"><i class="fa fa-eye"></i> {:__('Set to normal')}</a></li>
<li><a class="btn btn-link btn-multi btn-disabled disabled" href="javascript:;" data-params="status=hidden"><i class="fa fa-eye-slash"></i> {:__('Set to hidden')}</a></li>
</ul>
</div>
</div>
<table id="table" class="table table-striped table-bordered table-hover table-nowrap"
data-operate-edit="{:$auth->check('house_activity/edit')}"
data-operate-del="{:$auth->check('house_activity/del')}"
width="100%">
</table>
</div>
</div>
</div>
</div>
</div>
... ...
<!-- 商品规格属性模板 -->
<script id="tpl_spec_attr" type="text/template">
<% for(var j=0;j< spec_attr.length;j++){ %>
<div class="spec-group-item" data-index="<%=j%>" data-group-id="<%=spec_attr[j].group_id%>">
<div class="spec-group-name">
<span><%=spec_attr[j].group_name%></span>
<i class="spec-group-delete fa fa-trash icon-shanchu1" title="点击删除"></i>
</div>
<div class="spec-list am-cf">
<% for(var k=0;k<spec_attr[j].spec_items.length;k++){ %>
<div class="spec-item am-fl" data-item-index="<%=k%>">
<span><%=spec_attr[j].spec_items[k].spec_value%></span>
<i class="spec-item-delete fa fa-trash icon-shanchu1" title="点击删除"></i>
</div>
<% } %>
<div class="spec-item-add am-cf am-fl">
<input type="text" class="ipt-specItem am-fl am-field-valid">
<button type="button" class="btn-addSpecItem btn btn-xs btn-success am-fl">添加</button>
</div>
</div>
</div>
<% } %>
</script>
<!-- 商品规格table模板 -->
<script id="tpl_spec_table" type="text/template">
<tbody>
<tr>
<% for(var i=0;i< spec_attr.length;i++){ %>
<th><%=spec_attr[i].group_name%></th>
<% } %>
<th>报名费用</th>
</tr>
<% for(var i=0;i<spec_list.length;i++){ %>
<tr data-index="<%=i%>" data-sku-id="<%=spec_list[i].spec_sku_id %>">
<% for(var k=0;k<spec_list[i].rows.length;k++){ %>
<td class="td-spec-value am-text-middle" rowspan="<%=spec_list[i].rows[k].rowspan%>">
<%=spec_list[i].rows[k].spec_value%>
</td>
<% } %>
<td>
<input type="number" name="price" data-rule="required" value="<%=spec_list[i].form.price%>" class="am-field-valid ipt-w80"
required>
</td>
</tr>
<% } %>
</tbody>
</script>
... ...
... ... @@ -167,13 +167,12 @@ class House extends Api
$data = Db::name('house_board')
->field('id,house_id,title,content,look_num,createtime')
->where('deletime','')
->where('id',$id)
->find();
$data['createtime'] = date('Y-m-d',$data['createtime']);
$data['avatar'] = Db::name('house_board')
$data['avatar'] = Db::name('house_board_detail')
->alias('a')
->join('user b','a.user_id = b.id')
->where('a.house_board_id',$id)
... ... @@ -251,19 +250,17 @@ class House extends Api
$qiniu = get_addon_config('qiniu')['cdnurl'];
$user_id = $this->auth->id;
$area = $this->request->param('area');
if(empty($area)){
$this->error('缺少必要参数');
}
$keyword = $this->request->param('keyword');
$where = [];
if(!empty($area)){
$where['area'] = ['like',"%$area%"];
}
if(!empty($keyword)){
$where['name'] = ['like',"%$keyword%"];
}else{
$where = true;
}
//查询该市区下的所有小区
$data = Db::name('house')
->where('area','like',"%$area%")
->where($where)
->field('id,name,area')
->order('createtime desc')
... ...
... ... @@ -148,7 +148,7 @@ class HouseBoard extends Api
* @ApiMethod (POST)
*
* @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
* @ApiParams (name="house_board_id", type=inter, required=true, description="社区id")
* @ApiParams (name="house_id", type=inter, required=true, description="社区id")
* @ApiParams (name="page", type="inter", required=false, description="当前页(默认1)")
* @ApiParams (name="pageNum", type="inter", required=false, description="每页显示数据个数(默认10)")
*
... ... @@ -174,7 +174,7 @@ class HouseBoard extends Api
$page = $this->request->param('page', 1, 'intval');
$pageNum = $this->request->param('pageNum', 10, 'intval');
$user_id = $this->auth->id;
$house_id = $this->request->param('house_board_id');
$house_id = $this->request->param('house_id');
if(empty($house_id)){
$this->error('社区id不能为空');
}
... ... @@ -375,4 +375,171 @@ class HouseBoard extends Api
$this->success('success',$info);
}
/**
* @ApiTitle (社区公告-社区活动)
* @ApiSummary (社区公告-社区活动)
* @ApiMethod (POST)
*
* @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
* @ApiParams (name="house_id", type="inter", required=true, description="社区id")
*
* @ApiReturn({
"code": 1,
"msg": "success",
"time": "1598587213",
"data": [
{
"id": // 活动id
"title": // 活动标题
"spec_type": // 活动规格:0=无规格(免费),1=单规格,2=多规格
"content": // 活动描述
"activity_time": 活动日期
"price": // 报名费用
"status": { // 活动状态
"text": // 状态名称
"value": // 状态值 0=报名中,1=已报名,2=已到期
}
}
]
})
*/
public function activity()
{
$user_id = $this->auth->id;
$house_id = $this->request->param('house_id'); //社区id
empty($house_id) && $this->error('缺少必要参数');
$list = $this->getActivityList("find_in_set({$house_id},house_ids)");
$this->success('success',$list);
}
/**
* @ApiTitle (社区公告-社区活动-详情)
* @ApiSummary (社区公告-社区活动-详情)
* @ApiMethod (POST)
*
* @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
* @ApiParams (name="house_activity_id", type="inter", required=true, description="社区活动id")
*
* @ApiReturn({
"code": 1,
"msg": "success",
"time": "1598587213",
"data": {
"id": // 活动id
"title": // 活动标题
"spec_type": // 活动规格:0=无规格(免费),1=单规格,2=多规格
"content": // 活动描述
"activity_time": 活动日期
"price": // 报名费用
"status": { // 活动状态
"text": // 状态名称
"value": // 状态值 0=报名中,1=已报名,2=已到期
}
}
})
*/
public function activityInfo()
{
$user_id = $this->auth->id;
$house_activity_id = $this->request->param('house_activity_id'); //社区id
empty($house_activity_id) && $this->error('缺少必要参数');
$list = $this->getActivityList(['ha.id'=>$house_activity_id]);
$info = !empty($list) ? $list[0] : [];
$this->success('success',$info);
}
/**
* 获取活动信息
*/
private function getActivityList($where){
$list = Db::name('house_activity')
->alias('ha')
->join('house_join hj','hj.house_activity_id = ha.id','left')
->where($where)
->field('
ha.id,
ha.title,
ha.content,
ha.start_time,
ha.end_time,
ha.spec_type,
hj.pay_status
')
->order("ha.createtime desc")
->select();
foreach ($list as $k => &$v) {
// 活动报名费用
$price = Db::name('house_activity_spec')->where('house_activity_id',$v['id'])->value('price');
$v['price'] = $price > 0 ? $price : 0;
// 活动日期
$v['activity_time'] = date('Y-m-d',$v['start_time']).'-'.date('Y-m-d',$v['end_time']);
// 活动状态
if($v['pay_status'] == '1'){
$status = ['text'=>'已报名','value'=>1];
}else{
$status = $v['end_time'] < time() ? ['text'=>'已到期','value'=>2] : ['text'=>'报名中','value'=>0];
}
$v['status'] = $status;
unset($v['start_time'],$v['end_time'],$v['pay_status']);
}
return $list;
}
/**
* @ApiTitle (社区公告-社区活动-获取规格)
* @ApiSummary (社区公告-社区活动-获取规格)
* @ApiMethod (POST)
* @ApiParams (name="house_activity_id", type="integer", required=true, description="活动ID")
* @ApiReturnParams (name="code", type="integer", required=true, sample="0")
* @ApiReturnParams (name="msg", type="string", required=true, sample="返回成功")
* @ApiReturnParams (name="data", type="object", description="扩展数据返回")
* @ApiReturn ({
"code": 1,
"msg": "成功",
"time": "1598600665",
"data": {
"spec_attr": [
{
"group_id": 25,
"group_name": "颜色",
"spec_items": [
{
"item_id": 52,
"spec_value": "白色"
},
{
"item_id": 54,
"spec_value": "黑色"
}
]
}
],
"spec_list": {
"52_50": {
"spec_sku_id": "52_50",
"price": "12.00"
}
}
}
})
*/
public function specData()
{
$house_activity_id = $this->request->param('house_activity_id');
$activity = \app\admin\model\HouseActivity::get($house_activity_id);
empty($activity) && $this->error('活动信息不存在');
// 规格信息
$spec_data = $activity['spec_type'] == '2' ? $activity->getManySpecData($activity['spec_rel'], $activity['spec']) : null;
// 规格价格信息
if($spec_data){
$spec_list = [];
foreach($spec_data['spec_list'] as $v){
$spec_list[$v['spec_sku_id']]['spec_sku_id'] = $v['spec_sku_id'];
$spec_list[$v['spec_sku_id']]['price'] = $v['form']['price'];
}
$spec_data['spec_list'] = $spec_list;
}
$this->success(__('成功'),$spec_data);
}
}
\ No newline at end of file
... ...
此 diff 太大无法显示。
define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'backend/house_activity.spec'], function ($, undefined, Backend, Table, Form, spec) {
var Controller = {
index: function () {
// 初始化表格参数配置
Table.api.init({
extend: {
index_url: 'house_activity/index' + location.search,
add_url: 'house_activity/add',
edit_url: 'house_activity/edit',
del_url: 'house_activity/del',
multi_url: 'house_activity/multi',
table: 'house_activity',
}
});
var table = $("#table");
// 初始化表格
table.bootstrapTable({
url: $.fn.bootstrapTable.defaults.extend.index_url,
pk: 'id',
sortName: 'id',
columns: [
[
{checkbox: true},
{field: 'id', title: __('Id')},
{field: 'title', title: __('Title')},
{field: 'spec_type', title: __('Spec_type'), searchList: {"0":__('Spec_type 0'),"1":__('Spec_type 1'),"2":__('Spec_type 2')}, formatter: Table.api.formatter.normal},
{field: 'start_time', title: __('Start_time'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
{field: 'end_time', title: __('End_time'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
{field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
{field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
]
]
});
// 为表格绑定事件
Table.api.bindevent(table);
},
add: function () {
setTimeout(function () {
$('select[name="row[spec_type]"]').trigger("change");
}, 100);
Form.api.bindevent($("form[role=form]"), function(data, ret){
Fast.api.close(data);
Toastr.success("活动提交成功");
}, function(data, ret){
Toastr.success("活动提交失败");
}, function(success, error){
//注意如果我们需要阻止表单,可以在此使用return false;即可
//如果我们处理完成需要再次提交表单则可以使用submit提交,如下
console.log(this);
var form = this;
if (form.size() === 0) {
Toastr.error("表单未初始化完成,无法提交");
return false;
}
var type = form.attr("method") ? form.attr("method").toUpperCase() : 'GET';
type = type && (type === 'GET' || type === 'POST') ? type : 'GET';
url = form.attr("action");
url = url ? url : location.href;
//修复当存在多选项元素时提交的BUG
var params = {};
var multipleList = $("[name$='[]']", form);
if (multipleList.size() > 0) {
var postFields = form.serializeArray().map(function (obj) {
return $(obj).prop("name");
});
$.each(multipleList, function (i, j) {
if (postFields.indexOf($(this).prop("name")) < 0) {
params[$(this).prop("name")] = '';
}
});
}
var dataParam = {spec_many: specMany.getData()};
console.log(dataParam);
Fast.api.ajax({
type: type,
url: url,
data: form.serialize() + (Object.keys(params).length > 0 ? '&' + $.param(params) : '') + (Object.keys(dataParam).length > 0 ? '&' + $.param(dataParam) : ''),
dataType: 'json',
complete: function (xhr) {
var token = xhr.getResponseHeader('__token__');
if (token) {
$("input[name='__token__']", form).val(token);
}
//关闭弹窗
var index = parent.Layer.getFrameIndex(window.name);
var callback = parent.$("#layui-layer" + index).data("callback");
parent.Layer.close(index);
//刷新列表
parent.$("#table").bootstrapTable('refresh');
}
}, function (data, ret) {
$('.form-group', form).removeClass('has-feedback has-success has-error');
if (data && typeof data === 'object') {
if (typeof data.token !== 'undefined') {
$("input[name='__token__']", form).val(data.token);
}
if (typeof data.callback !== 'undefined' && typeof data.callback === 'function') {
data.callback.call(form, data);
}
}
}, function (data, ret) {
if (data && typeof data === 'object' && typeof data.token !== 'undefined') {
$("input[name='__token__']", form).val(data.token);
}
});
return false;
});
// 注册商品多规格组件
var specMany = new GoodsSpec({
container: '.goods-spec-many',
OutForm:Form
});
// 切换单/多规格
$('select[name="row[spec_type]"').change(function (e) {
var $goodsSpecMany = $('.goods-spec-many')
, $goodsSpecSingle = $('.goods-spec-single');
if (e.currentTarget.value === '1') {
$goodsSpecMany.hide() && $goodsSpecSingle.show();
} else if (e.currentTarget.value === '2') {
$goodsSpecMany.show() && $goodsSpecSingle.hide();
} else {
$goodsSpecMany.hide() && $goodsSpecSingle.hide();
}
});
},
edit: function () {
setTimeout(function () {
$('select[name="row[spec_type]"]').trigger("change");
}, 100);
Form.api.bindevent($("form[role=form]"), function(data, ret){
//Fast.api.close(data);
Toastr.success("商品提交成功");
}, function(data, ret){
Toastr.success("商品提交失败");
}, function(success, error){
//注意如果我们需要阻止表单,可以在此使用return false;即可
//如果我们处理完成需要再次提交表单则可以使用submit提交,如下
console.log(this);
var form = this;
if (form.size() === 0) {
Toastr.error("表单未初始化完成,无法提交");
return false;
}
var type = form.attr("method") ? form.attr("method").toUpperCase() : 'GET';
type = type && (type === 'GET' || type === 'POST') ? type : 'GET';
url = form.attr("action");
url = url ? url : location.href;
//修复当存在多选项元素时提交的BUG
var params = {};
var multipleList = $("[name$='[]']", form);
if (multipleList.size() > 0) {
var postFields = form.serializeArray().map(function (obj) {
return $(obj).prop("name");
});
$.each(multipleList, function (i, j) {
if (postFields.indexOf($(this).prop("name")) < 0) {
params[$(this).prop("name")] = '';
}
});
}
var dataParam = {spec_many: specMany.getData()};
console.log(dataParam);
Fast.api.ajax({
type: type,
url: url,
data: form.serialize() + (Object.keys(params).length > 0 ? '&' + $.param(params) : '') + (Object.keys(dataParam).length > 0 ? '&' + $.param(dataParam) : ''),
dataType: 'json',
complete: function (xhr) {
var token = xhr.getResponseHeader('__token__');
if (token) {
$("input[name='__token__']", form).val(token);
}
//关闭弹窗
var index = parent.Layer.getFrameIndex(window.name);
var callback = parent.$("#layui-layer" + index).data("callback");
parent.Layer.close(index);
//刷新列表
parent.$("#table").bootstrapTable('refresh');
}
}, function (data, ret) {
$('.form-group', form).removeClass('has-feedback has-success has-error');
if (data && typeof data === 'object') {
if (typeof data.token !== 'undefined') {
$("input[name='__token__']", form).val(data.token);
}
if (typeof data.callback !== 'undefined' && typeof data.callback === 'function') {
data.callback.call(form, data);
}
}
}, function (data, ret) {
if (data && typeof data === 'object' && typeof data.token !== 'undefined') {
$("input[name='__token__']", form).val(data.token);
}
});
return false;
});
// 注册商品多规格组件
var specMany = new GoodsSpec({
container: '.goods-spec-many',
OutForm:Form
}, from_specData);
// 切换单/多规格
$('select[name="row[spec_type]"').change(function (e) {
var $goodsSpecMany = $('.goods-spec-many')
, $goodsSpecSingle = $('.goods-spec-single');
if (e.currentTarget.value === '1') {
$goodsSpecMany.hide() && $goodsSpecSingle.show();
} else if (e.currentTarget.value === '2') {
$goodsSpecMany.show() && $goodsSpecSingle.hide();
} else {
$goodsSpecMany.hide() && $goodsSpecSingle.hide();
}
});
},
api: {
bindevent: function () {
Form.api.bindevent($("form[role=form]"));
}
}
};
return Controller;
});
\ No newline at end of file
... ...
(function () {
// 商品规格数据
var data = {
spec_attr: [],
spec_list: []
}
// 配置信息
, setting = {
container: '.goods-spec-many',
OutForm:''
};
function GoodsSpec(options, baseData) {
// 配置信息
setting = $.extend(true, {}, setting, options);
// 已存在的规格数据
typeof baseData !== 'undefined' && baseData !== null && (data = baseData);
// 初始化
this.initialize();
}
GoodsSpec.prototype = {
/**
* 初始化
*/
initialize: function () {
// 注册html容器
this.$container = $(setting.container);
this.$specAttr = this.$container.find('.spec-attr');
// 显示添加规则组表单事件
this.showAddSpecGroupEvent();
// 确认新增规则组事件
this.submitAddSpecGroupEvent();
// 取消新增规则组事件
this.cancelAddSpecGroupEvent();
// 注册添加规格元素事件
this.addSpecItemEvent();
// 注册删除规则组事件
this.deleteSpecGroupEvent();
// 注册删除规则元素事件
this.deleteSpecItemEvent();
// 注册删除单一sku事件
this.deleteSKUEvent();
// 注册批量设置sku事件
this.batchUpdateSku();
// 注册表格input数据修改事件
this.updateSpecInputEvent();
// 渲染已存在的sku信息
this.renderHtml();
},
/**
* 显示添加规则组表单
*/
showAddSpecGroupEvent: function () {
// 显示添加规则组表单
this.$container.on('click', '.btn-addSpecGroup', function () {
var $specGroupButton = $(this).parent()
, $specGroupAdd = $specGroupButton.next();
$specGroupButton.hide();
$specGroupAdd.show();
});
},
/**
* 确认新增规则组
*/
submitAddSpecGroupEvent: function () {
var _this = this;
// 确认添加
_this.$container.on('click', '.btn-addSpecName', function () {
var $specGroupAdd = $(this).parent().parent()
, $specGroupButton = $specGroupAdd.prev()
, $specNameInput = _this.$container.find('.input-specName')
, $specValueInput = _this.$container.find('.input-specValue')
, specValueInputValue = $specValueInput.val()
, specNameInputValue = $specNameInput.val();
if (specNameInputValue === '' || specValueInputValue === '') {
layer.msg('请填写规则名或规则值');
return false;
}
// 添加到数据库
var load = layer.load();
$.post('house_activity/addSpec', {
spec_name: specNameInputValue,
spec_value: specValueInputValue
}, function (result) {
console.log(result);
layer.close(load);
if (result.code !== 1) {
layer.msg(result.msg);
return false;
}
// 清空输入内容
$specNameInput.val('') && $specValueInput.val('');
// 记录规格数据
data.spec_attr.push({
group_id: result.data.spec_id,
group_name: specNameInputValue,
spec_items: [{
item_id: result.data.spec_value_id,
spec_value: specValueInputValue
}]
});
// 渲染规格属性html
_this.renderHtml();
// 隐藏添加规格组表单
$specGroupAdd.hide() && $specGroupButton.show();
});
});
},
/**
* 取消新增规格组
*/
cancelAddSpecGroupEvent: function () {
this.$container.on('click', '.btn-cancleAddSpecName', function () {
var $specGroupAdd = $(this).parent().parent()
, $specGroupButton = $specGroupAdd.prev();
// 隐藏添加规格组表单
$specGroupAdd.hide() && $specGroupButton.show()
});
},
/**
* 添加规则元素事件
*/
addSpecItemEvent: function () {
var _this = this;
_this.$container.on('click', '.btn-addSpecItem', function () {
var $this = $(this)
, $iptSpecItem = $this.prev('.ipt-specItem')
, specItemInputValue = $iptSpecItem.val()
, $specItemAddContainer = $this.parent()
, $specGroup = $specItemAddContainer.parent().parent();
if (specItemInputValue === '') {
layer.msg('规格值不能为空');
return false;
}
// 添加到数据库
var load = layer.load();
$.post('house_activity/addSpecValue', {
spec_id: $specGroup.data('group-id'),
spec_value: specItemInputValue
}, function (result) {
layer.close(load);
if (result.code !== 1) {
layer.msg(result.msg);
return false;
}
// 记录规格数据
data.spec_attr[$specGroup.data('index')].spec_items.push({
item_id: result.data.spec_value_id,
spec_value: specItemInputValue
});
// 渲染规格属性html
_this.renderHtml();
});
});
},
/**
* 删除规则组事件
*/
deleteSpecGroupEvent: function () {
var _this = this;
_this.$container.on('click', '.spec-group-delete', function () {
// 规则组索引
var index = $(this).parent().parent().attr('data-index');
layer.confirm('确定要删除该规则组吗?确认后不可恢复请谨慎操作', function (layerIndex) {
// 删除指定规则组
data.spec_attr.splice(index, 1);
// 重新渲染规格属性html
_this.renderHtml();
layer.close(layerIndex);
});
});
},
/**
* 删除规则组事件
*/
deleteSpecItemEvent: function () {
var _this = this;
_this.$container.on('click', '.spec-item-delete', function () {
var $item = $(this).parent()
, $specGroup = $item.parent().parent()
, groupIndex = $specGroup.attr('data-index')
, itemIndex = $item.attr('data-item-index');
layer.confirm('确定要删除该规则吗?确认后不可恢复请谨慎操作', function (layerIndex) {
// 删除指定规则组
data.spec_attr[groupIndex].spec_items.splice(itemIndex, 1);
// 重新渲染规格属性html
_this.renderHtml();
layer.close(layerIndex);
});
});
},
/**
* 注册批量设置sku事件
*/
batchUpdateSku: function () {
var _this = this,
$specBatch = _this.$container.find('.spec-batch');
$specBatch.on('click', '.btn-specBatchBtn', function () {
var formData = {};
$specBatch.find('input').each(function () {
var $this = $(this)
, formType = $this.data('type')
, value = $this.val();
if (typeof formType !== 'undefined' && formType !== '' && value !== '') {
formData[formType] = value;
}
});
if (!$.isEmptyObject(formData)) {
data.spec_list.forEach(function (item, index) {
data.spec_list[index].form = $.extend({}, data.spec_list[index].form, formData);
});
// 渲染商品规格table
_this.renderTabelHtml();
}
});
},
/**
* 渲染多规格模块html
*/
renderHtml: function () {
// 渲染商品规格元素
this.$specAttr.html(Template('tpl_spec_attr', data));
// 渲染商品规格table
this.renderTabelHtml();
},
deleteSKUEvent: function () {
var _this = this;
_this.$container.on('click', '.delsku-bt', function () {
// sku索引
var index = $(this).parent().parent().attr('data-index');
var sh_num = data.spec_list[index].form.stock_num;
var msgs = sh_num < 0? '确定要显示该sku吗?': '确定要隐藏该sku吗?';
layer.confirm(msgs, function (layerIndex) {
data.spec_list[index].form.stock_num = sh_num<0? 0 : -1;
console.log(data);
_this.$specAttr.html(Template('tpl_spec_attr', data));
var $specTabel = _this.$container.find('.spec-sku-tabel')
, $goodsSku = $specTabel.parent();
// 商品规格为空:隐藏sku容器
if (data.spec_attr.length === 0) {
$specTabel.empty();
$goodsSku.hide();
return false;
}
// 渲染table
$specTabel.html(Template('tpl_spec_table', data));
// 显示sku容器
$goodsSku.show();
(setting.OutForm).events.plupload($(".spec-sku-tabel"));
(setting.OutForm).events.faselect($(".spec-sku-tabel"));
layer.close(layerIndex);
return;
//_this.renderHtml();
//layer.close(layerIndex);
});
});
},
/**
* 渲染表格html
*/
renderTabelHtml: function () {
var $specTabel = this.$container.find('.spec-sku-tabel')
, $goodsSku = $specTabel.parent();
// 商品规格为空:隐藏sku容器
if (data.spec_attr.length === 0) {
$specTabel.empty();
$goodsSku.hide();
return false;
}
// 构建规格组合列表
this.buildSpeclist();
// 渲染table
$specTabel.html(Template('tpl_spec_table', data));
// 显示sku容器
$goodsSku.show();
//绑定按钮;
(setting.OutForm).events.plupload($(".spec-sku-tabel"));
(setting.OutForm).events.faselect($(".spec-sku-tabel"));
},
/**
* 构建规格组合列表
*/
buildSpeclist: function () {
// 规格组合总数 (table行数)
var totalRow = 1;
for (var i = 0; i < data.spec_attr.length; i++) {
totalRow *= data.spec_attr[i].spec_items.length;
}
// 遍历tr 行
var spec_list = [];
for (i = 0; i < totalRow; i++) {
var rowData = [], rowCount = 1, specSkuIdAttr = [];
// 遍历td 列
for (var j = 0; j < data.spec_attr.length; j++) {
var skuValues = data.spec_attr[j].spec_items;
rowCount *= skuValues.length;
var anInterBankNum = (totalRow / rowCount)
, point = ((i / anInterBankNum) % skuValues.length);
if (0 === (i % anInterBankNum)) {
rowData.push({
rowspan: anInterBankNum,
item_id: skuValues[point].item_id,
spec_value: skuValues[point].spec_value
});
}
specSkuIdAttr.push(skuValues[parseInt(point.toString())].item_id);
}
spec_list.push({
spec_sku_id: specSkuIdAttr.join('_'),
rows: rowData,
form: {}
});
}
// 合并旧sku数据
if (data.spec_list.length > 0 && spec_list.length > 0) {
for (i = 0; i < spec_list.length; i++) {
var overlap = data.spec_list.filter(function (val) {
return val.spec_sku_id === spec_list[i].spec_sku_id;
});
if (overlap.length > 0) spec_list[i].form = overlap[0].form;
}
}
data.spec_list = spec_list;
},
/**
* 输入规格信息自动同步更新spec_list
*/
updateSpecInputEvent: function () {
var _this = this;
_this.$container.find('.spec-sku-tabel').on('propertychange change', 'input', function () {
var $this = $(this)
, dataType = $this.attr('name')
, specIndex = $this.parent().parent().data('index');
data.spec_list[specIndex].form[dataType] = $this.val();
});
},
/**
* 获取当前data
*/
getData: function () {
return data;
},
/**
* sku列表是否为空
* @returns {boolean}
*/
isEmptySkuList: function () {
return !data.spec_list.length;
}
};
window.GoodsSpec = GoodsSpec;
})();
... ...