<?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\smartbc\controller;
use app\smartbc\model\SmartbcCoupon;
use app\smartbc\model\SmartbcQueen;
use app\smartbc\model\SmartbcStoreCate;
use app\smartbc\model\SmartbcStore;
use app\smartbc\model\SmartbcCouponUser;
use app\smartbc\model\SmartbcOrder;
use app\smartbc\model\SmartbcConfig;
use app\common\facade\AliApi;
use app\common\model\SystemUser;
use app\smartbc\model\SmartbcStoreUnion;
use filter\Filter;
use think\helper\Time;
use think\facade\Request;
use think\facade\Validate;

class Store extends Common{

    public function initialize(){
        parent::initialize();
        $this->assign('pathMaps',[['name'=>'商家管理','url'=>url("smartbc/store/index")]]);
    }

    /**
     * 列表
     */
    public function index(int $types = 0){
        $condition   = [];
        $time      = Request::param('time/d',0);
        $starttime = Request::param('starttime/s');
        $endtime   = Request::param('endtime/s');
        if($time){
            switch ($time) {
                case 2:
                    list($start, $end) = Time::yesterday();
                    break;
                case 30:
                    list($start, $end) = Time::month();
                    break;
                case 60:
                    list($start, $end) = Time::lastMonth();
                    break;
                default:
                    list($start, $end) = Time::today();
                    break;
            }
            $condition[] = ['create_time','>=',$start];
            $condition[] = ['create_time','<=',$end];
        }else{
            if($starttime){
                $condition[] = ['create_time','>=',strtotime($starttime)];
            }
            if($endtime){
                $condition[] = ['create_time','<=',strtotime($endtime)];
            }
        }
        $keyword = Request::param('keyword/s');
        if(!empty($keyword)){
            $condition[] = ['name','like','%'.$keyword.'%'];
        }
        $view['is_top_num'] = SmartbcStore::where($this->mini_program)->where($condition)->where(['is_top' => 1])->count('is_top');
        $view['store_num']  = SmartbcStore::where($this->mini_program)->where($condition)->count();
        $view['lock_num']   = SmartbcStore::where($this->mini_program)->where($condition)->where(['is_lock' => 1])->count();
        if($types){
            $condition[] = ['is_lock','=',$types == 2 ? 1 : 0];
        }
        $view['lists']      = SmartbcStore::where($this->mini_program)->where($condition)->order('is_top desc,sort desc,id desc')->paginate(20,false,['query' => ['types' => $types,'starttime' => $starttime,'endtime' => $endtime,'time'=>$time]]);
        $view['keyword']    = $keyword;
        $view['types']      = $types;
        $view['time']       = $time;
        $view['starttime']  = $starttime;
        $view['endtime']    = $endtime;
        return view()->assign($view);
    }

    /**
     * 选择商家列表
     */
    public function selectStore(){
        $condition = [];
        $condition[] = ['is_lock','=',0];
        $view['keyword'] = $this->request->param('keyword/s');
        if(!empty($view['keyword'])){
            $condition[] = ['name','like','%'.$view['keyword'].'%'];
        }
        $view['lists']  = SmartbcStore::where($this->mini_program)->where($condition)->order('is_top desc,sort desc,id desc')->paginate(20);
        $view['input']  = $this->request->param('input');
        return view()->assign($view);
    }

    /**
     * 好店预览
     */
    public function review(int $id){
        $condition['id'] = $id;
        $view['info']   = SmartbcStore::where($condition)->find();
        if(!$view['info']){
            $this->error('内容不存在');
        }
        $view['manage'] = SystemUser::where($this->mini_program)->where(['id' => $view['info']['manage_uid']])->find();
        $view['orders']  = SmartbcOrder::where($this->mini_program)->where(['store_id'=>$id,'state' => 1])->order('id desc')->paginate(10,false,['query' => ['id' => $id]]);
        return view()->assign($view);
    }
    
