<?php

namespace app\admin\controller\store;

use app\admin\controller\AuthController;
use app\admin\model\order\StoreOrder as StoreOrderModel;
use app\admin\model\order\StoreOrderStatus;
use app\admin\model\system\ShippingTemplates;
use app\admin\model\system\SystemStore;
use app\models\store\StoreBargainUser;
use app\models\store\StoreBargainUserHelp;
use app\models\store\StoreCart;
use app\models\store\StoreCouponUser;
use app\models\store\StoreOrder;
use app\models\store\StorePink;
use app\models\system\CardInfo;
use app\models\system\SystemStoreMember;
use app\models\system\SystemStoreStock;
use app\models\user\User;
use app\models\user\UserAddress;
use app\models\user\UserLevel;
use app\Request;
use crmeb\repositories\OrderRepository;
use think\facade\Route as Url;
use crmeb\services\{FormBuilder, UtilService as Util, JsonService as Json, UtilService};
use app\admin\model\store\StoreProductAttrValue;

/**
 *
 * Class Placeorder
 * @package app\admin\controller\store
 */
class Placeorder extends AuthController
{

    /**
     * 购物车 列表
     * @param Request $request
     * @return mixed
     */
    public function lst()
    {
        return app('json')->successful(StoreCart::getUserProductCartList($this->request->get('uid'), '', 0, $this->adminInfo['store_id']));
    }

    /**
     * 下单
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $store = [];
        if ($this->adminInfo['type'] == 0) {
            $store = SystemStore::where('is_del', 0)->where('is_show', 1)->field('id,name')->select()->toArray();
        } else {
            $store = SystemStore::where('id', $this->adminInfo['store_id'])->field('id,name')->select();
        }
        $this->assign('store', $store);
        $this->assign('type', $this->adminInfo['type']);
        return $this->fetch();
    }

    /**
     * 获取会员卡
     * @param $card_no
     */
    public function getCardNo($card_no)
    {
        if ($card_no == '') return app('json')->fail('会员码不能为空');
        if (intval($card_no) == 1) {
            $info['user'] = User::where('uid', $card_no)->field("uid,real_name,addres , phone, '' as nickname, now_money,integral")->find();
            $info['uid'] = $info['user']['uid'];
            return app('json')->successful($info);
        }
        if (strlen($card_no) == 15) {
            $info = CardInfo::where(['type' => 1, 'card_number' => $card_no])->find();
            if (!$info) return app('json')->fail('充值卡号不存在');
            if ($info['use_uid'] == 0) return app('json')->fail('充值卡未激活');
            $info['user'] = User::where('uid', $info['use_uid'])->field('uid,real_name,addres,phone,nickname,now_money,integral')->find();
            $info['uid'] = $info['user']['uid'];
            return app('json')->successful($info);
        }
        if (strlen($card_no) == 8 || strlen($card_no) == 11) {
            if (!User::where('SN|phone', $card_no)->find()) return app('json')->fail('会员码不存在');
            $info['user'] = User::where('SN|phone', $card_no)->field('uid,real_name,addres,phone,nickname,now_money,integral')->find();
            $info['uid'] = $info['user']['uid'];
        } else {
            if (!SystemStoreMember::be(['card_no' => $card_no])) return app('json')->fail('会员码不存在');
            $info = SystemStoreMember::where('card_no', $card_no)->find()->toArray();
            $info['user'] = User::where('uid', $info['uid'])->field('real_name,addres,phone,nickname,now_money,integral')->find();
        }
        return app('json')->successful($info);
    }

