<?php
// +----------------------------------------------------------------------
// | [ WE CAN DO IT MORE SIMPLE  ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2020 rights reserved.
// +----------------------------------------------------------------------
// | Author: TABLE ME
// +----------------------------------------------------------------------
// | Date: 2020-08-25 17:23
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\api\controller;

use app\BaseController;

use app\model\api\User as UserModel;
use app\model\api\UserDetail as UserDetailModel;
use app\model\api\ServiceType as ServiceTypeModel;
use app\model\api\InfoAudit;
use app\model\api\TypeAudit;
use app\model\api\UserAudit;
use app\model\api\ServiceType;
use app\model\api\ServiceLabel as ServiceLabelModel;
use app\model\api\ServiceTimeType;
use app\model\api\City as CityModel;
use app\model\api\Sys as SysModel;
use app\model\api\ShowTemplate;
use app\model\api\ShowTemplateOrder;
use app\model\api\UserShowTemplate;
use app\model\api\UserWorkType;
use app\model\api\PayTrade as PayTradeModel;

use app\Request;
use library\services\UtilService;
use library\utils\QRcodeComm;
use library\utils\Qiniu;
use library\utils\IdentityCard;
use library\utils\WxpayV2 as wxpayApi;
use think\db\exception\DbException;
use library\lib\weixina;
use think\facade\Db;
use think\Image;
use think\Route;

class User extends BaseController
{
    
    /**
     * 获取用户详情
     * @param Request $request
     */
    public function userInfo(Request $request){
        //资料审核信息
        $infoAuditData = (new InfoAudit)->where("uid",$request->user["uid"])->order("id desc")->find();
        $userAuditData = (new UserAudit)->where("uid",$request->user["uid"])->order("id desc")->find();
        $typeAuditData = (new TypeAudit)->where("uid",$request->user["uid"])->order("id desc")->find();
        $data = [];
        $data['uid']               = $request->user['uid'];
        $data['nickname']          = $request->user['nickname'];
        $data['mobile']            = $request->user['mobile'];
        $data['avatar']            = $request->user['avatar'];
        $data['name']              = $request->user['name'];
        $data['sex']               = $request->user['sex'];
        $data['type']              = $request->user['type'];//用户类型
        $data['type_name']         = "";//用户类型名称
        $data['work_type_id']      = $request->user['work_type_id'];//用户职称类型
        $data['work_type_title']   = $request->user['work_type_title'];//用户职称类型名称
        $data['card_look_count']   = $request->user['card_look_count'];//用户名片浏览次数
        
        $data['info_audit_status'] = empty($infoAuditData)?-2:$infoAuditData["status"];
        $data['user_audit_status'] = empty($userAuditData)?-2:$userAuditData["status"];
        $data['type_audit_status'] = empty($typeAuditData)?-2:$typeAuditData["status"];
        
        
        //资料通过需要重新提交认证
        if(!empty($infoAuditData) && !empty($typeAuditData)){
            if($infoAuditData["status"]==1 && $typeAuditData["status"]==1 && $infoAuditData["admin_time"]>$typeAuditData["admin_time"]){
                $data['type_audit_status'] = -3;
            }
        }
        
        
        $data['show_template_code'] = "";
        $data['show_template_id']   = "";
        $tmpData = (new UserShowTemplate)
                ->field("t.id,t.code,t.title,t.is_init,b.is_default")
                ->alias("b")
                ->join("show_template t","t.id = b.show_template_id","left")
                ->where("b.uid",$request->user['uid'])
                ->order("b.is_default","desc")
                ->order("b.id","desc")
                ->find();
        if(!empty($tmpData)){
            $data['show_template_code']    = $tmpData["code"];
            $data['show_template_id']      = $tmpData["id"];
            $data['show_template_init']    = $tmpData["is_init"];
            $data['show_template_default'] = $tmpData["is_default"];
        }
        return app('json')->success($data);
    }
    
    /**
     * 获取用户子级列表
     * @param Request $request
     */
    public function getChildList(Request $request){
        $post = UtilService::getMore([
            ['page', 1],
            ['pageSize', 50],
        ], $request);
        $post["pageSize"]  = $post["pageSize"]>50 ? 50 : (int)$post["pageSize"];
        $post["page"]      = $post["page"]<=0     ? 1  : (int)$post["page"];
        $post["parent_uid"]= $request->user["uid"];
        $data = (new UserModel)->getDataList($post,"u.uid,u.mobile,u.nickname");
        return app('json')->success($data);
    }
    
