<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\web\controller;

use service\UserService;
use think\Db;
use app\common\plugin\Jwt;

//ar类
class UserController extends MainController
{
    public $pages = 20;

    public function __construct()
    {
        parent::__construct();
//        echo '这是永固构造';

    }

    public function userInfo()
    {
        if (empty($this->userid))
            $this->api_return_json(array('msg' => '登录过期'), 0);
        $user = file_get_contents(CMF_ROOT . 'public/user.json');
        if (empty($user))
            $this->api_return_json(array('msg' => '用户数据异常'));
        $user = json_decode($user, true);
        $userInfo = array();
        foreach ($user as $val) {
            if ($this->userid == $val['user_id']) {
                $userInfo = $val;
                break;
            }
        }
        if (empty($userInfo))
            $this->api_return_json(array('msg' => '用户信息异常'));
        $tem = array('dianliu0' => 0.1, 'dianliu1' => 10, 'wendu0' => 50, 'wendu1' => 100);
        if (!file_exists(CMF_ROOT . 'public/userConfig.json'))
            file_put_contents(CMF_ROOT . 'public/userConfig.json', json_encode($tem), LOCK_EX);
        $userConfig = file_get_contents(CMF_ROOT . 'public/userConfig.json');
        $userConfig = empty($userConfig) ? array() : json_decode($userConfig, true);
        $this->api_return_json(array('userInfo' => $userInfo, 'userConfig' => $userConfig), 1);
    }

    public function editUser()
    {
        if (empty($this->userid))
            $this->api_return_json(array('msg' => '登录过期'), 0);
        $phone = $this->request->param('phone', '');
        $nickname = $this->request->param('nickname', '');
        if (empty($nickname))
            $this->api_return_json(array('msg' => '昵称不能为空'));
        if (!isset($phone) || empty($phone) || !preg_match('/^1[345789]\d{9}$/', $phone)) {
            $this->api_return_json(array('msg' => '手机号不合法'));
        }
        $user = file_get_contents(CMF_ROOT . 'public/user.json');
        if (empty($user))
            $this->api_return_json(array('msg' => '用户数据异常'));
        $user = json_decode($user, true);
        foreach ($user as &$val) {
            if ($this->userid == $val['user_id']) {
                $val['phone'] = $phone;
                $val['nickname'] = $nickname;
                break;
            }
        }
        file_put_contents(CMF_ROOT . 'public/user.json', json_encode($user), LOCK_EX);
        $this->api_return_json(array('msg' => '修改成功'), 1);
    }

    public function uploadAvatar()
    {
        if (empty($this->userid))
            $this->api_return_json(array('msg' => '登录过期'), 0);
        $type = $this->request->param('type');
        $file = $this->request->file('file');
        $info = $file->validate(array('ext' => 'jpg,png'))->move(CMF_ROOT . 'public/upload' . DIRECTORY_SEPARATOR . 'image'); //上传后的文件名
        if ($info) {
            $upame = $info->getSaveName(); //数据库存储文件名
            $path = 'image/' . $upame;
            $user = file_get_contents(CMF_ROOT . 'public/user.json');
            if (empty($user))
                $this->api_return_json(array('msg' => '用户数据异常'));
            $user = json_decode($user, true);
            foreach ($user as &$val) {
                if ($this->userid == $val['user_id']) {
                    if ($type == 0)
                        $val['avatar'] = $path;
                    else
                        $val['cover'] = $path;
                    break;
                }
            }
            file_put_contents(CMF_ROOT . 'public/user.json', json_encode($user), LOCK_EX);
            $this->api_return_json(array('path' => $path), 1);
        } else {
            $this->api_return_json(array('msg' => $file->getError()));
        }
    }

