<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\Amount;
use App\Models\Apply;
use App\Models\DwbsUser;
use App\Models\DwbsWarea;
use App\Models\Order;
use App\Models\Store;
use App\Handlers\SignHandler;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class StoreController extends Controller
{
    //获取数据信息
    public function getDataInfo(){
        $admin_id=Auth::user()->id;
        $admin=Admin::where('id',$admin_id)->first();
        $lists=[];
        if($admin && in_array($admin->role_id,[22,24])){//超级管理员
//            $agent_ids=DwbsUser::where('status',0)->where('cert_status',6)->whereNull('deleted_at')->where('service_status',0)->pluck('id');
            $apply=Store::query()->groupBy('is_apply')->select(DB::raw('count(id) as num'),'is_apply')->pluck('num','is_apply');//->whereIn('user_id',$agent_ids)
        }else{
            $agent_ids=DwbsUser::whereHas('warea',function($query)use($admin_id){
                $query->where('admin_id',$admin_id);
            })->where('status',0)->where('cert_status',6)->whereNull('deleted_at')->where('service_status',0)->pluck('id');
            $apply=Store::whereIn('user_id',$agent_ids)->groupBy('is_apply')->select(DB::raw('count(id) as num'),'is_apply')->pluck('num','is_apply');
        }
        $lists['no_cert']=isset($apply[0])?$apply[0]:0;
        $lists['authing']=isset($apply[1])?$apply[1]:0;
        $lists['wait_sign']=isset($apply[2])?$apply[2]:0;
        $lists['finish']=isset($apply[3])?$apply[3]:0;
        $lists['rejected']=isset($apply[4])?$apply[4]:0;
        $lists['frozen']=isset($apply[5])?$apply[5]:0;
        $lists['delete']=Store::onlyTrashed()->where('is_failure',0)->count();
        return $this->success($lists);
    }
    //获取所有门店
    public function list(Request $request){
        $page_size=$request->input('page_size');
        $page_index=$request->input('page_index');
        $num=$page_size*($page_index-1);
        $admin_id=Auth::user()->id;
        $admin=Admin::where('id',$admin_id)->first();
        if($admin && in_array($admin->role_id,[22,24])){//超级管理员
            $agent_ids=DwbsUser::where('status',0)->where('cert_status',6)->whereNull('deleted_at')->where('service_status',0)->pluck('id');
            $total=count($agent_ids);//所有可开通店铺人数
//            DB::connection()->enableQueryLog();
            $data=Store::where('is_failure',0);
        }else{
            Log::Info('客服id:'.$admin_id);
            $warea_ids=DwbsWarea::where('admin_id',$admin_id)->pluck('id');
            Log::Info('战区id:'.$warea_ids);
//            if($request->has('is_delete') && $request->input('is_delete')==1){
                $agent_ids=DwbsUser::withTrashed()->where('status',0)->whereIn('cert_status',[3,6])->where('service_status',0)->whereIn('warea_id',$warea_ids)->pluck('id');
//            }else{
//                $agent_ids=DwbsUser::where('status',0)->whereIn('cert_status',[3,6])->whereNull('deleted_at')->where('service_status',0)->whereIn('warea_id',$warea_ids)->pluck('id');
//            }
            $total=count($agent_ids);//客服可开通店铺人数
            $store_ids=Store::withTrashed()->where('is_failure',0)->whereIn('user_id',$agent_ids)->pluck('id');
            $data=Store::where('is_failure',0)->whereIn('id',$store_ids);
        }
        $data->with(['user' => function($query){
            $query->with(['warea:id,admin_name',])->select('id','nickname','deleted_at');
        }]);
        $nums=$data->count();

        $lists['num']=$nums;
        $lists['total']=$total;

//        var_dump(DB::getQueryLog());
        //审核状态筛选
        if($request->has('is_apply') && $request->input('is_apply') <> 'all'){
            $data->where('is_apply',$request->input('is_apply'));
        }
        if($request->has('is_delete') && $request->input('is_delete')==1){
            $data->onlyTrashed()->where('is_failure',0);
        }
        //筛选
        if($request->has('search_name') && $request->input('search_name')) {
            if(preg_match("/^[0-9]*$/",$request->input('search_name')) &&  strlen($request->input('search_name'))<4){
                return $this->error('450001','数字搜索不能少于4个字符');
            }
            $data->where(function ($query) use ($request) {
                $query->where('name', 'like', '%' . $request->input('search_name') . '%')
                    ->orWhere('phone', 'like', '%' . $request->input('search_name') . '%');
            });
        }else{
            if(!$admin || !in_array($admin->role_id,[22,24])) {//超级管理员
                $lists['list']=[];
                return $this->success_list($lists,'成功',0);
            }
        }
        $count=$data->count();
        $data->select('id','name','img','user_id','created_at','status','is_apply','created_at',
            'phone','star','province','city','area','address','username','deleted_at','is_failure');
        $list=$data->orderBy('id','desc')->skip($num)->take($page_size)->get();

//        foreach($list as $key=>$val){
//            $second=mt_rand(2880,7200);
//            $list[$key]->phone='';
//        }
        $lists['list']=$list;
        return $this->success_list($lists,'成功',$count);
    }

    public function export(Request $request){
        return $this->success([]);
    }
    //获取所有用户
    public function getAllUser(Request $request){
        $page_size=$request->input('page_size');
        $page_index=$request->input('page_index');
        $store_id=$request->input('store_id');
        $num=$page_size*($page_index-1);

        $data=Order::leftJoin('user as u','u.id','=','order.user_id')->where('order.store_id',$store_id)
            ->where('order.is_pay',1)->whereIn('order.apply_cancel',[0,1,3])->whereIn('order.is_refund',[0,1])
            ->groupBy('order.user_id')->select('u.nickname','u.phone','u.avatar',DB::raw('sum(order.total) as total'),DB::raw('sum(order.account) as account'));

//        $data=User::with('store:id,name')->where('store_id',$store_id)
//            ->select('id','nickname','name','phone','avatar','status','store_id');
        if($request->has('search_name') && $request->input('search_name')){
            $data->where(function($query)use($request){
                $query->where('u.phone',$request->input('search_name'))
                    ->orWhere('u.nickname','like','%'.$request->input('search_name').'%');
            });
        }
//        if($store_id){
//            $data->where('store_id',$store_id);
//        }
        $count=$data->get()->count();
        $list=$data->orderByDesc('total')->orderByDesc('account')->OrderBy('u.id')->skip($num)->take($page_size)->get();
        return $this->success_list($list,'成功',$count);
    }

    //店铺禁用
    public function disabled(Request $request){
        $admin_id=Auth::user()->id;
        $admin=Admin::where('id',$admin_id)->first();
        $id=$request->input('id');
        $remark=$request->input('remark');
        $store=Store::where('id',$id)->first();
        $store->status=$store->status ? 0 : 1;
        $store->remark .= '|'.$admin->name.'-'.date("Y-m-d H:i:s").'禁用店铺，原因：'.$remark;
        $res=$store->save();
        if($res){
            return $this->success([]);
        }else{
            return $this->error();
        }
    }
    //删除店铺
    public function deleteStore(Request $request)
    {
        $admin_id=Auth::user()->id;
        $admin=Admin::where('id',$admin_id)->first();
        $id=$request->input('id');
        $remark=$request->input('remark');
        try{
            DB::beginTransaction();
            $store=Store::where('id',$id)->first();
            $store->remark .= '|'.$admin->name.'-'.date("Y-m-d H:i:s").'删除店铺，原因：'.$remark;
            $store->save();

            Store::where('id',$id)->delete();
            DB::commit();
            return $this->success([]);
        }catch(Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }
    }
    //恢复店铺删除
    public function resDelStore(Request $request)
    {
        $admin_id=Auth::user()->id;
        $admin=Admin::where('id',$admin_id)->first();
        $id=$request->input('id');
        try{
            DB::beginTransaction();
            Store::withTrashed()->where('is_failure',0)->where('id',$id)->restore();
            $store=Store::where('id',$id)->first();
            $store->remark .= '|'.$admin->name.'-'.date("Y-m-d H:i:s").'恢复店铺删除';
            $store->save();
            DB::commit();
            return $this->success([]);
        }catch(Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }
    }
    //重开店铺
    public function newStore(Request $request)
    {
        $admin_id=Auth::user()->id;
        $admin=Admin::where('id',$admin_id)->first();
        $id=$request->input('id');
        try{
            DB::beginTransaction();
            $store=Store::onlyTrashed()->where('id',$id)->first();
            $store->is_failure = 1;
            $store->save();
            $user=DwbsUser::where('id',$store->user_id)->first();
            Store::create([
                'img'=>$user->headimgurl,
                'name'=>$user->nickname,
                'user_id'=>$user->id,
                'phone'=>$user->mobile,
                'remark'=>$admin->name.'-'.date("Y-m-d H:i:s").'重开店铺'
            ]);
            DB::commit();
            return $this->success([]);
        }catch(Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }
    }
    //查询进件状态
    public function query(Request $request){
        return $this->success([]);
        $store_id=$request->input('id');
        $store=Store::withTrashed()->where('is_failure',0)->where('id',$store_id)->first();
        $applyment_id=$store->applyment_id??$request->input('applyment_id');//申请编号
        if(empty($applyment_id)){
            Log::info($store->name.'未提交认证');
            return $this->success([]);
        }
        $handle=new SignHandler();
        $url='https://api.mch.weixin.qq.com/v3/ecommerce/applyments/'.$applyment_id;//查询地址
        $merchant_id=config('wechat.payment.default.mch_id');//商户号
        $serial_no=config('wechat.payment.default.serial_no');//不是平台证书序列号
        $mch_private_key=$handle->getPublicKey();//读取商户api证书公钥 getPublicKey()获取方法 见下文
        $timestamp=time();//时间戳
        $nonce=$handle->nonce_str();//随机字符串
        $body="";
        $sign=$handle->sign($url,'GET',$timestamp,$nonce,$body,$mch_private_key,$merchant_id,$serial_no);//签名
        $header=[
            'Authorization:WECHATPAY2-SHA256-RSA2048 ' . $sign,
            'Accept:application/json',
            'User-Agent:' . $merchant_id,
            'Content-Type:application/json',
            'Wechatpay-Serial:' . $handle->getzhengshu()//获取平台证书序列号
        ];
        $result=$handle->curl($url,'',$header,'GET');
        $result=json_decode($result,true);
        $apply=Apply::where('store_id',$store->id)->where('applyment_id',$applyment_id)->OrderBy('id','desc')->first();
        if($result['applyment_state']=="ACCOUNT_NEED_VERIFY"){
            Apply::where('id',$apply->id)->update(['audit_detail'=>$result['legal_validation_url']]);
        }
        if($result['applyment_state']=="NEED_SIGN"){
            Store::withTrashed()->where('is_failure',0)->where('id',$store_id)->update(['sub_mchid'=>$result['sub_mchid'],'is_apply'=>2]);
            Apply::where('id',$apply->id)->update(['sub_mchid'=>$result['sub_mchid'], 'audit_detail'=>$result['sign_url']]);
        }
        if($result['applyment_state']=="FINISH" && $store->is_apply != 3){
            Store::withTrashed()->where('is_failure',0)->where('id',$store_id)->update(['sub_mchid'=>$result['sub_mchid'],'is_apply'=>3]);//'is_cert'=>1,
            Apply::where('id',$apply->id)->update(['sub_mchid'=>$result['sub_mchid']]);
        }
        if($result['applyment_state']=="REJECTED"){//已驳回
            Store::withTrashed()->where('is_failure',0)->where('id',$store_id)->update(['is_apply'=>4]);
            Apply::where('id',$apply->id)->update(['audit_detail'=>$result['audit_detail'][0]['reject_reason']]);
        }
        if($result['applyment_state']=="FROZEN"){
            Store::withTrashed()->where('is_failure',0)->where('id',$store_id)->update(['is_apply'=>5]);//已冻结
            Apply::where('id',$apply->id)->update(['audit_detail'=>$result['audit_detail'][0]['reject_reason']]);
        }
        if($apply->applyment_state != $result['applyment_state'] && $apply->applyment_state_desc != $result['applyment_state_desc']){
            Apply::where('id',$apply->id)->update(['applyment_state'=>$result['applyment_state'],'applyment_state_desc'=>$result['applyment_state_desc']]);
        }
        return $this->success($result);
//        $result['applyment_state']=="FINISH"; //完成签约  其它状态：CHECKING：资料校验中   ACCOUNT_NEED_VERIFY：待账户验   AUDITING：审核中   REJECTED：已驳回   NEED_SIGN：待签约  FINISH：完成 FROZEN：已冻结
    }
    //获取账户实时余额
    public function getAccountInfo(Request $request){
        return $this->success([]);
        $handle=new SignHandler();
        $id=$request->input('id');
        $sub_mchid=Store::withTrashed()->where('is_failure',0)->where('id',$id)->value('sub_mchid');
//        return $sub_mchid;
        $url='https://api.mch.weixin.qq.com/v3/ecommerce/fund/balance/'.$sub_mchid;//查询地址
        $merchant_id=config('wechat.payment.default.mch_id');//商户号
        $serial_no=config('wechat.payment.default.serial_no');//不是平台证书序列号
        $mch_private_key=$handle->getPublicKey();//读取商户api证书公钥 getPublicKey()获取方法 见下文
        $timestamp=time();//时间戳
        $nonce=$handle->nonce_str();//随机字符串
        $body="";
        $sign=$handle->sign($url,'GET',$timestamp,$nonce,$body,$mch_private_key,$merchant_id,$serial_no);//签名
        $header=[
            'Authorization:WECHATPAY2-SHA256-RSA2048 ' . $sign,
            'Accept:application/json',
            'User-Agent:' . $merchant_id,
            'Content-Type:application/json',
            'Wechatpay-Serial:' . $handle->getzhengshu()//获取平台证书序列号
        ];
        $result=$handle->curl($url,'',$header,'GET');
        $result=json_decode($result,true);
        if($result['sub_mchid']){
            Store::withTrashed()->where('is_failure',0)->where('sub_mchid',$result['sub_mchid'])
                ->update([
                    'available_amount'=>round($result['available_amount']/100,2),
                    'pending_amount'=>round($result['pending_amount']/100,2)
                ]);
        }
        return $this->success($result);
    }
    //获取收款记录
    public function getAccountDetail(Request $request){
        $id=$request->input('id');
        $type=$request->input('type');
        $cycle=$request->input('cycle');
        $page_size=$request->input('page_size');
        $page_index=$request->input('page_index');
        $num=$page_size*($page_index-1);
        $data= Amount::where('store_id',$id)->where('type',$type);
        switch($cycle){
            case 'year':
                $data->whereYear('created_at',date("Y"));
                break;
            case 'today':
                $data->whereDate('created_at',date("Y_m-d"));
                break;
            case 'week':
                $data->whereBetween('created_at',[date("Y-m-d",strtotime("-7 day")),date("Y-m-d 23:59:59")]);
                break;
            case 'month':
                $data->whereBetween('created_at',[date("Y-m-01"),date("Y-m-d  23:59:59")]);
                break;
            case 'quarter':
                $start=(ceil(date("m")/3)-1)*3+1;
                $data->whereBetween('created_at',[date("Y-".$start."-01"),date("Y-m-d  23:59:59")]);
                break;
            case 'all':
                $data->query();
                break;
            default :
                $start_at=$request->input('start_at');
                $end_at=$request->input('end_at');
                $data->whereBetween('created_at',[$start_at,$end_at]);
        }

        if($type==3){
            $data_clone= clone $data;
            $ll['account']=$data_clone->where('status',1)->where('status_code','SUCCESS')->sum('money');
        }else{
            $ll['account']=$data->sum('money');
        }
//        $data->where(function($query){
//            $query->where('status',1)->orWhere(function($q){
//                $q->where('status',0)->where('status_code','!=','SUCCESS');
//            });
//        });
        $count=$data->count();
        $ll['list']=$data->OrderByDesc('id')->skip($num)->take($page_size)->get();
        return $this->success_list($ll,'',$count);
    }

    public function getAccountDetailAll(Request $request){
        $id=$request->input('id');
//        $type=$request->input('type');
        $cycle=$request->input('cycle');
        $page_size=$request->input('page_size');
        $page_index=$request->input('page_index');
        $num=$page_size*($page_index-1);
        $data= Amount::where('store_id',$id);
        switch($cycle){
            case 'year':
                $data->whereYear('created_at',date("Y"));
                break;
            case 'today':
                $data->whereDate('created_at',date("Y_m-d"));
                break;
            case 'week':
                $data->whereBetween('created_at',[date("Y-m-d",strtotime("-7 day")),date("Y-m-d 23:59:59")]);
                break;
            case 'month':
                $data->whereBetween('created_at',[date("Y-m-01"),date("Y-m-d  23:59:59")]);
                break;
            case 'quarter':
                $start=(ceil(date("m")/3)-1)*3+1;
                $data->whereBetween('created_at',[date("Y-".$start."-01"),date("Y-m-d  23:59:59")]);
                break;
            case 'all':
                $data->query();
                break;
            default :
                $start_at=$request->input('start_at');
                $end_at=$request->input('end_at');
                $data->whereBetween('created_at',[$start_at,$end_at]);
        }
        $count=$data->count();
        $ll['list']=$data->OrderByDesc('id')->skip($num)->take($page_size)->get();
        return $this->success_list($ll,'',$count);
    }
}
