Decorate.php 15.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
<?php

namespace app\admin\controller\groupon;

use app\common\controller\Backend;
use app\admin\model\groupon\DecorateContent;
use think\Db;
use fast\Http;
use think\exception\PDOException;
use think\exception\ValidateException;
use Exception;
/**
 * 店铺装修
 *
 * @icon fa fa-circle-o
 */
class Decorate extends Backend
{

    protected $noNeedLogin = ['select'];
    /**
     * Decorate模型对象
     * @var \app\admin\model\groupon\Decorate
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\groupon\Decorate;
    }

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

    public function lists($type = '')
    {
        if ($this->request->isAjax()) {
            $data = $this->model->with('contents')->where('type', $type)->order('id', 'desc')->select();
            return json([
                'code' => 1,
                'msg' => '模板列表',
                'data' => $data
            ]);
        }
        return $this->view->fetch();
    }


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

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    //添加默认数据
                    if ($params['type'] === 'shop') {
                        DecorateContent::create([
                            'type' => 'header',
                            'category' => 'home',
                            'name' => '头部',
                            'content' => '{"name":"Index","bgcolor":"#0FC7CD"}',
                            'decorate_id' => $this->model->id
                        ]);
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    //添加默认模板数据
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($id = null)
    {
        $row = $this->model->get($id);
        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();
            if ($params) {
                $params = $this->preExcludeFields($params);
                //检查是否有同平台冲突的已发布模板
                if ($row->status === 'normal' && $row['type'] === 'shop') {
                    $platformArray = explode(',', $params['platform']);
                    $where = ['deletetime' => null, 'status' => 'normal', 'type' => 'shop', 'id' => ['neq', $id]];
                    foreach ($platformArray as $v) {
                        $publishDecorate = $this->model->where('find_in_set(:platform,platform)', ['platform' => $v])->where($where)->find();
                        if ($publishDecorate) {
                            $this->error(__($v) . ' 已经被使用');
                        }
                    }
                }

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 模板管理 发布
     * @param string $id
     * @param int $force
     */
    public function publish($id, $force = 0)
    {
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (empty($row->platform)) {
            $this->error('请选择模板的发布平台', null, 0);
        }
        $platformArray = explode(',', $row->platform);
        $where = ['deletetime' => null, 'status' => 'normal', 'type' => 'shop'];
        $existPublish = [];
        foreach ($platformArray as $v) {
            $publishDecorate = $this->model->where('find_in_set(:platform,platform)', ['platform' => $v])->where($where)->find();
            if ($publishDecorate) {
                if ($force == 1) {
                    $platform = array_diff(explode(',', $publishDecorate->platform), [$v]);
                    $publishDecorate->platform = implode(',', $platform);
                    if ($publishDecorate->platform == '') {
                        $publishDecorate->status = 'hidden';
                    }
                    $publishDecorate->save();
                } else {
                    $existPublish[$publishDecorate->name][] = __($v);
                }
            }
        }

        if ($existPublish !== [] && $force == 0) {
            $str = '';
            foreach ($existPublish as $k => $e) {
                $str .= $k . ',';
            }
            $this->error("${str} 已存在相同的支持平台,确定替换吗?");
        }
        $row->status = 'normal';
        $row->save();
        $this->success('发布成功');
    }

    /**
     * 模板管理 下架
     * @param string $id
     */
    public function down($id)
    {
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $where = ['deletetime' => null, 'status' => 'normal', 'type' => 'shop'];
        $publishDecorate = $this->model->where($where)->select();
        if (count($publishDecorate) == 1) {
            $this->error('您需要至少保留一个发布模板~');
        }

        $row->status = 'hidden';
        $row->save();
        $this->success('下架成功');
    }