    public function login()
    {
        $username = $this->request->param('username');
        $password = $this->request->param('password');
        if (empty($username))
            $this->api_return_json(array('msg' => '用户不能为空'));
        if (empty($password))
            $this->api_return_json(array('msg' => '密码不能为空'));
        if (!file_exists(CMF_ROOT . 'public/user.json'))
            file_put_contents(CMF_ROOT . 'public/user.json', '', LOCK_EX);
        $user = file_get_contents(CMF_ROOT . 'public/user.json');
        if (empty($user)) {
            //注册
            $this->api_return_json(array('msg' => '用户不存在'));
            $id = 1;
            $userData = array(array('user_id' => $id, 'username' => $username, 'password' => $password, 'phone' => '', 'avatar' => '', 'cover' => '', 'nickname' => '', 'add_time' => time(), 'update_time' => time()));
            file_put_contents(CMF_ROOT . 'public/user.json', json_encode($userData), LOCK_EX);
        } else {
            $user = json_decode($user, true);
            $jsonUserName = array_column($user, 'username');
            if (in_array($username, $jsonUserName)) {
                //登录
                foreach ($user as &$val) {
                    if ($username == $val['username']) {
                        if ($password != $val['password'])
                            $this->api_return_json(array('msg' => '密码错误'));
                        $id = $val['user_id'];
                    }

                }
            } else {
                //注册追加
                $this->api_return_json(array('msg' => '用户不存在'));
                $id = max(array_column($user, 'user_id')) + 1;
                $userData = array('user_id' => $id, 'username' => $username, 'password' => $password, 'phone' => '', 'avatar' => '', 'cover' => '', 'nickname' => '', 'add_time' => time(), 'update_time' => time());
                array_push($user, $userData);
                file_put_contents(CMF_ROOT . 'public/user.json', json_encode($user), LOCK_EX);
            }
        }
        $token = JWT::getToken($id, $this->major);
        $this->api_return_json(array('msg' => '登录成功', 'sid' => $token), 1);
    }

    public function register()
    {
        if (empty($this->userid))
            $this->api_return_json(array('msg' => '登录过期'), 0);
        if ($this->userid != 1)
            $this->api_return_json(array('msg' => '您没权限操作'), 0);
        $username = $this->request->param('username');
        $password = $this->request->param('password');
        if (empty($username))
            $this->api_return_json(array('msg' => '用户不能为空'));
        if (empty($password))
            $this->api_return_json(array('msg' => '密码不能为空'));
        $user = file_get_contents(CMF_ROOT . 'public/user.json');
        $user = json_decode($user, true);
        $jsonUserName = array_column($user, 'username');
        if (in_array($username, $jsonUserName)) {
            //登录
            $this->api_return_json(array('msg' => '账号已存在'));
        }

        $id = max(array_column($user, 'user_id')) + 1;
        $userData = array('user_id' => $id, 'username' => $username, 'password' => $password, 'phone' => '', 'avatar' => '', 'cover' => '', 'nickname' => '', 'add_time' => time(), 'update_time' => time());
        array_push($user, $userData);
        file_put_contents(CMF_ROOT . 'public/user.json', json_encode($user), LOCK_EX);
        $this->api_return_json(array('msg' => '账号注册成功'), 1);
    }

    public function forgetSecret()
    {
        if (empty($this->userid))
            $this->api_return_json(array('msg' => '登录过期'), 0);
        $ori_password = $this->request->param('ori_password');
        $new_password = $this->request->param('new_password');
        $re_password = $this->request->param('re_password');
        if ($new_password == "" || strlen($new_password) < 6) {
            $this->api_return_json(array('msg' => '请输入不少于6位数的新密码'));
        } else if ($re_password == "") {
            $this->api_return_json(array('msg' => '请再次输入新密码'));
        } else if ($new_password != $re_password) {
            $this->api_return_json(array('msg' => '两次密码不一致'));
        } else if ($ori_password == "")
            $this->api_return_json(array('msg' => '旧密码不能为空'));

        $user = file_get_contents(CMF_ROOT . 'public/user.json');
        if (empty($user))
            $this->api_return_json(array('msg' => '用户数据异常'));
        $user = json_decode($user, true);
        foreach ($user as &$val) {
            if ($this->userid == $val['user_id']) {
                if ($val['password'] != $ori_password)
                    $this->api_return_json(array('msg' => '旧密码不正确'));
                $val['password'] = $new_password;
                break;
            }
        }
        file_put_contents(CMF_ROOT . 'public/user.json', json_encode($user), LOCK_EX);
        $this->api_return_json(array('msg' => '密码修改成功'), 1);
    }

