<?php
/**
 * User: nickbai
 * Date: 2017/10/23 13:33
 * Email: 1902822973@qq.com
 */
namespace app\admin\controller;

use think\Loader;
use think\Controller;
use think\Db;

class Material extends Base
{
    // 素材列表
    public function index()
    {
        $div = '<div>';
        if(request()->isAjax()){
            $param  = input('param.');
            $limit  = $param['pageSize'];
            $offset = (($param['pageNumber'] - 1) * $limit);
            $where = [];
            if (empty($param['searchText']) === false || intval($param['searchText']) == 0) {
                if($param['user'] == 'user_account'){
                    $where['user_account'] = ['like', '%' . $param['searchText'] . '%'];
                }
                if($param['user'] == 'user_name'){
                    $where['user_name'] = ['like', '%' . $param['searchText'] . '%'];
                }
                // $where['user_account|user_name|user_job_number|fullname'] = ['like', '%' . $param['searchText'] . '%'];
            }else{
                return 1;
            }
            $result = db('material')->where($where)->limit($offset, $limit)->order('id', 'desc')->select();

            foreach($result as $key=>$vo){
                // 优化显示头像
                $result[$key]['url'] = '<img src="' . $vo['url'] . '" height="40px">';

                $div .= $result[$key]['url'];
                // 生成操作按钮
                $result[$key]['operate'] = $this->makeBtn($vo['id']);
            }

//            $return['total'] = db('users')->where($where)->count();  //总数据
//            $return['rows'] = $result;

//            return json($return);

        }

        //所有素材
        $material = db('material')->order('name', 'asc')->select();
        $allmaterial = '';
        if(!empty($material)){
            $allmaterial = '<div style="margin-top: 20px;">';
            for($i=0;$i<count($material);$i++){
                $allmaterial .= '<div style="width: 33.3%;height:150px;float: left;border: 1px solid red;">';
                $allmaterial .= '<img src="' . $material[$i]['url'] . '" height="30%">';
                $allmaterial .= '</div>';
            }
            $allmaterial .= '</div>';
        }
        $this->assign([
            'div' => $div,
            'material' => $material,
            'allmaterial' => $allmaterial
        ]);

        return $this->fetch();
    }

    // 添加素材
    public function add()
    {
        if(request()->isPost()){

            $param = input('post.');
            unset($param['file']); // 删除layui头像上传隐藏字段

            // 检测图片名称
            $res = db('material')->where('name',$param['name'])->select();
            if(!empty($res)){
                return json(['code' => -1, 'data' => '', 'msg' => '名称已存在']);
            }

            // 检测图片
            if(empty($param['material'])){
                return json(['code' => -2, 'data' => '', 'msg' => '请上传素材']);
            }
            $info =array();
            $info['url'] = $param['material'];
            $info['name'] = $param['name'];

            try{
                db('material')->insert($info);
            }catch(\Exception $e){
                return json(['code' => -5, 'data' => '', 'msg' => $e->getMessage()]);
            }

            return json(['code' => 1, 'data' => 'material/index', 'msg' => '添加素材成功']);
        }

        $this->assign([
            'status' => config('kf_status')
        ]);

        return $this->fetch('add');
    }

    // 删除素材
    public function del()
    {
        if(request()->isAjax()){
            $id = input('param.id/d');
            $material = db('material')->where('id',$id)->find();
            $name = './'.$material['url'];
//            $name = iconv("UTF-8", "gbk",$name);
            try{
                if (file_exists($name)) {
                    unlink($name);
                }
                db('material')->where('id', $id)->delete();
            }catch(\Exception $e){
                return json(['code' => -2, 'data' => '', 'msg' => $e->getMessage()]);
            }

            return json(['code' => 1, 'data' => url('material/index'), 'msg' => '删除图片成功']);
        }
    }

    // 删除全部素材
    public function delAll()
    {
        if(request()->isAjax()){
            $material = db('material')->select();
            try{
                for($i=0;$i<count($material);$i++){
                    $name = './'.$material[$i]['url'];
                    if (file_exists($name)) {
                        unlink($name);
                    }
                }
                Db::execute("truncate table ws_material");
            }catch(\Exception $e){
                return json(['code' => -2, 'data' => '', 'msg' => $e->getMessage()]);
            }
            return json(['code' => 1, 'data' => url('material/index'), 'msg' => '删除全部图片成功']);
        }
    }

    // 上传图片(图片原名)
//    public function upMaterial()
//    {
//        if(request()->isAjax()) {
//            $file = request()->file('file');
//            if (!empty($file)) {
//                // 移动到框架应用根目录/public/static/material/ 目录下
//                $name = $_FILES['file']['name'];
//                $res = db('material')->where('url','/static/material/'.$name)->find();
//                if(!empty($res)){
//                    return json(['code' => -1, 'data' => '', 'msg' => '素材已存在']);
//                }
//                //中文乱码问题
//                $name = iconv("UTF-8", "gbk",$name);
//                $info = $file->move(ROOT_PATH . 'public' . DS . 'static/material/',$savename = $name,$replace = true);
//                $name = iconv("gbk","UTF-8",$name);
//                if ($info) {
//                    $src = '/static/material' . '/' . $name;
//                    return json(['code' => 0, 'data' => ['src' => $src,'name' => $name], 'msg' => 'ok']);
//                } else {
//                    // 上传失败获取错误信息
//                    return json(['code' => -1, 'data' => '', 'msg' => $file->getError()]);
//                }
//            }
//        }
//    }

    // 上传图片
    public function upMaterial()
    {
        if(request()->isAjax()) {

            $file = request()->file('file');
            if (!empty($file)) {
                // 移动到框架应用根目录/public/uploads/ 目录下
                $info = $file->move(ROOT_PATH . 'public' . DS . 'static/material/');
                if ($info) {
                    $src = '/static/material' . '/' . date('Ymd') . '/' . $info->getFilename();
                    return json(['code' => 0, 'data' => ['src' => $src], 'msg' => 'ok']);
                } else {
                    // 上传失败获取错误信息
                    return json(['code' => -1, 'data' => '', 'msg' => $file->getError()]);
                }
            }
        }
    }

    // 生成按钮
    private function makeBtn($id)
    {
//        $operate = '<a href="' . url('users/edituser', ['id' => $id]) . '">';
//        $operate .= '<button type="button" class="btn btn-primary btn-sm"><i class="fa fa-paste"></i> 编辑</button></a> ';

        $operate = '<a href="javascript:resetPwd(' . $id . ')"><button type="button" class="btn btn-primary btn-sm"><i class="fa fa-paste"></i> 重置密码</button></a>';

        $operate .= '<a style="margin-left:5px;" href="' . url('users/editUser', ['id' => $id]) . '">';
        $operate .= '<button type="button" class="btn btn-primary btn-sm"><i class="fa fa-paste"></i> 编辑</button></a> ';

        $operate .= '<a style="margin-left:5px;" href="javascript:userDel(' . $id . ')"><button type="button" class="btn btn-danger btn-sm">';
        $operate .= '<i class="fa fa-trash-o"></i> 删除</button></a> ';

        //$operate .= '<a href="javascript:;">';
        //$operate .= '<button type="button" class="btn btn-info btn-sm"><i class="fa fa-institution"></i> 详情</button></a>';

        return $operate;
    }
}