    /**
     * 添加
     */
    public function add(){
        if(request()->isAjax()){
            $data = [
                'member_miniapp_id' => $this->member_miniapp_id,
                'manage_uid'        => Request::param('manage_uid/d', 0),
                'cate_id'           => Request::param('cate_id/d', 0),
                'cate_sid'          => Request::param('cate_sid/d', 0),
                'name'              => Request::param('name/s'),
                'address'           => Request::param('address/s'),
                'longitude'         => Request::param('longitude/s'),
                'latitude'          => Request::param('latitude/s'),
                'telphone'          => Request::param('telphone/s'),
                'img'               => Request::param('img/s'),
                'imgs'              => Request::param('imgs/a'),
                'mch_id'            => Request::param('mch_id/s'),
            ];
            $validate = $this->validate($data,'Store.edit');
            if(true !== $validate){
                return json(['code'=>0,'msg'=>$validate]);
            }
            $store = SmartbcStore::where(['manage_uid' => $data['manage_uid']])->find();  
            if($store){
                return json(['code'=>0,'msg'=>'禁止绑定,设置的店长已属于['.$store->name.']的店长']);
            }
            $cate = SmartbcStoreCate::field('name')->where(['id' =>$data['cate_sid']])->find();
            $data['cate_name'] = empty($cate['name']) ? '' : $cate['name'];
            $store_id =  SmartbcStore::edit($data);
            if($store_id){
                return json(['code'=>200,'url'=>url('smartbc/store/index',['cate_id' => $data['cate_id']]),'msg'=>'操作成功']);
            }else{
                return json(['code'=>0,'msg'=>'操作失败']);
            }
        }else{
            $view['cate']    = SmartbcStoreCate::field('name,id')->where($this->mini_program)->where(['parent_id' => 0])->order('sort desc,id desc')->select();
            $view['setting'] = SmartbcConfig::getConfig($this->member_miniapp_id);
            return view()->assign($view);
        }
    }

    //编辑
    public function edit(){
        if(request()->isAjax()){
            $data = [
                'member_miniapp_id' => $this->member_miniapp_id,
                'id'                => Request::param('id/d'),
                'manage_uid'        => Request::param('manage_uid/d',0),
                'cate_id'           => Request::param('cate_id/d',0),
                'cate_sid'          => Request::param('cate_sid/d',0),
                'name'              => Request::param('name/s'),
                'address'           => Request::param('address/s'),
                'longitude'         => Request::param('longitude/s'),
                'latitude'          => Request::param('latitude/s'),
                'telphone'          => Request::param('telphone/s'),
                'img'               => Request::param('img/s'),
                'imgs'              => Request::param('imgs/a'),
                'mch_id'            => Request::param('mch_id/s'),
            ];
            $validate = $this->validate($data,'Store.edit');
            if(true !== $validate){
                return json(['code'=>0,'msg'=>$validate]);
            }
            $store = SmartbcStore::where([['manage_uid','=',$data['manage_uid']],['id','<>',$data['id']]])->find();  
            if($store){
                return json(['code'=>0,'msg'=>'禁止绑定,设置的店长已属于['.$store->name.']的店长']);
            }
            $cate = SmartbcStoreCate::field('name')->where(['id' =>$data['cate_sid']])->find();
            $data['cate_name'] = empty($cate['name']) ? '' : $cate['name'];
            $store_id =  SmartbcStore::edit($data);
            return json(['code'=>200,'url'=>url('store/index',['cate_id' => $data['cate_id']]),'msg'=>'操作成功']);
        }else{
            $info = SmartbcStore::where($this->mini_program)->where(['id' => $this->request->param('id/d')])->find();
            if(!$info){
                $this->error("404 NOT FOUND");
            }
            $view['info']     = $info;
            $view['imgs']     = json_decode($info['imgs'],true);
            $view['cate']     = SmartbcStoreCate::field('name,id')->where($this->mini_program)->where(['parent_id' => 0])->order('sort desc,id desc')->select();
            $view['cate_sub'] = SmartbcStoreCate::field('name,id')->where(['parent_id' => $info['cate_id'],'member_miniapp_id' => $this->member_miniapp_id])->order('sort desc,id desc')->select();
            $view['setting']  = SmartbcConfig::getConfig($this->member_miniapp_id);
            return view()->assign($view);
        }
    }
     
    /**
     * 排序
     */
    public function sort(){
        if(request()->isAjax()){
            $data = [
                'sort' => Request::param('sort/d'),
                'id'   => Request::param('id/d'),
            ];
            $validate = $this->validate($data,'Store.sort');
            if(true !== $validate){
                return json(['code'=>0,'msg'=>$validate]);
            }
            $result = SmartbcStore::where(['id' => $data['id']])->update(['sort' => $data['sort']]);
            if($result){
                return json(['code'=>200,'msg'=>'操作成功']);
            }else{
                return json(['code'=>0,'msg'=>'操作失败']);
            }
        }
    }
    
    /**
     * 置顶/取消
     * @param integer $id 用户ID
     */
    public function isTop(int $id){
        $result = SmartbcStore::isTop($id);
        if(!$result){
            return json(['code'=>0,'message'=>'操作失败']);
        }else{
            return json(['code'=>200,'message'=>'操作成功']);
        }
    } 

     /**
     * 置顶/取消
     * @param integer $id 用户ID
     */
    public function isLock(int $id){
        $result = SmartbcStore::isLock($id,$this->member_miniapp_id);
        if(!$result){
            return json(['code'=>0,'message'=>'操作失败']);
        }else{
            return json(['code'=>200,'message'=>'操作成功']);
        }
    } 
   