    public function userConfig()
    {
        $k = $this->request->param('key');
        $v = $this->request->param('value');
        if (empty($k) || !is_numeric($v))
            $this->api_return_json(array('msg' => '参数有误'), 0);
        if (empty($this->userid))
            $this->api_return_json(array('msg' => '登录过期'), 0);
        if ($this->userid != 1)
            $this->api_return_json(array('msg' => '您没有权限操作'), 0);
        $tem = array('dianliu0' => 0.1, 'dianliu1' => 10, 'wendu0' => 50, 'wendu1' => 100);
        if (!file_exists(CMF_ROOT . 'public/userConfig.json') || empty(file_get_contents(CMF_ROOT . 'public/userConfig.json')))
            file_put_contents(CMF_ROOT . 'public/userConfig.json', json_encode($tem), LOCK_EX);
        $userConfig = file_get_contents(CMF_ROOT . 'public/userConfig.json');
        $userConfig = empty($userConfig) ? array() : json_decode($userConfig, true);
        if (array_key_exists($k, $userConfig)) {
            $userConfig[$k] = $v;
            file_put_contents(CMF_ROOT . 'public/userConfig.json', json_encode($userConfig), LOCK_EX);
        } else
            $this->api_return_json(array('msg' => '修改失败'), 0);
        $this->api_return_json(array('msg' => '修改成功'), 1);
    }

    //关注
    public function collect()
    {
        $ID = $this->request->param('ID');
        if (!intval($this->userid)) {
            $this->api_return_json(array('msg' => '请重新登录'), 0);
        }
        $data = array();
        if (!intval($ID))
            $this->api_return_json(array('msg' => '数据获取失败'), 0);
        $data[$this->userid] = array($ID);

        if(!is_file(CMF_ROOT . 'public/collect.json')){
            file_put_contents(CMF_ROOT . 'public/collect.json', json_encode($data), LOCK_EX);
        }
        $i=0;
        $res = file_get_contents(CMF_ROOT . 'public/collect.json');
        if ($res) {
            $userli = json_decode($res,true);
            if (is_array($userli)) {
                if(isset($userli[$this->userid])){
                    $re = array_search($ID, $userli[$this->userid]);
                    if ($re!==false) {
                        unset($userli[$this->userid][$re]);
                        $i=1;
                        $data = $userli;
                    } else {
                        array_unshift($userli[$this->userid],$ID);
                        $data=$userli;
                    }
                }else{
                    $userli[$this->userid]=array($ID);
                    $data=$userli;
                }
            }
        }

        file_put_contents(CMF_ROOT . 'public/collect.json', json_encode($data), LOCK_EX);

        $this->api_return_json(array('msg' => $i?'关注':'取消关注'), 1);
    }

    //取关
    public function quitCollect()
    {
        $id = $this->request->param('id');
        $collect = empty(file_get_contents(CMF_ROOT . 'public/collect.json')) ? array() : json_decode(file_get_contents(CMF_ROOT . 'public/collect.json'), true);
        foreach ($collect as $key => $val) {
            if ($val['id'] == $id)
                array_splice($collect, $key, 1);
        }
        file_put_contents(CMF_ROOT . 'public/collect.json', json_encode($collect), LOCK_EX);
        $this->api_return_json(array('msg' => '取关成功'), 1);
    }


    public function home()
    {
        $user = file_get_contents(CMF_ROOT . 'public/user.json');
        if (empty($user))
            $this->api_return_json(array('msg' => '用户数据异常'));
        $user = json_decode($user, true);
        $userInfo = array();
        foreach ($user as $val) {
            if (1 == $val['user_id']) {
                $userInfo = $val;
                break;
            }
        }
        $userInfo['map'] = !empty($userInfo['cover']) ? $userInfo['cover'] : 'map.jpg';
        $this->api_return_json(array('home' => $userInfo), 1);
    }

    //我的消息
    public function myMessage()
    {
        $page = $this->request->param('page');
        if (!isset($this->userid) || empty($this->userid)) {
            $this->api_return_json(array('msg' => '登录过期'));
        }
        if (!isset($page) || empty($page)) {
            $page = 1;
        }
        $where = array('c.user_id' => $this->userid, 'c.is_delete' => 0);
        $products = Db::name('user_message')
            ->field('c.add_time,c.id,c.type,m.desc,m.url,c.user_id,c.content,c.siteurl,u.user_message_id')
            ->alias("c")
            ->join('message m', 'm.id=c.message_id', 'left')
            ->join('user_message_read u', 'u.user_message_id=c.id', 'left')
            ->where('(c.user_id=0 or c.user_id=' . $this->userid . ') and c.is_delete=0')
            //->group('c.message_id')
            ->order('c.add_time desc')
            ->limit(($page - 1) * $this->pages, $this->pages)
            ->select()
            ->each(function ($v) {
                $v['add_time'] = $this->getChatTimeStr($v['add_time']);
                if ($v['type'] == 1) {
                    $v['url'] = $v['siteurl'];
                    $v['desc'] = $v['content'];
                }
                if (empty($v['user_message_id']))
                    $v['is_read'] = 0;
                else
                    $v['is_read'] = 1;
                return $v;
            })
            ->toArray();
        //未读总数
        $count = Db::name('user_message')
            ->alias("c")
            ->field('user_message_id')
            ->join('user_message_read u', 'u.user_message_id=c.id', 'left')
            ->where('(c.user_id=0 or c.user_id=' . $this->userid . ') and c.is_delete=0')
            //->group('c.message_id')
            ->select()
            ->toArray();
        $i = 0;
        foreach ($count as $val) {
            if ($val['user_message_id'] == null)
                $i++;
        }
        $this->api_return_json(array('myMessage' => $products, 'count' => $i, 'pages' => $this->pages), 1);
    }