    /**
     * 设置用户信息
     * @param Request $request
     */
    public function setUserInfo(Request $request){
        $post = UtilService::getMore([
            ['avatar',''],
            ['nickname',''],
            ['name',''],
//            ['mobile',''],
            ['sex', ''],
        ],$request);
        $save=[];
        if(!empty($post["avatar"])){
            $save["avatar"] = $post["avatar"];
        }
        if(!empty($post["nickname"])){
            $save["nickname"] = $post["nickname"];
        }
        if(!empty($post["name"])){
            $save["name"] = $post["name"];
        }
//        if(!empty($post["mobile"])){
//            if(is_mobile($post["mobile"])){
//                return app("json")->fail("请输入正确的手机号码"); 
//            }
//            $save["mobile"] = $post["mobile"];
//        }
        if(in_array((string)$post["sex"],["0","1","2"])){
            $save["sex"] = (int)$post["sex"];
        }
        if(empty($save)){
            return app("json")->fail("提交数据为空");
        }
        //是否需要审核
        $isInfoAudit = 0;
        if($isInfoAudit==0){
            $r = (new UserModel)->where("uid",$request->user["uid"])->update($save);
            if(!$r){
               return app("json")->fail("提交数据为空"); 
            }
        }else{
            $data = (new UserAudit)->where("uid",$request->user["uid"])->order("id desc")->find();
            if(!empty($data) && $data["status"]==0){
                return app('json')->fail("资料审核中,请勿重复提交");
            }
            $save["uid"] = $request->user["uid"];
            $save["status"] = 0; 
            $r = (new UserAudit)->insert($save);
            if(!$r){
               return app("json")->fail("提交数据为空"); 
            }
        }
        return app("json")->success("提交成功");
        
    }
    
    
    /**
     * 绑定手机号
     * @param Request $request
     */
    public function bindMobile(Request $request){
        [$code] = UtilService::getMore([
            ['code', '', 'empty', 'code参数错误'],
        ], $request, true);
        if(!empty($request->user['mobile'])){
            return app('json')->fail("当前账户已绑定过手机号码");
        }
        $weixinA = new weixina();
        $data=$weixinA->getPhoneNumber($code);//新版
        if(empty($data) || empty($data['purePhoneNumber'])) {
            return app('json')->fail("绑定失败，请重新绑定01".$weixinA->error);
        }
        $save=[
//            "countryCode"=>empty($data['countryCode'])?"":$data['countryCode'],
            "mobile"=>$data['purePhoneNumber'],
        ];
        $r = (new UserModel)->where('uid', $request->user['uid'])->update($save);
        if(!$r){
            return app('json')->fail("绑定失败，请重新绑定02");
        }
        $result                    = [];
        $result['nickname']        = $request->user['nickname'];
        $result['avatar']          = $request->user['avatar'];
        return app('json')->success($result);
    }
    
