<?php
/**
 * Created by PhpStorm.
 * User: 中闽 < 1464674022@qq.com >
 * Date: 2019/12/5
 * Time: 17:44
 */

namespace app\admin\controller;

use app\admin\controller\base\Permissions;
use app\common\model\Templet as tpModel;
use app\common\service\UploadService;
use file\FileHelper;
use paginate\PaginateHelper;

class Templet extends Permissions
{
    public function index()
    {
        if ($this->request->isAjax()) {
            $name = $this->request->param('name');
            $data = tpModel::getTemplets(trim($name));
            $total = count($data);
            //分页
            $helper = new PaginateHelper($total, $this->request->param('limit'), $this->request->param('page'));
            $start = $helper->start() - 1;
            $end = $helper->end() - 1;
            foreach ($data as $k => $v) {
                if ($k > $end || $k < $start)
                    unset($data[$k]);
            }
            return array('code' => 0, 'data' => $data, 'count' => $total);
        } else {
            $this->assign('tpPath', tpModel::getTempletDir());
            return $this->fetch();
        }
    }

    public function publish()
    {
        $rootpath = tpModel::getTempletDir();
        $post = $this->request->post();
        $filename = trim($this->request->param('filename'));//文件名
        $name = $this->request->param('name');//新增模板名

        if ($filename) {
            //修改操作
            $filePath = $rootpath . $filename . ".html";
            if ($this->request->isPost()) {
                $getfilemtime = $this->request->param('filemtime');
                if ($getfilemtime != filemtime($filePath)) {
                    $this->error('文件版本不正确，请刷新后重新提交');
                }
                try {
                    FileHelper::save($filePath, $post['content']);
                } catch (\Exception $e) {
                    $this->error('修改失败.' . $e->getMessage());
                }
                $this->success('修改成功', '', filemtime($filePath));
            } else {
                if (file_exists($filePath)) {
                    $this->assign('filename', $filename);
                    $this->assign('filemtime', filemtime($filePath));
                    $this->assign('content', FileHelper::read($filePath));
                    return $this->fetch();
                } else {
                    $this->error('模板格式不正确');
                }
            }
        } else {
            //新增操作
            if ($this->request->isPost()) {
                $validate = new \think\Validate([
                    ['name|模板名称', 'require|alphaDash'],
                ]);
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }
                $filePath = $rootpath . $name . ".html";
                if (file_exists($filePath)) {
                    $this->error('该文件已存在，请修改名称');
                } else {
                    try {
                        FileHelper::save($filePath, $post['content']);
                    } catch (\Exception $e) {
                        $this->error('添加失败.' . $e->getMessage());
                    }
                }
                $this->success('添加成功', 'index');
            } else {
                return $this->fetch();
            }
        }
    }

    public function delete()
    {
        if ($this->request->isAjax()) {
            $fullname = $this->request->param('fullname');
            $rootpath = tpModel::getTempletDir();

            if (false == unlink($rootpath . $fullname)) {
                $this->error('删除失败');
            } else {
                $this->success('删除成功', 'index');
            }
        }
    }

    public function rename()
    {
        if ($this->request->isAjax()) {
            $oldname = $this->request->param('oldname');
            $newname = $this->request->param('newname');
            $rootpath = tpModel::getTempletDir();
            if (file_exists($rootpath . $newname)) {
                $this->error('文件已存在');
            }
            if (FileHelper::rename($rootpath . $oldname, $rootpath . $newname)) {
                (new \app\common\model\Catalog())->save(['catalog_templet' => $newname], ['catalog_templet' => $oldname]);
                (new \app\common\model\Catalog())->save(['article_templet' => $newname], ['article_templet' => $oldname]);
                $this->success('重命名成功', 'index');
            } else {
                $this->error('重命名失败');
            }
        }
    }

    public function upload()
    {
        $rootpath = tpModel::getTempletDir();
        (new UploadService())->upload2path($rootpath);
    }
}