    /**
     * 获取条形码商品
     * @param string $bar_code
     * @return array|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getBarCode($bar_code = '')
    {
        if ($bar_code == '') return $this->failed('条形码不存在');
        $info = SystemStoreStock::alias('a')->join("StoreProduct b", "a.product_id=b.id", "left")->where('a.bar_code', $bar_code)->field('a.price,a.unique,a.in_stock,a.is_consumer,a.product_id,b.store_name,b.image')->find();
        if ($info) {
            $info = $info->toArray();
            $info['suk'] = StoreProductAttrValue::where('unique', $info['unique'])->value('suk');
        } else {
            $info = StoreProductAttrValue::alias('a')->join("StoreProduct b", "a.product_id=b.id", "left")->where('a.bar_code', $bar_code)->where('a.type', 0)->field('a.price,a.unique,0 as in_stock,b.is_consumer,a.product_id,b.store_name,b.image')->find();
            if ($info) {
                $info = $info->toArray();
            } else {
                $info = [];
            }
        }
        if ($info) {
            $product = \app\admin\model\store\StoreProduct::get($info['product_id']);
            $discounts = json_decode($product['time_area_discount'] ?: '[]', true);
            $discount = 0;
            if (count($discounts) > 0) {
                foreach ($discounts as $kk => $v) {
                    $times = explode('-', $kk);
                    if (!(count($times) == 2)) {
                        break;
                    }
                    $start = strtotime(date('Y-m-d') . $times[0]);
                    $end = strtotime(date('Y-m-d') . $times[1]);
                    if (time() > $start && time() <= $end) {
                        $discount = $v;
                    }
                }
            }
            if ($discount > 0) {
                $info['price'] = bcmul(bcdiv($discount, 100, 4), $info['price'], 2);
            }
        }
        return app('json')->successful($info);
    }

    /**
     * 增加购物车
     * @param $data
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add_cart()
    {
        list($productId, $cartNum, $uniqueId, $combinationId, $secKillId, $bargainId, $new, $uid) = UtilService::postMore([
            ['productId', 0],//普通产品编号
            ['cartNum', 1], //购物车数量
            ['uniqueId', ''],//属性唯一值
            ['combinationId', 0],//拼团产品编号
            ['secKillId', 0],//秒杀产品编号
            ['bargainId', 0],//砍价产品编号
            ['new', 1], // 1 加入购物车直接购买  0 加入购物车
            ['uid', 0],//用户编号
        ], $this->request, true);
        $request = $this->request;
        if (!$productId || !is_numeric($productId)) return app('json')->fail('参数错误');
        if ($bargainId && StoreBargainUserHelp::getSurplusPrice($bargainId, $uid)) return app('json')->fail('请先砍价');
        $res = StoreCart::setCart($uid, $productId, $cartNum, $uniqueId, 'product', $new, $combinationId, $secKillId, $bargainId, 0, $this->adminInfo['store_id']);
        if (!$res) return app('json')->fail(StoreCart::getErrorInfo());
        else  return app('json')->successful('ok', ['cartId' => $res->id]);
    }

    /**
     * 清空购物车
     * @return mixed
     * @throws \Exception
     */
    public function clear_cart()
    {
        list($uid) = UtilService::postMore([
            ['uid', 0],//用户编号
        ], $this->request, true);
        $is_pay = 0;
        $store_id = $this->adminInfo['store_id'];
        StoreCart::where(compact('uid', 'is_pay', 'store_id'))->delete();
        return app('json')->successful('清空完成!');
    }

    /**
     * 购物车 删除产品
     * @param Request $request
     * @return mixed
     */
    public function del(Request $request)
    {
        list($ids, $uid) = UtilService::postMore([
            ['ids', []],//购物车编号
            ['uid', 0],
        ], $request, true);
        if (!count($ids))
            return app('json')->fail('参数错误!');
        if (StoreCart::removeUserCart($uid, $ids))
            return app('json')->successful();
        return app('json')->fail('清除失败！');
    }

