<?php
/**
 * @package merchant
 *
 * @author xaboy
 * @day 2020/5/30
 *
 * 
 */

namespace app\common\repositories\store\order;


use app\common\dao\store\order\AgentOrderDao;
use app\common\model\user\UserBill;
use app\common\repositories\BaseRepository;
use app\common\repositories\user\UserBillRepository;
use app\controller\api\store\order\AgentOrder;
use app\controller\api\user\User;
use think\Exception;
use think\exception\ValidateException;
use app\controller\api\user\Im;
use think\facade\Db;
use Alipay\AopClient;
use Alipay\request\AlipayTradeAppPayRequest;
/**
 * @author cabbage
 * @day 2020/11/10
 * @mixin AgentOrderDao
 */
class AgentOrderRepository extends BaseRepository
{
    /**
     * StoreCartRepository constructor.
     * @param AgentOrderDao $dao
     */
    public function __construct(AgentOrderDao $dao)
    {
        $this->dao = $dao;
    }

    /*创建订单*/
    public function createOrder($uid,$type){
        $data = Db::name("user_agent")->where(['user_id'=>$uid,'status'=>1,'pay_status'=>[0,2]])->find();
        if(!$data){
            return ['code'=>400,'msg'=>'异常操作'];
        }

        try{
            $agent_order = [
                'type'=>$type,
                'price'=>$data['price'],
                'link_id'=>$data['id'],
                'identity'=>$data['identity'],
                'uid'=>$uid,
                'order_sn'=>$this->getNewOrderId("DL"),
                'create_time'=>date('Y-m-d H:i:s'),
            ];

            //创建支付记录
            $agentOrderDetail =  Db::name("agent_order")->where(['uid'=>$uid,'link_id'=>$data['id'],'status'=>[0,2]])->find();

            if(!$agentOrderDetail){
                $agentOrder = Db::name("agent_order")->insertGetId($agent_order);
            }else{
                $save = Db::name("agent_order")->where(['agent_order_id'=>$agentOrderDetail['agent_order_id']])->update($agent_order);
                if(!$save){ throw new ValidateException("支付失败");}
                $agentOrder = $agentOrderDetail['agent_order_id'];
            }
            if(!$agentOrder){
                throw new ValidateException("支付失败");
            }
            //余额支付
            if($type ==1){
                $result =   $this->orderPay($agent_order, $agentOrder);
            }elseif($type == 2){
                $result =   $this->payAlipay($uid,$agent_order);
            }
            return $result;
        }catch (\Exception $e) {
            throw new ValidateException($e->getMessage());
        }
    }

