<?php
/**
 * @package merchant
 *
 * @author xaboy
 * @day 2020-04-28
 *
 *
 */

namespace app\common\repositories\user;

use app\common\dao\user\UserThirdDao;
use app\common\enum\CommonEnum;
use app\common\enum\shared\SharedProsperityRewardRecordEnum;
use app\common\enum\user\UserWithdrawalLimitRecordEnum;
use app\common\model\user\User;
use app\common\repositories\BaseRepository;

use app\common\repositories\shared\SharedProsperityRewardRecordRepository;
use app\common\repositories\shared\SharedProsperityUserRepository;
use app\common\repositories\store\order\StoreOrderRepository;
use app\common\repositories\store\product\ProductRepository;
use app\model\common\TbOrderModel;
use think\exception\ValidateException;
use think\facade\Log;
use think\test\queue\LoopBreakerException;
use function GuzzleHttp\Psr7\str;

use think\facade\Db;

//use think\Db;

/**
 * Class UserRepository
 * @package app\common\repositories\user
 * @author xaboy
 * @day 2020-04-28
 * @mixin UserThirdDao
 */
class UserThirdRepository extends BaseRepository
{
    /**
     * UserRepository constructor.
     * @param UserThirdDao $dao
     */
    public function __construct(UserThirdDao $dao)
    {
        $this->dao = $dao;
    }


    /*创建用户第三方pid*/
    public function createPid($data = [])
    {
        $res = Db::name("user_third")->insertGetId($data);
        return $res;
    }

    /*获取第三方pid*/
    public function getDetail($where = [], $field = "*")
    {
        $res = Db::name("user_third")->where($where)->field($field)->find();
        return $res;
    }

    /*获取配置信息*/
    public function config()
    {

        $config = $data = [
            'promoter_rate_technology' => systemConfig('promoter_rate_technology'), //技术服务费
            'yanglao_Meeting' => systemConfig('yanglao_Meeting'),//会费比例
            'yanglao_Meeting_total' => systemConfig('yanglao_Meeting_total'),//会费总金额
            'yanglaojin_admin' => systemConfig('yanglaojin_admin'), //养老金比例
            'mer_rate' => systemConfig('mer_rate'), //商家比例
            'third_day' => systemConfig('third_day'), //第三方订单结算天数
        ];
        return $config;
    }

    /*获取信息*/
    public function getOrderDetail($table, $where = [], $field = "*")
    {
        $res = DB::name("$table")->where($where)->field($field)->find();
        return $res;
    }

    /*创建订单*/
    public function createOrder($table, $data, $time = 0)
    {
        //获取订单结算时间
        $day = $this->config();
        if ($time > 0) {
            $data['bill_end_time'] = $time + $day['third_day'] * 24 * 60 * 60;
        }
        $res = Db::name("$table")->insertGetId($data);
        return $res;
    }

    //获取第三方订单的计算时间
    public function getSettleTime($time)
    {
        //获取订单结算时间
        $day = $this->config();
        if ($time > 0) {
            $time = $time + $day['third_day'] * 24 * 60 * 60;
        }
        return $time;
    }

    /*修改订单*/
    public function saveOrder($table, $where = [], $data = [])
    {
        $res = Db::name("$table")->where($where)->update($data);
        return $res;
    }


    /*计算用户本年已经扣除的会费*/
    public function getTotalHui($uid)
    {

        $data = Db::name("admin_bill")->where(['pm' => 0, 'status' => 1, 'type' => 2, 'link_id' => $uid])->count("number");
        return $data;

    }

