<?php

namespace app\admin\controller;

use app\common\controller\Common;
use think\Request;
use think\facade\Db;
use think\facade\View;

/**
 * 附件管理
 */
class Attachment extends Common
{
    /**
     * 附件列表
     */
    public function index()
    {
        $attachment = Db::name('im_attachment')
            ->order('add_time desc')
            ->paginate(10, false, [
                'query' => request()->param(),
                'type' => 'page\Admin',
                'var_page' => 'page'
            ]);

        View::assign([
            'attachment' => $attachment
        ]);
        return view();
    }

    /**
     * 删除操作
     */
    public function del(Request $r)
    {
        if ($r->isAjax() && $r->isPost()) {
            $id = $r->post('id', 0, 'intval');
            $vatta = Db::name('im_attachment')->find($id);
            if (!empty($vatta)) {
                if ($vatta['cun_type'] == 1) {
                    $file = str_replace("\\", '/', root_path()) . 'public' . $vatta['path'];
                    if (is_file($file)) {
                        unlink($file);
                    }
                } else {

                }
                Db::name('im_record')->where('content', 'like', "%{$vatta['path']}%")->delete();
                Db::name('im_attachment')->delete($id);
                return json([
                    'code' => 200,
                    'msg'  => '删除成功'
                ]);
            } else {
                return json([
                    'code' => 300,
                    'msg'  => '删除失败'
                ]);
            }
        }
    }
}