    //删除
    public function delete(int $id){
        $coupon = SmartbcCoupon::where($this->mini_program)->where(['store_id' => $id,'is_end' => 0])->count();
        if($coupon){
            return json(['code'=>403,'msg'=>'请先删除好店优惠券']);
        }
        $couponUser =  SmartbcCouponUser::where($this->mini_program)->where(['store_id' => $id,'is_end' => 0])->count();
        if($couponUser){
            return json(['code'=>403,'msg'=>'请先删除用户已领优惠券']);
        }
        SmartbcStore::where($this->mini_program)->where(['id' => $id])->delete();   //删除好店
        SmartbcStoreUnion::where($this->mini_program)->where(['store_id' => $id])->delete();   //删除好店群组关联
        return json(['code'=>200,'msg'=>'操作成功']);
    }

    /**
     * 选择所属用户
     */
    public function selectStoreManage(){
        $keyword = Request::param('keyword');
        $input   = Request::param('input');
        $condition[] = ['is_lock','=',0];
        if(!empty($keyword)){
            if(Validate::isMobile($keyword)){
                $condition[] = ['phone_uid','=',$keyword];
            }else{
                $condition[] = ['nickname','like','%'.$keyword.'%'];
            }
        }
        $manage_uid      = SmartbcStore::where($this->mini_program)->column('manage_uid');
        $view['list']    = SystemUser::where($this->mini_program)->where($condition)->whereNotIn('id',$manage_uid)->order('id desc')->paginate(10,false,['query' => ['input' => $input,'keyword' => $keyword]]);
        $view['keyword'] = $keyword;
        $view['input']   = $input;
        $view['id']      = $this->member_miniapp_id;
        return view()->assign($view);
    }

    /**
     * 读取好店分类
     * @return void
     */
    public function storecate(int $cate_id){
        $cate = SmartbcStoreCate::where(['member_miniapp_id' => $this->member_miniapp_id,'parent_id' => $cate_id])->field('id,name')->order('sort desc,id desc')->select(); 
        return json(['code'=>200,'msg'=>'成功','data' => $cate]);
    }
 
    /**
     *  根据地址位置转账
     * @return void
     */
    public function baidu($address){
        $view['address']  = $address;
        return view()->assign($view);
    }   

    /**
     *  根据地址位置读取地址
     * @return void
     */
    public function maps($address){
        $rel = AliApi::address($address);
        if(!$rel){
            return enjson(0,'请确认是否帐号欠费');
        }
        $address = $rel['geocodes'][0];
        $location =  explode(',',$address['location']);
        return enjson(200,'成功',$location);
    }

    /**
     * 微信分账队列
     * @return void
     */
    public function queen(int $types = 0,string $order = ''){
        $condition = [];
        if(!empty($order)){
            $condition['out_order_no'] = Filter::filter_escape(trim($order));
        }
        $store_id  = Request::param('store_id',0);
        $store_name  = Request::param('store_name');
        if($store_id){
            $condition['store_id'] = $store_id;
        }
        $view['amount_quree']   = SmartbcQueen::where($this->mini_program)->where($condition)->where(['is_finish' => 0])->sum('amount');
        $view['amount_success'] = SmartbcQueen::where($this->mini_program)->where($condition)->where(['is_finish' => 2])->sum('amount');
        $view['amount_fail']    = SmartbcQueen::where($this->mini_program)->where($condition)->where(['is_finish' => 1])->sum('amount');
        if($types){
            switch ($types) {
                case 2:
                    $is_finish = 2;
                    break;
                case 3:
                    $is_finish = 1;
                    break;
                default:
                    $is_finish = 0;
                    break;
            }
            $condition['is_finish'] = $is_finish;
        }
        $orderby = $types == 1 ? 'id asc':'id desc';
        $view['lists'] = SmartbcQueen::where($this->mini_program)->where($condition)->order($orderby)->paginate(10,false,[
            'query' => ['types' => $types,'store_id' => $store_id,'store_name' => $store_name],
        ]);
        $view['types'] = $types;
        $view['order'] = $order;
        $view['store_id']   = $store_id;
        $view['store_name'] = $store_name;
        $view['pathMaps'] = [['name'=>'结算队列','url'=>url("store/queen")]];
        return view()->assign($view);
    }


    /**
     * 重置分账队列
     * @return void
     */
    public function resetQueen(string $order){
        $condition = [];
        $condition['out_order_no'] = Filter::filter_escape(trim($order));
        $condition['is_finish']    = 1;
        $rueen = SmartbcQueen::where($this->mini_program)->where($condition)->update(['is_finish' => 0]);
        if($rueen){
            return json(['code'=>200,'message'=>'成功']);
        }else{
            return json(['code'=>0,'message'=>'失败,只有分账失败的才允许重置队列']);
        }
    }
}