<?php

namespace app\api\controller;

use app\admin\model\Collection;
use app\admin\model\Rcoupon;
use app\common\controller\Api;
use fast\Http;
use think\db\Query;
use think\Validate;
use think\Db;
use think\db\Expression;

/**
 * 个人中心接口
 */
class User extends Api
{
    //无需登录,*表都不需要
//    protected $noNeedLogin = ['login', 'mobilelogin'];
    protected  $noNeedLogin = ['login'];
    protected $noNeedRight = '*';
    protected $uid = '';
    public function _initialize()
    {
        parent::_initialize();
        $this->uid = $this->auth->getUserId();
    }

    /**
     * @ApiTitle    (小程序登录)
     * @ApiSummary  (小程序登录)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/login)
     * @ApiParams   (name="code", type="string", required=true, description="小程序code")
     * @ApiParams   (name="nickname", type="string", required=true, description="小程序昵称")
     * @ApiParams   (name="avatar", type="string", required=true, description="小程序头像")
     * @ApiReturn({
            "code": 1,
            "msg": "登录成功",
            "time": "1553839125",
            "data": {
                "token": "677afb39-1a4f-4492-84d3-0bcf32016b8a",//token
                "user_id": 27,//用户id
                "createtime": 1553839125,//登录时间
                "expiretime": 1556431125,//token失效时间
                "expires_in": 2592000//token失效剩余时间(单位s)
                "openid": 1485212522522//openid
            })
     */
    public function login(){
        if($this->request->isPost()){
            //小程序配置
            $config =  config('verify.raw');
            //小程序传递数据,包含昵称,头像,code
            $raw_data = $this->request->post();
            //验证表数据
            $rule = config('verify.user');
            $validate = new Validate($rule['rule'],$rule['msg']);
            if (!$validate->check($raw_data)) {
                $this->error($validate->getError());
            }
            $params = [
                'appid'      => $config['app_id'],
                'secret'     => $config['secret'],
                'js_code'    => $raw_data['code'],
                'grant_type' => 'authorization_code'
            ];
            $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
            if ($result['ret']) {
                $json = (array)json_decode($result['msg'], true);
                if (isset($json['openid'])) {
                    $result = [
                        'openid' => $json['openid'],
                        'nickname' => $raw_data['nickname'],
                        'avatar' => $raw_data['avatar']
                    ];
                    $ret = $this->auth->login($result);
                    if ($ret) {
                        $data = $this->auth->getUserinfo();
                        $data['nickname'] = $this->auth->emoji_decode($data['nickname']);

                        //增加访客数
                        $type = config('verify.browse_type')[0];
                        Common::statistics($type,$data['user_id']);
                        $this->success('登录成功', $data);
                    }else {
                        $this->error($this->auth->getError());
                    }
                } else {
                    $this->error("登录失败",$json);
                }
            }
        }else{
            $this->error('请求方式错误');
        }
    }

    /**
     * @ApiTitle    (获取个人信息(新人/旧人))
     * @ApiSummary  (获取个人信息(新人/旧人))
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/user/info)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1575188985",
        "data": {
            "id": 2,//用户id
            "openid": "orhy25PeYJsTeN70aoTL_Hvfvz20",//openid
            "nickname": "风起时",//昵称
            "mobile": "",
            "avatar": "",//头像
            "token": "2794e6d4-14d5-4725-ba79-8b863d3ef8c6",//token
            "user_id": 2,
            "createtime": 1574927973,
            "expiretime": 1577519973,
            "expires_in": 2330988,
            "is_news": 0//是否为新人(0:是,1:否)
        }
    })
     */
    public function info(){
        if($this->request->isGet()){
            $data = $this->auth->getUserinfo();
            if($data){
                $res = Common::findSoftWhereData('order',['uid'=>$data['id'],'status'=>config('verify.status')[8]],'id');
                if($res){
                    $data['is_news'] = 1;//旧人
                }else{
                    $data['is_news'] = 0;//新人
                }
            }
            $data['nickname'] = $this->auth->emoji_decode($data['nickname']);
            $this->success('成功', $data);
        }else{
            $this->error('请求方式错误');
        }
    }

