<?php
declare (strict_types=1);

namespace app\api\controller\v1;
// +----------------------------------------------------------------------
// | [ WE CAN DO IT MORE SIMPLE  ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2020 rights reserved.
// +----------------------------------------------------------------------
// | Author: TABLE ME
// +----------------------------------------------------------------------
// | Date: 2020-08-31 15:05
// +----------------------------------------------------------------------
use app\model\admin\MemberLevel;
use app\model\admin\Product;
use app\model\admin\SiteLevel;
use app\model\api\ExpCost;
use app\model\api\Member;
use app\model\api\MemberDetail;
use app\model\api\MemberShop;
use app\model\api\Order;
use app\model\api\OrderInfo;
use app\model\api\OrderInfoAsw;
use app\model\api\OrderInfoDd;
use app\model\api\PayTrade;
use app\model\api\Recharge;
use app\model\api\SiteDetail;
use app\model\api\SiteProduct;
use app\model\api\Tx;
use app\model\api\Warehouse;
use app\model\api\WeixinPushUser;
use app\model\system\MemberFollow;
use app\model\system\News;
use app\Request;
use app\api\controller\AuthController;
use library\services\UtilService;
use library\utils\alipay;
use library\utils\Qiniu;
use library\utils\Region;
use think\db\exception\DbException;
use think\db\Where;
use think\facade\Db;
use think\Image;
use Alipay\EasySDK\Kernel\Factory;
use Alipay\EasySDK\Kernel\Config;

class User extends AuthController
{

    /**
     * 获取配置
     */
    public function index(Request $request)
    {
        $post = [];
        //获取公告
        [$page, $data] = (new News)->getList(0, ['cate_id' => 2,'is_show'=>1], '6', '*', 'time desc');
        $newData      = UtilService::getParam([
            'id',
            'title',
            ['time', 'time', 'date("Y-m-d",$1)'],
        ], $data);
        $post['news'] = $newData;
        //快递费用
        $expCode         = new ExpCost;
        $expData         = $expCode->getExpCostData($request->site['sassid'], $request->user['levelid']);
        $post['expData'] = $expData;
        //

        //总金额
        $total         = (new Order)
            ->where('uid', $request->user['uid'])
            ->where('status', '>', 0)
            ->sum('all_price');
        $post['total'] = $total;

        //未支付
        $unpaid         = (new Order)
            ->where('uid', $request->user['uid'])
            ->where('status', 0)
            ->count();
        $post['unpaid'] = $unpaid;

        //打单子中
        $inOrder         = (new Order)
            ->where('uid', $request->user['uid'])
            ->where('status', 1)
            ->count();
        $post['inOrder'] = $inOrder;
        //打单子中
        $sendOrder         = (new Order)
            ->where('uid', $request->user['uid'])
            ->where('status', 2)
            ->count();
        $post['sendOrder'] = $sendOrder;

        //异常订单
        $abnormalOrder         = (new Order)
            ->where('uid', $request->user['uid'])
            ->where('status', 9)
            ->count();
        $post['abnormalOrder'] = $abnormalOrder;

        $dateAr = [];
        $order  = new  Order;
        //8天订单量
        for ($i = 0; $i < 8; $i++) {
            $time     = strtotime('-' . $i . ' day');
            $date     = date('Y-m-d', $time);
            $count    = $order
                ->where('uid', $request->user['uid'])
                ->where('sassid', $request->site['sassid'])
                ->whereDay('time', $date)
                ->count();
            $dateAr[] = ['count' => $count, 'name' => $date];
        }
        $post['date'] = array_reverse($dateAr);
        //绑定数据
        $wxPush = (new  WeixinPushUser)
            ->field("avatar,nickname")
            ->where('sassid', $request->site['sassid'])
            ->where('uid', $request->user['uid'])
            ->find();
        if (empty($wxPush)) {
            $token            = base64_encode(crypto_encrypt($request->user['uid'] . "|" . time(), 'md5_user_token'));
            $url              = \config('app')['API_URL']
                . '/api/bind/system_bind?token=' . $token . '&secret_key=' . $request->site['secret_key'];
            $post['bind']     = false;
            $post['bind_url'] = $url;
        } else {
            $post['bind'] = true;
        }


        return app('json')->success($post);
    }

    /**
     * 获取个人信息
     */
    public function init(Request $request)
    {
        $user = (new Member)->where('uid',$request->user['uid'])->whereTime('lasttime', 'today')->find();
        if(!$user){
            (new Member)->where('uid',$request->user['uid'])->save(['lasttime'=>time()]);
            $data['uid'] = $request->user['uid'];
            $data['ip'] = $request->ip();
            $data['time'] = time();
            Db::name("login_record")->insert($data);
        }
        $level = (new MemberLevel)->where('id', $request->user['levelid'])->find();
        $info  = [
            'mobile'    => $request->user['mobile'],
            'name'      => $request->user['name'],
            'nickname'  => $request->user['nickname'],
            'avatar'    => $request->user['avatar'],
            'money'     => $request->user['money'],
            'openid'    => $request->user['openid'],
            'levelname' => $level['name'],
            'levelid'   => $level['id'],
        ];
        return app('json')->success($info);
    }