    /*获取用户商家信息*/
    public function getMer($uid)
    {
        $data = Db::name("user")->where(['uid' => $uid])->value("mer_id");
        return $data;
    }
    /*处理订单反养老金逻辑
         *$order_id 订单id
         *$commission 佣金
         * $pid  用户广告位id
         * $order_sn   订单号
         * $table 表名
        */
    public function successOrder($order_id, $commission, $pid, $order_sn, $type, $table)
    {
        try {
            $bill= Db::name("user_bill")->where("order_sn",$order_sn)->select();
            foreach ($bill as $v){
                if ($v["commission_type"]==5){
                    Db::name("user")->where("uid",$v["uid"])->inc('annuity',$v["number"]) ->update();
                    Db::name("user")->where("uid",$v["uid"])->inc('annuity_num', 1) ->update();
                }else{

                    if($v['title']!='平台奖励'){
                        Db::name("user")->where("uid",$v["uid"])->inc('brokerage_price', $v["number"]) ->update();
                    }else{
                        Db::name("user")->where("uid",$v["uid"])->inc('now_score', $v["number"]) ->update();
                    }
                }

                $annuity_once = Db::name("user")->where("uid",$v['uid'])->value('annuity_once');
                if($annuity_once == 0){
                    $spreadUid = Db::name('user') -> where('uid',$v['uid']) -> value('spread_uid');
//                Db::name('user')->where('uid',$spreadUid)->inc('score', systemConfig('ylj_first_score'))->update();
//                $ins_data['uid'] = $spreadUid;
//                $ins_data['reward_socre'] = systemConfig('ylj_first_score');
//                $ins_data['addtime'] = time();
//                $ins_data['status'] = 1;
//                $ins_data['mark'] = '好友首次获得已结算养老金奖励积分';
//                Db::name('user_sign_score')->insert($ins_data);

                    // $userRepository = app()->make(UserRepository::class);
                    // $userRepository -> sign_add($spreadUid,systemConfig('ylj_first_score'),1,'好友首次获得已结算养老金奖励积分','','','');
                    Db::name("user")->where("uid",$v['uid'])->update(['annuity_once'=>1]);
                }

            }
            Db::name("user_bill")->where("order_sn",$order_sn)->update(["status"=>1]);



            $orderUpdate = ['bill_status' => 1];
            if ($type == 6) {//京东订单
                $orderUpdate['bill_create_time'] = time();
            } else {
                $orderUpdate['bill_create_time'] = date("Y-m-d H:i:s");
            }
            Db::name("$table")->where($table . "_id", $order_id)->update($orderUpdate);
        } catch (\Exception $e) {
            log::error($e->getFile().'：'.$e->getLine().'【'.$e->getMessage().'】');
            throw new ValidateException($e->getMessage());
        }
    }
    public function invalidOrder($order_sn){
        return Db::name("user_bill")->where("order_sn",$order_sn)->update(["status"=>-1]);
    }
    /*处理订单预估反养老金逻辑
     *$order_id 订单id
     *$commission 佣金
     * $pid  用户广告位id
     * $order_sn   订单号
     * $table 表名
    */
    public function yuguOrder($order_id, $commission, $pid, $order_sn, $type, $table)
    {
        //配置信息
//        $config = $this->config();
        //用户pid信息
//        if ($type == 6) {//京东联盟改成京推推
//            $user['uid'] = intval($pid - pow(10, 5));
//        } else {
//            $user = $this->getDetail(['pid' => $pid, 'type' => $type]);
//        }
        //用户商家信息
        $user_mer = $this->getMer($pid);
        try {
            $money=$commission;
            //返佣比例
            $base_commission= floatval(systemConfig('extension_tao_rate'));

            //刷卡手续费
            $souxufees=0;
            $souxufee =floatval(systemConfig('yanglao'));
            if ($souxufee){
                $souxufees = bcmul($money, $souxufee * 0.01, 3);
            }
            //返佣总额 返利总额=（交易金额-手续费）*返利比例
            $moneys=bcmul($money-$souxufees,$base_commission/100,3);

            $extension_one=$moneys;
            $order=[
                "order_sn"=>$order_sn,
                "order_id"=>$order_id,
                "uid"=>$pid,
                "mer_id"=>$user_mer,
                "total_price"=>$commission,
                "extension_one"=>$extension_one,
                "type_shop"=>$type,
                "table"=>$table
            ];

            /** @var StoreOrderRepository $StoreOrderRepository */
            $StoreOrderRepository = app()->make(StoreOrderRepository::class);
//            $StoreOrderRepository->yugu_rebate($order);
            log::info("===待进入养老金22222222222");
            $StoreOrderRepository->yugu_rebate_gong_fu($order);


//            $money_hui = 0;
//            $money_user = 0;
//            $money_jishu = 0;
//            $money_mer = 0;
//            //给用户返
//            $huiTotal = $this->getTotalHui($user['uid']); //计算已经扣除的会费
//            if ($huiTotal < $config['yanglao_Meeting_total']) {
//                $money_hui = $commission * ($config['yanglaojin_admin'] / 100) * ($config['yanglao_Meeting'] / 100);//会费
//                //存储会费记录
//                if (number_format($money_hui, 2) >= 0.01) {
//                    $this->admin_bill($user['uid'], $money_hui, '养老金扣除会费' . $config['yanglao_Meeting'] . '%', '第三方平台', $order_sn, '2');
//                }
//                $money_user = ($commission * $config['yanglaojin_admin']) / 100 - $money_hui;//养老金
//            } else {
//                $money_user = $commission * $config['yanglaojin_admin'] / 100;
//            }
////            if (number_format($money_user, 2) >= 0.01) {
////                $this->add_bill($order_id, $user['uid'], $money_user, $order_sn, $type, '购买商品获得养老金' . $config['yanglaojin_admin'] . '%', '第三方平台',$type,0);
////                //修改用户养老金信息
////                Db::name("user")->where("uid", $user['uid'])->inc('annuity', $money_user)->update();
////            }
//            //给用户所属商家返
//            if ($user_mer) {
//                $money_jishu = $commission * $config['mer_rate'] / 100 * $config['promoter_rate_technology'] / 100;
//                $money_mer = $commission * $config['mer_rate'] / 100 - $money_jishu;
//                if (number_format($money_jishu, 2) >= 0.01) {
//                    $this->admin_bill($user_mer, $money_jishu, '佣金扣除技术服务费' . $config['yanglao_Meeting'] . '%', '第三方平台', $order_sn, '4');
//                }
//                if (number_format($money_mer, 2) >= 0.01) {
//                    $this->add_bill($order_id, $user_mer, $money_mer, $order_sn, $type, '用户购买商品获得佣金' . $config['mer_rate'] . '%', '第三方平台',$type,0);
//                    //修改商户佣金
//                    Db::name("user")->where("uid", $user_mer)->inc('brokerage_price', $money_mer)->update();
//                }
//            }
//            //所有金额都小于0.01 佣金金额全归平台所有
//            if (number_format($money_hui, 2) <= 0 && number_format($money_jishu, 2) <= 0 && number_format($money_user, 2) <= 0 && number_format($money_mer, 2) <= 0) {
//                $this->admin_bill($user['uid'], $commission, '分成后所有金额小于一分存于平台', '第三方平台,不参与用户分成', $order_sn, '5');
//            }
            //修改订单结算状态
//            $orderUpdate = ['bill_status' => 1];
//            if ($type == 6) {//京东订单
//                $orderUpdate['bill_create_time'] = time();
//            } else {
//                $orderUpdate['bill_create_time'] = date("Y-m-d H:i:s");
//            }
//            Db::name("$table")->where($table . "_id", $order_id)->update($orderUpdate);
        } catch (\Exception $e) {
            throw new ValidateException($e->getMessage());
        }
    }
    /*处理订单预估反养老金逻辑
     *$order_id 订单id
     *$commission 佣金
     * $pid  用户广告位id
     * $order_sn   订单号
     * $table 表名
    */
    public function repurchaseAreaEstimateAnnuityOrder($order_id, $commission, $pid, $order_sn, $type, $table)
    {
        //用户商家信息
//        $user_mer = $this->getMer($pid);
        try {
            $money=$commission;
            //返佣比例
            $base_commission= floatval(systemConfig('extension_tao_rate'));

            //刷卡手续费
            $souxufees=0;
            $souxufee =floatval(systemConfig('yanglao'));
            if ($souxufee){
                $souxufees = bcmul($money, $souxufee * 0.01, 3);
            }
            //返佣总额 返利总额=（交易金额-手续费）*返利比例
            $moneys=bcmul($money-$souxufees,$base_commission/100,3);

            $extension_one=$moneys;
            $order=[
                "order_sn"=>$order_sn,
                "order_id"=>$order_id,
                "uid"=>$pid,
                "mer_id"=>Db::name("store_order")->where("order_id",$order_id)->value("mer_id"),
                "total_price"=>$commission,
                "extension_one"=>$extension_one,
                "type_shop"=>$type,
                "table"=>$table
            ];

            /** @var StoreOrderRepository $StoreOrderRepository */
            $StoreOrderRepository = app()->make(StoreOrderRepository::class);
            // @todo 复购区养老金
            $StoreOrderRepository->repurchaseAreaEstimateAnnuity($order);
        } catch (\Exception $e) {
            throw new ValidateException($e->getMessage());
        }
    }

