<?php
/**
 * Created by PhpStorm.
 * User: 30868
 * Date: 2018/9/13
 * Time: 20:59
 */

namespace app\admin\controller;

use app\admin\controller\AuthBase;
use app\common\model\Admin as AdminModel;
use app\admin\controller\Upload;
use app\common\model\Catalogs;
use app\common\model\Citys;
use app\common\model\Project as ProjectModel;
use app\common\model\Tags;

class Project extends AuthBase
{
    protected $tag_model;
    protected $city_model;
    protected $catalog_model;
    protected $project_model;
    protected $appoint_model;

    public function _initialize()
    {
        $this->project_model = model("project");
        $this->tag_model     = model("Tags");
        $this->city_model    = model("Citys");
        $this->catalog_model = model("Catalogs");
        $this->appoint_model = model("Reservations");
        parent::_initialize();
    }

    //活动列表
    public function index()
    {
        $title      = input('get.title');
        $type       = input('get.type');
        $catalog_id = input('get.catalog_id');
        $condition  = [];
        if ($title) {
            $condition['title'] = ['like', "%" . $title . "%"];
        }
        if ($type) {
            $condition['type'] = $type;
        }
        if ($catalog_id) {
            $condition['catalog_id'] = $catalog_id;
        }
        if (input('order') == 2) {
            $order = ['sort' => 'desc', 'id' => 'desc'];
        } else {
            $order = ['id' => 'desc'];
        }
        $catalog_list = $this->catalog_model->order('sort', 'asc')->select();
        $this->assign('catalog_list', $catalog_list);
        $project_list =
            $this->project_model
                ->where($condition)
                ->order($order)
                ->paginate(10, false, ['query' => ['title' => $title, 'type' => $type, 'catalog_id' => $catalog_id]]);
        $this->assign('project_list', $project_list);
        return $this->fetch('');
    }

    // 添加项目
    public function create()
    {

        if (request()->isPost()) {
            // 引入上传类
            $upload = new Upload();

            $file      = input('file.');
            $data      = input('post.');
            $poster    = '';
            $kf_qrcode = '';
            $banners   = [];
            //如果是商家则保存客服二维码
            if ($data['type'] == 2) {
                $file = request()->file('kf_qrcode');
                $info = $file->move('./upload/qrcode/');
                if ($info) {
                    $kf_qrcode         = "/upload/qrcode/" . $info->getSaveName();
                    $data['kf_qrcode'] = $kf_qrcode;
                }
            }
            //保存封面
            $result = $upload->sava(input('file.poster'));
            if (!$result['error']) {
                $poster         = $result['result']['url'];
                $data['poster'] = $poster;
            }
            //遍历banner数组并保存
            foreach (input('file.banners') as $name => $f) {
                $result = $upload->sava($f);
                if (!$result['error']) {
                    $banners[]       = $result['result']['url'];
                    $data['banners'] = json_encode($banners);
                }
            }

            //去除null
            foreach ($data as $k => $v) {
                if ($v === 'null') {
                    unset($data[$k]);
                }
            }

            //写入数据库
            $res = $this->project_model->data($data)->save();
            if ($res) {
                $this->success('添加成功', '', '', 1);
            } else {
                $this->error('添加到数据库失败', '', '', 1);
            }
        } else {
            $tag_list = $this->tag_model->order('sort', 'asc')->select();
            $this->assign('tag_list', $tag_list);
            $catalog_list = $this->catalog_model->order('sort', 'asc')->select();
            $this->assign('catalog_list', $catalog_list);
            $city_list = $this->city_model->order('sort', 'asc')->select();
            $this->assign('city_list', $city_list);
            $this->assign('project_info', 0);
            $this->assign('tags', 0);
            return $this->fetch('updateproject');
        }

    }

    //删除项目、商家
    public function delete()
    {
        $id   = input('post.id');
        $used = model('Orders')->where('pid', $id)->count();
//        if ($used > 0) {
//            $this->error('该项目已有用户下单,不可删除！', '', '', 1);
//        }

        $res = model('project')->destroy($id);
        if ($res) {
            $this->success('删除成功', '', '', 1);
        } else {
            $this->error('删除失败', '', '', 1);
        }
    }