    /**
     * @ApiTitle    (获取二维码)
     * @ApiSummary  (获取二维码)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/user/getWxCode)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     *
     * @ApiParams   (name="goods_id", type="inter", required=true, description="商品id")
     *
     * @ApiReturn ({
        "code": 1,
        "msg": "成功",
        "time": "1572602867",
        "data": {
            "code_url": "http://feifangu.w.brotop.cn/wx_code_img/code_6.jpg"//二维码路径
        }
    })
     */
    public function getWxCode(){
        if($this->request->isGet()){
            $goods_id = $this->request->get('goods_id');
            $rule = config('verify.goods_detail');
            $validate = new Validate($rule['rule'],$rule['msg']);
            if (!$validate->check(['goods_id'=>$goods_id])) {
                $this->error($validate->getError());
            }

            //获取access_token
            $config = config('verify.raw');
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$config['app_id'].'&secret='.$config['secret'];
            $res = $this->auth->http_get($url);
            $json_arr = json_decode($res,true);
            if(!isset($json_arr['access_token'])&&empty($json_arr['access_token'])){
                //用户登录
                $this->error('失败');
            }
            $access_token = $json_arr['access_token'];
            //获取二维码链接
            $get_code_url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token;
            $data = [
                'scene' => 'share_uid='.$this->uid.'&id='.$goods_id,
                'width' => 280,
                'page' => 'pages/index/goodsDetail/goodsDetail',
            ];
            $data = json_encode($data);
            $code_res = $this->auth->http_post($get_code_url,$data);
            file_put_contents('wx_code_img/code_'.$this->uid.'_'.$goods_id.'.jpg',$code_res);
            $code_url = config('verify.ffg_host').'/wx_code_img/code_'.$this->uid.'_'.$goods_id.'.jpg';
            $this->success('成功', ['code_url'=>$code_url]);
        }else{
            $this->error('请求方式错误');
        }
    }

    /**
     * @ApiTitle    (收藏)
     * @ApiSummary  (收藏)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/collection)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     *
     * @ApiParams   (name="goods_id", type="inter", required=true, description="商品id")
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1571037179",
        "data": null
    })
     */
    public function collection(){
        if($this->request->isPost()){
            $goods_id = $this->request->post('goods_id');
            $rule = config('verify.goods_detail');
            $validate = new Validate($rule['rule'],$rule['msg']);
            if (!$validate->check(['goods_id'=>$goods_id])) {
                $this->error($validate->getError());
            }

            $collectionModel = new Collection();
            $res1 = Common::findWhereData('collection',['uid'=>$this->uid,'g_id'=>$goods_id],'id');
            if($res1){
                $this->error('已经收藏过了');
            }else{
                $res = $collectionModel->create(['g_id'=>$goods_id,'uid'=>$this->uid]);
                if($res){
                    $goodsModel = new \app\admin\model\Goods();
                    $goodsModel->where(['id'=>$goods_id])->setInc('collections',1);

                    //增加商品收藏数
                    $type = config('verify.browse_type')[2];
                    Common::statistics($type,$this->uid,$goods_id);
                    $this->success('成功');
                }else{
                    $this->error('失败');
                }
            }
        }else{
            $this->error('请求方式错误');
        }
    }

    /**
     * @ApiTitle    (取消收藏)
     * @ApiSummary  (取消收藏)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/cancelCollection)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     *
     * @ApiParams   (name="goods_id", type="inter", required=true, description="商品id")
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1571037179",
        "data": null
    })
     */
    public function cancelCollection(){
        if($this->request->isPost()){
            $goods_id = $this->request->post('goods_id');
            $rule = config('verify.goods_detail');
            $validate = new Validate($rule['rule'],$rule['msg']);
            if (!$validate->check(['goods_id'=>$goods_id])) {
                $this->error($validate->getError());
            }

            $collectionModel = new Collection();
            $res = $collectionModel->where(['uid'=>$this->uid,'g_id'=>$goods_id])->delete();
            if($res){
                $goodsModel = new \app\admin\model\Goods();
                $goodsModel->where(['id'=>$goods_id])->setDec('collections',1);
                $this->success('成功');
            }else{
                $this->error('失败');
            }
        }else{
            $this->error('请求方式错误');
        }
    }