    /**
     * 平台账单记录
     * `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_id, $uid, $commission, $order_sn, $type, $title = "养老金", $mark = '',$type_shop=0,$status=1)
    {
        $data = [
            'link_id' => $order_id,
            "uid" => $uid,
            "title" => $title,
            "category" => "now_money",
            "type" => "commission",
            "number" => $commission,
            "balance" => 0,
            "mark" => $mark,
            "status" =>$status,
//            'type' => $type,
            "commission_type" => 3,
            "order_sn" => $order_sn,
            "type_shop"=>$type_shop
        ];
        Db::name("user_bill")->insert($data);
        // Db::name("user")->where("uid",$spread_uid)->inc('brokerage_price', $commission) ->update();

    }


    /*淘宝物料分类*/
    public function getMaterial()
    {

        $data = Db::name("material")->where(['status' => 1])->select();

        return $data;
    }


    /*京东订单*/
    public function GetJdOrder($where = [], $page = 1, $limit = 10)
    {
        $query = Db::name("order_jd");
        $query = $query->when(isset($where['date']) && $where['date'] != '', function ($query) use ($where) {
            getModelTime($query, $where['date']);
        })->when(isset($where['status']) && $where['status'] != '', function ($query) use ($where) {
            $query->where('status', $where['status']);
        })->when(isset($where['order_sn']) && $where['order_sn'] != '', function ($query) use ($where) {
            $query->where('order_sn', $where['order_sn']);
        })->when($where['bill_status'] != '', function ($query) use ($where) {
            $query->where('bill_status', $where['bill_status']);
        })->when(isset($where['keywords']) && $where['keywords'] != '', function ($query) use ($where) {
            $query->whereLike("shop_name|uid", "%" . $where['keywords'] . "%");
        });
        $count = $query->count();
        $list = $query->page($page, $limit)->order('order_jd_id DESC')->select();
        $sql = $query->getLastSql();
        $userList = User::whereIn('uid', $list->column('uid'))->column('*', 'uid');
        $list->each(function ($value) use ($userList) {
            $info = $userList[$value['uid']] ?? [];
            if ($info) {
                $value['account'] = $info['account'];
            } else {
                $value['account'] = '匹配用户不存在';
            }
            return $value;
        });
        return compact('count', 'list', 'sql');
    }