    /**
     * 获取仓库列表
     * @param Request $request
     */
    public function warehouse(Request $request)
    {
        $warehouse = new Warehouse;
        $expCode   = new ExpCost;
        $expCode->getExpCostData($request->site['sassid'], $request->user['levelid']);
        $data     = $warehouse->field("name,id,platform_ids,address,exp_time,exp_star,tran_star,beijing,shanghai,qinghai")
            ->where("status", 1)
            ->whereIn("sassid",[0,$request->site['sassid']])
            ->order("sassid", "desc")
            ->order("seq", "desc")
            ->select()
            ->toArray();
        $platform = (new \app\model\system\Platform());
        foreach ($data as $k => $v) {
            $idsAr = explode(',', $v['platform_ids']);
            //平台
            $data[$k]['platform'] = array_map(
                function ($item) use ($platform) {
                    return $platform->getPlatformId($item, '*');
                }, $idsAr);
            //邮费模板
            $data[$k]['expCode'] = $expCode->getWareHouseExpCost($v['id'], '*');

        }

        return app('json')->success($data);
    }


    /**
     * 提交
     * @param Request $request
     */
    public function subOrder(Request $request)
    {
        [$orderAr, $proId, $warehouseId, $expId, $platformId, $mono, $extraFreight] = UtilService::getMore([
            ['orderAr', '', 'empty', '参数错误'],
            ['proId', '', 'empty', '参数错误'],
            ['warehouseId', '', 'empty', '参数错误'],
            ['expId', '', 'empty', '请选择运送方式'],
            ['platformId', '', 'empty', '参数错误'],
            ['mono', ''],
            ['extraFreight', 0]
        ], $request, true);
        $expPrice          = 0;  //邮费费用
        $expressId         = 0; //快递ID
        $siteExpCommission = 0;//分站佣金费用
        //检测数据
        $sitePro = (new SiteProduct)->getItem($proId);
        if ($sitePro['count'] <= 0 || count($orderAr) > $sitePro['count']) {
            return app('json')->fail("订单产品数量不足，请重新选择！");
        }
        //判断仓库是否可以下单
        $warehouseIds = explode(',',$sitePro['warehouse_ids']);
        if(!in_array($warehouseId,$warehouseIds)) {
           return app('json')->fail("请重新选择产品！");
        }

        $warehouse = (new Warehouse)->where('id',$warehouseId)->find();
        if(empty($warehouse) || empty($warehouse['status'])) {
            return app('json')->fail("分仓已下架，请选择其他分仓");
        }
        $region = new Region;
        //检查地址数据
        foreach ($orderAr as $k => $v) {
            $rData = $region->getRegion($v['address']);
            if (empty($rData['province']) ||
                empty($rData['city']) ||
                empty($rData['area'])
            ) {
                //  return app('json')->fail('第' . (intval($k) + 1) .'行，'.$v['address'] .'地址信息有误，请重新检查省市区！');
            }
        }

        //订单总数
        $orderCount        = count($orderAr);
        $price             = $sitePro['price'] * $orderCount;
        $siteProCommission = $sitePro['price'] > $sitePro['commission'] ? ($sitePro['price'] - $sitePro['commission']) : 0;//分站佣金
        //快递信息
        $expCode = new ExpCost;
        $expCode->getExpCostData($request->site['sassid'], $request->user['levelid']);
        $expData = array_filter($expCode->getWareHouseExpCost($warehouseId, '*'), function ($item) use ($expId) {
            if ($item['id'] == $expId) {
                return true;
            }
        });
        //如果有快递信息，分析分账提成 || 用户推荐佣金
        if (!empty($expData)) {
            $expressId = $expData[0]['express_id'];
            $expPrice  = $expData[0]['money'];
            //分站金额
            $money             = $expCode->getSysExpCostPrice($expressId, $warehouseId, $request->site['sassid']);
            $siteExpCommission = empty($money) ? 0 : ($expPrice > $money ? ($expPrice - $money) : 0);
        }

        if (empty($expressId)) {
            return app('json')->fail("本次邮寄方式不存在，请重新选择邮寄方式。");
        }

        //获取低价
        $floorExp = $expCode
            ->where('warehouse_id', $warehouseId)
            ->where('express_id', $expressId)
            ->where('sassid', 0)
            ->where('level_id', -1)
            ->value('money');
        //会员店铺
        $shopAr = [];
        foreach ($orderAr as $v) {
            $shop_name = trim($v['shop_name']);
            if (!empty($shop_name)) {
                $shopAr[$shop_name] = ['name' => $shop_name];
            }
        }
        try {
            Order::beginTrans();
            $mShop = new MemberShop;
            foreach ($shopAr as $k => $v) {
                $shopId = $mShop->where('name', $k)
                    ->where('uid', $this->user['uid'])
                    ->value('id');
                if (empty($shopId)) $shopId = $mShop->insertGetId(['name' => $k, 'uid' => $this->user['uid']]);
                $shopAr[$k]['id'] = $shopId;
            }
            //下单
            $save['order_id']            = 'TF' . time() . sprintf('%04d', rand(0, 1000)) . $request->user['uid'];//订单号
            $save['all_price']           = $price + $expPrice * $orderCount + $extraFreight;//总金额 [价格 + 快递*产品数量]
            $save['pro_site_commission'] = $siteProCommission * $orderCount;//产品分站佣金
            $save['exp_site_commission'] = $siteExpCommission * $orderCount;//快递分站佣金
            $save['site_commission']     = $save['pro_site_commission'] + $save['exp_site_commission'];//分站提成
            $save['pro_id']              = $sitePro['id'];//产品ID
            $save['platform_id']         = $platformId;//来源[拼多多，淘宝]
            $save['warehouse_id']        = $warehouseId;//仓库来源
            $save['status']              = 0;//状态
            $save['time']                = time();
            $save['express_id']          = $expressId;//快递类型
            $save['sassid']              = $request->site['sassid'];//分站
            $save['mono']                = $mono;//备注
            $save['pro_price']           = $price;//产品价格
            $save['uid']                 = $request->user['uid'];
            $oId                         = (new Order)->insertGetId($save);

            foreach ($orderAr as $k => $v) {
                $shop_name                = trim($v['shop_name']);
                $d                        = [];
                $d['o_id']                = $oId;
                $d['in_order_id']         = $save['order_id'] . '-' . ($k + 1);
                $d['out_order_id']        = $v['out_order_id'];
                $d['name']                = $v['name'];
                $d['mobile']              = $v['mobile'];
                $d['address']             = $v['address'];
                $d['pro_price']           = $sitePro['price'];
                $d['pro_id']              = $sitePro['id'];
                $d['exp_id']              = $expressId;
                if(strstr($d['address'], '北京')){
                    $d['exp_price'] = $expPrice + $warehouse['beijing'];
                }else if(strstr($d['address'], '上海')){
                    $d['exp_price'] = $expPrice + $warehouse['shanghai'];
                }else if(strstr($d['address'], '青海')){
                    $d['exp_price'] = $expPrice + $warehouse['qinghai'];
                }else{
                    $d['exp_price'] = $expPrice;
                }
                $d['money']               = $sitePro['price'] + $d['exp_price'];
                $d['sassid']              = $request->site['sassid'];
                $d['uid']                 = $request->user['uid'];
                $d['time']                = time();
                $d['platform_id']         = $platformId;
                $d['warehouse_id']        = $warehouseId;
                $d['pro_site_commission'] = $siteProCommission;
                $d['exp_site_commission'] = $siteExpCommission;
                $d['site_commission']     = $siteProCommission + $siteExpCommission;
                $d['exp_floor_price']     = empty($floorExp) ? 0 : $floorExp;
                $d['shop_id']             = empty($shop_name) ? 0 : $shopAr[$shop_name]['id'];
                (new OrderInfo)->insert($d);
            }
            Order::commitTrans();
        } catch (DbException $db) {
            Order::rollbackTrans();
            return app('json')->fail("下单失败，理由:" . $db->getMessage());
        }
        return app('json')->success([
            'order_id' => $save['order_id'],
            'price'    => $save['all_price'],
        ]);
    }