    //消息是否已读
    public function isRead()
    {
        $id = $this->request->param('id');
        if (!isset($id) || empty($id))
            $this->api_return_json(array('msg' => '消息id异常'));
        if (!isset($this->userid) || empty($this->userid))
            $this->api_return_json(array('msg' => '登录过期'));
        $data['user_id'] = $this->userid;
        $data['user_message_id'] = $id;
        $data['add_time'] = time();
        Db::name('user_message_read')->insert($data);
        $this->api_return_json(array('msg' => '阅读成功'), 1);
    }

    //删除消息
    public function deleteMessage()
    {
        $id = $this->request->param('id');
        if (!isset($id) || empty($id))
            $this->api_return_json(array('msg' => '消息id异常'));
        Db::name('user_message')->where(array('id' => $id))->update(array('is_delete' => 1));
        $this->api_return_json(array('msg' => '删除成功'), 1);
    }


    //更新用户信息
    public function updateUser()
    {
        //微信小程序
        $avatar = $this->request->param('avatar', '');
        $wx_nickname = $this->request->param('nickName', '');
        $msg = '未修改';
        if (!empty($avatar)) {
            $update_date['avatar'] = $avatar;
            $update_date['wx_nickname'] = $wx_nickname;
            db('wx_user')->where('user_id', $this->userid)->update($update_date);
            $msg = '已修改';
        }
        $this->api_return_json(array('msg' => $msg), 1);
    }


    //上传
    public function upload()
    {
        $file = $this->request->file('file');
        $info = $file->validate(array('ext' => 'jpg,png'))->move(CMF_ROOT . 'public/upload' . DIRECTORY_SEPARATOR . 'portal'); //上传后的文件名
        if ($info) {
            $upame = $info->getSaveName(); //数据库存储文件名
            $path = 'portal/' . $upame;
            $this->api_return_json(array('path' => $path), 1);
        } else {
            $this->api_return_json(array('msg' => $file->getError()));
        }

    }

    public function deleteFile()
    {
        $image_url = $this->request->param('file');
        if (!isset($image_url) || empty($image_url)) {
            $this->api_return_json(array('msg' => '资源错误'));
        }
        if (file_exists(CMF_ROOT . 'public/upload/' . $image_url)) {
            unlink(CMF_ROOT . 'public/upload/' . $image_url);
            $this->api_return_json(array('msg' => '删除成功'), 1);
        } else {
            $this->api_return_json(array('msg' => '文件不存在删除失败'));
        }

    }