    /*拼多多订单*/
    public function GetPddOrder($where = [], $page = 1, $limit = 10)
    {
        $query = Db::name("order_pdd");
        $query = $query->when(isset($where['date']) && $where['date'] != '', function ($query) use ($where) {
            getModelTime($query, $where['date']);
        })->when(isset($where['pin_order_status']) && $where['pin_order_status'] != '', function ($query) use ($where) {
            $query->where('pin_order_status', $where['pin_order_status']);
        })->when(isset($where['order_sn']) && $where['order_sn'] != '', function ($query) use ($where) {
            $query->where('order_sn', $where['order_sn']);
        })->when($where['bill_status'] != '', function ($query) use ($where) {
            $query->where('bill_status', $where['bill_status']);
        })->when(isset($where['keywords']) && $where['keywords'] != '', function ($query) use ($where) {
            $query->whereLike("goods_name|uid", "%" . $where['keywords'] . "%");
        });
        $count = $query->count();
        $list = $query->page($page, $limit)->order('create_time DESC')->select();
        $userList = User::whereIn('uid', $list->column('uid'))->column('*', 'uid');
        $list->each(function ($value) use ($userList) {
            $info = $userList[$value['uid']] ?? [];
            if ($info) {
                $value['account'] = $info['account'];
            } else {
                $value['account'] = '匹配用户不存在';
            }
            return $value;
        });
        return compact('count', 'list');
    }

    /*唯品会订单*/
    public function GetVipOrder($where = [], $page = 1, $limit = 10)
    {
        $query = Db::name("order_vip");
        $query = $query->when(isset($where['date']) && $where['date'] != '', function ($query) use ($where) {
            getModelTime($query, $where['date']);
        })
            ->when(isset($where['settled']) && $where['settled'] != '', function ($query) use ($where) {
                $query->where('settled', $where['settled']);
            })->when(isset($where['order_status']) && $where['order_status'] != '', function ($query) use ($where) {
                $query->where('order_status', $where['order_status']);
            })->when(isset($where['order_sn']) && $where['order_sn'] != '', function ($query) use ($where) {
                $query->where('order_sn', $where['order_sn']);
            })->when($where['bill_status'] != '', function ($query) use ($where) {
                $query->where('bill_status', $where['bill_status']);
            })->when(isset($where['keywords']) && $where['keywords'] != '', function ($query) use ($where) {
                $query->whereLike("goods_name|uid", "%" . $where['keywords'] . "%");
            });
        $count = $query->count();
        $list = $query->page($page, $limit)->order('order_vip_id DESC')->select()->each(function ($value) {
            $orderTime = $value['order_time'];
//            $value['order_time'] = date('Y-m-d H:i:s', $orderTime);
            //订单关联用户信息
            $value['account'] = User::where('uid', $value['uid'])->value('account', '匹配用户不存在');
            return $value;
        });
        return compact('count', 'list');
    }

    /*苏宁订单*/
    public function GetSuOrder($where = [], $page = 1, $limit = 10)
    {
        $query = Db::name("order_su");
        $query = $query->when(isset($where['date']) && $where['date'] != '', function ($query) use ($where) {
            getModelTime($query, $where['date']);
        })->when(isset($where['status']) && $where['status'] != '', function ($query) use ($where) {
            $query->where('status', $where['status']);
        })->when(isset($where['order_sn']) && $where['order_sn'] != '', function ($query) use ($where) {
            $query->where('order_sn', $where['order_sn']);
        })->when($where['bill_status'] != '', function ($query) use ($where) {
            $query->where('bill_status', $where['bill_status']);
        })->when(isset($where['keywords']) && $where['keywords'] != '', function ($query) use ($where) {
            $query->whereLike("goods_name|uid", "%" . $where['keywords'] . "%");
        });
        $count = $query->count();
        $list = $query->page($page, $limit)->order('create_time DESC')->select()->each(function ($value) {
            $orderTime = $value['order_time'];
            $value['order_time'] = date('Y-m-d H:i:s', $orderTime);
            $payTime = $value['pay_time'];
            $value['pay_time'] = date('Y-m-d H:i:s', $payTime);
            //订单关联用户信息
            $value['account'] = User::where('uid', $value['uid'])->value('account', '匹配用户不存在');
            return $value;
        });
        return compact('count', 'list');
    }

    /*淘宝订单*/
    public function GetTbOrder($where = [], $page = 1, $limit = 10)
    {
        $query = Db::name("order_tb");
        $query = $query->when(isset($where['date']) && $where['date'] != '', function ($query) use ($where) {
            getModelTime($query, $where['date']);
        })->when(isset($where['tk_status']) && $where['tk_status'] != '', function ($query) use ($where) {
            $query->where('tk_status', $where['tk_status']);
        })->when(isset($where['order_sn']) && $where['order_sn'] != '', function ($query) use ($where) {
            $query->where('order_sn', $where['order_sn']);
        })->when($where['bill_status'] != '', function ($query) use ($where) {
            $query->where('bill_status', $where['bill_status']);
        })->when(isset($where['keywords']) && $where['keywords'] != '', function ($query) use ($where) {
            $query->whereLike("item_title|uid", "%" . $where['keywords'] . "%");
        });
        $count = $query->count();
        $list = $query->page($page, $limit)->order('create_time DESC')->select()->each(function ($value) {
            $orderTime = $value['create_time'];
//            $value['create_time'] = date('Y-m-d H:i:s', $orderTime);
            //淘客订单状态
            $tkStatus = $value['tk_status'];
            $tkStatusName = TbOrderModel::$statusName[$tkStatus] ?? '未知状态';
            $value['status_name'] = $tkStatusName;
            //订单关联用户信息
            $value['account'] = User::where('uid', $value['uid'])->value('account', '匹配用户不存在');
            return $value;
        });
        return compact('count', 'list');
    }