    /**
     * 获取支单独单号
     * @param Request $request
     */
    public function getPayOrder(Request $request)
    {
        [$orderId] = UtilService::getMore([
            ['order_id', '', 'empty', '参数错误'],
        ], $request, true);
        $data = Order::where('order_id', $orderId)->find();
        if (empty($data)) {
            return app('json')->fail('找不到订单信息');
        }
        //订单已付款
        if (!empty($data['is_pay'])) {
            return app('json')->fail('订单已经支付成功');
        }
        $orderCount = (new OrderInfo)->where('o_id', $data['id'])->count();
        $sitePro    = (new SiteProduct)->getProItem($data['pro_id']);
        if ($sitePro['count'] <= 0 || $orderCount > $sitePro['count']) {
            return app('json')->fail("订单产品数量不足，请重新选择！");
        }
        $post               = [];
        $post['order_id']   = $orderId;
        $post['count']      = $orderCount;
        $post['title']      = $sitePro['title'];
        $post['img']        = $sitePro['img'];
        $post['all_price']  = $data['all_price'];
        $post['user_money'] = $request->user['money'];
        return app('json')->success($post);
    }

    /**
     * 余额支付
     * @param Request $request
     */
    public function balancePay(Request $request)
    {
        [$orderId] = UtilService::getMore([
            ['order_id', '', 'empty', '参数错误'],
        ], $request, true);
        $data = Order::where('order_id', $orderId)->find();
        if (empty($data)) {
            return app('json')->fail('找不到订单信息');
        }
        if (empty($data)) {
            return app('json')->fail('找不到订单信息');
        }

        //订单已付款
        if (!empty($data['is_pay'])) {
            return app('json')->fail('订单已经支付成功');
        }

        if ($data['all_price'] > $request->user['money']) {
            return app('json')->fail('余额不足！');
        }

        $infoCount = OrderInfo::where('o_id', $data['id'])->count();

        //平台分佣
        if ($request->site['tj_sassid'] > 0) {
            (new ExpCost)
                ->difference($request->site, [
                    'count'        => $infoCount,
                    'user'         => $request->user['mobile'],
                    'money'        => $data['site_commission'],
                    'warehouse_id' => $data['warehouse_id'],
                    'express_id'   => $data['express_id'],
                    'sassid'       => $request->site['tj_sassid'],
                    'orderid'      => $orderId,
                ]);
        }
        $bool = (new MemberDetail)->consumption($data['all_price'], $request->user['uid'], [
            'name'     => $request->user['mobile'],
            'order_id' => $orderId,
            'allmoney' => $data['all_price'],
            'money'    => $data['all_price'],
        ], $request->site['sassid']);
        //提交数据
        if ($bool) {
            //判断是否有推荐人
            if ($request->user['i_uid'] > 0) {
                //每单提成
                $money = $infoCount * 0.05;
                (new MemberDetail)->income(
                    $money,
                    $request->user['i_uid'],
                    ['user' => $request->user['mobile'], 'order_id' => $orderId, 'count' => $infoCount, 'money' => $money],
                    $request->site['sassid']
                );
            }
            //减库存
            (new Product)->where('id', $data['pro_id'])->dec('count', $infoCount)->inc('sales', $infoCount)->update();
            //改状态
            Order::where('order_id', $orderId)->save([
                'is_pay'   => 1,
                'pay_time' => time(),
                'status'   => 1,
            ]);
            //修改子订单数据
            OrderInfo::where('o_id', $data['id'])->save([
                'status' => 1,
            ]);

            //设置维护人
            $last_con_time = (new Member)->where('uid', $request->user['uid'])->value('last_con_time');
            if($last_con_time == 0){
                $follow = (new MemberFollow)->where('uid', $request->user['uid'])->where('admin_id', 99)->find();
                if($follow){
                    (new Member)->where('uid', $request->user['uid'])->save(['admin_id' => 99]);
                }else{
                    (new Member)->where('uid', $request->user['uid'])->save(['admin_id' => 100]);
                }
            }
            (new Member)->where('uid', $request->user['uid'])->save(['last_con_time' => time()]);

            //平台佣金
            if ($data['site_commission'] > 0) {
                (new SiteDetail)->commission($data['site_commission'],
                    $request->site['sassid'],
                    $orderId,
                    ['user'      => $request->user['mobile'],
                     'pro_money' => $data['pro_site_commission'],
                     'exp_money' => $data['exp_site_commission'],
                     'order_id'  => $orderId,
                     'count'     => $infoCount,
                     'money'     => $data['site_commission'],
                    ]
                );
            }


            return app('json')->success(['msg' => '支付成功']);
        } else {
            return app('json')->fail('支付失败');
        }
    }