    /**
     * @ApiTitle    (我的收藏)
     * @ApiSummary  (我的收藏)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/user/myCollectionList)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     *
     * @ApiParams   (name="page", type="inter", required=true, description="分页页码")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1574941706",
        "data": {
            "data": [
                {
                    "id": 7,//商品id
                    "image": "http://jinglong.springchunjia.cn/uploads/20191128/8a677f5a0418059bf1b974c50026af13.png",//图片路径
                    "name": "MONENT 动感系列",//商品名称
                    "tag": [//商品标签
                        "日式简约",
                        "隐秘乡奢",
                        "家庭情侣"
                    ],
                    "style": [//商品规格
                        "主餐匙,茶匙各1件",
                        "古堡灰"
                    ],
                    "sale_price": 2299//销售价格
                    "expense_price": //运费(0:显示包运费标签)
                    "is_new_tag": 0//新人价格标签(0:不显示,1:显示)
                },
                {
                    "id": 4,
                    "image": "http://jinglong.springchunjia.cn/uploads/20191128/93971e55b83d1a09c1831f8197514305.png",
                    "name": "MONENT 动感系列",
                    "tag": [
                        "AB级",
                        "ABX级",
                        "ABN级"
                    ],
                    "new_price": 2499,
                    "sale_price": 2599
                },
            ],
            "total_page": 1
        }
    })
     */
    public function myCollectionList(){
        if($this->request->isGet()){
            $page = $this->request->get('page');
            $rule = config('verify.page');
            $validate = new Validate($rule['rule'],$rule['msg']);
            if (!$validate->check(['page'=>$page])) {
                $this->error($validate->getError());
            }
            
            $collection = Common::selectWhereData('collection',['uid'=>$this->uid],'id,g_id');
            $g_ids = array_column($collection,'g_id');

            //按照指定的顺序排序
            $g_id_str = implode(',',$g_ids);
            $exp = new Expression('field(id,'.$g_id_str.')');

            $limit = config('verify.limit');
            $arr = Common::goodsList(['id'=>['in',$g_ids]],$page,$this->uid,$limit,$exp);
            $this->success('成功',$arr);
        }else{
            $this->error('请求方式错误');
        }
    }

    /**
     * @ApiTitle    (我的优惠券)
     * @ApiSummary  (我的优惠券)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/user/myCouponList)
     *
     * @ApiParams   (name="is_flag", type="inter", required=true, description="优惠券标识(0:未使用,1:已使用,2:已过期)")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1575372162",
        "data": [
            {
                "id": 2,//优惠券id
                "coupon_tag": "无门槛",//优惠券(无门槛,折扣券,满减券)
                "coupon_price": "¥300",//(折扣或减少金额)
                "coupon_tag1": "无门槛",优惠券(无门槛,满多少可用)
                "coupon_name": "全场优惠券",//优惠券名称
                "end_time": "2020.1.31",//优惠券有效期
                "type": "全场通用"//优惠券用途
            },
            {
                "id": 10,
                "coupon_tag": "折扣券",
                "coupon_price": "9.5折",
                "coupon_tag1": "满2000可用",
                "coupon_name": "商品优惠券",
                "end_time": "2020.1.31",
                "type": "商品可用"
            }
        ]
    })
     */
    public function myCouponList(){
        if($this->request->isGet()){
            $is_flag = $this->request->get('is_flag');
            $rule = config('verify.my_coupon');
            $validate = new Validate($rule['rule'],$rule['msg']);
            if (!$validate->check(['is_flag'=>$is_flag])) {
                $this->error($validate->getError());
            }

            $flag = config('verify.flag');
            $where['uid'] = $this->uid;
            $current_time = time();
            if($is_flag == 0){
                //未使用
                $where['is_use'] = $flag[0];
                $where1['start_time'] = ['<',$current_time];
                $where1['end_time'] = ['>',$current_time];
            }else if($is_flag == 1){
                //已使用
                $where['is_use'] = $flag[1];
                $where1['start_time'] = ['<',$current_time];
                $where1['end_time'] = ['>',$current_time];
            }else{
                //已过期
                $where1['end_time'] = ['<',$current_time];
            }

            //查询已经领取过
            $receive = Common::selectWhereData('rcoupon',$where,'id,c_id');
            $receive_s = array_column($receive,'c_id');
            $where1['id'] = ['in',$receive_s];
            $data = Common::selectWhereData('coupon',$where1,'id,type,coupon_name,c_type,coupon_type,full_reduce,reduce,discount,coupon_number,end_time','sort desc,id desc');
            $res = [];
            foreach($data as $key=>$value){

                $res[$key]['id'] = $value['id'];
                //无门槛,有门槛
                if($value['c_type'] == 0){
                    //无门槛
                    if($value['coupon_type'] == 0){
                        //减少券,去掉满减金额,折扣字段,
                        unset($value['full_reduce']);
                        unset($value['discount']);
                        $res[$key]['coupon_tag'] = '无门槛';
                        $res[$key]['coupon_price'] = '¥'.$value['reduce'];
                        $res[$key]['coupon_tag1'] = '无门槛';
                    }else{
                        //折扣券,去掉满减金额,减少金额字段,
                        unset($value['full_reduce']);
                        unset($value['reduce']);
                        $res[$key]['coupon_tag'] = '折扣券';
                        $res[$key]['coupon_price'] = $value['discount'].'折';
                        $res[$key]['coupon_tag1'] = '无门槛';
                    }
                }else{
                    //有门槛
                    if($value['coupon_type'] == 0){
                        //减少券,去掉折扣字段,
                        unset($value['discount']);
                        $res[$key]['coupon_tag'] = '满减券';
                        $res[$key]['coupon_price'] = '¥'.$value['reduce'];
                        $res[$key]['coupon_tag1'] = '满'.$value['full_reduce'].'可用';
                    }else{
                        //折扣券,去掉减少金额字段,
                        unset($value['reduce']);
                        $res[$key]['coupon_tag'] = '折扣券';
                        $res[$key]['coupon_price'] = $value['discount'].'折';
                        $res[$key]['coupon_tag1'] = '满'.$value['full_reduce'].'可用';
                    }
                }

                $res[$key]['coupon_name'] = $value['coupon_name'];//优惠券名称
                $res[$key]['end_time'] = date('Y.n.j',$value['end_time']);//优惠券有效期
                //全场,品牌,商品
                if($value['type'] == 0){
                    $res[$key]['type'] = '全场通用';

                }else if($value['type'] == 1){
                    $res[$key]['type'] = '部分品牌可用';

                }else{
                    $res[$key]['type'] = '部分商品可用';

                }
            }
            $this->success('成功',$res);
        }else{
            $this->error('请求方式错误');
        }
    }