    /*话费订单*/
    public function GetHfOrder($where = [], $page = 1, $limit = 10)
    {
        $query = Db::name("order_huafei");
        $query = $query->when(isset($where['date']) && $where['date'] != '', function ($query) use ($where) {
            getModelTime($query, $where['date']);
        })->when(isset($where['status']) && $where['status'] != '', function ($query) use ($where) {
            $query->where('status', $where['status']);
        })->when(isset($where['order_sn']) && $where['order_sn'] != '', function ($query) use ($where) {
            $query->where('order_sn', $where['order_sn']);
        })->when($where['bill_status'] != '', function ($query) use ($where) {
            $query->where('bill_status', $where['bill_status']);
        })->when(isset($where['keywords']) && $where['keywords'] != '', function ($query) use ($where) {
            $query->whereLike("mobile|uid", "%" . $where['keywords'] . "%");
        });
        $count = $query->count();
        $list = $query->page($page, $limit)->order('create_time DESC')->select()->each(function ($value) {
            // $value['create_time'] = date('Y-m-d H:i:s', $value['create_time']);
            //淘客订单状态
            // $tkStatus = $value['status'];
            // $tkStatusName = TbOrderModel::$statusName[$tkStatus] ?? '未知状态';
            // $value['status_name'] = $tkStatusName;
            //订单关联用户信息
            $value['account'] = User::where('uid', $value['uid'])->value('account', '匹配用户不存在');
            return $value;
        });
        return compact('count', 'list');
    }



    /*详情*/
    public function GetThirdDetail($id, $table)
    {
        $data = Db::name("order_" . $table)->where(['order_' . $table . '_id' => $id])->find();
        //养老金修改
        $commission = $data['commission'];
        $yanglao = 0;
        if ($commission) {
            $yanglao = app()->make(ProductRepository::class)->yanglaojin(0, $commission);
        }
        $data['yanglao'] = $yanglao;
        switch ($table) {
            case 'jd':
                $billEndTime = $data['bill_end_time'];
                $data['bill_end_time'] = $billEndTime ? date('Y-m-d H:i:s', $billEndTime) : '';
                break;
            case 'vip':
                $orderTime = $data['order_time'];
                $data['order_time'] = date('Y-m-d H:i:s', $orderTime);
                $updateTime = $data['last_update_time'];
                $data['last_update_time'] = date('Y-m-d H:i:s', $updateTime);
                $billEndTime = $data['bill_end_time'];
                $data['bill_end_time'] = $billEndTime ? date('Y-m-d H:i:s', $billEndTime) : '';
                break;
            case 'pdd':
                $payTime = $data['pay_time'];
                $data['pay_time'] = $payTime ? date('Y-m-d H:i:s', $payTime) : '';
                $groupTime = $data['group_time'];
                $data['group_time'] = $groupTime ? date('Y-m-d H:i:s', $groupTime) : '';
                $billEndTime = $data['bill_end_time'];
                $data['bill_end_time'] = $billEndTime ? date('Y-m-d H:i:s', $billEndTime) : '';
                break;
            case 'su':
                $payTime = $data['pay_time'];
                $data['pay_time'] = $payTime ? date('Y-m-d H:i:s', $payTime) : '';
                $billEndTime = $data['bill_end_time'];
                $data['bill_end_time'] = $billEndTime ? date('Y-m-d H:i:s', $billEndTime) : '';
                break;
            case 'tb':
                $createTime = $data['create_time'];
                $data['create_time'] = $createTime ? $createTime : '';
                $billEndTime = $data['bill_end_time'];
                $data['bill_end_time'] = $billEndTime ? date('Y-m-d H:i:s', $billEndTime) : '';
                break;
            case 'huafei':
                $createTime = $data['create_time'];
                $data['create_time'] = $createTime ? $createTime : '';
                $billEndTime = $data['bill_end_time'];
                $data['bill_end_time'] = $billEndTime ? date('Y-m-d H:i:s', $billEndTime) : '';
                break;
        }
        return $data;
    }

    /*pdd满足分佣的订单*/
    public function pddOrder()
    {
        $query = Db::name("order_pdd");
        $data = $query->where(['pin_order_status' => 5, 'bill_status' => 0])
            ->whereTime("bill_end_time", '<=', time())
            ->order('create_time DESC')
            ->select()->toArray();
        return $data;
    }

    /*京东满足分佣的订单*/
    public function JdOrder()
    {
        $query = Db::name("order_jd");
        $data = $query->where(['status' => 17, 'bill_status' => 0])
            ->whereTime("bill_end_time", '<=', time())
            ->order('order_jd_id DESC')
            ->select()->toArray();
        return $data;
    }

    /*抖音满足分佣的订单*/
    public function dyOrder()
    {
        $query = Db::name("order_dy");
        $data = $query->where(['flow_point' => 'SETTLE', 'bill_status' => 0])
            ->whereTime("bill_end_time", '<=', time())
            ->order('order_dy_id DESC')
            ->select()->toArray();
        return $data;
    }

    /*苏宁满足分佣的订单*/
    public function SuOrder()
    {
        $query = Db::name("order_su");
        $data = $query->where(['status' => '已结算', 'bill_status' => 0])
            ->whereTime("bill_end_time", '<=', time())
            ->order('create_time DESC')
            ->select()->toArray();
        return $data;
    }

