<?php

namespace app\controller;

use app\model\Event as EventModel;
use think\facade\Filesystem;
use think\Request;

class Event
{
    public function ShowEvent()
    {
        $list = EventModel::paginate(20)->toArray();
        $i = 0;
        foreach ($list['data'] as $ll) {
            if (strpos($ll['pic'], ',') !== false) {
                $arr = explode(',', $ll['pic']);
                $s = 0;
                foreach ($arr as $a) {
                    $arr[$s] = $a;
                    $s += 1;
                }
                $list['data'][$i]['pic'] = $arr;
            } else {
                $list['data'][$i]['pic'] = (array)$list['data'][$i]['pic'];
            }
            $i += 1;
        }
        return json($list);
    }

    public function AddEvent(Request $request, $str_file = [], $str_list_file = '')
    {
        $data = $request->param();
        $title = $data['title'];
        $content = $data['content'];
        $file = $request->file();
        // 设定文件上传的大小
        $fileSize = 1024 * 1024 * 10;
        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
        $savename = [];
        $listname = [];
        if (!empty($file)) {
            foreach ($file as $f) {
                if (is_array($f)) {
                    foreach ($f as $singleFile) {
                        if (!in_array($singleFile->getMime(), $allowedTypes)) {
                            return json(['code' => 1, 'Msg' => '不支持的文件类型', 'data' => '']);
                        }
                    }
                } else {
                    if (!in_array($f->getMime(), $allowedTypes)) {
                        return json(['code' => 1, 'Msg' => '不支持的文件类型', 'data' => '']);
                    }
                }
            }
        }

        $pico = $this->SavePic($str_file, $fileSize, $file, $request, $savename, $listname, $str_list_file);
        $save = (new \app\model\Event)->save(['title' => $title, 'content' => $content, 'pic' => $pico['pic'], 'listpic' => $pico['listpic']]);
        if ((int)$save == 1) {
            return json(['code' => 200, 'Msg' => '新增成功', 'data' => ['title' => $title, 'content' => $content, 'pic' => $pico['pic'], 'listpic' => $pico['listpic']]]);
        } else {
            return json(['code' => 1, 'Msg' => '新增失败', 'data' => '']);
        }

    }

    public function EditEvent(Request $request, $str_file = [], $str_list_file = '')
    {
        $data = $request->param();
        $id = $data['id'];
        $title = $data['title'];
        $content = $data['content'];
        $status = (int)$data['status'];
        $edit = EventModel::find($id);
        $file = $request->file();
        // 设定文件上传的大小
        $fileSize = 1024 * 1024 * 10;
        $savename = [];
        $listname = '';
        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
        try {
            if (!empty($file)) {
                foreach ($file as $f) {
                    if (is_array($f)) {
                        foreach ($f as $singleFile) {
                            if (!in_array($singleFile->getMime(), $allowedTypes)) {
                                return json(['code' => 1, 'Msg' => '不支持的文件类型', 'data' => '']);
                            }
                        }
                    } else {
                        if (!in_array($f->getMime(), $allowedTypes)) {
                            return json(['code' => 1, 'Msg' => '不支持的文件类型', 'data' => '']);
                        }
                    }
                }
            }

            $pico = $this->SavePic($str_file, $fileSize, $file, $request, $savename, $listname, $str_list_file);
            $edit = $edit->save(['title' => $title, 'content' => $content, 'pic' => $pico['pic'], 'listpic' => $pico['listpic'], 'status' => $status]);
            if ((int)$edit == 1) {
                return json(['code' => 200, 'Msg' => '修改成功', 'data' => ['title' => $title, 'content' => $content, 'pic' => $pico['pic'], 'status' => $status, 'listpic' => $pico['listpic']]]);
            } else {
                return json(['code' => 1, 'Msg' => '修改失败', 'data' => '']);
            }
        } catch (\think\exception\ValidateException $e) {
            return json(['code' => 1, 'Msg' => $e->getMessage(), 'data' => '']);
        }

    }

    public function DeleteEvent($id)
    {
        $ee = EventModel::find($id);
        if ($ee != null) {
            $result = EventModel::destroy($id);
            if ($result) {
                return json(['code' => 200, 'Msg' => '删除成功']);
            } else {
                return json(['code' => 1, 'Msg' => '删除失败']);
            }
        } else {
            return json(['code' => 1, 'Msg' => '活动编号不存在']);
        }
    }