    /**
     * 获取订单数据
     * @param Request $request
     */
    public function getOrderList(Request $request)
    {
        $pageSize        = 50;
        $post            = UtilService::getMore(
            [
                ['page', 1],
                ['order_id', ''],
                ['mono', ''],
                ['platform_id', ''],
                ['data', []],
                ['orderType', ''],
                ['timeType', ''],
                ['shop_id', ''],
            ], $request
        );
        $where           = $post;
        $where['sassid'] = $request->site['sassid'];
        $where['uid']    = $request->user['uid'];
        $order           = new Order;
        list($pageCount, $data) = $order->getList($post['page'], $where, $pageSize, 'id desc');
        $result = UtilService::getParam([
            "id",
            ['time', 'time', 'date("Y-m-d H:i:s",$1)'],
            "order_id",
            "order_count",
            "all_price",
            "status",
            "platfrom_name",
            "pro_title",
            "pro_img",
            "mono",
            "err_msg",
        ], $data);
        foreach ($result as $k=>$v) {
            $imgAr =  explode(',',$v['pro_img']);
            $result[$k]['pro_img'] = empty($imgAr) ? '' : $imgAr[0];
        }
        return app('json')->success([
            'list'      => $result,
            'pageCount' => $pageCount,
            'pageSize'  => $pageSize,
            'page'      => $post['page'],
        ]);
    }

    /**
     * 订单列表-初始化数据
     * @param Request $request
     */
    public function orderInit(Request $request)
    {
        //总金额
        $total = (new Order)
            ->where('uid', $request->user['uid'])
            ->where('status', '>', 0)
            ->sum('all_price');
        //未支付
        $unpaid = (new Order)
            ->where('uid', $request->user['uid'])
            ->where('status', 0)
            ->count();
        //打单中
        $inOrder = (new Order)
            ->where('uid', $request->user['uid'])
            ->where('status', 1)
            ->count();
        //已出单
        $sendOrder = (new Order)
            ->where('uid', $request->user['uid'])
            ->where('status', 2)
            ->count();
        //异常订单
        $abnormalOrder = (new Order)
            ->where('uid', $request->user['uid'])
            ->where('status', 9)
            ->count();
        //取消订单
        $cancelOrder = (new Order)
            ->where('uid', $request->user['uid'])
            ->where('status', -1)
            ->count();
        //退货订单
        $refundOrder = (new Order)
            ->where('uid', $request->user['uid'])
            ->where('status', -2)
            ->count();
        //子订单
        $subOrder = (new OrderInfo)
            ->where('uid', $request->user['uid'])
            ->where('status', '>', 0)
            ->count();
        //
        return app('json')->success([
            'total'         => $total,
            'unpaid'        => $unpaid,
            'inorder'       => $inOrder,
            'sendOrder'     => $sendOrder,
            'abnormalOrder' => $abnormalOrder,
            'cancelOrder'   => $cancelOrder,
            'refundOrder'   => $refundOrder,
            'subOrder'      => $subOrder,
        ]);
    }

    /**
     * 取消订单
     * @param Request $request
     */
    public function cancelOrder(Request $request)
    {
        $post  = UtilService::getMore(
            [
                ['id', '', 'empty', '参数错误'],
            ], $request
        );
        $order = new Order;
        $data  = $order
            ->where('sassid', $request->site['sassid'])
            ->where('uid', $request->user['uid'])
            ->where('id', $post['id'])
            ->find();
        if (empty($data)) {
            return app('json')->fail('找不到订单信息');
        }
        //订单状态
        if ($data['status'] != 0) {
            return app('json')->fail('当前订单无法取消');
        }
        $order->where('id', $data['id'])->save([
            'status' => -1,
        ]);
        (new OrderInfo())->where('o_id', $data['id'])->save(['status' => -1]);
        return app('json')->success(['msg' => '取消成功']);
    }