    /**
     * 修改积分，养老金，贡献值记录状态
     */
    public static  function  updateJilu($user_id,$order_id,$type_shop){
//        if (empty($user_id)) {
//            Db::name('log')->insert(['data' => "type_shop:{$type_shop}, $order_sn, $order_sn, 修改积分，养老金，贡献值记录, 不存在用户ID"]);
//            return false;
//        }

        log::info("订单修改开始");
        // 更新养老金
        Db::name("user_bill")->where("type_shop", $type_shop)->where("link_id", $order_id)->update(['status'=>-1]);
        //更新积分
        Db::name("user_sign_score")->where("order_type", $type_shop)->where("order_id", $order_id)->update(['status'=>0]);
        //更新贡献值
        Db::name("user_sign_gongxian")->where("order_type", $type_shop)->where("order_id", $order_id)->update(['status'=>0]);
        //更新红包
        Db::name("user_sign_hongbao")->where("order_type", $type_shop)->where("order_id", $order_id)->update(['status'=>0]);
        log::info("订单 {$order_id}  用户id ={$user_id} 三方来源={$type_shop} 积分，贡献值，养老金，红包更新更新");
        Db::name('log')->insert(['data' => "type_shop:{$type_shop}, $order_id, $order_id, 修改积分，养老金，贡献值，红包记录, 更新成功！！！"]);
    }


    //添加预估复购金记录
    public static function yuguFugou($price,$user_id,$order_sn,$type_shop){
        try {
            $inc_score = $price * 0.1;//推广者的佣金抽10%到个人复购金

            $make="";
            if($type_shop==1){
                $make="拼多多";
            }else if($type_shop==5){
                $make="淘宝";
            }else if($type_shop==6){
                $make="京东";
            }else if($type_shop==3){
                $make="苏宁";
            }else if($type_shop==2){
                $make="唯品会";
            }else if($type_shop==9){
                $make="话费";
            }

            $bill = [
                'uid'=>$user_id,
                'number'=>$inc_score,//数量
                'status'=>-1,//复购金状态1-有效 0-失效 -1待确认
                'mark'=>"购买{$make}商品赠送复购金",//备注
                'order_id'=>$order_sn,//订单id
                'surplus'=>0,//剩余
                'order_type'=>$type_shop,//关联订单ID
                'type'=>1,//复购金类型 :1赠送，2消耗
                'settlement_time'=>date('Y-m-d H:i:s'),//添加时间,
                'addtime'=>time(),
            ];

            Db::name('user_sign_fugou')->insert($bill);
        }  catch (Exception $e) {
            return app("json")->fail($e->getMessage());
        }
    }


