<?php

namespace app\api\controller\v1;

use app\BaseController;
use app\model\api\ExpCost;
use app\model\api\MemberDetail;
use app\model\Api\MemberShop;
use app\model\api\Order as OrderModel;
use app\model\api\OrderInfo;
use app\model\api\Product;
use app\model\api\SiteProduct;
use app\model\api\UserAddress;
use app\model\api\Warehouse;
use app\model\system\ProductAttr;
use app\Request;
use library\services\UtilService;
use library\utils\Region;
use think\db\exception\DbException;
use think\facade\Db;

class Order extends BaseController
{
    /**
     * 获取产品信息
     */
    public function getProductInfo(Request $request){
        $where = UtilService::getMore([
            ['product_id', 0],
            ['unique', '']
        ], $request);
        $data = Db::name('ProductAttrValue')->where('product_id', $where['product_id'])->where('unique', $where['unique'])->find();
        if($data['price'] == '0.00'){
            $data['price'] = round($data['ot_price'] * 1.15, 2);
        }
        $data['store_name'] = Db::name('Product')->where('id', $where['product_id'])->value('store_name');
        return app('json')->success($data);
    }

    /**
     * 买样订单
     * @param Request $request
     */
    public function buyOrder(Request $request)
    {
        $data = UtilService::getMore([
            ['pro_id', '', 'empty', '参数错误'],
            ['unique', '', 'empty', '参数错误'],
            ['num', '', 'empty', '参数错误'],
            ['addressId', '', 'empty', '参数错误'],
            ['pro_price', 0],
            ['postage', 0],
            ['all_price', 0],
            ['mono', '']
        ], $request);
        try {
            OrderModel::beginTrans();
            $addressId = $data['addressId'];
            unset($data['addressId']);
            $data['order_id'] = 'TF' . time() . sprintf('%04d', rand(0, 1000)) . $request->user['uid']; //订单号
            $data['uid'] = $request->user['uid'];
            $data['time'] = time();
            $oId = OrderModel::insertGetId($data);
            $address = UserAddress::find($addressId);
            $save['o_id'] = $oId;
            $save['uid'] = $request->user['uid'];
            $save['name'] = $address['real_name'];
            $save['mobile'] = $address['phone'];
            $save['address'] = $address['province'] . $address['city'] . $address['district'] . $address['detail'];
            $save['money'] = $data['all_price'];
            $save['pro_price'] = $data['pro_price'];
            $save['pro_id'] = $data['pro_id'];
            $save['exp_price'] = $data['postage'];
            $save['time'] = time();
            OrderInfo::insert($save);
            OrderModel::commitTrans();
        } catch (DbException $db) {
            OrderModel::rollbackTrans();
            return app('json')->fail("下单失败，原因:" . $db->getMessage());
        }
        return app('json')->success([
            'order_id' => $data['order_id'],
            'price'    => $data['all_price']
        ]);
    }

    /**
     * 代发订单
     * @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 {
            \app\model\api\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 balancePay(Request $request)
    {
        [$orderId] = UtilService::getMore([
            ['order_id', '', 'empty', '参数错误'],
        ], $request, true);
        $order = OrderModel::where('order_id', $orderId)->find();
        if (empty($order)) {
            return app('json')->fail('找不到订单信息');
        }
        //订单已付款
        if (!empty($order['is_pay'])) {
            return app('json')->fail('订单已经支付成功');
        }
        if ($order['all_price'] > $request->user['money']) {
            return app('json')->fail('余额不足！');
        }

        $res = (new MemberDetail)->consumption($order['all_price'], $request->user['uid'], [
            'mobile'   => $request->user['mobile'],
            'order_id' => $orderId,
            'money'    => $order['all_price']
        ]);
        if ($res) {
            //减库存加销量
            (new Product)->where('id', $order['pro_id'])->dec('stock', $order['num'])->inc('sales', $order['num'])->update();
            Db::name('ProductAttrValue')->where('product_id', $order['pro_id'])->where('unique', $order['unique'])->dec('stock', $order['num'])->inc('sales', $order['num'])->update();
            //改订单状态
            OrderModel::where('order_id', $orderId)->save([
                'status'   => 1,
                'is_pay'   => 1,
                'pay_type' => 'yue',
                'pay_time' => time()
            ]);
            //改子订单状态
            OrderInfo::where('o_id', $order['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()]);*/

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