    /**
     * 获取名片信息
     * @param Request $request
     */
    public function getUserCardInfo(Request $request){
        $data = (new InfoAudit)->getItem(["uid"=>$request->user["uid"],"status"=>1]);
        if(empty($data)){
            return app('json')->fail("您还没有通过名片信息审核");
        }
        $typeData = (new TypeAudit)->where("uid",$request->user["uid"])->order("id","desc")->find();
        $data["is_type_audit"] = (empty($typeData) || $typeData["status"]!=1)?0:1;   
        return app('json')->success($data);
    }
    
    
    
    
    /**
     * 提交资料审核
     * @param Request $request
     */
    public function subInfoAudit(Request $request){
        $data = (new InfoAudit)->where("uid",$request->user["uid"])->order("id desc")->find();
        if(!empty($data) && $data["status"]==0){
            return app('json')->fail("资料审核中,请勿重复提交");
        }
        $post = UtilService::getMore([
            ['avatar',''],
            ['name','','empty','请输入真实姓名'],
            ['mobile','','is_moblie','请输入正确的手机号码'],
            ['idcard','','empty','请输入正确的身份证号码'],
            ['birthday',''],
            ['service_type',''],
            ['service_price',''],
            ['service_min_price',''],
            ['service_max_price',''],
            ['service_area',[]],
            ['service_project',[]],
            ['service_intro_content',''],
            ['service_intro_imgs',[]],
            ['service_audit_imgs',[]],//此处为我的证书
            ['service_imgs',[]],//我的服务照片
            
            ['work_year',''],
            ['ancestral_place',''],
            ['education',''],
            ['minority',''],
            
            ['user_work_type_id','0'],//服务职称
            ['service_label',[]],//服务标签
            
            
        ],$request);
        if(!IdentityCard::isValid($post["idcard"])){
            return app('json')->fail("请输入正确的身份证号码");
        }
        $save=[];
        $save["avatar"]   = empty($post["avatar"])  ? "" : $post["avatar"];
        $save["name"]     = empty($post["name"])    ? "" : $post["name"];
        $save["mobile"]   = empty($post["mobile"])  ? "" : $post["mobile"];
        $save["idcard"]   = empty($post["idcard"])  ? "" : $post["idcard"];
//        $save["birthday"] = empty($post["birthday"])? 0  : strtotime($post["birthday"]);
        
        $save["constellation"] = IdentityCard::get_starsign($post["idcard"]);//星座
        $save["twelve"]        = IdentityCard::get_zodiac($post["idcard"]);//星座
        $save["birthday"]      = strtotime(IdentityCard::get_birthday($post["idcard"]));
        
        //服务类型
        if(!empty($post["service_type"])){
            $timeTypeData = (new ServiceTimeType)->where("code",$post["service_type"])->where("status",1)->select();
            if(empty($timeTypeData)){
                return app('json')->fail("服务时长类型不存在");
            }
            $save["service_type"] = $post["service_type"];
        }
        //服务价格区间
//        $save["service_price"]     = empty($post["service_price"])     ? "" : $post["service_price"];
        $save["service_min_price"] = empty($post["service_min_price"]) ? 0 : $post["service_min_price"];
        $save["service_max_price"] = empty($post["service_max_price"]) ? 0 : $post["service_max_price"];
        //服务区域
        $cityModel = new CityModel();
        if(!empty($post["service_area"]) && is_array($post["service_area"])){
            $saveAre=[];
            foreach($post["service_area"] as $k=>$v){
                if(empty(trim($v))){
                    continue;
                }
                $itemData = $cityModel->where("name",trim($v))->where("level",2)->find();
                if(!empty($itemData)){
                    $saveAre[]=$itemData["id"];
                }
            }
            if(!empty($saveAre)){
                $save["service_area"] = implode(",", $saveAre);
            }
        }
        //服务内容
        $serviceTypeModel = new ServiceTypeModel();
        if(!empty($post["service_project"]) && is_array($post["service_project"])){
            $saveCon=[];
            foreach($post["service_project"] as $k=>$v){
                if(empty(trim($v))){
                    continue;
                }
                $itemData = $serviceTypeModel->where("id",(int)$v)->where("status",1)->find();
                if(!empty($itemData)){
                    $saveCon[]=$itemData["id"];
                }
            }
            if(!empty($saveCon)){
                $save["service_project"] = implode(",", $saveCon);
            }
        }
        //服务标签
        $save["service_label"]="";
        $labelData = (new ServiceLabelModel)->getColumnList("id","id",$post["service_label"]);
        if(!empty($labelData)){
            $save["service_label"] = implode(",", $labelData);
        }
        $save["service_intro_content"]  = empty($post["service_intro_content"])? "" : $post["service_intro_content"];
        $save["service_intro_imgs"]     = empty($post["service_intro_imgs"])   ? "" : implode(",", $post["service_intro_imgs"]);
        $save["service_audit_imgs"]     = empty($post["service_audit_imgs"])   ? "" : implode(",", $post["service_audit_imgs"]);
        $save["service_imgs"]           = empty($post["service_imgs"])         ? "" : implode(",", $post["service_imgs"]);//我的服务展示
        
        
        
        $save['work_year']       = empty($post["work_year"])      ? "": $post["work_year"];
        $save['ancestral_place'] = empty($post["ancestral_place"])? "": $post["ancestral_place"];
        $save['education']       = empty($post["education"])      ? "": $post["education"];
        $save['minority']        = empty($post["minority"])       ? "": $post["minority"];
        
        
        $save["status"] = 0;
        $save["time"]   = time();
        $save["uid"]    = $request->user["uid"];
        
        //服务职称
        $save["user_work_type_id"] = empty($post["user_work_type_id"]) ? 0: (int)$post["user_work_type_id"];
        if($save["user_work_type_id"]>0 && (new UserWorkType)->where("id",$post["user_work_type_id"])->where("status",1)->count()<=0){
            return app('json')->fail("当前类型不能选择");
        }
        
        
        $r = (new InfoAudit)->insertGetId($save);
        if(!$r){
            return app('json')->fail("系统错误");
        }
        $no = "CARD-".date("YmdHis")."-".$r;
        (new InfoAudit)->where("id",$r)->update(["no"=>$no]);
        return app('json')->success("提交成功,请耐心等待审核");
    }
    /**
     * 平台认证
     * @param Request $request
     */
    public function subTypeAudit(Request $request){
        $data = (new TypeAudit)->where("uid",$request->user["uid"])->order("id desc")->find();
        if(!empty($data) && $data["status"]==0){
            return app('json')->fail("平台审核中,请勿重复提交");
        }
        $post = UtilService::getMore([
            ['service_audit_imgs',[],"empty","请上传服务认证截图"],
        ],$request);
        $save=[];
        $save["service_audit_imgs"] = empty($post["service_audit_imgs"])   ?"": implode(",", $post["service_audit_imgs"]);
        $save["status"] = 0;
        $save["time"]   = time();
        $save["uid"]    = $request->user["uid"];
        if(empty($save["service_audit_imgs"])){
            return app('json')->fail("请上传服务认证截图");
        }
        
        $r = (new TypeAudit)->insertGetId($save);
        if(!$r){
            return app('json')->fail("系统错误");
        }
        $no = "CERT-".date("YmdHis")."-".$r;
        (new TypeAudit)->where("id",$r)->update(["no"=>$no]);
        return app('json')->success("提交成功,请耐心等待审核");
    }
    
    
    /**
     * 模板订单提交[第一步]
     * @param Request $request
     */
    public function subShowTemplateOrder(Request $request){
        [$id,$pay_type] = UtilService::getMore([
            ['id','','empty','参数错误'],
            ['pay_type','','empty','请选择支付方式'],
        ],$request,true);
        
        if(!in_array($pay_type,["wxpay","balance"])){
            return app('json')->fail('不支持该支付方式！');
        }
        
        $weixinConfig = (new SysModel)->getWeixinConfig();
//        if(empty($weixinConfig)){
//            return app('json')->fail('支付配置为空！');
//        }
        
        
        //缓存
        $redis = \think\facade\Cache::store('redis');
        $key   = 'show_template_order_sub_' . $request->user['uid'];
        $bool  = $redis->handler()->exists($key);
        if ($bool) {
            return app('json')->fail('请务重复操作，请稍等在重试！');
        }
        $redis->set($key,1,5);//5秒缓存
        $proData = (new ShowTemplate)->where("id",$id)->where("status",1)->find();
        if(empty($proData)){
            return app('json')->fail("当前模板已下架");
        }
        $proData = $proData->toArray();
        $count = (new UserShowTemplate)->where("uid",$request->user['uid'])->where("show_template_id",$id)->count();
        if($count>0){
            return app('json')->fail("您已购买过当前模板");
        }
        //验证
        $orderCount = (new ShowTemplateOrder)->where("uid",$request->user['uid'])->where("show_template_id",$id)->where("status",1)->count();
        if($orderCount>0){
            return app('json')->fail("您已下单该模板,请勿重复下单");
        }
        $price = floatval($proData["price"]);
//        if($price<0.01){
//            return app('json')->fail("模板信息错误");
//        }
        $allMoney    = $price;//订单商品费用
        $total_money = $allMoney;//订单总费用
        $payMoney    = $total_money;//订单需支付费用
        $payMoney    = $payMoney <= 0 ? 0 : $payMoney;
        $nowTime     = time();
        
        //余额支付验证
        if($pay_type=="balance" && $payMoney > $request->user["money"]){
            return app('json')->fail("当前余额不足");
        }

        //主订单数据
        $save=[];
        $save['uid']          = $request->user['uid'];
        $save['order_id']     =  makeOrderId($request->user['uid'],"ST");
        $save['pay_type']     = $pay_type;//
        $save['total_money']  = $total_money;//订单总金额
        $save['all_money']    = $allMoney;//商品中金额
        $save['pay_money']    = $payMoney;//实际支付金额
        $save['balance']      = 0;//余额支付了多少(目前不用)
        $save['status']       = $payMoney <= 0 ? 1 : 0;
        $save['pay_time']     = $payMoney <= 0 ? time() : 0;
        $save['time']         = $nowTime;
        
        $save['show_template_id']    = $proData["id"];
        $save['show_template_title'] = $proData["title"];;
        $save['show_template_price'] = $proData["price"];
        $save['show_template_img']   = empty($proData["imgs"]) ? "" : explode(",", $proData["imgs"])[0];
        $save['show_template_code']  = $proData["code"];
        //余额实时支付
        if($pay_type=="balance"){
            $save['status']       = 1;
            $save['pay_time']     = time();
        }
        try{
            Db::startTrans();
            $o_id = (new ShowTemplateOrder)->insertGetId($save);
            if(empty($o_id)){
                return app('json')->fail("订单提交失败");
            }
            //不需要支付
            if($payMoney<=0 && $save['status']==1){
                //验证并绑定当前模板
                (new UserShowTemplate)->userBindTemp($save["show_template_id"],$save['uid']);
                Db::commit();
                return app("json")->success(["order_id"=>$save['order_id'],"money"=>$payMoney,"status"=>$save['status']]);
            }
            //余额支付
            if($pay_type=="balance"){
                //验证并绑定当前模板
                (new UserShowTemplate)->userBindTemp($save["show_template_id"],$save['uid']);
                //修改用户余额
                $res = (new UserDetailModel)->balancePay($request->user["uid"],$payMoney,"show_temp_pay",["to_id"=>$o_id]);
                if(!$res){
                    Db::rollback();
                    return app('json')->fail("余额支付失败");
                }
                Db::commit();
                return app("json")->success(["order_id"=>$save['order_id'],"money"=>$payMoney,"status"=>$save['status']]);
            }
            //微信支付
            if(empty($request->user['openid'])){
                Db::rollback();
                return app('json')->fail('用户还未绑定微信！');
            }
            //清理之前支付凭证 || 防止重复购买
            $payTrade = (new PayTradeModel)
                    ->where("uid",$request->user["uid"])
                    ->where("o_id",$o_id)
                    ->where("type","temp")
                    ->where("status",0)
                    ->where("time","<",time() - 7*24*60*60)
                    ->select()
                    ->toArray();
            $wxpay = new wxpayApi();
//            $wxpay = new wxpayApi($weixinConfig);
            
            foreach ($payTrade as $v) {
//                if($v['pay_type'] == 'wxpay') {
//                    $result = $wxpay->closeOrder($v['pay_no']);
//                }
                (new PayTradeModel)->where("id",$v['id'])->where("status",0)->delete();
            }
            $mtime = microtime(true)*10000;
            $payOn = "T".date("Ymd").$mtime .rand(100,999) . $request->user['uid'];
            $out_trade_no="";
            $payType  = $save["pay_type"];
            //添加交易记录
            $trade = [
                'uid'      => $request->user['uid'],
                'o_id'     => $o_id,
                'order_id' =>$save["order_id"],
                'pay_no'   => $payOn,
                'out_trade_no' => empty($out_trade_no) ? $payOn : $out_trade_no,
                'pay_type' => $payType,
                'money'    => $payMoney,
                'type'     => 'temp',
                'd_json'   => serialize(['orderId'=>$save["order_id"],"give_score"=>0]),
                'time'     => time(),
                'status'   => 0,
            ];
            $r=(new PayTradeModel)->insert($trade);
            if(!$r){
                Db::rollback();
                return app('json')->fail('支付信息获取失败！');
            }
            $clictip = get_client_ip();
            if(empty($clictip)){
                $clictip = $request->ip();
            }
            $payData =  $wxpay->wxmpPay([
                'body'            => "微信小程序购买模板",
                'out_trade_no'    => $payOn,
                'total'           => $payMoney,
                'openid'          => $request->user['openid'],
                'payer_client_ip' => $clictip,
            ]);
            if(empty($payData)){
                Db::rollback();
                return app('json')->fail($wxpay->errorMsg);
            }
            Db::commit();
            $redis->delete($key);
            return app('json')->success([
                'jsApiParameters'=> $payData,
                'pay_no'         => $payOn,
                'order_id'       => $save["order_id"],
                "status"         => $save['status'],
                "money"          => $payMoney,
            ]);
        } catch (DbException $db){
            Db::rollback();
            return app('json')->fail("订单生成失败");
        }
    }
    /**
     * 获取模板购买订单详情
     * @param Request $request
     */
    public function payShowTemplateOrderInfo(Request $request){
        [$order_id] = UtilService::getMore([
            ['order_id','','empty','参数错误'],
        ],$request,true);
        $data = (new ShowTemplateOrder)
                ->field("order_id,total_money,all_money,pay_money,status,time")
                ->where("order_id",$order_id)
                ->where("uid",$request->user["uid"])
                ->find();
        if(empty($data)){
            return app('json')->fail('信息不存在！');
        }
        $data=$data->toArray();
        if($data["status"]==0 && $data["time"]<time() - 30*60){
            (new ShowTemplateOrder)->where("id",$data["id"])->where("uid",$request->user["uid"])->update(["status"=>-1]);
            $data["status"]==-1;
        }
        $data["time"] = date("Y-m-d H:i:s",$data["time"]);
        return app('json')->success($data);
    }
    
    
    /**
     * 用户模板列表
     * @param Request $request
     */
    public function userShowTemplateList(Request $request){
        $post = UtilService::getMore([
            ['page', 1],
            ['pageSize', 50],
        ], $request);
        $post["pageSize"] = $post["pageSize"]>50 ? 50 : (int)$post["pageSize"];
        $post["page"]     = $post["page"]<=0 ? 1 : (int)$post["page"];
        $where=[];
        $where[]=["ut.uid","=",$request->user["uid"]];
        $totalCount = (new UserShowTemplate)->alias("ut")->where($where)->count();
        $data=null;
        if($totalCount>0){
            $data = (new UserShowTemplate)
                ->field("ut.id,t.id as show_template_id,t.title,t.price,t.old_price,t.status,t.imgs,t.is_hot,t.is_recommend,t.code,look_count,t.real_sales,t.unreal_sales,ut.is_default")
                ->alias("ut")
                ->join("show_template t", "t.id = ut.show_template_id","left")
                ->where($where)
                ->order("ut.is_default", "desc")
                ->order("ut.id", "desc")
                ->page($post["page"], $post["pageSize"])
                ->select();
            foreach($data as $k=>$v){
                $data[$k]["is_use"]      = 1;//是否已经购买或者可以使用
                $data[$k]["imgs"]        = getImageAr($v["imgs"]);
                $data[$k]["img"]         = empty($data[$k]["imgs"]) ? "" : $data[$k]["imgs"][0];
                $data[$k]["sales_count"] = $data[$k]["real_sales"] + $data[$k]["unreal_sales"];
                unset($data[$k]["real_sales"]);
                unset($data[$k]["unreal_sales"]);
            }
        }
        $data = empty($data)?[]:$data;
        return app('json')->success(["list" => $data, "pageSize" => $post["pageSize"],"page"=>$post["page"],"totalCount"=>$totalCount]);
    }
    /**
     * 设置默认模板
     * @param Request $request
     */
    public function setShowTemplate(Request $request){
        [$show_template_id] = UtilService::getMore([
            ['show_template_id','','empty','参数错误'],
        ],$request,true);
        (new UserShowTemplate)->where("uid",$request->user["uid"])->where("is_default",0)->update(["is_default"=>0]);
        (new UserShowTemplate)->where("uid",$request->user["uid"])->where("show_template_id",$show_template_id)->update(["is_default"=>1]);
        return app('json')->success("设置成功");
    }
    
    
    /**
     * 获取邀请海报小程序码
     * @param Request $request
     */
    public function getWxmpInviteQrcode(Request $request){
        $weixinA = new weixina();
        $data = $weixinA->getUnlimitedQRCode("pages/index/index","scene=".$request->user["uid"]);
//        var_dump($data);
        if(empty($data)){
            return app('json')->fail("小程序码获取失败".$weixinA->error);
        }
        $base64 = 'data:'.$data['contentType'].';base64,'.base64_encode($data['buffer']);
        $res = $this->uploadImageBase64("wximg",$base64,1);
        if($res["code"]!=1){
            return app('json')->fail($res["msg"]);
        }
        $inviteData = (new SysModel)->getDataInfo("invite");
        $bgimg = $inviteData["img"];
        return app('json')->success(["qrcode"=>$res["url"],"bgimg"=>$bgimg]);
    }
    
    
    public function createImg($bg,$qrcode){
        $bgSize = getimagesize($bg);
        $qrcodeSize = getimagesize($qrcode);
        $handle = Image::open($bg);
       
        $handle->water($qrcode);
        $handle->save($savePath);
    }
    