    /**
     * 添加预估积分记录
     */
    public function yuguJifen($order_id,$price,$user_id,$order_sn,$type_shop)
    {
        if (empty($user_id)) {
            Db::name('log')->insert(['data' => "type_shop:{$type_shop}, $order_sn, $order_sn, 赠送积分, 不存在用户ID"]);
            return false;
        }
        //查询用户是否已经存在该订单
        $user_sign_score_list = Db::name('user_sign_score')
            ->where('uid', $user_id)
            ->where('order_type', $type_shop)
            ->where('order_id', $order_id)
            ->find();
        if (!empty($user_sign_score_list)) {
            Db::name('log')->insert(['data' => "type_shop:{$type_shop}, $order_sn, $order_sn, 赠送积分, 订单已存在积分发放记录"]);
            return false;
        }
        Db::name('log')->insert(['data' => "type_shop:{$type_shop}, $order_sn, $order_sn, 赠送积分, $price"]);

        try {
            // 所有第三方所下订单，消费者获得 提现额度
            $withdrawalLimit = bcmul($price, CommonEnum::WITHDRAWAL_LIMIT_RATIO, CommonEnum::DECIMAL_PLACES_OF_THE_AMOUNT);
            /** @var UserWithdrawalLimitRecordRepository $userWithdrawalLimitRecordRepository */
            $userWithdrawalLimitRecordRepository = app()->make(UserWithdrawalLimitRecordRepository::class);
            $userWithdrawalLimitRecordRepository->addUserWithdrawalLimitRecord(
                (int)$user_id,
                UserWithdrawalLimitRecordEnum::PM['INCOME']['code'],
                (float)$withdrawalLimit,
                (int)$type_shop,
                $order_sn,
                '消费获得提现额度'
            );

            //更新用户积分

            $user = Db::name('user')->where('uid', $user_id)->find();
            $systemvalueObj= $goods_obj = Db::name('system_config_value')
                -> where('config_key','sanfangfenpei')->find();;

            $sanfangfenpei=json_decode($systemvalueObj['value'],true);
            $inc_score = $gongxian = round($price*$sanfangfenpei['pv'],2);//pv=佣金的50%=积分=贡献值


            //每个表的统计值
            $jfzongwei=Db::name('user_sign_score')->where('status', -1)->where('uid', $user_id)->sum('reward_socre');
            $gxzongwei=Db::name('user_sign_gongxian')->where('status', -1)->where('uid', $user_id)->sum('number');

            $make="";
            if($type_shop==1){
                $make="拼多多";
            }else if($type_shop==5){
                $make="淘宝";
            }else if($type_shop==6){
                $make="京东";
            }else if($type_shop==3){
                $make="苏宁";
            }else if($type_shop==2){
                $make="唯品会";
            }else if($type_shop==9){
                $make="话费";
            }

            $user_score = $user['score'];
            $surplus=$user_score + $inc_score+$jfzongwei;
            $surplusgongxian=$user['contribute'] + $gxzongwei;

            $data = [
                "uid"           =>  $user_id,
                "reward_socre"  =>  $inc_score,
                "addtime"       =>  time(),
                "status"        =>  -1,
                "order_type"    =>  $type_shop,
                "order_id"      =>  $order_id,
                "mark"          =>  "购买{$make}商品赠送积分",
                "surplus"       =>  $surplus,
                "pm"            =>  1,
                "source_type"   =>  3
                ];
            log::info("{$make}==准备开始添加积分，贡献");
            Db::name("user_sign_score")->insert($data);//添加积分记录
            log::info("准备开始添加积分");


            //赠送贡献值
            $gongxian_data = [
                "uid"           =>$user_id,
                "number"  =>    $gongxian,
                "addtime"       =>time(),
                "status"        =>-1,
                "order_type"    =>$type_shop,
                "order_id"      =>$order_id,
                "mark"          =>"购买{$make}商品赠送贡献值",
                "desc"          =>'',
                "surplus"       =>$surplusgongxian+$gxzongwei,
                "type"          =>1
            ];
            Db::name("user_sign_gongxian")->insert($gongxian_data);//添加贡献记录
            log::info("===添加完积分和贡献值");

            /** @var SharedProsperityUserRepository $sharedProsperityUserRepository */
            $sharedProsperityUserRepository = app()->make(SharedProsperityUserRepository::class);
            $sharedProsperityUserEntity = $sharedProsperityUserRepository->getSharedProsperityUserEntityByUserId($user_id);
            // 判断推广者 如果推广者 是共富体系会员
            if (empty($sharedProsperityUserEntity->getId())) {
                // 添加pv记录
                $pv_data = [
                    "uid"           =>$user_id,
                    "pv"            =>$gongxian,
                    "addtime"       =>time(),
                    "status"        =>-1,
                    "order_type"    =>$type_shop,
                    "order_id"      =>$order_id,
                    "mark"          =>"购买{$make}商品获得的PV",
                ];
                Db::name("user_pv_log")->insert($pv_data);//添加pv记录
            } else {
                /** @var SharedProsperityRewardRecordRepository $sharedProsperityRewardRecordRepository */
                $sharedProsperityRewardRecordRepository = app()->make(SharedProsperityRewardRecordRepository::class);
                $sharedProsperityRewardRecordRepository->addSharedProsperityRewardRecord(
                    $sharedProsperityUserEntity->getUserId(),
                    SharedProsperityRewardRecordEnum::TYPE['PV']['code'],
                    SharedProsperityRewardRecordEnum::PM['INCOME']['code'],
                    $gongxian,
                    $type_shop,
                    $order_sn,
                    "购买{$make}商品获得的PV"
                );
            }

            //判断是否是老用户  is_old=1是1.0的用户，1.0的用户要总pv*45%的红包
            if($user["is_old"]==1){
                //添加红包
                $hongbao = $this->roundOptimize($inc_score*0.45,2);
                $hongbao_data = [
                    "uid"           =>$user_id,
                    "number"  =>    $hongbao,
                    "addtime"       =>time(),
                    "status"        =>-1,
                    "order_type"    =>$type_shop,
                    "order_id"      =>$order_id,
                    "mark"          =>"购买{$make}商品赠送红包",
                    "desc"          =>'',
                    "surplus"       =>$hongbao,
                    "type"          =>1
                ];
                Db::name("user_sign_hongbao")->insert($hongbao_data);//添加贡献记录
                log::info("===添加完红包奖励");
            }


            // 添加推荐奖励
            $zijiUser=Db::name("user")->where('uid',$user_id)->find();
            $sprerdUser= Db::name("user")->where('uid',$zijiUser['spread_uid'])->find();
            //不为空的时候进行添加推荐奖励
            if($sprerdUser){
                //奖励推广
                $yongjinbili=0;
        
                // @todo 用户身份比例
                $yongjinbili = StoreOrderRepository::getUserGroupRate($sprerdUser['user_group']);
                $tuiguanyongjin=$this->roundOptimize($yongjinbili*$inc_score,2);//按照身份获得佣金

                //添加推广积分
                $tuijifendata = [
                    "uid"           =>  $sprerdUser['uid'],
                    "reward_socre"  =>  $tuiguanyongjin,
                    "addtime"       =>  time(),
                    "status"        =>  -1,
                    "order_type"    =>  $type_shop,
                    "order_id"      =>  $order_id,
                    "mark"          =>  "推广{$make}商品赠送积分",
                    "surplus"       =>  $sprerdUser['score'] + $tuiguanyongjin,
                    "pm"            =>  1,
                    "source_type"   =>  4
                ];
                log::info("{$make}==准备开始添加推广积分，贡献");
                Db::name("user_sign_score")->insert($tuijifendata);//添加积分记录


                //添加推荐献值 普通用户 贡献值为 pv* 30%；推广人是业务员及以上身份，贡献值为:pv的1:1
                if($sprerdUser['user_group'] <= 1){
                    $gongxian = $this->roundOptimize($gongxian*0.3,2);
                }
                $tuigangongxian_data = [
                    "uid"           =>$sprerdUser['uid'],
                    "number"  =>    $gongxian,
                    "addtime"       =>time(),
                    "status"        =>-1,
                    "order_type"    =>$type_shop,
                    "order_id"      =>$order_id,
                    "mark"          =>"推广{$make}商品赠送贡献值",
                    "desc"          =>'',
                    "surplus"       => $sprerdUser['contribute'] + $gongxian,
                    "type"          =>1
                ];

                Db::name("user_sign_gongxian")->insert($tuigangongxian_data);//添加贡献记录
                log::info("===添加完积分和贡献值");
            }



//
//            Db::name('user')->where('uid', $user_id)->inc('score', $inc_score)->update();
//            Db::name('user')->where('uid', $user_id)->inc('contribute', $inc_score)->update();


//            $now_score= Db::name('user')->where('uid',$user_id)->value('now_score_estimate');
//            $now_score_no= Db::name('user')->where('uid',$user_id)->value('now_score');
//            Db::name('user')->where('uid',$user_id)->update(['now_score_estimate'=>$now_score+$price]);
//            $insertDta=[
//                'user_id'=>$user_id,
//                'before_price'=>$now_score,//变化前的积分
//                'price'=>$price,//此次变化的积分
//                'after_price'=>$now_score+$price,//变化后的积分
//                'type'=>$type,// 类型 1自营订单  2 第三方订单  3 签到积分 6 其它渠道的积分
//                'third_type'=>$third_type,//第三方的类型  1 淘宝  2 京东  3 唯品会  4 拼多多 5 苏宁易购
//                'other'=>$order_sn,//商城订单 记录订单号   签到记录日期 其它渠道记录获取方式
//                'ctime'=>time(),//创建时间
//                'thaw_time'=>$bill_end_time,//结算的时间
//            ];
//            $billData=[
//                'uid'=>$user_id,
//                'link_id'=>1,
//                'pm'=>1,
//                'title'=>'平台奖励',
//                'category'=>'now_money',
//                'type'=>'integral',
//                'number'=>$price,
//                'balance'=>$now_score_no,
//                'mark'=>'购买商品获得积分 比例 1:1',
//                'create_time'=>date("Y-m-d H:i:s",time()),
//                'status'=>0,
//                'order_sn'=>$order_sn,
//                'type_shop'=>$type_shop,
//                'commission_type'=>8,
//                'order_type'=>2
//            ];
//            Db::name('integral_log')->insert($insertDta);
//            Db::name('user_bill')->insert($billData);

        }  catch (Exception $e) {
            return app("json")->fail($e->getMessage());
        }
    }

