<?php
/**
* @author 龙虾 <15108148@qq.com>
* @version 2.0 2020-08-05
* @copyright 睿谷信息 <www.rgxx.com>
*/
namespace app\admin\controller;
use app\admin\model\Media as MediaModel;
use think\Controller;
use Request;

class Media extends Base
{
	// 文件列表
	public function index($type='all')
	{
		if(Request::isPost())
		{
			$data = MediaModel::when($type !== 'all',function($query)use($type){
				$query->whereType($type);
			})->order('create_time desc')->paginate(input('post.limit/d'))->toArray();
			return json(['code'=>0,'msg'=>lang('getdatatrue'),'data'=>$data['data'],'count'=>$data['total']]);
		}
		return $this->fetch('',compact('type'));
	}

	// 删除
	public function del()
	{
		if(Request::isPost()) {
			$data = Request::post();
			$result = MediaModel::del($data['id']);
			adminlog(2,'删除('.MediaModel::getLastsql().')',$result['code'] == 1?1:0);
			if ($result['code'] == 1) {
				$this->success($result['msg']);
			} else {
				$this->error($result['msg']);
			}
		}
	}

	// 清除不存在的文件
	public function dels()
	{
		if(Request::isPost()) {
			$data = Request::post();
			$result = MediaModel::dels();
			adminlog(2,'删除('.MediaModel::getLastsql().')',$result['code'] == 1?1:0);
			if ($result['code'] == 1) {
				$this->success($result['msg']);
			} else {
				$this->error($result['msg']);
			}
		}
	}

	// 素材选择
	public function show($formname='',$type='',$stype='')
	{
		// 列出月份
		if(strtolower(config('database.type')) == 'sqlite') {
			$allmonth = \think\Db::query("SELECT strftime('%Y%m',datetime(`create_time`, 'unixepoch', 'localtime')) AS themonth FROM `".config("database.prefix")."media` GROUP BY strftime('%Y%m',datetime(`create_time`, 'unixepoch', 'localtime'))");
		} else {
			$allmonth = \think\Db::query("SELECT FROM_UNIXTIME(`create_time`,'%Y%m%d') AS themonth FROM `".config("database.prefix")."media` GROUP BY FROM_UNIXTIME(`create_time`,'%Y%m%d')");
		}
		$allmonth = array_column($allmonth, 'themonth');
		rsort($allmonth);
		$type = empty($type) ? 'image' : $type;
		$stype = empty($stype) ? 'radio' : $stype;
		if(request()->isPost())
		{
			$themonth = input('post.themonth');
			if(empty($themonth)) {
				$data = MediaModel::where('type',$type)->order('create_time desc')->paginate(input('post.limit/d'))->toArray();
			} else {
				if(strtolower(config('database.type')) == 'sqlite') {
					$data = MediaModel::where("`type` = '{$type}' and strftime('%Y%m',datetime(`create_time`, 'unixepoch', 'localtime')) = '{$themonth}'")->order('create_time desc')->paginate(input('post.limit/d'))->toArray();
				} else {
					$data = MediaModel::where("`type` = '{$type}' and FROM_UNIXTIME(`create_time`,'%Y%m%d') = '{$themonth}'")->order('create_time desc')->paginate(input('post.limit/d'))->toArray();
				}
			}
			return json(['code'=>0,'msg'=>lang('getdatatrue'),'data'=>$data['data'],'count'=>$data['total']]);
		}
		return $this->fetch('',compact('type','stype','formname','allmonth'));
	}
}