    // 修改项目
    public function updateProject($id)
    {
        if (request()->isPost()) {
            // 引入上传类
            $id     = input('post.id');
            $upload = new Upload();
            $file   = input('file.');
            $data   = input('post.');
            $data   = array_merge(array_diff($data, array('id' => $id)));

            // unset($data['description']);
            // echo json_encode($data); exit;
            $poster       = '';
            $kf_qrcode    = '';
            $banners      = [];
            $project_info = $this->project_model->find($id);

            $old_banners   = json_decode($project_info['banners_native']);
            $old_poster    = $project_info['poster'];
            $old_kf_qrcode = $project_info['kf_qrcode'];
            //如果是商家则保存客服二维码
            if ($data['type'] == 2) {
                if (input('file.kf_qrcode')) {
                    $file = request()->file('kf_qrcode');
                    $info = $file->move('./upload/qrcode/');
                    if ($info) {
                        $kf_qrcode         = "/upload/qrcode/" . $info->getSaveName();
                        $data['kf_qrcode'] = $kf_qrcode;
                    }
                }
            }
            //保存封面
            if (input('file.poster')) {
                $result = $upload->sava(input('file.poster'));
                if (!$result['error']) {
                    $poster         = $result['result']['url'];
                    $data['poster'] = $poster;
                }
            }
            //遍历banner数组并保存
            if (input('file.banners')) {
                $file_banners = input('file.banners');
                foreach ($file_banners as $name => $f) {
                    $result = $upload->sava($f);
                    if (!$result['error']) {
                        $banners[] = $result['result']['url'];
                    }
                }
                $data['banners'] = json_encode(array_merge($banners, $old_banners));
            }

            //去除null
            foreach ($data as $k => $v) {
                if ($v === 'null') {
                    unset($data[$k]);
                }
            }

            //写入数据库
            $res = $this->project_model->save($data, ['id' => $id]);
            if ($res) {
                $this->success('修改成功', '', '', 1);
            } else {
                $this->error('修改失败', '', '', 1);
            }
        } else {
            $project_info = $this->project_model->find($id);
            // return;
            $this->assign('project_info', $project_info);
            //反显，处理项目/商品已使用标签
            $value = $project_info->tags_id_str;
            $value = trim($value, '|');
            $tags  = explode('|', $value);
            $this->assign('tags', $tags);
            //反显，读取所有tags
            $tag_list = $this->tag_model->order('sort', 'asc')->select();
            $this->assign('tag_list', $tag_list);
            //反显，读取所有分类
            $catalog_list = $this->catalog_model->order('sort', 'asc')->select();
            $this->assign('catalog_list', $catalog_list);
            //反显，读取所有城市
            $city_list = $this->city_model->order('sort', 'asc')->select();
            $this->assign('city_list', $city_list);
            return $this->fetch();
        }
    }

    // 标签管理
    public function tags()
    {
        $title    = input('get.name', '');
        $tag_list = $this->tag_model->where('name', 'like', "%" . $title . "%")->order('sort', 'desc')->order('id', 'desc')->paginate(15);
        $this->assign("tag_list", $tag_list);
        return $this->fetch('');
    }

    //添加标签
    public function addTag()
    {
        $data     = array(
            'name' => trim(input('post.name')),
            'sort' => input('post.sort', 0),
        );
        $validate = validate('Project');
        if (!$validate->scene('addTag')->check($data)) {
            $this->error($validate->getError(), $_SERVER["HTTP_REFERER"], '', 1);
        } else {
            $res = $this->tag_model->data($data)->save();
            if (!$res) {
                $this->error('添加失败', $_SERVER["HTTP_REFERER"], '', 1);
            } else {
                $this->redirect($_SERVER["HTTP_REFERER"]);
            }
        }
    }

    public function editTag($id)
    {
        $this->assign('id', $id);
        $tag_info = $this->tag_model->where('id', $id)->find();
        $this->assign('tag_info', $tag_info);
        return $this->fetch();
    }

    //修改标签
    public function updateTag()
    {
        $id       = input('post.id');
        $data     = array(
            'id'   => $id,
            'name' => trim(input('post.name')),
            'sort' => input('post.sort', 0)
        );
        $validate = validate('Project');
        if (!$validate->scene('updateTag')->check($data)) {
            $this->error($validate->getError(), $_SERVER["HTTP_REFERER"], '', 1);
        } else {
            $res = $this->tag_model->save($data, ['id' => $id]);
            if (!$res) {
                $this->error('修改失败', $_SERVER["HTTP_REFERER"], '', 1);
            } else {
                $this->redirect(url('admin/project/tags'));
            }
        }
    }

    //删除标签
    public function deleteTag()
    {
        $id   = input('post.id');
        $used = $this->project_model->where('tags', 'like', "%" . '|' . $id . '|' . "%")->count();
        if ($used > 0) {
            $this->error('该标签已在项目中引用,不可删除！', '', '', 1);
        }
        $res = model('tags')->destroy($id);
        if ($res) {
            $this->success('删除成功', '', '', 1);
        } else {
            $this->error('删除失败', '', '', 1);
        }
    }