    /**
     * 微信展示时间的方法
     * @param $addTime
     * @return string
     */
    public static function getChatTimeStr($addTime)
    {
        $nowTime = time();
        if ($addTime > $nowTime) {
            return "";
        }

        //返回的时间
        $timeStr = "";
        //获取当前时间
        $addTime = explode(',', date('Y,m,d,w,a,h,i,Y', $addTime));//年，月，日，星期，上下午，时，分
        $nowTime = explode(',', date('Y,m,d,w,a,h,i,Y', $nowTime));

        $dayPerMonthAddTime = self::getDayPerMonth($addTime[0]);
        $week = array(0 => "星期日", 1 => "星期一", 2 => "星期二", 3 => "星期三", 4 => "星期四", 5 => "星期五", 6 => "星期六");
        //如果时间差小于一天的,显示（上午 时间） / （下午 时间）
        if ($addTime[0] == $nowTime[0] && $addTime[1] == $nowTime[1] && $addTime[2] == $nowTime[2]) {
            $timeStr .= $addTime[5] . ":" . $addTime[6];
        } else if (($addTime[0] == $nowTime[0] && $addTime[1] == $nowTime[1] && $addTime[2] == $nowTime[2] - 1)
            || ($addTime[0] == $nowTime[0] && $nowTime[1] - $addTime[1] == 1 && $dayPerMonthAddTime[(int)$addTime[1]] == $addTime[2] && $nowTime[2] == 1)
            || ($nowTime[0] - $addTime[0] == 1 && $addTime[1] == 12 && $addTime[2] == 31 && $nowTime[1] == 1 && $nowTime[2] == 1)) { //如果时间差在昨天,三种情况（同一月份内跨一天、月末跨越到月初、年末跨越到年初）显示格式：昨天 时:分 上午/下午
            $timeStr .= "昨天 " . $addTime[5] . ":" . $addTime[6] . " ";
        } else if (($addTime[0] == $nowTime[0] && $addTime[1] == $nowTime[1] && $nowTime[2] - $addTime[2] < 7)
            || ($addTime[0] == $nowTime[0] && $nowTime[1] - $addTime[1] == 1 && $dayPerMonthAddTime[(int)$addTime[1]] - $addTime[2] + $nowTime[2] < 7
                || ($nowTime[0] - $addTime[0] == 1 && $addTime[1] == 12 && $nowTime[1] == 1 && 31 - $addTime[2] + $nowTime[2] < 7))) { //如果时间差在一个星期之内的,也是三种情况，显示格式：星期 时:分 上午/下午

            $timeStr .= $week[$addTime[3]] . " " . $addTime[5] . ":" . $addTime[6];
        } else { //显示格式：月/日/年 时:分 上午/下午
            $timeStr .= $addTime[7] . "-" . $addTime[1] . "-" . $addTime[2] . " " . $addTime[5] . ":" . $addTime[6];
        }

        if ($addTime[4] == "am") {
            $timeStr .= " 上午";
        } else if ($addTime[4] == "pm") {
            $timeStr .= " 下午";
        }

        return $timeStr;

    }

    //根据年份获取每个月份的总天数和每年最后一个月的天数
    public static function getDayPerMonth($year)
    {
        $arr = array(
            1 => 31,
            3 => 31,
            4 => 30,
            5 => 31,
            6 => 30,
            7 => 31,
            8 => 31,
            9 => 30,
            10 => 31,
            11 => 30,
            12 => 31
        );
        //闰年
        if (($year % 4 == 0 && $year % 100 != 0) || ($year % 400 == 0)) {
            $arr[2] = 29;
        } else {
            $arr[2] = 28;
        }
        return $arr;
    }

    /*************** 校验身份证 start *******************/
    function checkIdCard($idc)
    {
        if (empty($idc)) {
            return false;
        }
        $idcard = $idc;
        $City = array(11 => "北京", 12 => "天津", 13 => "河北", 14 => "山西", 15 => "内蒙古", 21 => "辽宁", 22 => "吉林", 23 => "黑龙江", 31 => "上海", 32 => "江苏", 33 => "浙江", 34 => "安徽", 35 => "福建", 36 => "江西", 37 => "山东", 41 => "河南", 42 => "湖北", 43 => "湖南", 44 => "广东", 45 => "广西", 46 => "海南", 50 => "重庆", 51 => "四川", 52 => "贵州", 53 => "云南", 54 => "西藏", 61 => "陕西", 62 => "甘肃", 63 => "青海", 64 => "宁夏", 65 => "新疆", 71 => "台湾", 81 => "香港", 82 => "澳门", 91 => "国外");
        $iSum = 0;
        $idCardLength = strlen($idcard);
        //长度验证
        if (!preg_match('/^\d{17}(\d|x)$/i', $idcard) and !preg_match('/^\d{15}$/i', $idcard)) {
            return false;
        }
        //地区验证
        if (!array_key_exists(intval(substr($idcard, 0, 2)), $City)) {
            return false;
        }
        // 15位身份证验证生日，转换为18位
        if ($idCardLength == 15) {
            $sBirthday = '19' . substr($idcard, 6, 2) . '-' . substr($idcard, 8, 2) . '-' . substr($idcard, 10, 2);
            //    $d = new DateTime($sBirthday);
            //    $dd = $d->format('Y-m-d');
            //    if($sBirthday != $dd)
            if ($sBirthday != $sBirthday) {
                return false;
            }
            $idcard = substr($idcard, 0, 6) . "19" . substr($idcard, 6, 9);//15to18
            $Bit18 = $this->getVerifyBit($idcard);//算出第18位校验码
            $idcard = $idcard . $Bit18;
        }
        // 判断是否大于2078年，小于1900年
        $year = substr($idcard, 6, 4);
        if ($year < 1900 || $year > 2078) {
            return false;
        }

        //18位身份证处理
        $sBirthday = substr($idcard, 6, 4) . '-' . substr($idcard, 10, 2) . '-' . substr($idcard, 12, 2);
        //    var_dump($sBirthday);
        //    $d = new DateTime($sBirthday);

        //    $dd = $d->format('Y-m-d');
        //    echo $dd;
        //    die();
        //    if($sBirthday != $dd)
        if ($sBirthday != $sBirthday) {
            return false;
        }
        //身份证编码规范验证
        $idcard_base = substr($idcard, 0, 17);
        if (strtoupper(substr($idcard, 17, 1)) != $this->getVerifyBit($idcard_base)) {
            return false;
        }
        return true;
    }