    /**
     * 子订单数据
     * @param Request $request
     */
    public function orderSubItem(Request $request)
    {
        $pageSize        = 20;
        $post            = UtilService::getMore(
            [
                ['id', ''],
                ['page', 1],
                ['order_id', ''],
                ['mobile', ''],
                ['name', ''],
                ['shop_id', ''],
            ], $request
        );
        $where           = $post;
        $where['sassid'] = $request->site['sassid'];
        $where['id']     = $post['id'];
        $where['uid']    = $request->user['uid'];
        list($pageCount, $data) = (new OrderInfo)->getList($post['page'], $where, $pageSize, "*", "id desc");
        $result = UtilService::getParam([
            "id",
            "exp_name",
            "order_id",
            "out_order_id",
            "name",
            "mobile",
            "address",
            "mono",
            "shop_name",
            "time",
            "send_time",
            "exp_number",
            "msg_err",
            "money",
            "status",
            ['_send_time', 'send_time', 'date("Y-m-d H:i:s",$1)']
        ], $data);
        return app('json')->success([
            'list'      => $result,
            'pageCount' => $pageCount,
            'pageSize'  => $pageSize,
            'page'      => $post['page'],
        ]);
    }

    /**
     * 导出数据
     * @param Request $request
     */
    public function orderDown(Request $request)
    {
        $region          = new Region;
        $post            = UtilService::getMore([
            ['id', '', 'empty', '参数错误'],
            ['shop_id', ''],
        ], $request);
        $where           = [];
        $where['sassid'] = $request->site['sassid'];
        $where['uid']    = $request->user['uid'];
        $where['id']     = $post['id'];
        if (!empty($post['shop_id'])) $where['shop_id'] = $post['shop_id'];
        $data = (new OrderInfo)->getAllList($where, 'id desc');
        $tAr  = [];
        foreach ($data as $v) {
            $d                  = [];
            $d['name']          = $v['name'];
            $d['mobile']        = $v['mobile'];
            $d['out_order_id']  = $v['out_order_id'];
            $d['address']       = $v['address'];
            $d['exp_name']      = $v['exp_name'];
            $d['exp_number']    = $v['exp_number'];
            $d['platform_name'] = $v['platform_name'];
            $d['pro_name']      = $v['pro_name'];
            $d['send_time']     = $v['send_time'] <= 0 ? '' : date('Y-m-d H:i:s', $v['send_time']);
            //  $v['address'] = '贵州省 贵阳市 观山湖区 世纪城社区服务中心福建街世纪城龙耀苑10栋12楼(000000)';
            $rData          = $region->getRegion($v['address']);
            $d['address']   = $rData['address'];
            $d['province']  = $rData['province'];
            $d['shop_name'] = $v['shop_name'];
            $d['city']      = $rData['city'];
            $d['area']      = $rData['area'];
            $tAr[]          = $d;
        }
        return app('json')->success($tAr);
    }


    /**
     * 升级显示
     * @param Request $request
     */
    public function rechargeXinit(Request $request)
    {
        $inAr      = [
            ['name' => '30元', 'v' => 30, 'upname' => ''],
            ['name' => '10000元', 'v' => 10000, 'upname' => ''],
        ];
        $siteLevel = (new SiteLevel)
            ->field("sl.update_money,l.name")
            ->alias("sl")
            ->join("member_level l", "l.id = sl.level_id")
            ->where('sl.sass_id', $request->site['sassid'])
            ->select();


        foreach ($siteLevel as $v) {
            if (!empty($v['update_money']) && $v['update_money'] > 0) {
                $update_money = floatval($v['update_money']);
                $len          = 0;
                $isAdd        = false;
                foreach ($inAr as $kk => $vv) {
                    $val = floatval($vv['v']);
                    if ($update_money > $val) {
                        $len   = $kk;
                        $isAdd = true;
                    }
                    if ($update_money == $val) {
                        $len   = $kk;
                        $isAdd = false;
                        break;
                    }
                }
                if ($isAdd) {
                    array_splice($inAr, $len, 0, [[
                        'name'   => $v['update_money'] . '元',
                        'v'      => $update_money,
                        'upname' => $v['name'],
                    ]]);
                } else {
                    $inAr[$len]['upname'] = $v['name'];
                }
            }
        }
        //排序
        $flag = [];
        foreach ($inAr as $v){
            $flag[] = $v['v'];
        }
        array_multisort($flag,SORT_ASC,$inAr);



        return app('json')->success($inAr);
    }


    /**
     * 充值
     * @param Request $request
     */
    public function rechargeX(Request $request)
    {
        $post = UtilService::getMore([
            ['v', '0', 'empty', '请选择充值金额'],
        ], $request);
        //充值
        try {
            Recharge::beginTrans();
            $recharge      = new Recharge();
            $d             = [];
            $d['order_id'] = 'RE' . time() . sprintf('%04d', rand(0, 1000)) . $request->user['uid'];
            $d['v']        = $post['v'];
            $d['status']   = '0';
            $d['time']     = time();
            $d['sassid']   = $request->site['sassid'];
            $d['uid']      = $request->user['uid'];
            $recharge->insert($d);
            //生成支付凭证
            (new PayTrade)->mkTrade([
                'out_trade_no' => $d['order_id'],
                'uid'          => $request->user['uid'],
                'tag'          => 'alipay',
                'type'         => 'recharge',
                'money'        => $post['v'],
                'content'      => '会员充值' . $d['v'] . '元',
                'sassid'       => $request->site['sassid'],
            ]);
            Recharge::commitTrans();
            $url = config('app.API_URL') . '/api/ott/alipay?order_id=' . $d['order_id'];
            return app('json')->success(['url' => $url, 'orderId' => $d['order_id']]);
        } catch (DbException $db) {
            Recharge::rollbackTrans();
            return app('json')->fail("充值失败，请联系客服人员");
        }
    }