    // 预约管理
    public function appoint()
    {
        $title = input('get.name', '');
        $items = $this->appoint_model->where('nickname', 'like', "%" . $title . "%")->order('id', 'desc')->paginate(15, false, ['query' => ['nickname' => $title]])->each(function ($item) {
            $project                = \app\common\model\Project::withTrashed()->find($item['pid']);
            $item['project_poster'] = $project['poster'];
            $item['project_title']  = $project['title'];
        });
        $this->assign("items", $items);
        return $this->fetch('');
    }

    // 城市管理
    public function citys()
    {
        $title    = input('get.name', '');
        $tag_list = $this->city_model->where('name', 'like', "%" . $title . "%")->order('sort', 'desc')->order('id', 'desc')->paginate(15);
        $this->assign("tag_list", $tag_list);
        return $this->fetch('');
    }

    //添加城市
    public function addCity()
    {
        $data     = array(
            'name' => trim(input('post.name')),
            'sort' => input('post.sort', 0),
        );
        $validate = validate('Project');
        if (!$validate->scene('addTag')->check($data)) {
            $this->error($validate->getError(), $_SERVER["HTTP_REFERER"], '', 1);
        } else {
            $res = $this->city_model->data($data)->save();
            if (!$res) {
                $this->error('添加失败', $_SERVER["HTTP_REFERER"], '', 1);
            } else {
                $this->redirect($_SERVER["HTTP_REFERER"]);
            }
        }
    }

    public function editCity($id)
    {
        $this->assign('id', $id);
        $tag_info = $this->city_model->where('id', $id)->find();
        $this->assign('tag_info', $tag_info);
        return $this->fetch();
    }

    //编辑城市
    public function updateCity()
    {
        $id       = input('post.id');
        $data     = array(
            'id'   => $id,
            'name' => trim(input('post.name')),
            'sort' => input('post.sort', 0)
        );
        $validate = validate('Project');
        if (!$validate->scene('updateTag')->check($data)) {
            $this->error($validate->getError(), $_SERVER["HTTP_REFERER"], '', 1);
        } else {
            $res = $this->city_model->save($data, ['id' => $id]);
            if (!$res) {
                $this->error('修改失败', $_SERVER["HTTP_REFERER"], '', 1);
            } else {
                $this->redirect(url('admin/project/citys'));
            }
        }
    }

    //删除城市
    public function deleteCity()
    {
        $id   = input('post.id');
        $used = $this->project_model->where('city', $id)->count();
        if ($used > 0) {
            $this->error('该城市已在项目中引用,不可删除！', '', '', 1);
        }

        $res = model('citys')->destroy($id);
        if ($res) {
            $this->success('删除成功', '', '', 1);
        } else {
            $this->error('删除失败', '', '', 1);
        }
    }

    // 分类管理
    public function catalogs()
    {
        $title    = input('get.name', '');
        $tag_list = $this->catalog_model->where('name', 'like', "%" . $title . "%")->order('sort', 'asc')->paginate(15, false, ['query' => ['name' => $title]]);
        $this->assign("tag_list", $tag_list);
        return $this->fetch('');
    }

    //添加分类
    public function addCatalogs()
    {
        if (request()->isPost()) {
            $data     = array(
                'name'   => trim(input('post.name')),
                'sort'   => input('post.sort', 0),
                'poster' => input('file.poster')
            );
            $validate = validate('Project');
            if (!$validate->scene('addCatalogs')->check($data)) {
                $this->error($validate->getError(), $_SERVER["HTTP_REFERER"], '', 1);
            } else {
                $upload = new Upload();
                $result = $upload->sava(input('file.poster'));
                if ($result['error']) {
                    $this->assign('msg', $result['error']);
                    return view();
                }
                $data['poster'] = $result['result']['url'];
                $res            = $this->catalog_model->data($data)->save();
                if (!$res) {
                    $this->error('添加失败', $_SERVER["HTTP_REFERER"], '', 1);
                } else {
                    $this->success('添加成功', $_SERVER["HTTP_REFERER"], '', 1);
                }
            }
        } else {
            $this->assign('id', null);
            $this->assign('tag_info', 0);
            return $this->fetch('editcatalogs');
        }
    }

    public function editCatalogs($id)
    {
        $this->assign('id', $id);
        $tag_info = $this->catalog_model->where('id', $id)->find();
        $this->assign('tag_info', $tag_info);
        return $this->fetch();
    }