    /**
     * @ApiTitle    (分享获取礼包)
     * @ApiSummary  (分享获取礼包)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/share)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     *
     * @ApiParams   (name="share_uid", type="inter", required=true, description="分享人uid")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1571037179",
        "data": null
    })
     */
    public function share(){
        if($this->request->isPost()){
            $share_uid = $this->request->post('share_uid');
            $rule = config('verify.share');
            $validate = new Validate($rule['rule'],$rule['msg']);
            if (!$validate->check(['share_uid'=>$share_uid])) {
                $this->error($validate->getError());
            }

            if($share_uid == $this->uid){
                //携带参数错误
                $this->error('失败');
            }

            $rCouponModel = new Rcoupon();
            //查询分享人已领取优惠券
            $receive = Common::selectWhereData('rcoupon',['uid'=>$share_uid],'id,c_id');
            $receive_s = array_column($receive,'c_id');
            //查询分享人优惠券
            $res_coupon = Common::selectWhereData('coupon',['gift'=>1,'end_time'=>['>',time()]],'id');
            $res_coupon = array_column($res_coupon,'id');
            $res = array_diff($res_coupon,$receive_s);//数组1不存在数组2中的数组
            $arr = [];
            foreach($res as $key=>$value){
                $arr[$key]['uid'] = $share_uid;
                $arr[$key]['c_id'] = $value;
                $arr[$key]['is_share'] = 1;
            }
            $rCouponModel->saveAll($arr);

            //查询被分享人已领取优惠券
            $receive = Common::selectWhereData('rcoupon',['uid'=>$this->uid],'id,c_id');
            $receive_s = array_column($receive,'c_id');
            //查询分享人优惠券
            $res_coupon = Common::selectWhereData('coupon',['gift'=>2,'end_time'=>['>',time()]],'id');
            $res_coupon = array_column($res_coupon,'id');
            $res = array_diff($res_coupon,$receive_s);//数组1不存在数组2中的数组
            $arr1 = [];
            foreach($res as $key=>$value){
                $arr1[$key]['uid'] = $this->uid;
                $arr1[$key]['c_id'] = $value;
                $arr1[$key]['is_share'] = 1;
            }
            $rCouponModel->saveAll($arr1);
            $this->success('成功');
        }else{
            $this->error('请求方式错误');
        }
    }
}