    /**
     * 检查充值
     * @param Request $request
     */
    public function checkRecharge(Request $request)
    {
        $post     = UtilService::getMore([
            ['order_id', '0', 'empty', '订单不存在'],
        ], $request);
        $recharge = new Recharge();
        $data     = $recharge->where('order_id', $post['order_id'])->find();
        if (empty($data)) {
            return app('json')->fail('无充值订单');
        }

        if (empty($data['status'])) {
            return app('json')->fail('');
        }
        return app('json')->success(['data' => $data]);
    }

    /**
     * 资金情况
     * @param Request $request
     */
    public function rechargeInit(Request $request)
    {
        $info = [
            'money'    => $request->user['money'],
            'tx_money' => $request->user['tx_money'],//提现金额
            'in_money' => (new Tx)->where('uid', $request->user['uid'])->where('is_type', 0)->sum('money'),
        ];
        return app('json')->success($info);
    }


    /**
     * 提现列表
     * @param Request $request
     */
    public function txList(Request $request)
    {
        $pageSize        = 10;
        $post            = UtilService::getMore(
            [
                ['page', 1],
            ], $request
        );
        $where['sassid'] = $request->site['sassid'];
        $where['uid']    = $request->user['uid'];
        $tx              = new Tx();
        list($pageCount, $data) = $tx->getList($post['page'], $where, $pageSize, "*", "time desc");
        $result = UtilService::getParam([
            "id",
            "money",
            "bank",
            'name',
            'code',
            "is_type",
            ["time", "time", "date('Y-m-d H:i:s',$1)"],
        ], $data);
        return app('json')->success([
            'list'      => $result,
            'pageCount' => $pageCount,
            'pageSize'  => $pageSize,
            'page'      => $post['page'],
        ]);
    }

    /**
     * 操作明细
     * @param Request $request
     */
    public function detailList(Request $request)
    {
        $pageSize        = 10;
        $post            = UtilService::getMore(
            [
                ['page', 1],
                ['tabType', 'all'],
            ], $request
        );
        $where['sassid'] = $request->site['sassid'];
        $where['uid']    = $request->user['uid'];
        if (!empty($post['tabType']) && $post['tabType'] != 'all') {
            $where['code'] = $post['tabType'];
        }
        $detail = new MemberDetail();
        list($pageCount, $data) = $detail->getList($post['page'], $where, $pageSize, "*", "time desc");
        $result = UtilService::getParam([
            "id",
            "code",
            "v",
            'title',
            'content',
            "type",
            ["time", "time", "date('Y-m-d H:i:s',$1)"],
        ], $data);
        return app('json')->success([
            'list'      => $result,
            'pageCount' => $pageCount,
            'pageSize'  => $pageSize,
            'page'      => $post['page'],
        ]);
    }

    /**
     * 我要提现
     * @param Request $request
     */
    public function subTx(Request $request)
    {
        $post = UtilService::getMore(
            [
                ['bank', "", "empty", "请输入到账账号"],
                ['money', '0', "empty", "请输入提现金额"],
                ['name', '', 'empty', '请输入真实姓名'],
            ], $request
        );
        //提现金额
        if ($request->user['tx_money'] < $post['money']) {
            return app('json')->fail("余额不足，无法提现！");
        }
        (new Tx)
            ->insert([
                'uid'     => $request->user['uid'],
                'money'   => $post['money'],
                'bank'    => '支付宝',
                'name'    => $post['name'],
                'code'    => $post['bank'],
                'time'    => time(),
                'is_type' => 0,
                'sassid'  => $request->site['sassid'],
            ]);

        return app('json')->success(
            '提现成功，请等待打款！'
        );
    }

    /**
     * 订单详情数据
     * @param Request $request
     */
    public function orderInfoItem(Request $request)
    {
        $post      = UtilService::getMore(
            [
                ['id', "", "empty", "参数错误"],
            ], $request
        );
        $orderInfo = (new OrderInfo())->getItem($post['id']);
        if (empty($orderInfo)) {
            return app('json')->fail('找不到订单数据');
        }

        return app('json')->success([
            'id'           => $orderInfo['id'],
            'out_order_id' => $orderInfo['out_order_id'],
            'exp_name'     => $orderInfo['exp_name'],
            'exp_number'   => $orderInfo['exp_number'],
            'pro_name'     => $orderInfo['pro_title'],
            "mono"         => $orderInfo['mono'],
        ]);
    }