    /**
     * 获取小程序码
     * @param Request $request
     */
    public function getWxmpQrcode(Request $request){
        $weixinA = new weixina();
        $data = $weixinA->getUnlimitedQRCode("pages/index/index","a=1");
        if(empty($data)){
            return app('json')->fail("小程序码获取失败".$weixinA->error);
        }
        $base64 = 'data:'.$data['contentType'].';base64,'.base64_encode($data['buffer']);
        $res = $this->uploadImageBase64("wximg",$base64);
        if($res["code"]!=1){
            return app('json')->fail($res["msg"]);
        }
        return app('json')->success(["img"=>$res["data"]]);
    }
    
    /**
     * 
     * @param Request $request
     */
    public function uploadBase64(Request $request){
        [$img,$code] = UtilService::getMore([
            ['img', '','empty',"请上传图片"],
            ['code', 'image'],
        ], $request,true);
//        $imgAr = explode("base64,",$img);
//        if(empty($imgAr)){
//            return app("json")->fail("请上传base64图片");
//        }
//        $imgBase64 = count($imgAr)==1?$imgAr[0]:$imgAr[1];
//        //判断字符串是否经过编码方法 
//        if($imgBase64!=base64_encode(base64_decode($imgBase64))){
//            return app("json")->fail("请上传base64图片");
//        }
//        $base64 = "data:application/octet-stream;base64,".$imgBase64;//七牛
        $res = $this->uploadImageBase64($code,$img);
        if($res["code"]!=1){
            return app('json')->fail($res["msg"]);
        }
        return app('json')->success(["img"=>$res["data"]]);
        
        
    }
    
    

    
    