    //编辑分类
    public function updateCatalogs()
    {
        $id       = input('post.id');
        $data     = array(
            'id'   => $id,
            'name' => trim(input('post.name')),
            'sort' => input('post.sort', 0)
        );
        $validate = validate('Project');
        if (!$validate->scene('updateTag')->check($data)) {
            $this->error($validate->getError(), $_SERVER["HTTP_REFERER"], '', 1);
        } else {
            if (input('file.poster')) {
                //            上传封面到七牛云
                $upload = new Upload();
                $result = $upload->sava(input('file.poster'));
                if ($result['error']) {
                    $this->assign('msg', $result['error']);
                    return view();
                }
                $data['poster'] = $result['result']['url'];
            }
            $res = $this->catalog_model->save($data, ['id' => $id]);
            if (!$res) {
                $this->error('修改失败', $_SERVER["HTTP_REFERER"], '', 1);
            } else {
                $this->redirect(url('admin/project/catalogs'));
            }
        }
    }

    //删除分类
    public function deleteCatalog()
    {
        $id   = input('post.id');
        $used = $this->project_model->where('catalog_id', $id)->count();
        if ($used > 0) {
            $this->error('该分类下有项目,不可删除！', '', '', 1);
        }
        $res = model('catalogs')->destroy($id);
        if ($res) {
            $this->success('删除成功', '', '', 1);
        } else {
            $this->error('删除失败', '', '', 1);
        }
    }


    // 处理删除某一张bannner图
    public function deleteBanners()
    {
        $id           = input('post.id');
        $address      = input('post.address');
        $project_info = $this->project_model->find($id);
        $banners      = json_decode($project_info['banners_native']);
        $new_banners  = array_merge(array_diff($banners, array($address)));
        $up_res       = 0;
        if ($new_banners != $banners) {
            $up_res = $this->project_model->save([
                'banners' => json_encode($new_banners)
            ], ['id' => $id]);
        }
        if ($up_res) {
            return array(
                'success'     => '成功删除该图',
                'data'        => input('post.'),
                'old_banners' => $banners,
                'new_banner'  => $new_banners,
            );
        } else {
            return array(
                'error'       => '删除失败，该图片不存在或已经被删除',
                'data'        => input('post.'),
                'old_banners' => $banners,
                'new_banner'  => $new_banners,
            );
        }
    }

    //设置置顶排序
    public function setHeat()
    {
        $heat = input('post.heat');
        $id   = input('post.id');
        $res  = model('project')->save(['heat' => $heat], ['id' => $id]);
        if ($res) {
            $this->success('开启成功');
        } else {
            $this->success('开启失败');
        }
    }

    //设置排序
    public function setSort()
    {
        $project = new \app\common\model\Project();
        $project->allowField('id', 'sort')->update(input('post.'));
        halt($project->getLastSql());
    }

    //商家保存
    public function save()
    {
        if (input('id')) {
            $info             = ProjectModel::get(input('id'));
            $info['tags_arr'] = explode('|', trim($info->getData('tags'), '|'));
            $this->assign('info', $info);
        }
        //分类
        $catalogs = Catalogs::all();
        //城市
        $city = Citys::all();
        //标签
        $tags = Tags::all();
        if (request()->isPost()) {
            $isUpdate = input('id') ? true : false;
            $model    = new ProjectModel();
            $data     = input('post.');
            if (input('post.type') == 1) {
                unset($data['kf_qrcode']);
            } else {
                unset($data['sign_limits']);
                unset($data['time_period']);
                unset($data['sign_endtime']);
            }
            $res = $model->allowField(true)->isUpdate($isUpdate)->save($data);
            if ($res) {
                $this->success('操作成功', url('index') . "?page=" . input('page', 1));
            } else {
                $this->error('操作失败');
            }
        }
        return $this->fetch('', compact('catalogs', 'city', 'tags'));
    }

    //上传图片
    public function uploadImg()
    {
        $upload = new Upload();
        $res    = $upload->sava(input('file.file'));
        if ($res['error'] === 0) {
            return json(['code' => 0, 'msg' => '上传成功', 'url' => $res['result']['url']]);
        }
        return json(['code' => 1, 'msg' => $res['msg']]);
    }

    //上传本地图片
    public function uploadLocalImg()
    {
        $file = request()->file('file');
        $info = $file->move('./upload/qrcode/');
        if ($info) {
            $kf_qrcode = "/upload/qrcode/" . $info->getSaveName();
            return json(['code' => 0, 'msg' => '上传成功', 'url' => $kf_qrcode]);
        }
        return json(['code' => 1, 'msg' => '上传失败']);
    }

    //修改价格
    public function pricePage()
    {
        $info = ProjectModel::get(input('id'));
        $this->assign('info', $info);
        return $this->fetch();
    }

    //修改价格
    public function priceSave()
    {
        if (request()->isPost()) {
            $res = ProjectModel::update(input('post.'));
            if ($res) {
                return json(['code' => 0, 'msg' => '修改成功','data'=>$res]);
            } else {
                return json(['code' => 1, 'msg' => '修改失败']);
            }
        }
    }


}