    // 计算身份证校验码，根据国家标准GB 11643-1999
    function getVerifyBit($idcard_base)
    {
        if (strlen($idcard_base) != 17) {
            return false;
        }
        //加权因子
        $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
        //校验码对应值
        $verify_number_list = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
        $checksum = 0;
        for ($i = 0; $i < strlen($idcard_base); $i++) {
            $checksum += substr($idcard_base, $i, 1) * $factor[$i];
        }
        $mod = $checksum % 11;
        $verify_number = $verify_number_list[$mod];
        return $verify_number;
    }


    //全读
    public function isAllRead()
    {
        if (!isset($this->userid) || empty($this->userid))
            $this->api_return_json(array('msg' => '登录过期'));
        $result = Db::name('user_message')
            ->field('id')
            ->where('(user_id=0 or user_id=' . $this->userid . ') and is_delete=0')
            ->select()
            ->toArray();
        $datas = array();
        foreach ($result as $val) {
            $res = Db::name('user_message_read')->where(array('user_message_id' => $val['id'], 'user_id' => $this->userid))->find();
            if ($res)
                continue;
            $data['user_id'] = $this->userid;
            $data['user_message_id'] = $val['id'];
            $data['add_time'] = time();
            $datas[] = $data;
        }
        Db::name('user_message_read')->insertAll($datas);
        $this->api_return_json(array('msg' => '全部阅读成功'), 1);
    }

    /**
     * @name 获取城市
     */
    public function city()
    {
        $where[] = ['delete_time', '=', 0];
        $name = $this->request->get('name');
        //  $page=$this->request->get('page',1);
        $where[] = ['name', 'like', '%苏州%'];
        $index = City::where($where)->field('id,name')->order(['list_order' => 'asc', 'create_time' => 'desc'])->select();
        $keyword = Keyword::where([['delete_time', '=', 0]])->field('name')->order(['list_order' => 'desc', 'create_time' => 'desc'])->select();

        $this->api_return_json(['city' => $index, 'pages' => $this->pages, 'keyword' => $keyword], 1);
    }


    /**
     * @name 分类category
     */
    public function category()
    {
        $where[] = ['delete_time', '=', 0];
        $city_id = $this->request->get('city_id', '', 'intval');
        if (empty($city_id)) $this->api_return_json(['msg' => '请选择城市']);
        $city = City::where([['delete_time', '=', 0], ['id', '=', $city_id]])->find();
        if (empty($city)) $this->api_return_json(['msg' => '该城市不存在']);


        $categories = $city->category()->field('id,name,desc,icon,table_name,detail')->order(['list_order' => 'asc', 'create_time' => 'desc'])->select()->each(function ($v) {
            unset($v['pivot']);
            return $v;
        });

        $this->api_return_json(['category' => $categories], 1);

    }


