<?php

namespace app\admin\controller;

use think\facade\Session;
use think\facade\Request;

use think\facade\Filesystem;

use app\common\model\Attachment as AttachmentModel;

class Attachment
{

    // 文件上传
    public function tplFieldFile()
    {
        $file     = request()->file("file");
        $savename = \think\facade\Filesystem::disk('public')->putFile('files', $file);
        if ($file) {
            $filename   = str_replace(strrchr($_FILES['file']['name'], "."), "", $_FILES['file']['name']);
            $attachment = AttachmentModel::create([
                'filename'   => $filename,
                'atype'      => 4,
                'attachment' => request()->domain() . "/attachment/" . str_replace("\\", "/", $savename),
                'createtime' => time(),
            ]);
            exit(json_encode([
                'code' => 0,
                'msg'  => "",
                'data' => [
                    'src'   => request()->domain() . "/attachment/" . str_replace("\\", "/", $savename),
                    'path'  => "./attachment/" . str_replace("\\", "/", $savename),
                    'title' => $filename,
                ],
            ]));
        } else {
            exit(json_encode([
                'code' => 1,
                'msg'  => "上传失败，请稍后重试",
            ]));
        }
    }

    // 图片上传
    public function tplFieldImage()
    {
        $this->validateExt(['jpg', 'png', 'jpeg']);
        $file     = request()->file("file");
        $savename = \think\facade\Filesystem::disk('public')->putFile('images', $file);
        if ($file) {
            $filename   = str_replace(strrchr($_FILES['file']['name'], "."), "", $_FILES['file']['name']);
            $attachment = AttachmentModel::create([
                'filename'   => $filename,
                'atype'      => 1,
                'attachment' => request()->domain() . "/attachment/" . str_replace("\\", "/", $savename),
                'createtime' => time(),
            ]);
            exit(json_encode([
                'code' => 0,
                'msg'  => "",
                'data' => [
                    'src'   => request()->domain() . "/attachment/" . str_replace("\\", "/", $savename),
                    'title' => $filename,
                ],
            ]));
        } else {
            exit(json_encode([
                'code' => 1,
                'msg'  => "上传失败，请稍后重试",
            ]));
        }
    }


    // 图片
    public function image()
    {
        $years     = range(date('Y'), date('Y') - 9);
        $months    = [
            ['key' => 1, 'val' => 1],
            ['key' => 2, 'val' => 2],
            ['key' => 3, 'val' => 3],
            ['key' => 4, 'val' => 4],
            ['key' => 5, 'val' => 5],
            ['key' => 6, 'val' => 6],
            ['key' => 7, 'val' => 7],
            ['key' => 8, 'val' => 8],
            ['key' => 9, 'val' => 9],
            ['key' => 10, 'val' => 10],
            ['key' => 11, 'val' => 11],
            ['key' => 12, 'val' => 12],
        ];
        $yearmonth = [];
        foreach ($years as $key => $value) {
            $yearmonth[$key]['key']   = $value;
            $yearmonth[$key]['val']   = $value;
            $yearmonth[$key]['month'] = $months;
        }
        return view('attachment/image', [
            'yearmonth' => json_encode($yearmonth),
        ]);
    }

    public function listImage()
    {
        $limit    = input('limit');
        $page     = input('page');
        $map      = [];
        $map[]    = ['atype', '=', 1];
        $keywords = input('keywords/s');
        if (!empty($keywords)) {
            $map[] = ['filename', 'like', '%' . $keywords . '%'];
        }
        $yearmonth = input('yearmonth/s');
        if (!empty($yearmonth)) {
            $yearmontharr = explode(",", $yearmonth);
            if (!empty($yearmontharr[1])) {
                $year     = $yearmontharr[0];
                $month    = $yearmontharr[1];
                $monthday = date("t", strtotime($year . "-" . $month));
                $stime    = mktime(0, 0, 0, $month, 1, $year);
                $etime    = mktime(23, 59, 59, $month, $monthday, $year);
                $map[]    = ['createtime', 'between', [$stime, $etime]];
            } else {
                $year  = $yearmontharr[0];
                $stime = mktime(0, 0, 0, 1, 1, $year);
                $etime = mktime(23, 59, 59, 12, 31, $year);
                $map[] = ['createtime', 'between', [$stime, $etime]];
            }
        }
        $list  = AttachmentModel::where($map)->order(['id' => 'desc'])->limit($limit)->page($page)->select();
        $count = AttachmentModel::where($map)->count();
        if ($count == 0) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "未查询到数据",
            ]));
        }
        exit(json_encode([
            'code'  => 0,
            'msg'   => "",
            'count' => $count,
            'data'  => $list,
        ]));
    }


    // 附件公共操作
    public function fieldAttachment()
    {
        $id         = input('id/d');
        $attachment = AttachmentModel::findOrEmpty($id);
        if ($attachment->isEmpty()) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "附件信息不存在",
            ]));
        } else {
            $attachment->save([
                input('field/s') => input('value'),
            ]);
        }
        exit(json_encode([
            'code' => 0,
        ]));
    }

    public function delAttachment()
    {
        $idarr      = input('idarr/a');
        $attachment = AttachmentModel::whereIn('id', $idarr)->select();
        foreach ($attachment as $v) {
            $attachmenturl = str_replace(request()->domain(), ".", $v['attachment']);
            @unlink($attachmenturl);
        }
        $result = $attachment->delete();
        if ($result) {
            exit(json_encode([
                'code' => 0,
                'msg'  => "",
            ]));
        }
        exit(json_encode([
            'code' => 1,
            'msg'  => "删除失败，请稍后重试",
        ]));
    }

    public function validateExt($ext_arr)
    {
        $ext = pathinfo($_FILES['file']['name'])['extension'];
        if (!in_array($ext, $ext_arr)) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "文件格式不正确",
            ]));
        }
    }
}