    /**
     * @return string
     * @author cabbage
     */
    public function getNewOrderId($string)
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = number_format((floatval($msec) + floatval($sec)) * 1000, 0, '', '');
        $orderId = $string . $msectime . mt_rand(10000, max(intval($msec * 10000) + 10000, 98369));
        return $orderId;
    }

    /**
     * @param
     * @author cabbage
     * @day 2020/6/9
     */
    public function payAlipay($user,$groupOrder)
    {
        $aop = new AopClient;
        $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
        $aop->appId = "2021001197654668";
        $aop->rsaPrivateKey = 'MIIEpAIBAAKCAQEAlGWxvrR9KGkheEK4kTrcKDvK3ovhwi+zc4zxa11DZgpyUk2Kr2RT08ZQPaQLm9jQFlzwzqVgbAL9DFBTRAaD4nEMHoR0ZfR9ueRirko16Kjkx8AOPVYdEIy68U01gln/N9Y0iq8YVxu4Yv8vorY7U8aSJUcAnkx9bPbhei8SZxVgC2KldextzyVh9t/tAk2WAxbLmvieF746lY1u0W6AfmBIvQWdjbw3wJUMxMYrlp501zHr7kecgcYhnOnYkO9ehpVSAYJHoDDAulBEkapiSGiP09aOe3jhsutFDIrxL4BoFyNtaAOCbh6sUa9mMNu67wRBXwitfK7wOdt1gzfmOwIDAQABAoIBAQCODzQyzfGqh8nkqGqrjN9JHMQ+e0ZpcOSnT1ulXiixPHroUxbahH7DEuuptqruTIYXgm18RVCi1dGMwjCTxHDoizQA2ufa2kypcfsNwjkNOvGYT0DScudr+mzTpwf8e08ZEtRFlw0EBqNjEct2RmFQ95zcVrY+1BaWA1kicIF7b7/Zto7x7xAnR10tfRE2bUePBzruugZRk+Z9LbcKSRDAb/JBEFKHzfiBIFyIcEj9covcNVFF8QCkraxugDxH0dxYheFz7sxvjLyo2OYW+Xs2Q95/kVZIGWdz2T4IIqdvqjWzCn+azMvpB7056ziFrit6E2JNQH+8DrWsHj2b3xnhAoGBAOFwF44Qce7c9zTnvzZZlqONuHrzhsSxvHEU2mf+FitpFFASOhJcPoK18M0ZsUX7EwVQLCKSoKcdk34Y3msM0E+aihRpwBQbR1isdnSnbTcBRRpmVHnX50qXjHabvY4lPJQssMKsf0ezitFQP1NA7oNWhJzEDTRNZxqlo4Y3JGf5AoGBAKiD4MKR24l9EJ+aMnPW50jIkNj/sWslYTZn5b7zyt3e1gj39Er5ePCgzqVmKt5SK/SnS1PxEcQurVuw2Gs4/9vAYc25QAAYhZCbgHRTUhv1+1xontLyIIXChQABJElAEkTj+bpB5ps/rwOVR3znMyS1135o4Q+DyP+SW7BZ/NTTAoGBANp+J3Y7HhGh+7489igZAFUYIDqaGH4+vSLkUSIFMztzpopMgBgXa0aITBCc3CG1TCQUJhKEBkyx76eBNuCOFL9ySm2qaM2T+rxIuq4pL0LmajFCCJHm3XaAF1VFcJx6HpKGFfM3+ExoCR0BJ77q6cBFdFXz9dBBTLKY4zpL628RAoGAUeARejen9PtA8mrXDJVjtmdMiUJij26P9wEwDUEiVf6I+76NgUgIzNE01gP33CEMnkgSP2yndyw+qogX/rCpD7o/StcxE1rWulXzaZF6GX/Aazuhv1hJGPRT7pafbL+moLYrhaWzR8b/X7xOCY/Dt5hqZU7L2t/q7tHLnrl6MGUCgYBtgaNNSrj7wyqfresYG24h0cCSAg8ctG24CgrXc+kJF0rxHXuGjMSy0K22u3X/2CHRGGCmejFhbKI4Jg8FX+mZvG+7yMsQNVrx2Qzh1OSTHmd52nt7BW7mMrO7r3KYO7WzjeHtgwMp5/ZSPxsCkqLPf9Y3yzG+zwiwwZGrsSogVQ==';
        $aop->format = "json";
        $aop->charset = "UTF-8";
        $aop->signType = "RSA2";
        $aop->alipayrsaPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArHwMZtNYBkK5q2jQ0Ml18H8MhQX9Bpuz/ignvuJC47K7LHY+F6/U/+o/nYeDhqHzUajMAAyM06N3r2qBnWQRjC4JKFMO4i5xIDVycuumzcsWz3LwAkHOFG/S1pGXFWh74zdQDNednhvnNOiTDwjefZRnf5HUqEZK/7tRSaZvzSUIAwHG2zj0C6AYkhg5wr6ZJxgRDjPjqbs6ZMqLT+pITsnCcc6IgIisZbPTdtw1U2FKmQm5n228drI3XKYbE3UVT2y6R0mZNmqmiHDszmYSKOjDrpgtMExWpee8kUFn7J800HIyYtq0nRv1ypdWngUZtkm+szVWOTDGgN4eHQW3FwIDAQAB';
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        $request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数
        $bizcontent = json_encode([
            'body' => '代理支付',
            'subject' => '代理支付',
            'out_trade_no' => $groupOrder['order_sn'],
            'timeout_express' => '90m',
            'total_amount' => strval($groupOrder['price']),
            'product_code' => 'QUICK_MSECURITY_PAY',
        ]);
        $request->setNotifyUrl("https://app.bjtdba.com/api/notice/alipay_agent");
        $request->setBizContent($bizcontent);
        //这里和普通的接口调用不同，使用的是sdkExecute
        $response = $aop->sdkExecute($request);
        //htmlspecialchars是为了输出到页面时防止被浏览器将关键参数html转义，实际打印到日志以及http传输不会有这个问题
        return ['config' => $response, 'order_id' => $groupOrder['order_sn']];
    }


    /*余额支付方式支付
    *@data 支付订单信息
    *@$id 订单id
    */
    public  function  orderPay($data,$id){
        Db::transaction(function () use ($data, $id) {
            //查询用户余额
            $user = Db::name("user")->where(['uid' => $data['uid']])->field("now_money,uid")->find();
            if (!systemConfig('yue_pay_status'))
                throw new ValidateException('未开启余额支付');
            if ($user['now_money'] < $data['price'])
                throw new ValidateException('余额不足' . floatval($data['price']));
            //更改余额
            $now = $user['now_money'] - $data['price'];
            Db::name("user")->where(['uid' => $data['uid']])->update(['now_money'=>$now]);
            $userBillRepository = app()->make(UserBillRepository::class);
            $userBillRepository->decBill($user['uid'], 'now_money', 'pay_agent', [
                'link_id' => $id,
                'status' => 1,
                'title' => '代理费用支付',
                'number' => $now,
                'mark' => '余额支付支付' . floatval($data['price']) . '元支付代理费',
                'balance' =>$user['now_money'],
            ]);
            $this->paySuccess($id);
        });
    }

    /*处理订单状态
    代理支付订单的id
    */
    public  function  paySuccess($id){

        Db::transaction(function () use ($id) {
            $order = $this->get($id)->toArray();
            $agent  = Db::name("user_agent")->where("id",$order['link_id'])->find();
            //修改申请代理记录信息
            if (!Db::name("user_agent")->where(["id"=>$order['link_id']])->update(['pay_status'=>1]))
                throw new ValidateException('失败');
            $ard_id = 0;
            $user='';
            if(in_array($agent['identity'],[1,2,3])) {
                //修改所属区域的代理id
                if ($agent['identity'] == 1) {//镇代
                    $ard_id = $agent['street_id'];
                    $spread_adr = Db::name("user_street")->where(['street_id' => $ard_id])->update(['uid' => $agent['user_id']]);
                } elseif ($agent['identity'] == 2) {//县代
                    $ard_id = $agent['area_id'];
                    $spread_adr = Db::name("user_area")->where(['area_id' => $ard_id])->update(['uid' => $agent['user_id']]);
                } elseif ($agent['identity'] == 3) {//市代
                    $ard_id = $agent['city_id'];
                    $spread_adr = Db::name("user_city")->where(['city_id' => $ard_id])->update(['uid' => $agent['user_id']]);
                }
                if(!$spread_adr){throw new ValidateException('失败');}
                //清除用户之前的代理的区域uid
                $user = Db::name("user")->where(["uid" => $agent["user_id"]])->field("identity,uid,adr_id")->find();
                if ($user['identity'] == 1) {
                    Db::name("user_street")->where(['street_id' => $user['adr_id']])->update(['uid' => 0]);
                } else if ($user['identity'] == 2) {
                    Db::name("user_area")->where(['area_id' => $user['adr_id']])->update(['uid' => 0]);
                } else if ($user['identity'] == 3) {
                    Db::name("user_city")->where(['city_id' => $user['adr_id']])->update(['uid' => 0]);
                }
            }



            $save = ['identity'=>$agent['identity'],'adr_id'=>$ard_id,'is_promoter'=>1,'promoter_time'=>date('Y-m-d H:i:s')];
            //查询推荐人
            if($agent['spread_account']){
                $sp = DB::name("user")->where(['account'=>$agent['spread_account']])->field("uid,spread_count")->find();
                if($sp){
                    $save['spread_uid'] = $sp['uid'];
                    //推荐人推荐数量加1
                    Db::name("user")->where(['uid'=>$sp['uid']])->update(['spread_count'=>($sp['spread_count']+1)]);
                    //保存用户的推荐记录
                    $log =[
                        'uid'=> $sp['uid'],
                        'link_id'=>$agent["user_id"],
                        'identity'=>$agent['identity'],
                        'create_time'=>date("Y-m-d H:i:s"),
                    ] ;
                    Db::name("user_identity_log")->insert($log);
                }

            }

            //修改用户身份及所对应的区域以及推荐人
            if(!Db::name("user")->where(["uid"=>$agent["user_id"]])->update($save))
                throw new ValidateException('失败');
            //修改支付状态
            if(!$this->update($id,['status'=>1,'update_time'=>date("y-m-d H:i:s")]))
                throw new ValidateException('失败');
            //加入上级环信群聊
//            try {
//
//                $im=new Im();
//                $users = Db::name("user")->where(["uid" => $agent["user_id"]])->field("account,nickname,uid,im,im_uuid")->find();
//                if($users['im']==0){//没有环信账户 创建
//                    $im_uuid=$im->createIm($users['account'],$users['nickname']);
//                }else{//有环信账户 跳过创建 下一步
//                    $im_uuid=$users['im_uuid'];
//                }
//                //p 商户群  d  代理群  t 推广群
//                if ($agent['identity'] == 1) {//镇代
//
//                    $ard_id = $agent['street_id'];
//                    //县的代码
//                    $area_code = Db::name("user_street")->where(['street_id' => $ard_id])->value('area_code');
//                    //该镇县名称 该县的代理商uid
//                    $up_uid = Db::name("user_area")->where(['area_code' => $area_code])->field("uid,area_name")->find();
//                    $up_user=Db::name('user')->where("uid",$up_uid['uid'])->field('uid,im,im_uuid,account,nickname')->find();
//                    Db::name("log")->insert(array('data'=>'up 数据'.json_encode($up_uid)));//日志记录
//                    if($up_user['im']==0)
//                       $im->createIm($up_user['account'],$up_user['nickname']);
//
//                    //县有代理商执行
//                    if($up_uid['uid']!=0){
//                        $group_id=Db::name("im_group")->where(['uid'=>$up_user['account'],'type'=>'d'])->value('groupid');
//                        //判断是否有群
//                        if($group_id){//有则加入
//                            $im->createGroupUser($group_id,$up_user['account'],$users['uid']);
//                        }else{ //无则创建 再加入
//                            $group_id=$im->createGroup($up_user['account'],$up_uid['area_name'].'- 代理群','d');
//                            //获取到 该县所有的镇代理商 并加入群聊
//                            $data=Db::name('user_street')->where('area_code',$area_code)->where('uid','>','0')->select()->toArray();
//                            foreach ($data as $k=>$v){
//                                $user_im=Db::name('user')->where('uid',$v['uid'])->field('uid,im,im_uuid,account,nickname')->find();
//                                if($user_im['im']==0){
//                                    $user_im['im_uuid']=$im->createIm($user_im['account'],$user_im['nickname']);
//                                }
//                                $im->createGroupUser($group_id,$user_im['account'],$user_im['uid']);
//                            }
//                            $im->createGroupUser($group_id,$users['account'],$users['uid']);
//                        }
//                    }
//                } elseif ($agent['identity'] == 2) {//县代
//
//                    $ard_id = $agent['area_id'];
//                    //市的代码
//                    $city_code = Db::name("user_area")->where(['area_id' => $ard_id])->value('city_code');
//                    //该市县名称 该市的代理商uid
//                    $up_uid = Db::name("user_city")->where(['city_code' => $city_code])->field("uid,city_name")->find();
//                    $up_user=Db::name('user')->where("uid",$up_uid['uid'])->field('uid,im,im_uuid,account,nickname')->find();
//                    Db::name("log")->insert(array('data'=>'up 数据'.json_encode($up_uid)));//日志记录
//                    if($up_user['im']==0)
//                        $im->createIm($up_user['account'],$up_user['nickname']);
//
//                    //县有代理商执行
//                    if($up_uid['uid']!=0){
//                        $group_id=Db::name("im_group")->where(['uid'=>$up_user['account'],'type'=>'d'])->value('groupid');
//                        //判断是否有群
//                        if($group_id){//有则加入
//                            $im->createGroupUser($group_id,$up_user['account'],$users['uid']);
//                        }else{ //无则创建 再加入
//                            $group_id=$im->createGroup($up_user['account'],$up_uid['area_name'].'- 代理群','d');
//                            //获取到 该市所有的县代理商 并加入群聊
//                            $data=Db::name('user_area')->where('area_code',$city_code)->where('uid','>','0')->select()->toArray();
//                            foreach ($data as $k=>$v){
//                                $user_im=Db::name('user')->where('uid',$v['uid'])->field('uid,im,im_uuid,account,nickname')->find();
//                                if($user_im['im']==0){
//                                    $user_im['im_uuid']=$im->createIm($user_im['account'],$user_im['nickname']);
//                                }
//                                $im->createGroupUser($group_id,$user_im['account'],$user_im['uid']);
//                            }
//                            $im->createGroupUser($group_id,$users['account'],$users['uid']);
//                        }
//                    }
//                }
//            }catch (\Exception $e) {
//                Db::name("log")->insert(array('data'=>'环信错误'.$e->getMessage()));//日志记录
//            }
            //加入上级环信群聊 结束

            //处理佣金
            $this->yongjin($id);

        });
    }

    /*处理佣金
    *代理支付订单id
    */
    public  function yongjin($id){
        Db::transaction(function () use ($id) {
            $order = $this->get($id)->toArray();
//            var_dump($order);exit();
            //账单金额小于等于0直接成功,不进行分账
            if($order['price'] <= 0){
                return true;
            }
            $order_user=Db::name("user")->where("uid",$order["uid"])->field("adr_id,spread_uid")->find();
            //申请信息
            $agent_user=Db::name("user_agent")->where("user_id",$order["uid"])->field("identity,city_id,area_id,street_id")->find();
            //推广员id
            $spread_uid=$order_user["spread_uid"];

            //存再推广员 则开始算佣金
            if ($spread_uid){
                $spread_user_identity=Db::name("user")->where("uid",$spread_uid)->field("admin_agent_rate,jurisdiction,other_jurisdictions,promoter_rebate,identity")->find();

                if ($spread_user_identity&&$spread_user_identity["identity"]>0){
                    $commission_rate=$spread_user_identity["promoter_rebate"];
                    $other_jurisdictions=$spread_user_identity["other_jurisdictions"];
                    $jurisdiction=$spread_user_identity["jurisdiction"];
                    $admin_agent_rate=$spread_user_identity["admin_agent_rate"];
                    switch ($spread_user_identity["identity"]){
                        case 1://镇代
                            $commission_rate=floatval($commission_rate)?$commission_rate:systemConfig("town_agent_rate");
                            break;
                        case 2://县代
                            //自己辖区
                            $commission_rate=floatval($commission_rate)?$commission_rate:systemConfig("count_agent_rate");
                            //跨区自己
                            $jurisdiction=floatval($jurisdiction)?$commission_rate:systemConfig("count_agent_rate_kua");
                            //跨区对方县代
                            $other_jurisdictions=floatval($other_jurisdictions)?$commission_rate:systemConfig("count_agent_rate_correspond");
                            //平台收入
                            $admin_agent_rate=floatval($admin_agent_rate)?$commission_rate:systemConfig("admin_agent_rate");
                            break;

                        case 3://市代
                            //自己辖区
                            $commission_rate=floatval($commission_rate)?$commission_rate:systemConfig("city_agent_rate");
                            //跨区自己
                            $jurisdiction=floatval($jurisdiction)?$commission_rate:systemConfig("city_agent_rate_kua");
                            //跨区对方市代
                            $other_jurisdictions=floatval($other_jurisdictions)?$commission_rate:systemConfig("city_agent_rate_correspond");
                            //平台收入
                            $admin_agent_rate=floatval($admin_agent_rate)?$commission_rate:systemConfig("admin_agent_rate");
                            break;
                        case 4:
                            $commission_rate=floatval($commission_rate)?$commission_rate:systemConfig("mer_agent_rate");
                            break;
                        case 5:
                            $commission_rate=floatval($commission_rate)?$commission_rate:systemConfig("promoter_agent_rate");
                            break;
                    }
                    //   var_dump($commission_rate);exit;
                    // 除市代县代 直接分佣金
                    if (in_array($spread_user_identity["identity"],[1,4,5])){
                        if (floatval($commission_rate)){
                            $commission=round($order["price"]*$commission_rate/100,2);
                            $this->add_bill($order,$spread_uid,$commission,"代理费佣金","推荐代理获得佣金".$commission_rate);
                        }
                    }else{
                        //市代县代 分佣金
                        //首先检查是不是跨区域
                        //先查询用户注册所属的辖区
                        if ($agent_user["identity"]==1){
                            $adr_id=$agent_user["street_id"];
                        }
                        if ($agent_user["identity"]==2){
                            $adr_id=$agent_user["area_id"];
                        }
                        if ($agent_user["identity"]==3){
                            $adr_id=$agent_user["city_id"];
                        }
                        if ($agent_user["identity"]==4){
                            $adr_id=$agent_user["street_id"];
                        }
                        if ($agent_user["identity"]==5){
                            $adr_id=$agent_user["street_id"];
                        }
                        if ($spread_user_identity["identity"]==2){
                            $area_uid=Db::name("user_area")->where("area_id",$adr_id)->field("uid,area_code")->find() ;
                            $arr=Db::name("user_street")->where("street_code",$area_uid["area_code"])->column("uid");
                            $arr[]=  $area_uid["uid"];
//                            var_dump($area_uid,$arr);
                        }else{

                            //市代id
                            $area_uid=Db::name("user_city")->where("city_id",$adr_id)->field("uid,city_code")->find() ;
                            //下边所有县代id

                            $arr1=Db::name("user_area")->where("city_code",$area_uid["city_code"])->column("uid");
                            $area_code=Db::name("user_area")->where("city_code",$area_uid["city_code"])->column("area_code");
                            $arr2=[];
                            if ($area_code){
                                //下边所有镇代id
                                $arr2=Db::name("user_street")->where("area_code",implode(",",$area_code))->column("uid");
                            }
                            $arr=array_merge($arr1,$arr2);
                            $arr[]=  $area_uid["uid"];
//                            var_dump("BBB",$area_uid,$arr);exit();
                        }
                        //不跨区域 直接分佣
                        //辖区是推广员的辖区 判断推广员在不在用户所属的辖区内
                        if ($area_uid["uid"]==$spread_uid||in_array($spread_uid,$arr)){
                            $commission=round($order["price"]*$commission_rate/100,2);
                            $this->add_bill($order,$spread_uid,$commission,"代理费佣金","推荐代理获得佣金".$commission_rate);
                        }else{
                            if ($area_uid["uid"]){
                                $commission_zj=round($order["price"]*$jurisdiction/100,2);
                                $this->add_bill($order,$spread_uid,$commission_zj,"代理费佣金","推荐代理获得佣金:跨区自己");
                                //对方区域代理
                                $commission_df=round($order["price"]*$other_jurisdictions/100,2);
                                $this->add_bill($order,$area_uid["uid"],$commission_df,"代理费佣金","推荐代理获得佣金:跨区对方");
                                //跨区公司
                                $commission_gs=round($order["price"]*$admin_agent_rate/100,2);
                                $this->admin_bill($order["uid"],$commission_gs,"跨区域公司收入","跨区域县代公司收入",$order["order_sn"],3);
                            }
//                            var_dump($spread_uid,$arr,$order_user["adr_id"],$area_uid["uid"]);exit();
                            //跨区域
                            //自己

                        }

                    }
                }

            }

        });
    }
    /**
     * 平台账单记录
     * `type` int(1) DEFAULT '0' COMMENT '类型 1刷卡手续费 2 会费',
     * `number` decimal(8,2) unsigned NOT NULL DEFAULT '0.00' COMMENT '明细数字',
     * `title` varchar(64) NOT NULL COMMENT '账单标题',
     * `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '0 = 待确定 1 = 有效 -1 = 无效',
     */
    public function admin_bill($uid,$number,$title,$mark,$order_sn,$type){
        $number=round($number,2);
        $data=[
            'link_id' => $uid,
            "pm"=>1,
            "title"=>$title,
//            "category"=>"now_money",
            "type"=>$type,
            "number"=>$number,
//            "balance"=>0,
            "mark"=>$mark,
            "status"=>1,
            "order_sn"=>$order_sn,
        ];
        Db::name("admin_bill")->insert($data);
    }

    /**
     * 账单记录
     * @param $order
     * @param $spread_uid
     * @param $commission
     * @param string $title
     * @param $mark
     * @throws \think\db\exception\DbException
     */
    public function add_bill($order,$spread_uid,$commission,$title="代理费佣金",$mark,$mer_id=0){
        $data=[
            'link_id' => $order["agent_order_id"],
            "uid"=>$spread_uid,
            "title"=>$title,
            "category"=>"now_money",
            "type"=>"commission",
            "number"=>$commission,
            "balance"=>0,
            "mark"=>$mark,
            "status"=>1,
            "commission_type"=>3,
            "order_sn"=>$order["order_sn"],
            "mer_id"=>$mer_id,
        ];
        Db::name("user_bill")->insert($data);
        Db::name("user")->where("uid",$spread_uid)->inc('brokerage_price', $commission) ->update();

    }
    /*获取列表*/
    public function getList($where, $page, $limit)
    {
        $query = $this->dao->searchJoin($where)->order('a.create_time DESC');
        $count = $query->count();
        $list = $query->page($page, $limit)->select();
        $countnum=$this->dao->searchJoin($where)->sum("price");
        $cards=[
            ['className'=> 'el-icon-s-goods', 'count'=> $countnum, 'field'=>'元', 'name'=>'总金额']
        ];
        return compact('count', 'list','cards');
    }

    public function agentCount($where, $page, $limit)
    {
        $list=   Db::name("order_commission_news")->order("id desc")->select();
        $count = Db::name("order_commission_news")->count();
        return compact('count', 'list');
    }

}