    public function setLocation()
    {//$this->redis->flushAll();
        $this->api_return_json(['msg' => 'ok'], 1);
        $page = $this->request->get('page', 1);
        if (!$this->request->isGet()) {
            return $this->api_return_json(['msg' => '请求方式不对']);
        }
        if (!isset($this->userid) || empty($this->userid)) {
            return $this->api_return_json(['msg' => '请先登录']);
        }
        $data = $this->request->get();
//        if (!isset($data['lat']) || empty($data['lat'])) {
//            $this->api_return_json(['msg' => '请传入纬度']);
//        }
//        if (!isset($data['long']) || empty($data['long'])) {
//            $this->api_return_json(['msg' => '请传入经度']);
//        }

        if (!isset($data['city']) || empty($data['city'])) {
            $this->api_return_json(['msg' => '请输入城市名']);
        }
        //$citys = City::where('delete_time', 0)->field('id,name')->limit(($page - 1), $this->pages)->orderRaw('',["name <>".$data['city']])->select();
        $citys = Db::query('select id,name from rbi_city where delete_time=0 order by field(name,"' . $data['city'] . '") desc,list_order desc');
        $this->api_return_json(compact('citys'), 1);
    }


    /**
     * @name
     */
    public function gf()
    {
        $name = $this->request->post('name');
        $city_id = $this->request->post('city_id');
        if (empty($name)) $this->api_return_json(['msg' => '名称不能为空']);
        if (empty($city_id)) $this->api_return_json(['msg' => '请选择城市']);
        $GarbageForm = GarbageForm::where('name', $name)->where('city_id', $city_id)->where('delete_time', 0)->find();
        if (!empty($GarbageForm)) {
            $this->api_return_json(['msg' => '该名称已提交']);
        }

        $search = Db::field('name,list_order,create_time,category_id')
            ->table('rbi_recycled')
            ->alias('r')
            ->unionAll([
                'SELECT name,list_order,create_time,category_id FROM rbi_harmful where ' . 'delete_time=0 and ' . '(city_id=' . $city_id . ' or city_id=0) and name like "%' . $name . '%"',
                'SELECT name,list_order,create_time,category_id FROM rbi_perishable_refuse where ' . 'delete_time=0 and ' . '(city_id=' . $city_id . ' or city_id=0)  and name like "%' . $name . '%"',
                'SELECT name,list_order,create_time,category_id FROM rbi_kitchen_waste where ' . 'delete_time=0 and ' . '(city_id=' . $city_id . ' or city_id=0)and name like "%' . $name . '%"',
                'SELECT name,list_order,create_time,category_id FROM rbi_wet_refuse where ' . 'delete_time=0 and ' . '(city_id=' . $city_id . ' or city_id=0) and name like "%' . $name . '%"',
                'SELECT name,list_order,create_time,category_id FROM rbi_other where ' . 'delete_time=0 and ' . '(city_id=' . $city_id . ' or city_id=0) and name like "%' . $name . '%"',
            ])->where(function ($query) use ($city_id) {
                $query->where('r.city_id', 0)->whereOr('r.city_id', '=', $city_id);
            })->where('name', $name)->find();

        if (!empty($search)) {
            $this->api_return_json(['msg' => '该名称已提交']);
        }
        $result = GarbageFormService::store(compact('name', 'city_id'));
        if ($result['code'] != 0) $this->api_return_json(['msg' => "提交失败"]);
        $this->api_return_json(['msg' => "提交成功"], 1);
    }

    /**
     * @name 详情
     */
    public function info()
    {
        $data = $this->request->get();
        if (!$this->request->isGet()) {
            return $this->api_return_json(['msg' => '请求方式不对']);
        }
        if (!isset($this->userid) || empty($this->userid)) {
            return $this->api_return_json(['msg' => '请先登录']);
        }
        $user = UserService::getOne([['user_id', '=', $this->userid]]);
        $member = $user->member;
        $this->api_return_json(compact('member'), 1);

    }


    /**
     * @name 详情
     */
    public function store_info()
    {
        $data = $this->request->post();
        $id = isset($data['id']) && empty($data['id']) ? 0 : $data['id'];
        if (!$this->request->isPost()) {
            return $this->api_return_json(['msg' => '请求方式不对']);
        }
        if (!isset($this->userid) || empty($this->userid)) {
            return $this->api_return_json(['msg' => '请先登录']);
        }
        $user = UserService::getOne([['user_id', '=', $this->userid]]);
        $member = $user->member;
        if (empty($member)) {
            $result = HouseMemberService::store($data);
        } else {
            $result = HouseMemberService::store($data, $id);
        }

        if ($result['code'] == -1) {
            $return = ['msg' => $data['message']];
        } elseif ($result['code'] == 0) {
            $return = ['msg' => '操作失败'];
        } else {
            $return = ['msg' => "操作成功"];
        }

        $this->api_return_json($return, $result['code'] == 1 ? 1 : 0);

    }


}