    /**
     * [将Base64图片转换为本地图片并保存]
     * @E-mial wuliqiang_aa@163.com
     * @TIME   2017-04-07
     * @WEB    http://blog.iinu.com.cn
     * @param  [Base64] $base64_image_content [要保存的Base64]
     * @param  [目录] $path [要保存的路径]
     */
    function base64_image_content($base64_image_content, $path = '../public/static/img', $name = '')
    {
        //匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
            $type = $result[2];
            $new_file = $path;
            if (!file_exists($new_file)) {
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($new_file, 0700);
            }
            $new_file =  $new_file . ($name ?? date('YmdHis', time()) ). ".{$type}";
            if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))) {
                return 'https://' . $_SERVER['HTTP_HOST'] . '/' . substr($new_file, 10);
            } else {
                return false;
            }
        } else {
            return false;
        }
    }


    /**
     * @param $fileSize
     * @param $file
     * @param Request $request
     * @param array $savename
     * @return array
     */
    protected function SavePic($str_file, $fileSize, $file, Request $request, array $savename, $listname, $str_list_file): array
    {
        if (!empty($str_file)) {
            foreach ($str_file as $sfile) {
                $savename[] = $sfile;
            }
        }
        if (!empty($file)) {
            validate(['logo' => 'fileSize:' . $fileSize . '|fileExt:jpg,png'])
                ->check($file);
            $small_file = $request->file("small_file");
            if (!empty($small_file) && empty($str_list_file)) {
                $listname = 'https://' . $_SERVER['HTTP_HOST'] . '/static/' . str_replace('\\', '/', \think\facade\Filesystem::disk('public')->putFile('img', $small_file));
            } elseif (!empty($str_list_file) && empty($small_file)) {
                $listname = $str_list_file;
            } else {
                $listname = '';
            }
            $files = $request->file("file");
            // 将图片保存至本地
            if (!empty($files)) {
                foreach ($files as $file) {
                    $savename[] = 'https://' . $_SERVER['HTTP_HOST'] . '/static/' . str_replace('\\', '/', \think\facade\Filesystem::disk('public')->putFile('img', $file));
                }
            }
        } else {
            if (!empty($str_list_file)) {
                $listname = $str_list_file;
            }
        }

        $pico = '';
        $i = 1;
        foreach ($savename as $p) {
            if ($i == count($savename)) {
                $pico .= $p;
            } else {
                $pico .= $p . ',';
            }
            $i += 1;
        }
        return ['pic' => $pico, 'listpic' => $listname];
    }

    public function EventList()
    {
        $list = EventModel::order('id desc')->paginate([
            'list_rows' => 20,
            'query' => request()->param()
        ]);
        
          foreach ($list as $ll=>$value) {
            if ($value['status'] == 1) {
                $list[$ll]['statusMsg'] = '上线中';
            } elseif ($value['status'] == 2) {
                $list[$ll]['statusMsg'] = '已下架';
            }
        }
        return json($list);
    }

    /**
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     */
    public function EventDetail($id)
    {
        $DMessage = EventModel::where('id', $id)->find()->toArray();
        $Dpic = [];
        if (strpos($DMessage['pic'], ',') !== false) {
            $PicArray = explode(',', $DMessage['pic']);
            $i = 0;
            foreach ($PicArray as $pic) {
                if ($i != 0) {
                    $Dpic[] = $pic;
                }
                $i += 1;
            }
        } else {
            $Dpic[] = $DMessage['pic'];
        }
        $DMessage['pic'] = $Dpic;
        if ((int)$DMessage['status'] == 1) {
            $DMessage['statusMsg'] = '上线中';
        } elseif ((int)$DMessage['status'] == 2) {
            $DMessage['statusMsg'] = '已下架';
        }
        return json($DMessage);
    }

    public function FindEvent($name)
    {
        $list = EventModel::whereLike('title', '%' . $name . '%')->paginate(20)->toArray();
        $i = 0;
        foreach ($list['data'] as $ll) {
            if (strpos($ll['pic'], ',') !== false) {
                $list['data'][$i]['pic'] = explode(',', $ll['pic']);
            } else {
                $list['data'][$i]['pic'] = (array)$ll['pic'];
            }
            $i += 1;
        }
        return json($list);
    }
}