    /*
     * 问题件反馈
     */
    public function subOrderInfoMono(Request $request)
    {
        $post      = UtilService::getMore(
            [
                ['id', "", "empty", "参数错误"],
                ['mono', ""],
            ], $request
        );
        $orderInfo = (new OrderInfo())->getItem($post['id']);
        if (empty($orderInfo)) {
            return app('json')->fail('找不到订单数据');
        }
        (new OrderInfo)->where('id', $orderInfo['id'])->save([
            'mono' => $post['mono'],
        ]);
        $data = (new OrderInfoAsw)
            ->where('o_id', $orderInfo['o_id'])
            ->where('of_id', $orderInfo['id'])
            ->where('status', 0)
            ->find();
        if (!empty($data)) {
            (new OrderInfoAsw)->Where('id', $data['id'])->save(['mono' => $post['mono']]);
        } else {
            (new OrderInfoAsw)->insert([
                'o_id'   => $orderInfo['o_id'],
                'of_id'  => $orderInfo['id'],
                'mono'   => $post['mono'],
                'time'   => time(),
                'status' => 0,
            ]);
        }
        return app('json')->success('反馈成功');
    }

    /**
     * 底单申请
     * @param Request $request
     */
    public function subOrderDdInfo(Request $request)
    {
        $post      = UtilService::getMore(
            [
                ['id', "", "empty", "参数错误"],
                ['mono', ""],
            ], $request
        );
        $orderInfo = (new OrderInfo())->getItem($post['id']);
        if (empty($orderInfo)) {
            return app('json')->fail('找不到订单数据');
        }

        $count = (new OrderInfoDd)
            ->where('o_id', $orderInfo['o_id'])
            ->where('of_id', $orderInfo['id'])
            ->count();
        if ($count > 0) {
            return app('json')->fail('已提交申请，请勿重复提交');
        }
        (new OrderInfoDd)->insert([
            'o_id'   => $orderInfo['o_id'],
            'of_id'  => $orderInfo['id'],
            'mono'   => $post['mono'],
            'time'   => time(),
            'sassid' => $request->site['sassid'],
            'uid'    => $request->user['uid'],
            'status' => 0,
        ]);
        return app('json')->success('反馈成功');
    }

    /**
     * 问题反馈列表
     * @param Request $request
     */
    public function orderMonoList(Request $request)
    {
        $pageSize        = 10;
        $post            = UtilService::getMore(
            [
                ['page', 1],
                ['exp_number', ''],
                ['id', ''],
                ['date', ["", ""]],
                ['mobile', ''],
                ['name', ''],
                ['orderType', ''],
                ['out_order_id', ''],
                ['status', ''],
                ['timeType', ''],
            ], $request
        );
        $where           = $post;
        $where['sassid'] = $request->site['sassid'];
        $where['uid']    = $request->user['uid'];
        $tx              = new OrderInfoAsw();
        list($pageCount, $data) = $tx->getList($post['page'], $where, $pageSize, "*");
        $result = UtilService::getParam([
            "id",
            "o_id",
            "mono",
            "status",
            "cl_time",
            "cl_admin_time",
            "out_order_id",
            "name",
            "mobile",
            "address",
            "time",
            "send_time",
            "exp_number",
            'msg_mono',
            "exp_name",
        ], $data);
        return app('json')->success([
            'list'      => $result,
            'pageCount' => $pageCount,
            'pageSize'  => $pageSize,
            'page'      => $post['page'],
        ]);
    }

    /**
     * 订单撤销数据
     * @param Request $request
     */
    public function orderMonoCancel(Request $request)
    {
        $post = UtilService::getMore(
            [
                ['id', "", "empty", "参数错误"],
                ['mono', ""],
            ], $request
        );
        (new OrderInfoAsw)->where('id', $post['id'])->where('uid', $request->user['uid'])->delete();
        return app('json')->success('撤销成功');
    }

    /**
     * 底单申请
     * @param Request $request
     */
    public function orderDdList(Request $request)
    {
        $pageSize        = 10;
        $post            = UtilService::getMore(
            [
                ['page', 1],
                ['exp_number', ''],
                ['id', ''],
                ['date', ["", ""]],
                ['mobile', ''],
                ['name', ''],
                ['orderType', ''],
                ['out_order_id', ''],
                ['status', ''],
                ['timeType', ''],
            ], $request
        );
        $where           = $post;
        $where['sassid'] = $request->site['sassid'];
        $where['uid']    = $request->user['uid'];
        $tx              = new OrderInfoDd();
        list($pageCount, $data) = $tx->getList($post['page'], $where, $pageSize, "*");
        $result = UtilService::getParam([
            "id",
            "o_id",
            "mono",
            "status",
            "cl_time",
            "cl_admin_time",
            "out_order_id",
            "name",
            "mobile",
            "address",
            "time",
            "send_time",
            "exp_number",
            'msg_mono',
            "msg_img",
            "exp_name",
        ], $data);
        return app('json')->success([
            'list'      => $result,
            'pageCount' => $pageCount,
            'pageSize'  => $pageSize,
            'page'      => $post['page'],
        ]);
    }

    /**
     * 订单撤销数据
     * @param Request $request
     */
    public function orderDbCancel(Request $request)
    {
        $post = UtilService::getMore(
            [
                ['id', "", "empty", "参数错误"],
                ['mono', ""],
            ], $request
        );
        (new OrderInfoDd())->where('id', $post['id'])->where('uid', $request->user['uid'])->delete();
        return app('json')->success('撤销成功');
    }