    /**
     * 图片上传
     * @param Request $request
     * @return type
     */
    public function upload(Request $request){
        $uploadConfig = config('filesystem');
        $sysData = (new SysModel())->where("id",1)->find();
        $file = $request->file('file');
        $code = $request->post("code","image");
        if(empty($file)) {
            return app('json')->fail("未上传文件");
        }
        $size = $file->getSize();
        if(!empty($size) && $size>$uploadConfig["image"]["size"]*1024*1024){
            return app('json')->fail("图片不能超过{$uploadConfig["image"]["size"]}M");
        }
        
        if(!in_array($code, $uploadConfig['image']['path'])){
            return app('json')->fail("上传路径错误");
        }
        $ext = $file->extension();
        if(!in_array($ext, $uploadConfig['image']['ext'])){
            return app('json')->fail("图片类型错误");
        }
        $upPath = \think\facade\Filesystem::disk('resource')->putFile( $code, $file);
        if(!$upPath){
            return app('json')->fail("上传失败01");
        }
        $savePath = $sysData['system_url'].'/resource/' . $upPath;
        $imgUrl = str_replace("\\", "/", $savePath);
        return app('json')->success(['img'=>$imgUrl,'size'=>$size]);
    }
    
    /**
     * 视频上传
     * @param Request $request
     * @return type
     */
    public function uploadVideo(Request $request){
        $uploadConfig = config('filesystem');
        $sysData = (new SysModel())->where("id",1)->find();
        $file = $request->file('file');
        $code = $request->post("code","video");
        if(empty($file)) {
            return app('json')->fail("未上传文件");
        }
        if(!in_array($code, $uploadConfig['video']['path'])){
            return app('json')->fail("上传路径错误");
        }
        $ext = $file->extension();
        if(!in_array($ext, $uploadConfig['video']['ext'])){
            return app('json')->fail("视频类型错误");
        }
        $upPath = \think\facade\Filesystem::disk('resource')->putFile( $code, $file);
        if(!$upPath){
            return app('json')->fail("上传失败01");
        }
        $savePath = $sysData['system_url'].'/resource/' . $upPath;
        $imgUrl = str_replace("\\", "/", $savePath);
        return app('json')->success(['video'=>$imgUrl]);
    }
    