    /**
     * 购物车 修改产品数量
     * @param Request $request
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function num(Request $request)
    {
        list($id, $number, $uid) = UtilService::postMore([
            ['id', 0],//购物车编号
            ['number', 0],//购物车编号
            ['uid', 0],
        ], $request, true);
        if (!$id || !$number || !is_numeric($id) || !is_numeric($number)) return app('json')->fail('参数错误!');
        $res = StoreCart::changeUserCartNum($id, $number, $uid);
        if ($res) return app('json')->successful();
        else return app('json')->fail(StoreCart::getErrorInfo('修改失败'));
    }

    /**
     * 订单确认
     * @return mixed
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function confirm()
    {
        $request = $this->request;
        $temp = ShippingTemplates::get(1);
        if (!$temp) return app('json')->fail('默认模板未配置，无法下单');
        list($cartId) = UtilService::postMore(['cartId'], $request, true);
        if (!is_string($cartId) || !$cartId) return app('json')->fail('请提交购买的商品1');
        $uid = input('uid', 0);
        $cartGroup = StoreCart::getUserProductCartList($uid, $cartId, 1);
        if (count($cartGroup['invalid'])) return app('json')->fail($cartGroup['invalid'][0]['productInfo']['store_name'] . '已失效!');
        if (!$cartGroup['valid']) return app('json')->fail('请提交购买的商品2');
        $cartInfo = $cartGroup['valid'];
        $addr = UserAddress::where('uid', $uid)->where('is_default', 1)->find();
        $priceGroup = StoreOrder::getOrderPriceGroup($cartInfo, $addr);
        if ($priceGroup === false) {
            return app('json')->fail(StoreOrder::getErrorInfo('运费模板不存在'));
        }
        $other = [
            'offlinePostage' => sys_config('offline_postage'),
            'integralRatio' => sys_config('integral_ratio')
        ];
        $usableCoupons = StoreCouponUser::getUsableCouponList($uid, $cartGroup, $priceGroup['totalPrice']);
        $usableCoupon = isset($usableCoupons[0]) ? $usableCoupons[0] : null;
        $cartIdA = explode(',', $cartId);
        $seckill_id = 0;
        $combination_id = 0;
        $bargain_id = 0;
        if (count($cartIdA) == 1) {
            $seckill_id = StoreCart::where('id', $cartId)->value('seckill_id');
            $combination_id = StoreCart::where('id', $cartId)->value('combination_id');
            $bargain_id = StoreCart::where('id', $cartId)->value('bargain_id');
        }
        $data['deduction'] = $seckill_id || $combination_id || $bargain_id;
        $data['usableCoupon'] = $usableCoupon;
        $data['addressInfo'] = UserAddress::getUserDefaultAddress($uid);
        $data['seckill_id'] = $seckill_id;
        $data['combination_id'] = $combination_id;
        $data['bargain_id'] = $bargain_id;
        $data['cartInfo'] = $cartInfo;
        $data['priceGroup'] = $priceGroup;
        $data['orderKey'] = StoreOrder::cacheOrderInfo($uid, $cartInfo, $priceGroup, $other);
        $data['offlinePostage'] = $other['offlinePostage'];
        $vipId = UserLevel::getUserLevel($uid);
        $user = User::find($uid);
        if (isset($user['pwd'])) unset($user['pwd']);
        $user['vip'] = $vipId !== false ? true : false;
        if ($user['vip']) {
            $user['vip_id'] = $vipId;
            $user['discount'] = UserLevel::getUserLevelInfo($vipId, 'discount');
        }
        $data['userInfo'] = $user;
        $data['integralRatio'] = $other['integralRatio'];
        $data['offline_pay_status'] = (int)sys_config('offline_pay_status') ?? (int)2;
        $data['store_self_mention'] = (int)sys_config('store_self_mention') ?? 0;//门店自提是否开启
        $data['system_store'] = ($res = \app\models\system\SystemStore::getStoreDispose()) ? $res : [];//门店信息
        return app('json')->successful($data);
    }

    /**
     * 计算订单金额
     * @param Request $request
     * @param $key
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function computedOrder($key)
    {

        $request = $this->request;
        $uid = input('uid', 0);
        if (!$key) return app('json')->fail('参数错误!');
        if (StoreOrder::be(['order_id|unique' => $key, 'uid' => $uid, 'is_del' => 0]))
            return app('json')->status('extend_order', '订单已生成', ['orderId' => $key, 'key' => $key]);
        list($addressId, $couponId, $payType, $useIntegral, $mark, $combinationId, $pinkId, $seckill_id, $formId, $bargainId, $shipping_type) = UtilService::postMore([
            'addressId', 'couponId', ['payType', 'yue'], ['useIntegral', 0], 'mark', ['combinationId', 0], ['pinkId', 0], ['seckill_id', 0], ['formId', ''], ['bargainId', ''],
            ['shipping_type', 1],
        ], $request, true);
        $payType = strtolower($payType);
        if ($bargainId) {
            $bargainUserTableId = StoreBargainUser::getBargainUserTableId($bargainId, $uid);//TODO 获取用户参与砍价表编号
            if (!$bargainUserTableId)
                return app('json')->fail('砍价失败');
            $status = StoreBargainUser::getBargainUserStatusEnd($bargainUserTableId);
            if ($status == 3)
                return app('json')->fail('砍价已支付');
            StoreBargainUser::setBargainUserStatus($bargainId, $uid); //修改砍价状态
        }
        if ($pinkId) {
            $cache_pink = Cache::get(md5('store_pink_' . $pinkId));
            if ($cache_pink && bcsub($cache_pink['people'], $cache_pink['now_people'], 0) <= 0) {
                return app('json')->status('ORDER_EXIST', '订单生成失败，该团人员已满', ['orderId' => StoreOrder::getStoreIdPink($pinkId, $uid)]);
            }
            if (StorePink::getIsPinkUid($pinkId, $uid))
                return app('json')->status('ORDER_EXIST', '订单生成失败，你已经在该团内不能再参加了', ['orderId' => StoreOrder::getStoreIdPink($pinkId, $uid)]);
            if (StoreOrder::getIsOrderPink($pinkId, $uid))
                return app('json')->status('ORDER_EXIST', '订单生成失败，你已经参加该团了，请先支付订单', ['orderId' => StoreOrder::getStoreIdPink($pinkId, $uid)]);
        }
        $priceGroup = StoreOrder::cacheKeyCreateOrder($uid, $key, $addressId, $payType, (int)$useIntegral, $couponId, $mark, $combinationId, $pinkId, $seckill_id, $bargainId, true, 0, $shipping_type);
        if ($priceGroup)
            return app('json')->status('NONE', 'ok', $priceGroup);
        else
            return app('json')->fail(StoreOrder::getErrorInfo('计算失败'));
    }

    /**
     * 订单创建
     * @param Request $request
     * @param $key
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function create($key)
    {
        $request = $this->request;
        $uid = input('uid', 0);
        if (!$key) return app('json')->fail('参数错误!');
        if (StoreOrder::be(['order_id|unique' => $key, 'uid' => $uid, 'is_del' => 0]))
            return app('json')->status('extend_order', '订单已生成', ['orderId' => $key, 'key' => $key]);
        list($addressId, $couponId, $payType, $useIntegral, $mark, $combinationId, $pinkId, $seckill_id, $formId, $bargainId, $from, $shipping_type, $real_name, $phone, $storeId, $auth_code) = UtilService::postMore([
            'addressId', 'couponId', 'payType', ['useIntegral', 0], 'mark', ['combinationId', 0], ['pinkId', 0], ['seckill_id', 0], ['formId', ''], ['bargainId', ''], ['from', 'weixin'],
            ['shipping_type', 1], ['real_name', '散户'], ['phone', '18700010001'], ['store_id', 0], ['auth_code', ''],
        ], $request, true);
        if (empty($real_name)) $real_name = '散户';
        if (empty($phone)) $phone = '18700010001';
        $payType = strtolower($payType);
        if ($bargainId) {
            $bargainUserTableId = StoreBargainUser::getBargainUserTableId($bargainId, $uid);//TODO 获取用户参与砍价表编号
            if (!$bargainUserTableId)
                return app('json')->fail('砍价失败');
            $status = StoreBargainUser::getBargainUserStatusEnd($bargainUserTableId);
            if ($status == 3)
                return app('json')->fail('砍价已支付');
            StoreBargainUser::setBargainUserStatus($bargainId, $uid); //修改砍价状态
        }
        if ($pinkId) {
            $cache_pink = Cache::get(md5('store_pink_' . $pinkId));
            if ($cache_pink && bcsub($cache_pink['people'], $cache_pink['now_people'], 0) <= 0) {
                return app('json')->status('ORDER_EXIST', '订单生成失败，该团人员已满', ['orderId' => StoreOrder::getStoreIdPink($pinkId, $uid)]);
            }
            if (StorePink::getIsPinkUid($pinkId, $uid))
                return app('json')->status('ORDER_EXIST', '订单生成失败，你已经在该团内不能再参加了', ['orderId' => StoreOrder::getStoreIdPink($pinkId, $uid)]);
            if (StoreOrder::getIsOrderPink($pinkId, $uid))
                return app('json')->status('ORDER_EXIST', '订单生成失败，你已经参加该团了，请先支付订单', ['orderId' => StoreOrder::getStoreIdPink($pinkId, $uid)]);
        }
        $isChannel = 1;
        if ($from == 'weixin')
            $isChannel = 0;
        elseif ($from == 'weixinh5')
            $isChannel = 2;

        $order = StoreOrder::cacheKeyCreateOrder($uid, $key, $addressId, $payType, (int)$useIntegral, $couponId, $mark, $combinationId, $pinkId, $seckill_id, $bargainId, false, $isChannel, $shipping_type, $real_name, $phone, $storeId);
        if ($order === false) return app('json')->fail(StoreOrder::getErrorInfo('订单生成失败'));
        $orderId = $order['order_id'];
        $info = compact('orderId', 'key');
        if ($orderId) {
            event('OrderCreated', [$order]); //订单创建成功事件
//            event('ShortMssageSend', [$orderId, 'AdminPlaceAnOrder']);//发送管理员通知
            switch ($payType) {
                case "weixin":
                    $orderInfo = StoreOrder::where('order_id', $orderId)->find();
                    if (!$orderInfo || !isset($orderInfo['paid'])) return app('json')->fail('支付订单不存在!');
                    $orderInfo = $orderInfo->toArray();
                    if ($orderInfo['paid']) return app('json')->fail('支付已支付!');
                    //支付金额为0
                    if (bcsub((float)$orderInfo['pay_price'], 0, 2) <= 0) {
                        //创建订单jspay支付
                        $payPriceStatus = StoreOrder::jsPayPrice($orderId, $uid, $formId);
                        if ($payPriceStatus)//0元支付成功

                            return app('json')->status('success', '微信支付成功', $info);
                        else
                            return app('json')->status('pay_error', StoreOrder::getErrorInfo());
                    } else {
                        try {

                            $jsConfig = OrderRepository::barcodePay($orderId, $auth_code); //创建订单jspay

                        } catch (\Exception $e) {
                            return app('json')->status('pay_error', $e->getMessage(), $info);
                        }
                        $info['jsConfig'] = $jsConfig;
                        if ($from == 'weixinh5') {
                            return app('json')->status('wechat_h5_pay', '订单创建成功', $info);
                        } else {
                            return app('json')->status('wechat_pay', '订单创建成功', $info);
                        }
                    }
                    break;
                case 'yue':
                    if (StoreOrder::yuePay($orderId, $uid, $formId)) {
                        $orderInfo = StoreOrder::where('order_id', $orderId)->find();
                        $this->verify($orderInfo['id']);
                        return app('json')->status('success', '余额支付成功', $info);
                    } else {
                        $errorinfo = StoreOrder::getErrorInfo();
                        if (is_array($errorinfo))
                            return app('json')->status($errorinfo['status'], $errorinfo['msg'], $info);
                        else
                            return app('json')->status('pay_error', $errorinfo);
                    }
                    break;
                case 'offline':
                    $orderInfo = StoreOrder::where('order_id', $orderId)->find();
                    $this->offline($orderInfo['id']);
                    $this->verify($orderInfo['id']);
                    return app('json')->status('success', '订单创建成功', $info);
                    break;
                case 'jialie':
                    $orderInfo = StoreOrder::where('order_id', $orderId)->find();
                    if (!$orderInfo || !isset($orderInfo['paid'])) return app('json')->fail('支付订单不存在!');
                    $orderInfo = $orderInfo->toArray();
                    if ($orderInfo['paid']) return app('json')->fail('支付已支付!');
                    $rs = OrderRepository::jialiePay($orderId, $auth_code); //支付结果
                    if ($rs['ret_code'] == "00" && $rs['status'] == "2") {
                        $this->verify($orderInfo['id']);
                        StoreOrder::paySuccess($orderId, 'jialie');
                    } elseif ($rs['ret_code'] == "00" && $rs['status'] == 1) {
                        StoreOrder::edit(['jialie_do' => 1], $orderInfo['id']);
                    } else {
                        return app('json')->fail($rs['ret_msg']);
                    }
                    return app('json')->status('success', '订单创建成功', $info);
                    break;
            }
        } else return app('json')->fail(StoreOrder::getErrorInfo('订单生成失败!'));
    }

    public function verify($id)
    {
        StoreOrderModel::beginTrans();
        $orderInfo = StoreOrderModel::where('id', $id)->find();
        if ($orderInfo->combination_id && $orderInfo->pink_id) {
            $res = \app\admin\model\ump\StorePink::where('id', $orderInfo->pink_id)->where('status', '<>', 2)->count();
            if ($res) return Json::fail('拼团订单暂未成功无法核销！');
        }
        $orderInfo->status = 2;
        if ($orderInfo->save()) {
            OrderRepository::storeProductOrderTakeDeliveryAdmin($orderInfo);
            StoreOrderStatus::setStatus($orderInfo->id, 'take_delivery', '已核销');
            StoreOrderModel::commitTrans();
            return true;
        } else {
            StoreOrderModel::rollbackTrans();
            return false;
        }
    }

    /**
     * 立即支付
     * @param $id
     */
    public function offline($id)
    {
        $res = StoreOrderModel::updateOffline($id);
        if ($res) {
            event('StoreProductOrderOffline', [$id]);
            StoreOrderStatus::setStatus($id, 'offline', '线下付款');
            return true;
        } else {
            return false;
        }
    }

}