    /**
     * 邀请好友返利
     * @param Request $request
     */
    public function extension(Request $request)
    {
        $uid   = $request->user['uid'];
        $mkuid = base64_encode(crypto_encrypt($uid, $request->site['secret_key']));
        $url   = '/login/reg?uid=' . $mkuid;
        $url2  = '/mobile/reg/step1?uid=' . $mkuid;
        $url3  = '/h5/pages/users/register/index?uid=' . $mkuid;
        return app('json')->success([
            'url'   => $url,
            'url2'  => $url2,
            'url3'  => $url3,
            'count' => (new Member)->where('i_uid', $request->user['uid'])->where('sassid', $request->site['sassid'])->count(),
        ]);
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function extensionList(Request $request)
    {
        $pageSize        = 10;
        $post            = UtilService::getMore(
            [
                ['page', 1],
            ], $request
        );
        $where['sassid'] = $request->site['sassid'];
        $where['i_uid']  = $request->user['uid'];
        $member          = new Member;
        list($pageCount, $data) = $member->getList($post['page'], $where, $pageSize, "*");
        $result = UtilService::getParam([
            "uid",
            "mobile",
            ['regtime', 'regtime', 'date(\'Y-m-d H:i:s\',$1)'],
            'order_count',
            'lavel_name',
        ], $data);
        return app('json')->success([
            'list'      => $result,
            'pageCount' => $pageCount,
            'pageSize'  => $pageSize,
            'page'      => $post['page'],
        ]);
    }


    /**
     * 修改账号
     * @param Request $request
     */
    public function account(Request $request)
    {
        $post = UtilService::getMore(
            [
                ['nickname', ''],
                ['avatar', ''],
            ], $request
        );
        $m    = (new Member);
        $m->where('uid', $request->user['uid'])->save(['nickname' => $post['nickname'], 'avatar' => $post['avatar']]);
        return app('json')->success('修改成功');
    }


    /**
     * 修改密码
     * @param Request $request
     */
    public function password(Request $request)
    {
        $post = UtilService::getMore(
            [
                ['oldpass', '', 'empty', '请输入旧密码'],
                ['password', '', 'empty', '请输入新密码'],
            ], $request
        );

        if ($request->user['password'] != md5($post['password'])) {
            return app('json')->fail('旧密码错误，请检查之后在修改');
        }
        (new Member)->where('uid', $request->user['uid'])->save(['password' => md5($post['password'])]);
        return app('json')->success('修改成功');
    }

    /**
     * 绑定公众号
     * @param Request $request
     */
    public function bind(Request $request)
    {
        $token  = base64_encode(crypto_encrypt($request->user['uid'] . "|" . time(), 'md5_user_token'));
        $url    = \config('app')['API_URL']
            . '/api/bind/system_bind?token=' . $token . '&secret_key=' . $request->site['secret_key'];
        $wxPush = (new  WeixinPushUser)
            ->field("avatar,nickname")
            ->where('sassid', $request->site['sassid'])
            ->where('uid', $request->user['uid'])
            ->find();

        $result           = [];
        $result['url']    = $url;
        $result['isbind'] = empty($wxPush) ? false : true;
        $result['bind']   = $wxPush;
        return app('json')->success($result);
    }

    /**
     * 取消绑定
     * @param Request $request
     */
    public function delbind(Request $request)
    {
        (new WeixinPushUser)->where('uid', $request->user['uid'])->where('sassid', $request->site['sassid'])->delete();
        return app('json')->success('取消成功');
    }

    /**
     * vip
     * @param Request $request
     */
    public function vip(Request $request)
    {
        $wData    = (new Warehouse)->select()->toArray();
        $level    = (new \app\model\admin\MemberLevel)
            ->field("ml.*,(select update_money from table_site_level where level_id = ml.id and sass_id = " . $request->site['sassid'] . " ) as update_money")
            ->alias("ml")
            ->where('ml.is_show', 1)
            ->select()
            ->toArray();
        $levelIds = array_column($level, 'id');
        $expCost  = new ExpCost;
        $tAr      = [];
        foreach ($wData as $v) {
            $d         = [];
            $eAr       = [];
            $d['name'] = $v['name'];
            $d['id']   = $v['id'];
            $d['data'] = [];
            $exData    = $expCost
                ->field("ec.money,e.title,ec.level_id,ec.express_id")
                ->alias("ec")
                ->join('express e', 'e.id = ec.express_id')
                ->where('ec.warehouse_id', $v['id'])
                ->whereIn('ec.level_id', $levelIds)
                ->where('sassid', $request->site['sassid'])
                ->select();
            foreach ($exData as $vv) {
                $key = 'level_' . $vv['level_id'];
                if (empty($d[$key])) {
                    $d[$key] = $vv['money'];
                } else {
                    $d[$key] = $d[$key] > $vv['money'] ? $vv['money'] : $d[$key];
                }

                if (empty($eAr[$vv['express_id']])) $eAr[$vv['express_id']] = ['title' => $vv['title']];
                $eAr[$vv['express_id']][$key] = $vv['money'];
            }
            //处理数据
            foreach ($eAr as $vv) {
                $d['data'][] = $vv;
            }
            if (count($exData) > 0) $tAr[] = $d;
        }
        return app('json')->success(['data' => $tAr, 'level' => $level]);
    }

    /**
     * 店铺信息
     * @param Request $request
     */
    public function shop(Request $request)
    {
        return app('json')
            ->success((new MemberShop)
                ->where('uid', $this->user['uid'])
                ->select()
                ->toArray()
            );
    }

    /**
     * 删除店铺
     * @param Request $request
     */
    public function shopDel(Request $request)
    {
        [$id] = UtilService::getMore(
            [
                ['id', '', 'empty', '参数错误'],
            ]
            , $request, true);
        (new MemberShop)
            ->where('uid', $this->user['uid'])
            ->where('id', $id)->delete();
        return app('json')->fail('删除成功');
    }

}
