<?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\ais\controller\api\v1;
use app\ais\controller\api\Base;
use app\ais\model\AisConfig;
use app\ais\model\AisCouponUser;
use app\ais\model\AisOrder;
use app\ais\model\AisStore;
use app\ais\model\AisStoreBill;
use app\ais\model\AisStoreGroup;
use app\ais\model\AisStoreUnion;
use app\ais\model\AisShopOrder;
use app\ais\model\AisVip;
use app\ais\model\AisVipUser;
use app\common\facade\Upload;
use Yurun\Util\HttpRequest;
use think\Db;

class Config extends Base{

     /**
     * 获取应用配置
     **/
    public function index(){
        $info = AisConfig::getConfig($this->miniapp->id);
        if(!isset($info)) {
            return enjson(403,'应用未配置');
        }
        $writer = json_decode($info->writer);
        $config['service_telephone'] = $info->service_telephone ??'';
        $config['shore_img']         = $writer->shore_img ??'';
        $config['shore_text']        = $writer->shore_text ??'';
        $config['mch_text']          = $writer->mch_text ??'';
        $config['mch_qrcode']        = $writer->mch_qrcode ??'';
        $config['group_profit']      = $info->group_profit ??0;
        //未绑定手机
        $config['user_bindphone']    = "";
        //是否会员
        $config['vip']              = ['is_vip' => 0,'info' => []];;
        //判断用户是否商家
        $config['store']             = ['is_store' => 0,'info' => []];
        //判断是否圈主
        $config['group']             = [
            'is_group'     => 0,
            'join_num'     => 0,
            'order'        => 0,
            'count'        => 0,
            'help'         => 0,
            'group_member' => $info->group_member,
            'group_join'   => $info->group_join,
            'info'         => []
        ];
        $config['user_coupon_num']   = 0; //优惠券
        $config['user_order_num']    = 0; //买单数
        $config['user_save_money']   = 0; //已省钱
        $config['shop_order']        = 0; //优选订单数量
        if($this->user){
            //是否会员并返回会员信息
            $vip = AisVipUser::with(['vip' => function($query) {
                $query->field('id,name,is_auto_up,price,open_queue_reward,open_share_reward,open_store_num,open_vip_num,pay_queue_reward,pay_share_reward,price,rule');
            }])->where(['is_lock' => 0,'uid' => $this->user->id])->find();
            if(!empty($vip)){
                $config['vip']['is_vip'] = 1;
                $config['vip']['info']   = $vip->vip;
            }
            //统计订单
            $config['shop_order']        = AisShopOrder::where(['uid' =>$this->user->id,'paid_at' =>1,'status' => 0])->count(); //已支付未核销的订单
            $config['user_bindphone']    = $this->user->phone_uid ?? ''; //未绑定手机
            //优惠券
            $config['user_coupon_num']  = AisCouponUser::where(['member_miniapp_id' => $this->miniapp_id, 'is_end' => 0, 'uid' => $this->user->id])->count();
            //买单数
            $config['user_order_num']   = AisOrder::where(['member_miniapp_id' => $this->miniapp_id, 'state'  => 1, 'uid' => $this->user->id])->count();
            //已省钱
            $config['user_save_money']  = AisCouponUser::where(['member_miniapp_id' => $this->miniapp_id, 'is_end' => 1, 'uid' => $this->user->id])->where('money', '>', 0)->sum('money');
            $store = AisStore::manageStore($this->user->id);
            if ($store) {
                $config['store']['is_store'] = 1;
                $config['store']['info']     = $store->toArray();
                $group_ids = AisStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'type' => 0,'store_id' => $store->id])->column('group_id');
                //圈主加群数量
                $config['group']['join_num'] = AisStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'store_id' => $store->id,'type' => 0])->count();
                //买单
                $config['group']['order']    = AisStoreBill::where(['member_miniapp_id' => $this->miniapp_id])->whereIn('store_id',AisStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'type' => 0])->whereIn('group_id',$group_ids)->column('store_id'))->sum('money');
                //次数
                $config['group']['count']    = AisCouponUser::where(['member_miniapp_id' => $this->miniapp_id])->whereIn('store_id',AisStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'type' => 0])->whereIn('group_id',$group_ids)->column('store_id'))->count();
                //互助
                $help = 0;
                foreach ($group_ids as $group_id){
                    $help += AisCouponUser::where(['member_miniapp_id' => $this->miniapp_id,'is_end' => 1])->where('','EXP',Db::raw("FIND_IN_SET(".$group_id.",group_ids)"))->count();
                }
                $config['group']['help'] = $help;
            }
            $group = AisStoreGroup::where(['member_miniapp_id' => $this->miniapp_id,'uid' => $this->user->id])->find();
            if ($group) {
                $config['group']['is_group'] = 1;
                $config['group']['info']     = $group->toArray();
            }
       }
       return enjson(200,'应用配置',$config);
    }

    /**
     * 腾讯地图服务
     * @return void
     */
    public function lib(){
        $info = AisConfig::getConfig($this->miniapp->id);
        if(empty($info->qq_lbs_key)) {
            return enjson(403,'应用未配置QQLbs服务');
        }
        if(empty($this->lbs)){
            return enjson(204);
        }
        $http = new HttpRequest;
        $response = $http->get('https://apis.map.qq.com/ws/geocoder/v1/?location='.$this->lbs->lat.','.$this->lbs->lng.'&key='.$info->qq_lbs_key);
        $content = $response->json();
        if(empty($content)){
            return enjson(204,'位置请求失败');
        }
        if($content->status != 0){
            return enjson(403,$content->message);
        }
        return enjson(200,['address' => $content->result->formatted_addresses->recommend,'adcode' => $content->result->ad_info->adcode]);
    }

    /**
     * 上传图片
     * @return void
     */
    public function upImg(){
        $this->isUserAuth();
        if(request()->isPost()){
            $rel = Upload::index();
            if($rel['error'] == 0){
                return json(['code'=>200,'msg'=>'success','data' => $rel['url']]);
            }else{
                return json(['code'=>204,'msg'=>'error']);
            }
        }
    }
}