<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 好店
 */
namespace app\allwin\controller\api\v4;
use app\allwin\controller\api\Base;
use app\allwin\model\AllwinStore;
use app\allwin\model\AllwinShop;
use app\allwin\model\AllwinStoreCate;
use app\allwin\model\Coupon;
use app\allwin\model\CouponUser;
use app\allwin\model\StoreWorker;
use app\common\model\SystemMemberSms;
use app\common\event\User;
use app\common\facade\Inform;
use app\common\facade\Upload;
use filter\Filter;

class Store extends Base{

    /**
     * 首页显示
     */
    public function index(){
        $param['signkey'] = $this->request->param('signkey');
        $param['sign']    = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson(500,'签名验证失败');
        }
        $where = [];
        $where[] = ['member_miniapp_id','=',$this->miniapp_id];
        $where[] = ['is_lock','=',0];
        $where[] = ['is_top','=',1];
        $rel = AllwinStore::where($where)->field('id,name,longitude,latitude,img,telphone,address,score,tips,tags,is_top,state_text')->order('sort desc,id desc')->paginate(10)->toArray();
        if(empty($rel['data'])){
            return json(['code'=>204,'msg'=>'没有内容']);
        }else{
            $data = $rel['data'];
            foreach ($rel['data'] as $key => $value) {
                $data[$key]['tags']     = explode(',',$value['tags']);
                $data[$key]['img']      = $value['img']."?x-oss-process=style/w100";
                $data[$key]['distance'] = getDistance($this->qqgps['lng'],$this->qqgps['lat'],$value['longitude'],$value['latitude']);
            }
            return json(['code'=>200,'msg'=>'成功','data' => $data]);
        }
    }

    /**
     * 点赞
     **/
    public function like(){
        $this->isUserAuth();
        $param['id']   = $this->request->param('id/d',0);
        $param['sign'] = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson($rel['code'],'签名验证失败');
        }
        $condition['member_miniapp_id'] = $this->miniapp_id;
        $condition['id']                = $param['id'];
        $rel = AllwinStore::where($condition)->setInc('views',1);
        if(empty($rel)){
            return enjson(204);
        }else{
            return enjson(200);
        }
    }

    /**
     * 店铺预览
     */
    public function getView(){
        $param['store_id'] = $this->request->param('store_id/d',0);
        $param['sign']    = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson(500,'签名验证失败');
        }
        $where['id']                = $param['store_id'];
        $where['member_miniapp_id'] = $this->miniapp_id;
        $where['is_lock']           = 0;
        $info = AllwinStore::getView($where);
        if(empty($info)){
            return json(['code'=>204,'msg'=>'没有内容']);
        }else{
            $info['distance'] = getDistance($this->qqgps['lng'],$this->qqgps['lat'],$info['longitude'],$info['latitude']);
            $chain = [];
            foreach ($info['chains'] as $key => $value) {
                $chain[$key]['title']    = $value['title'];
                $chain[$key]['address']  = $value['address'];
                $chain[$key]['telphone'] = $value['telphone'];
                $chain[$key]['distance'] = getDistance($this->qqgps['lng'],$this->qqgps['lat'],$value->longitude,$value->latitude);
            }
            $info['chain'] = $chain;
            unset($info['chains']);
            AllwinStore::where(['id'=> $param['store_id']])->setInc('views',1);
            return json(['code'=>200,'msg'=>'成功','data' => $info]);
        }
    }

    /**
     * 读取行业信息列表（待删除） v4.0
     * @param integer 读取ID
     * @return json
     */
    public function cate(){
        $param['signkey'] = $this->request->param('signkey');
        $param['cate_id'] = $this->request->param('cate_id',0);
        $param['lists']   = $this->request->param('lists/d',0);
        $param['sign']    = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson($rel['code'],'签名验证失败');
        }
        $where['parent_id']         = $param['cate_id'];
        $where['member_miniapp_id'] = $this->miniapp_id;
        $data = AllwinStoreCate::where($where)->field('id,name,picture,title')->order('sort desc,id desc')->select()->toArray();
        if(empty($data)){
            return json(['code'=>404,'msg'=>'没有好店分类']);
        }else{
            $nav = [];
            if($param['cate_id'] == 0 && $param['lists'] == 0){
                $i = -1;
                foreach($data as $key => $value){
                    if($key%10 == 0){
                        $i++;
                        $nav[$i][] = $value;
                    }else{
                        $nav[$i][] = $value;
                    }
                }
            }else{
                $nav = $data;
            }
            return json(['code'=>200,'msg'=>'成功','data' => $data]);
        }
    }

    /**
     * 读取行业信息列表  v4.1
     * @param integer 读取ID
     * @return json
     */
    public function category(){
        $param['signkey'] = $this->request->param('signkey');
        $param['cate_id'] = $this->request->param('cate_id',0);
        $param['lists']   = $this->request->param('lists/d',0);
        $param['sign']    = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson($rel['code'],'签名验证失败');
        }
        $where['parent_id']         = $param['cate_id'];
        $where['member_miniapp_id'] = $this->miniapp_id;
        $data = AllwinStoreCate::where($where)->field('id,name,picture,title')->order('sort desc,id desc')->select()->toArray();
        if(empty($data)){
            return enjson(404,'没有数据');
        }
        return enjson(200,'成功',$data);
    }

    /**
     * 店铺列表
     */
    public function lists(){
        $param['keyword']  = $this->request->param('keyword','');
        $param['cate_id']  = $this->request->param('cate_id',0);
        $param['cate_sid'] = $this->request->param('cate_sid/d',0);
        $param['page']     = $this->request->param('page/d',0);
        $param['sign']     = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson($rel['code'],'签名验证失败');
        }
        $where = [];

        if($param['cate_sid']){
            $where[] = ['cate_sid','=',$param['cate_sid']];
        }
        if($param['cate_id']){
            $where[] = ['cate_id','=',$param['cate_id']];
        }
        $where[] = ['member_miniapp_id','=',$this->miniapp_id];
        $where[] = ['is_lock','=',0];
        $rel = AllwinStore::where($where)->withSearch(['name'],['name' => $param['keyword']])
            ->field('id,name,longitude,latitude,img,telphone,address,score,tips,tags,is_top,state_text')
            ->order('is_top desc,sort desc,id desc')->paginate(10)->toArray();
        if(empty($rel['data'])){
            return enjson(204,'没有内容');
        }else{
            $data = $rel['data'];
            foreach ($rel['data'] as $key => $value) {
                $data[$key]['tags']      = explode(',',$value['tags']);
                $data[$key]['img']       = $value['img']."?x-oss-process=style/w100";
                $data[$key]['distance']  = getDistance($this->qqgps['lng'],$this->qqgps['lat'],$value['longitude'],$value['latitude']);
            }
            return enjson(200,'成功',$data);
        }
    }

    /**
     * 店铺首页产品
     */
    public function getShop(){
        $param['store_id'] = $this->request->param('store_id/d',0);
        $param['page']     = $this->request->param('page/d',0);
        $param['sign']     = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson(500,'签名验证失败');
        }
        $condition['member_miniapp_id'] = $this->miniapp_id; 
        $condition['store_id'] = $param['store_id']; 
        $condition['is_sale'] = 1; 
        $condition['is_del'] = 0; 
        //统计数量
        $shop_num = 0;
        if($param['page'] == 0){
            $shop_num = AllwinShop::where($condition)->count();
        }
        //好店推荐
        $condition['types'] = 4; 
        $data = AllwinShop::where($condition)->field('id,category_id,name,title,img,sell_price,end_time,market_price')->limit(3)->select();
        return enjson(200,'成功',['shop' => $data,'shop_num' => $shop_num]);
    }

    /**
     * 店铺首页产品
     */
    public function getCoupon(){
        $param['store_id'] = $this->request->param('store_id/d',0);
        $param['page']     = $this->request->param('page/d',0);
        $param['sign']     = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson(403,'签名失败');
        }
        $condition   = [];
        $condition[] = ['member_miniapp_id','=',$this->miniapp_id];
        $condition[] = ['store_id','=',$param['store_id']];
        $condition[] = ['is_platform','=',0];
        $condition[] = ['is_lock','=',0];
        $condition[] = ['is_end','=',0];
        $condition[] = ['num','>',0];
        $condition[] = ['endtime','>',time()];
        //优惠券列表
        if($param['page'] == 0){
            $condition[] = ['is_top','=',1];
            $coupon = Coupon::where($condition)->order('is_top desc,sort desc,size desc')->limit(4)->select();
        }else{
            $coupon = Coupon::where($condition)->order('is_top desc,sort desc,size desc')->paginate(10);
        }        
        if ($coupon->isEmpty()) {
            return enjson(204,'没有优惠券');
        }
        //优惠券数量
        $coupon_num = 0;
        if($param['page'] == 0){
            $coupon_num = Coupon::where($condition)->count();
        }
        //判断用户已领取优惠券
        $user_coupon_id = [];
        if ($this->user) {
            $ids = CouponUser::userCouponIds($this->user->id);
            if (!empty($ids)) {
                $user_coupon_id = $ids;
            }
        }
        $data = [];
        foreach ($coupon as $key => $value) {
            $data[$key]['id']        = $value['id'];
            $data[$key]['store_id']  = $value->store->id;
            $data[$key]['store']     = $value->store->name;
            $data[$key]['address']   = $value->store->address;
            $data[$key]['img']       = $value['img'].'?x-oss-process=style/w100';
            $data[$key]['name']      = $value['name'];
            $data[$key]['size']      = $value['size'];
            $data[$key]['tips']      = $value['tips'];
            $data[$key]['price']     = $value['price'];
            $data[$key]['pay_price'] = $value['pay_price'];
            $data[$key]['theme']     = $value['theme'];
            $data[$key]['starttime'] = date('Y-m-d',$value['starttime']);
            $data[$key]['endtime']   = date('Y-m-d',$value['endtime']);
            $data[$key]['state']     = in_array($value['id'],$user_coupon_id) ? 1 : 0;
            $data[$key]['rate']      = rate($value['num'],$value['num_of']);
        }
        return enjson(200,'成功',['coupon' => $data,'coupon_num' => $coupon_num]);
    }

  /**
     * 申请入驻商家 
     */
    public function regstore(){
        $this->isUserAuth();
        //读取判断是否好店老板
        $store = AllwinStore::manageStore($this->user->id);
        if (!empty($store)) {
            return json(['code'=>404,'msg'=>'您已加入商业联盟,无需重复入驻.']);
        }
        $worker = StoreWorker::isManage($this->miniapp_id,$this->user->id);
        if (!empty($worker)) {
            return json(['code'=>404,'msg'=>'你是好店管理员无权入驻,请联系客服.']);
        }
        if (request()->isPost()) {
            $data = [
                'member_miniapp_id' => $this->miniapp_id,
                'name'              => input('post.name/s','','htmlspecialchars'),
                'state'             => input('post.state/d','','htmlspecialchars'),
                'work_time'         => input('post.work_time/s','','htmlspecialchars'),
                'address'           => input('post.address/s','','htmlspecialchars'),
                'telphone'          => input('post.telphone/s','','htmlspecialchars'),
                'tips'              => input('post.tips/s','','htmlspecialchars'),
                'tags'              => input('post.tags/s','','htmlspecialchars'),
                'imgs'              => input('post.imgs/a','','htmlspecialchars'),
                'manage_uid'        => intval($this->user->id),
                'money_coupon'      => 0,
                'is_lock'           => 1
            ];
            if(!empty($data['imgs'])){
                $data['imgs'] = Filter::filter_escape($data['imgs']);
                $data['img']  = $data['imgs'][0];
            }
            $data['state_text'] = $data['state'] ? '营业中' : '未营业';
            $validate = $this->validate($data, 'Store.reg');
            if (true !== $validate) {
                return json(['code'=>403,'msg'=>$validate]);
            }
            $data['imgs'] = json_encode($data['imgs']);
            $rel = AllwinStore::insert($data);
            if($rel){
                //通知到后台
                SystemMemberSms::sms($this->miniapp_id,'您有一条好店['.$data['name'].']信息待审核',url('allwin/store/index',['types' => 1]));
                //通知申请者到微信
                Inform::sms($this->user->id,$this->miniapp_id,['title' =>'业务进展通知','type' => '店铺入住申请','content' =>'您的店铺['.$data['name'].']入住申请正在审核中']);
                //通知到后台管理的微信
                Inform::sms(User::isFounder($this->miniapp_id)->user_id,$this->miniapp_id,['title' =>'店铺入住申请','type' => '店铺入住申请','content' =>'店铺['.$data['name'].']入住申请待审核']);
                return enjson(200,"好店入驻信息已提交,请等待审核。");
            }else{
                return enjson(200,"申请失败,请稍后重试");
            }
        }
    }

    /**
     * 商城图片
     * @return void
     */
    public function upImg(){
        $this->isUserAuth();
        $store = StoreWorker::isManage($this->user->member_miniapp_id,$this->user->id);
        if (empty($store)) {
            return enjson(404,'非好店管理员');
        }
        if(request()->isPost()){
            $rel = Upload::index();
            if($rel['error'] == 0){
                return enjson(200,'成功',$rel['url']);
            }else{
                return enjson(204);
            }
        }
    }
}