    public static function yuguZhitui($commission, $user_id, $type_shop, $order_sn, $order_id)
    {
        //查询直推人身份
        $user_info = Db::name('user')->where('uid', $user_id)->find();
        if (empty($user_info)) {
            Db::name('log')->insert(['data' => "type_shop:{$type_shop}, $order_sn, 三方订单直推奖, 用户信息不存在"]);
            return false;
        }
        $spread_uid = $user_info['spread_uid'];
        $spread_info = Db::name('user')->where('uid', $spread_uid)->find();
        if (empty($user_info)) {
            Db::name('log')->insert(['data' => "type_shop:{$type_shop}, $order_sn, 三方订单直推奖, 不存在推荐人"]);
            return false;
        }
        $user_bill = Db::name('user_bill')->where('uid', $spread_uid)->where('order_sn', $order_sn)->where('type_shop', $type_shop)->find();
        if (!empty($user_bill)) {
            Db::name('log')->insert(['data' => "type_shop:{$type_shop}, $order_sn, 订单已分润"]);
            return false;
        }
        $base_commission = 0;
        if ($spread_info['user_group'] == 2) {
            $base_commission = 20;
        }
        if ($spread_info['user_group'] >= 3) {
            $base_commission = 30;
        }
        if ($base_commission == 0) {
            Db::name('log')->insert(['data' => "type_shop:{$type_shop}, $order_sn, 三方订单直推奖, 收益比例不能为0"]);
            return false;
        }

        $souxufees=0;
        $souxufee =floatval(systemConfig('yanglao'));
        if ($souxufee){
            $souxufees = bcmul($commission, $souxufee * 0.01, 3);
        }
        $zhitui_money = bcmul($commission-$souxufees,$base_commission/100,3);
        if (empty($user_id)) {
            return false;
        }
        Db::name('log')->insert(['data' => "type_shop:{$type_shop}, $order_id, 三方订单直推奖, 收益:{$commission},手续费:{$souxufees},分润比例:{$base_commission},最终收益:{$zhitui_money}"]);
        $StoreOrderRepository = app()->make(StoreOrderRepository::class);
        $mark = $user_info['nickname'] . '购买商品';
        $title = "直推奖".date('m.d');
        $commission_type = 3;
        $StoreOrderRepository->add_bill_gongfu($title, $zhitui_money, $spread_uid, $mark, $commission_type, $order_sn, $order_id, 0, 0, 0, $type_shop);
    }
}
