<?php
namespace app\index\controller;

use think\Controller;
use think\Db;
/*
通用提交
*/
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://myucms.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 梦雨 <50361804@qq.com>
// +----------------------------------------------------------------------
class Api extends Controller
{
    //加入购物车
    public function gouwuche()
    {
        if (!session('userid')) {
            $this->error('未登录');
        }
        $_data = $this->request->post();
        $c = Db::name('shop')->where(array('id' => input('id')))->find();
        if ($_data['shuliang'] > $c['ku']) {
            $this->error('库存不足');
        }
        if ($_data['shuliang'] > set('kucun')) {
            $this->error('数量不能超过' . set('kucun'));
        }
        if (fun_st('shop_dingdan', array('open' => 1, 'gouwu' => 1, 'uid' => user('userid'))) > set('gouwuc')) {
            $this->error('购物车数量太多');
        }
        $data['time'] = time();
        $data['tid'] = $c['id'];
        $data['uid'] = session('userid');
        $data['oid'] = oid(16);
        $data['yunfei'] = $c['yunfeis'];
        $data['nu'] = $_data['shuliang'];
        $data['open'] = 1;
        $data['gouwu'] = 1;
        $data['title'] = $c['title'];
        $data['xn'] = $c['fs'];
        $data['config'] = json_encode($_data['config']);
        if (!Db::name('shop_dingdan')->strict(false)->data($data)->insert()) {
            $this->error('添加失败');
        } else {
            point(set('jifen8', 2), session('userid'), '添加购物车');
            //减掉库存
            Db::name('shop')->where(array('id' => $c['id']))->setDec('ku', $_data['shuliang']);
            $this->success('添加成功');
        }
    }
    //添加收货地址
    public function dizhi()
    {
        $data = $this->request->post();
        $data['time'] = time();
        $data['uid'] = session('userid');
        $data['open'] = 1;
        if (!Db::name('dizhi')->strict(false)->data($data)->insert()) {
            $this->error('添加失败');
        } else {
            $this->success('添加成功');
        }
    }
    public function yanzhengma()
    {
        if (!preg_match("/^1[34578]{1}\\d{9}\$/", input('phone'))) {
            $this->error('手机号码格式错误');
        }
        $phone = Db::name('member')->where('phone', input('phone'))->find();
        if ($phone) {
            $this->error('当前手机号码被注册');
        }
        $code = mt_rand(100000, 999999);
        $statusStr = array("0" => "短信发送成功", "-1" => "参数不全", "-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！", "30" => "配置密码错误", "40" => "账号不存在", "41" => "当前余额不足", "42" => "帐户已过期", "43" => "IP地址限制", "50" => "内容含有敏感词");
        $smsapi = "http://api.smsbao.com/";
        $user = set('dxb_name');
        //短信平台帐号
        $pass = md5(set('dxb_ps'));
        //短信平台密码
        $content = '' . set('dxb_title') . '，验证码:' . $code . '';
        $phone = input('phone');
        //要发送短信的手机号码
        $sendurl = $smsapi . "sms?u=" . $user . "&p=" . $pass . "&m=" . $phone . "&c=" . urlencode($content);
        $result = file_get_contents($sendurl);
        //查询当前时间该验证码是否过期
        //输出当天最新验证码过期时间
        $times = Db::name('yanzhengma')->where(array('phone' => input('phone'), 'fl' => 1))->where('time > ' . Date_k(0) . ' and time < ' . Date_k(1) . '')->order('id desc')->value('times');
        if ($times >= time()) {
            $this->error('验证码还未过期');
        }
        if (fun_tj('yanzhengma', 'time', Date_k(0), 'time', Date_k(1), array('open' => 1)) > set('dxb_ip')) {
            $this->error('您当前发送次数过多');
        }
        if (socha($result, '0') == 1) {
            $data['ma'] = $code;
            $data['phone'] = input('phone');
            $data['content'] = $content;
            $data['open'] = 1;
            $data['ip'] = $_SERVER["REMOTE_ADDR"];
            $data['time'] = time();
            $data['fl'] = 1;
            $data['times'] = time() + 300;
            Db::name('yanzhengma')->insert($data);
            $this->success('发送成功');
        } else {
            $this->error($statusStr[$result]);
        }
    }
    //提交登录
    public function login()
    {
        if (session('userid') != '') {
            // echo "<script>history.go(-1);</script>";
            $this->error('您已登录');
        }
        $member = Db::name('member');
        if (request()->isPost()) {
            $data = input('post.');
            $open['open'] = 1;
            $map['phone'] = $data['phone'];
            $key = 'www.115cms.com';
            $user = Db::name('member')->where($open)->where($map)->find();
            if ($user) {
                if (jiami($user['password'], 'DECODE', $key, 0) == $data['password']) {
                    session('phone', $user['phone']);
                    session('userid', $user['userid']);
                    $member->where($map)->setField(array('last_login_ip' => $_SERVER['REMOTE_ADDR'], 'last_login_time' => time()));
                    //登录送积分
                    point(set('jifen2', 2), session('userid'), '登录');
                    $this->success('登录成功');
                } else {
                    $this->error('密码错误');
                }
            } else {
                $this->error('手机号码不存在');
            }
        }
    }
    //提交注册
    public function reg()
    {
        if (session('userid') != '') {
            $this->error('您已登录');
        }
        $member = Db::name('member');
        if (request()->isPost()) {
            $data = input('post.');
            $password = input('password');
            $key = 'www.115cms.com';
            $map['phone'] = $data['phone'];
            $mail = $member->where($map)->find();
            //查询当前手机号码对应的验证码
            //查询过期时间
            $times = Db::name('yanzhengma')->where(array('phone' => input('phone'), 'fl' => 1))->where('time > ' . Date_k(0) . ' and time < ' . Date_k(1) . '')->order('id desc')->value('times');
            if ($times >= time()) {
                $ma = Db::name('yanzhengma')->where(array('phone' => input('phone'), 'fl' => 1))->where('time > ' . Date_k(0) . ' and time < ' . Date_k(1) . '')->order('id desc')->value('ma');
            }
            if ($ma != input('yanzhengma')) {
                $this->error('验证码错误');
            }
            if (!$mail) {
                $user = $member->where('usermail', $data['usermail'])->find();
                if (!preg_match("/^1[34578]{1}\\d{9}\$/", input('phone'))) {
                    $this->error('手机号码格式错误');
                }
                $data['regtime'] = time();
                $data['mailopen'] = 0;
                $data['dengji'] = 0;
                $data['open'] = 1;
                /*
                $data['point'] = cms('loginpoint');
                */
                $data['username'] = generate_password(10);
                $data['userhead'] = '/public/img/touxiang.jpg';
                $data['userip'] = $_SERVER['REMOTE_ADDR'];
                $data['password'] = jiami($password, 'ENCODE', $key, 0);
                if ($member->strict(false)->insert($data)) {
                    point(set('jifen1', 2), session('userid'), '注册');
                    $this->success('注册成功');
                } else {
                    $this->error('注册失败');
                }
            } else {
                $this->success('该手机号码已存在');
            }
        }
    }
    //找回发送验证码
    public function yanzhengmazh()
    {
        if (!preg_match("/^1[34578]{1}\\d{9}\$/", input('phone'))) {
            $this->error('手机号码格式错误');
        }
        $phone = Db::name('member')->where('phone', input('phone'))->find();
        if (!$phone) {
            $this->error('手机号码不存在');
        }
        $code = mt_rand(100000, 999999);
        $statusStr = array("0" => "短信发送成功", "-1" => "参数不全", "-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！", "30" => "配置密码错误", "40" => "账号不存在", "41" => "当前余额不足", "42" => "帐户已过期", "43" => "IP地址限制", "50" => "内容含有敏感词");
        $smsapi = "http://api.smsbao.com/";
        $user = set('dxb_name');
        //短信平台帐号
        $pass = md5(set('dxb_ps'));
        //短信平台密码
        $content = '' . set('dxb_title') . '，验证码:' . $code . '';
        $phone = input('phone');
        //要发送短信的手机号码
        $sendurl = $smsapi . "sms?u=" . $user . "&p=" . $pass . "&m=" . $phone . "&c=" . urlencode($content);
        $result = file_get_contents($sendurl);
        //查询当前时间该验证码是否过期
        //输出当天最新验证码过期时间
        $times = Db::name('yanzhengma')->where(array('phone' => input('phone'), 'fl' => 2))->where('time > ' . Date_k(0) . ' and time < ' . Date_k(1) . '')->order('id desc')->value('times');
        if ($times >= time()) {
            $this->error('验证码还未过期');
        }
        if (fun_tj('yanzhengma', 'time', Date_k(0), 'time', Date_k(1), array('open' => 1)) > set('dxb_ip')) {
            $this->error('您当前发送次数过多');
        }
        if (socha($result, '0') == 1) {
            $data['ma'] = $code;
            $data['phone'] = input('phone');
            $data['content'] = $content;
            $data['open'] = 1;
            $data['ip'] = $_SERVER["REMOTE_ADDR"];
            $data['time'] = time();
            $data['fl'] = 2;
            $data['times'] = time() + 300;
            Db::name('yanzhengma')->insert($data);
            $this->success('发送成功');
        } else {
            $this->error($statusStr[$result]);
        }
    }
    //找回密码
    public function zh()
    {
        $member = Db::name('member');
        if (request()->isPost()) {
            $data = input('post.');
            $password = input('password');
            $key = 'www.115cms.com';
            //不能随便更改会导致用户无法登录
            $map['phone'] = $data['phone'];
            $mail = $member->where($map)->find();
            //查询当前手机号码对应的验证码
            //查询过期时间
            $times = Db::name('yanzhengma')->where(array('phone' => input('phone'), 'fl' => 2))->where('time > ' . Date_k(0) . ' and time < ' . Date_k(1) . '')->order('id desc')->value('times');
            if ($times >= time()) {
                $ma = Db::name('yanzhengma')->where(array('phone' => input('phone'), 'fl' => 2))->where('time > ' . Date_k(0) . ' and time < ' . Date_k(1) . '')->order('id desc')->value('ma');
            }
            if (!$mail) {
                return json(array('code' => 0, 'msg' => '手机号码不存在'));
            } else {
                if ($ma != input('yanzhengma')) {
                    $this->error('验证码错误..');
                }
                $datam['password'] = jiami($password, 'ENCODE', $key, 0);
                if ($member->save($datam, ['phone' => $data['phone']])) {
                    Db::name('yanzhengma')->where(array('phone' => input('phone')))->setField(array('open' => 0));
                    $this->success('密码重置成功');
                } else {
                    $this->error('密码重置失败');
                }
            }
        }
    }
    public function logout()
    {
        session("userid", NULL);
        session("phone", NULL);
        return json(array('code' => 1, 'msg' => '退出成功'));
        return NULL;
    }
    //通用删除
    public function deletes()
    {
        if (!session('userid')) {
            $this->error('未登录');
        }
        $id = input('id');
        if (fun_sc_p(input('model'), array('id' => $id), 'uid') != session('userid')) {
            $this->error('参数不全');
        }
        if (Db::name(input('model'))->delete(array('id' => $id, 'uid' => session('userid')))) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
    //虚拟订单支付
    public function pay()
    {
        $c = Db::name('shopDingdan')->where(array('id' => input('id')))->find();
        $s = Db::name('shop')->where(array('id' => $c['tid']))->find();
        //查询是否有运费
        if ($s['yunfei'] == 1) {
            //无运费
            if ($s['youhui'] == 1) {
                $yunfei = 0;
                //有优惠
                $rmb = $s['rmb'] * $c['nu'] - $s['rmbs'] * $c['nu'];
            } else {
                //无优惠
                $rmb = $s['rmb'] * $c['nu'];
            }
        } else {
            //有运费
            $yunfei = $s['yunfeis'];
            if ($s['youhui'] == 1) {
                //有优惠
                $rmb = $s['rmb'] * $c['nu'] - $s['rmbs'] * $c['nu'] + $s['yunfeis'];
            } else {
                //无优惠
                $rmb = $s['rmb'] * $c['nu'] + $s['yunfeis'];
            }
        }
        if ($s['jifen'] == 0) {
            $this->error('非法参数');
        }
        $jifen = round($rmb * $s['jifend']);
        //查询积分
        $point = Db::name('member')->where('userid', session('userid'))->value('point');
        if ($point < $jifen && $jifen > 0) {
            $this->error('积分不足');
        }
        //更新订单
        //查询是否是虚拟订单
        if ($s['fs'] == 1) {
            //是直接提取附件
            $map['open'] = 4;
            $map['xn'] = 1;
        } else {
            //否代发货状态
            $map['open'] = 2;
            $map['xn'] = 0;
        }
        $map['times'] = time();
        $map['liuyan'] = xss(input('liuyan'));
        $map['dizhi'] = xss(input('dizhi'));
        $map['rmb'] = $rmb * $s['jifend'];
        $map['yunfei'] = $yunfei;
        $map['pay'] = 2;
        Db::name('shop')->where('id', $s['id'])->setInc('xiaoliang', 1);
        Db::name('shopDingdan')->where(array('id' => input('id')))->data($map)->strict(false)->update();
        //开始扣分
        point(-$jifen, session('userid'), $s['title'], $s['id']);
        point(set('jifen4', 2), session('userid'), '积分购买商品返现');
        //$this->success('支付成功');
        //添加发送短信通知站长
        if (set('pay1') == 1) {
            //添加发送短信通知站长记录
            $data['phone'] = set('phone');
            $data['content'] = '【下单通知】来自[' . set('title') . ']您还有新的订单 积分[' . $jifen . ']，订单号码' . $c['oid'] . '';
            $data['open'] = 1;
            // $data['uid'] = 1;
            $data['uid'] = session('userid');
            $data['ip'] = $_SERVER["REMOTE_ADDR"];
            $data['time'] = time();
            $data['fl'] = 4;
            Db::name('yanzhengma')->insert($data);
            duanxin(set('phone'), '【'.set('dxb_qmpz').'】来自[' . set('title') . ']您还有新的订单 积分[' . $jifen . ']，订单号码' . $c['oid'] . '');
        }
        return json(array('code' => 1, 'msg' => '支付成功', 'url' => url('index/home/dingdan', array('id' => $map['open']))));
    }
    //提醒发货
    public function tixing()
    {
        if (!session('userid')) {
            $this->error('未登录');
        }
        $id = input('id');
        if (fun_st('shopDingdan', array('oid' => $id)) == 0) {
            $this->error('参数不全');
        }
        //查询是否几天是否有记录
        $times = Db::name('tixing')->where(array('content' => $id, 'uid' => session('userid')))->where('time > ' . Date_k(0) . ' and time < ' . Date_k(1) . '')->count();
        if ($times != 0) {
            $this->error('明天再来');
        }
        //添加提醒记录
        $data['phone'] = set('phone');
        $data['content'] = $id;
        $data['open'] = 1;
        $data['uid'] = session('userid');
        $data['ip'] = $_SERVER["REMOTE_ADDR"];
        $data['time'] = time();
        Db::name('tixing')->insert($data);
        //添加发送短信通知站长记录
        $data['phone'] = set('phone');
        $data['content'] = '【订单通知】来自[' . set('title') . ']您还有未发货订单，订单号码' . $id . '';
        $data['open'] = 1;
        $data['uid'] = session('userid');
        $data['ip'] = $_SERVER["REMOTE_ADDR"];
        $data['time'] = time();
        $data['fl'] = 3;
        Db::name('yanzhengma')->insert($data);
        duanxin(set('phone'), '【'.set('dxb_qmpz').'】来自[' . set('title') . ']您还有未发货订单，订单号码' . $id . '');
        $this->success('提醒成功');
    }
    //确定收货
    public function shouhuo()
    {
        if (!session('userid')) {
            $this->error('未登录');
        }
        $id = input('id');
        if (fun_st('shopDingdan', array('oid' => $id)) == 0) {
            $this->error('参数不全');
        }
        point(set('jifen7', 2), session('userid'), '确定收货');
        //更新
        Db::name('shopDingdan')->where(array('oid' => input('id')))->update(array('open' => 4, 'timeq' => time()));
        $this->success('收货成功');
    }
    //确定收货评分
    public function pingfen()
    {
        if (!session('userid')) {
            $this->error('未登录');
        }
        $id = input('id');
        if (fun_st('shopDingdan', array('oid' => $id, 'uid' => session('userid'), 'open' => 4)) == 0) {
            $this->error('参数不全');
        }
        $data['tid'] = fun_sc_p('shopDingdan', array('oid' => $id), 'tid');
        $data['oid'] = $id;
        $data['pf'] = input('pingfen');
        $data['time'] = time();
        $data['content'] = xss(input('content'));
        $data['uid'] = session('userid');
        $data['ip'] = $_SERVER['REMOTE_ADDR'];
        //获取平均评分
        $pf = $data['pf'] + fun_sc_p('shop', array('id' => $data['tid']), 'pingfen');
        $pfs = $pf / 2;
        if (Db::name('comment')->insert($data)) {
            Db::name('shopDingdan')->where(array('oid' => $id))->update(array('open' => 5));
            Db::name('shop')->where(array('id' => $data['tid']))->update(array('pingfen' => $pfs));
            return json(array('code' => 1, 'msg' => '评分成功'));
        } else {
            return json(array('code' => 0, 'msg' => '评分失败'));
        }
    }
    /*基本设置资料修改*/
    public function set()
    {
        if (!session('userid')) {
            $this->error('请登录');
        } else {
            $member = Db::name('member');
            $uid = session('userid');
            $key = 'www.115cms.com';
            if (request()->isPost()) {
                $data = $this->request->post();
                $data['userid'] = $uid;
                $_data['username'] = xss($data['username']);
                if (mb_strlen($_data['username'], 'UTF-8') > 12) {
                    $this->error('用户名不能大于12个字符');
                }
                $_data['userhome'] = xss($data['userhome']);
                $_data['description'] = xss($data['description']);
                $_data['sex'] = $data['sex'];
                $_data['usermail'] = $data['usermail'];
                if (!is_email($data['usermail'])) {
                    $this->error('邮箱格式错误');
                }
                if (!empty(input('passwords') || !empty(input('password')))) {
                    $password = input('password');
                    if (input('password') == input('passwords')) {
                        $_data['password'] = jiami($password, 'ENCODE', $key, 0);
                    } else {
                        return json(array('code' => 0, 'msg' => '两次输入的密码不一致'));
                    }
                }
                if ($member->where(array('userid' => $uid))->update($_data)) {
                    return json(array('code' => 1, 'msg' => '修改成功'));
                } else {
                    return json(array('code' => 0, 'msg' => '修改失败'));
                }
            }
        }
    }
    /*收藏*/
    public function shoucang()
    {
        if (!session('userid')) {
            $this->error('亲！请登录');
        } else {
            //查询是否点收藏过
            $t = Db::name('shoucang')->where('uid', session('userid'))->where('tid', input('id'))->count();
            if ($t > 0) {
                if (!Db::name('shoucang')->where('tid', input('id'))->where('uid', session('userid'))->delete()) {
                    $this->error('取消收藏失败');
                } else {
                    return json(array('code' => 2, 'msg' => '取消收藏成功'));
                }
            }
            $data['tid'] = input('id');
            $data['uid'] = session('userid');
            $data['open'] = 1;
            $data['time'] = time();
            if (!Db::name('shoucang')->data($data)->insert()) {
                $this->error('收藏失败');
            } else {
                point(set('jifen6', 2), session('userid'), '收藏商品');
                $this->success('收藏成功');
            }
        }
    }
}