<?php

namespace app\admin\controller;

use app\admin\common\AdminController;
use app\common\api\CommonFileApi;

/**
 * Description of System
 *
 * @author sgq
 */
class CommonFile extends AdminController {

    /**
     * @auth {{/commonFile/}}
     * @return type
     */
    public function index() {
        return view();
    }

    public function list() {
        $params = $this->request->param();
        $res = CommonFileApi::getList($params);
        return json($res);
    }

    public function add() {
        $params = $this->request->param();
        $returnObj = new \stdClass();
        $returnObj->obj = $params["index"];
        try {
            if (!$this->request->file())
                throw new \think\Exception("请上传附件");

            $file = $this->request->file("fileUrl");
            $upload = new \app\common\api\UploadApi();
            $result = $upload->uploadOne($file, "system", "common/file");
            if ($result->code != 200)
                throw new \think\Exception($result->msg);

            $data["url"] = $result->filepath;
            $data["originalName"] = $file->getOriginalName();
            $data["description"] = $params["description"];
            if (CommonFileApi::edit($data)) {
                $returnObj->msg = "上传附件成功";
                $returnObj->code = 200;
                echo sprintf("<script>parent.CommonFile.callback(%s);</script>", json_encode($returnObj));
                exit();
            }
            throw new \think\Exception("上传附件失败");
        } catch (\think\exception $e) {
            $returnObj->msg = $e->getMessage();
            $returnObj->code = 500;
            echo sprintf("<script>parent.CommonFile.callback(%s);</script>", json_encode($returnObj));
            exit();
        }
    }

    public function delete() {
        $id = $this->request->param("id");
        $file = CommonFileApi::getOne($id);
        if ($file && CommonFileApi::delete($id)) {
            $url = "storage/" . $file["url"];
            @unlink($url);
            return json(["code" => 200, "msg" => "删除成功"]);
        }
        return json(["msg" => "找不到对应附件"]);
    }

}