    /**
     * 模板管理 复制
     * @param string $id
     */
    public function copy($id)
    {
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $this->model->save([
            'name' => "复制 {$row->name}",
            'type' => $row->type,
            'memo' => $row->memo,
            'image' => $row->image,
            'status' => 'hidden',
            'platform' => $row->platform,
        ]);
        $id = $this->model->id;
        $content = collection(DecorateContent::where('decorate_id', $row->id)
            ->order('id asc')
            ->field("type, category, content, name, $id as decorate_id")
            ->select())->toArray();

        $decorateContent = new DecorateContent();
        $decorateContent->saveAll($content);
        $this->success('复制成功');
    }


    /**
     * 自定义页面
     */
    public function custom()
    {
        return $this->view->fetch();
    }


    /**
     * 页面装修
     * @param string $id
     */
    public function dodecorate($id)
    {
        $content = new DecorateContent();
        $query = $content->where(['decorate_id' => $id]);
        if ($this->request->isPost()) {
            $params = $this->request->post("templateData");
            if ($params) {
                $params = json_decode($params, true);
                $result = false;
                Db::startTrans();
                try {
                    $decorateArray = [];
                    foreach ($params as $p => $a) {
                        foreach ($a as $c => &$o) {
                            if (isset($o['id'])) {
                                unset($o['id']);
                            }
                            $decorateArray[] = [
                                'category' => $p,
                                'content' => json_encode($o['content'], JSON_UNESCAPED_UNICODE),
                                'decorate_id' => $id,
                                'name' => $o['name'],
                                'type' => $o['type']
                            ];
                        }
                    }

                    $query->delete();
                    $result = new \app\admin\model\groupon\DecorateContent;
                    $result->saveAll($decorateArray);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error('请完善装修页面');
        }
        $template = $query->select();
        if ($template) {
            foreach ($template as &$t) {
                $t['content'] = json_decode($t['content'], true);
            }
        } else {
            $template = [];
        }
        $categoryArray = array_column($template, 'category');
        $templateData = [];
        foreach ($categoryArray as $k => $c) {
            $templateData[$c][] = $template[$k];
        }

        $this->assignconfig('templateData', $templateData);
        $this->assignconfig('preview_id', $id);
        return $this->view->fetch();
    }

    /**
     * 页面装修 保存
     * @param string $id
     */
    public function dodecorate_save($id)
    {
        if ($this->request->isPost()) {
            $decorate = $this->model->get($id);

            if (!$decorate) {
                $this->error(__('No Results were found'));
            }

            $params = $this->request->post("templateData");
            $result = $this->updateDecorateContent($id, $params);
            if ($result) {
                $this->success('保存成功', null, $decorate);
            } else {
                $this->error('保存失败');
            }
        }
    }

    private function updateDecorateContent($id, $params)
    {
        $result = false;

        if ($params) {
            $params = json_decode($params, true);
            Db::startTrans();
            try {
                $decorateArray = [];
                foreach ($params as $p => $a) {
                    foreach ($a as $c => &$o) {
                        if (isset($o['id'])) {
                            unset($o['id']);
                        }
                        $decorateArray[] = [
                            'category' => $p,
                            'content' => json_encode($o['content'], JSON_UNESCAPED_UNICODE),
                            'decorate_id' => $id,
                            'name' => $o['name'],
                            'type' => $o['type']
                        ];
                    }
                }

                DecorateContent::where(['decorate_id' => $id])->delete();
                $result = new DecorateContent();
                $result->saveAll($decorateArray);
                Db::commit();
                return $result;
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        return $result;
    }

    

    /**
     * 真实删除
     */
    public function destroy($ids = "")
    {
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        if ($ids) {
            $this->model->where($pk, 'in', $ids);
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->onlyTrashed()->select();
            foreach ($list as $k => $v) {
                DecorateContent::where('decorate_id', $v->id)->delete();
                $count += $v->delete(true);
            }
            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        } else {
            $this->error(__('No rows were deleted'));
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    public function select()
    {
        if ($this->request->isAjax()) {
            return $this->index();
        }
        return $this->view->fetch();
    }
}