<?php
/**
 *  画册海报
 *  @author  system
 *  @version    1.0
 *  @date 2019-03-04 13:38:57
 *
 */
namespace App\Http\Controllers\Admin\Album;
use App\Http\Controllers\Admin\Controller;
use Illuminate\Http\Request;
use App\Repositories\Base\Criteria\OrderBy;
use App\Repositories\Album\Criteria\MultiWhere;
use App\Repositories\Album\PosterRepository;

class PosterController extends Controller
{
    private $repository;

    public function __construct(PosterRepository $repository)
    {
        if (!$this->repository) {
            $this->repository = $repository;
        }
    }

    /**
     * 修改
     */
    public function update(Request $request)
    {
        if ($request->method() == 'POST') {
            return $this->updateSave();
        }
        $data = $this->repository->findWhere(['store_id' => $this->getStoreId()])->toArray();
        if (!empty($data)) {
            $data = $data[0];
            $data['posters'] = json_decode($data['posters'], true);
            $data['words'] = json_decode($data['words'], true);
        }
        return view('admin.album.poster.edit', compact('data'));
    }

    /**
     * 保存修改
     */
    private function updateSave()
    {
        $data = (array) request('data');
        if (!empty($data['posters']['url'])) {
            foreach ($data['posters']['url'] as $key => $val) {
                $data['posters']['url'][$key] = $this->formatImgUrl($val);
            }
            $data['posters'] = json_encode($data['posters']['url']);
        }
        $data['share'] = $this->formatImgUrl($data['share']);
        $data['qrcode'] = $this->formatImgUrl($data['qrcode']);
        if (!empty($data['words'])) {
            $data['words'] = json_encode($data['words']);
        }
        $id = request('id');
        if (empty($id)) {
            $data['store_id'] = $this->getStoreId();
            $ok = $this->repository->create($data);
        } else {
            $ok = $this->repository->update($id, $data);
        }
        if ($ok) {
            $url[] = array('url' => U('Album/Poster/index'), 'title' => '返回列表');
            return $this->showMessage('操作成功', urldecode(request('_referer')));
        } else {
            $url[] = array('url' => U('Album/Poster/index'), 'title' => '返回列表');
            return $this->showWarning('操作失败', $url);
        }
    }

}