    /**
     * base64文件上传
     * @param type $code
     * @param type $base64
     */
    public function uploadImageBase64($code,$base64,$isQiniu=0){
        $sysData = (new SysModel())->where("id",1)->find();
        $uploadConfig = config('filesystem');
        //验证base64格式
        preg_match('/^(data:\s*image\/(\w+);base64,)/',$base64, $result);
        if(!$result){
            return ["code"=>-1,"msg"=>"base64格式格式错误"];
        }
        //验证图片后缀
        if (!in_array($result[2], $uploadConfig['image']['ext'], true)) {
            return ["code"=>-1,"msg"=>"不支持的图片格式"];
        }
        $rootPath = config('filesystem.disks.resource.root');
        $hashName = $code.DIRECTORY_SEPARATOR.date('Ymd') . DIRECTORY_SEPARATOR . md5((string) microtime(true)).".".$result[2];
        $filePath = $rootPath. DIRECTORY_SEPARATOR .$hashName;
        $path = dirname($filePath);
        // 检测目录
        if (!is_dir($path)) {
            if (!mkdir($path, 0777, true)) {
                return ["code"=>-1,"msg"=>"生成目录失败"];
            }
            return ["code"=>-1,"msg"=>"上传目录不存在"];
        }
        
        
        //重名文件验证
        if (is_file($filePath)) {
            return ["code"=>-1,"msg"=>"文件已存在"];
        }
        if(!file_put_contents($filePath, base64_decode(str_replace($result[1], '', $base64)))){
            return ["code"=>-1,"msg"=>"文件报错失败"];
        }
        //七牛上传
        if($isQiniu==1){
            $qiniu   = new  Qiniu;
            $img_url = $qiniu->updateFile('img', $filePath, $filePath);
            if (empty($img_url['url'])) {
                return ["code"=>-1,"msg"=>"文件报错失败:".$qiniu->getError()];
            }
            @unlink($filePath);
            return ["code"=>1,"url"=>str_replace("\\", "/", $img_url['url'])];
        }
        
        
        $savePath = $sysData['system_url'].config('filesystem.disks.resource.url').DIRECTORY_SEPARATOR.$hashName;
        return ["code"=>1,"url"=>str_replace("\\", "/", $savePath)];
    }
    

    
    /**
     * 七牛上传图片
     * @param Request $request
     */
    public function qiniuUpload(Request $request)
    {
        $file = $request->file('file');
        if (empty($file)) {
            return app('json')->fail("未上传文件");
        }
        $rootTmp    = config('filesystem.disks.local.root') . '/' . \think\facade\Filesystem::putFile('tmp', $file);
        $image_size = @getimagesize($rootTmp);
        if ($image_size[0] > 1000) {
            $imgS = Image::open($rootTmp);
            $imgS->thumb(1000, $image_size[1]);
            $imgS->save($rootTmp);
        } else {
            if ($image_size[1] > 1000) {
                $imgS = Image::open($rootTmp);
                $imgS->thumb($image_size[0], 1000);
                $imgS->save($rootTmp);
            }
        }
        $qiniu   = new  Qiniu;
        $img_url = $qiniu->updateFile('img', $rootTmp, $rootTmp);
        if (empty($img_url['url'])) {
            return app('json')->fail($qiniu->getError());
        }
        @unlink($rootTmp);
        return app('json')->success(['img' => $img_url['url']]);
    }
    
    /**
     * 七牛上传token
     * @param Request $request
     */
    public function qiniuUploadToken(Request $request){
        [$bucket] = UtilService::getMore([
            ['bucket', ''],
        ], $request,true);
        $qiniu   = new  Qiniu;
        $token = $qiniu->createUploadToken($bucket);
        return app('json')->success(['token' => $token]);
    }
    
    
    
   
    
    
}
