<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use Cookie;
use App\Http\Page;
use App\Http\Controllers\PermController;
use App\Http\Error;

Class AddOrderController extends Controller
{
	// 页面用户、菜单信息
    public function getPageInfo(Request $request)
    {
        $uri = '/' . $request->path();

        $username = $request->user->email;
        $useremail= $request->user->email;

        // 菜单
        $menuconfig = DB::table('config')->where('config_title', '订单系统')->first();
        $menus = [];
        if ($menuconfig && !($menus = json_decode($menuconfig->config_data)))
            $menus = [];

        $perm = new PermController;

        // 用户角色
        $role = $perm->getUserRole($request);

        // 获取权限菜单
        if ($role != 1) {
            $menus = $perm->getPermMenu($menus, $request->user->userId);   
        }

        $data = [
            'header'    => $request->user->header,
            'uri'       => $uri,
            'username'  => $username,
            'useremail' => $useremail,
            'menus'     => $menus,
        ];

        return $data;
    }

    // 新增联营订单
    public function addOrder(Request $request)
    {
        $info = $this->getPageInfo($request);

        $info['title'] = '新增联营订单';

        $info['sale_id'] = $request->user->userId;

        return view('addOrder', $info);
    }

    // 新增自营线上订单
    public function addOnline(Request $request)
    {
        $info = $this->getPageInfo($request);

        $info['title'] = '新增自营线上订单';

        $info['sale_id'] = $request->user->userId;

        return view('addOnline', $info);
    }

    // 获取用户信息
    public function getUserInfo(Request $request)
    {
        if ($request->isMethod('post')) {
            $mobile = $request->input('mobile');

            if (preg_match('/@/', $mobile)) {
                $user = DB::connection('order')->table('lie_user_main')->where('email', $mobile)->select('user_id', 'email', 'is_test')->first();
            } else {
                $user = DB::connection('order')->table('lie_user_main')->where('mobile', $mobile)->select('user_id', 'mobile', 'is_test')->first();
            }      

            if (!empty($user)) {
                // 收货地址
                $address = DB::connection('order')->table('lie_user_address')->where('user_id', $user->user_id)->get();

                // 发票信息
                $invoice = DB::connection('order')->table('lie_taxinfo')->where('user_id', $user->user_id)->get();
                
                $info['user'] = $user;
                $info['address'] = $address;
                $info['invoice'] = $invoice;
            }           

            if (isset($info)) {
                return ['errcode' => 0, 'errmsg' => '', 'data' => $info];
            } else {
                return ['errcode' => -1, 'errmsg' => '未找用户信息'];
            }
        }
    }

    // 选择收货地址
    public function selectAddr(Request $request)
    {
        if ($request->isMethod('post')) {
            $address_id = $request->input('address_id');

            $address = DB::connection('order')->table('lie_user_address')->where('address_id', $address_id)->first();

            $address->province_val = $this->getAddress($address->province);
            $address->city_val = $this->getAddress($address->city);
            $address->district_val = $this->getAddress($address->district);

            return ['errcode' => 0, 'errmsg' => '', 'data' => $address];
        }
    }

    // 选择发票信息
    public function selectInv(Request $request)
    {
        if ($request->isMethod('post')) {
            $tax_id = $request->input('tax_id');

            $invoice = DB::connection('order')->table('lie_taxinfo')->where('tax_id', $tax_id)->first();

            $invoice->province_val = $invoice->consignee_province ? $this->getAddress($invoice->consignee_province) : '';
            $invoice->city_val = $invoice->consignee_city ? $this->getAddress($invoice->consignee_city) : '';
            $invoice->district_val = $invoice->consignee_district ? $this->getAddress($invoice->consignee_district) : '';

            return ['errcode' => 0, 'errmsg' => '', 'data' => $invoice];
        }
    }

    // 根据发票类型选择发票信息
    public function selectInvType(Request $request)
    {
        if ($request->isMethod('post')) {
            $user_id = $request->input('user_id');
            $inv_type = $request->input('inv_type');

            if ($inv_type == 3) {
                $invoice = DB::connection('order')->table('lie_taxinfo')->where(['user_id' => $user_id, 'inv_type' => $inv_type])->get();
            } else {
                $invoice = DB::connection('order')->table('lie_taxinfo')->where('user_id', $user_id)->whereIn('inv_type', [2, 4])->get();
            }
            
            return ['errcode' => 0, 'errmsg' => '', 'data' => $invoice];
        }
    }

    // 获取可用优惠券
    public function getCoupon(Request $request)
    {
        if ($request->isMethod('post')) {        
            $data['uid'] = $request->input('uid');
            $data['order_goods_type'] = $request->input('goods_type');
            $data['cart_ids'] = $request->input('cart_ids');        

            $data['k1'] = time();
            $data['k2'] = md5(md5($data['k1']).'fh6y5t4rr351d2c3bryi');

            $url = Config('website.api_domain').'ucoupon/bestusebyordersystem';

            $response = json_decode(curlApi($url, $data), true); 

            if ($response['err_code'] == 0) {
                return ['errcode' => $response['err_code'], 'errmsg' => $response['err_msg'], 'data'=>$response['data']];
            } else {
                return ['errcode' => $response['err_code'], 'errmsg' => $response['err_msg']];
            }
        }
    }

    // 查询省市区
    public function getAddress($id)
    {
        $addr = DB::connection('order')->table('lie_region')->where('region_id', $id)->select('region_name')->first();

        return $addr->region_name;
    }

	// 新增自营线下订单
    public function addOffline(Request $request) 
    {
        $info = $this->getPageInfo($request);

        $info['title'] = '新增自营线下订单';

        // 默认内部账号ID
        $internal = DB::connection('order')->table('lie_user_main')->where('mobile', Config('website.internal-account'))->select('user_id')->first();
        $info['internal_uid'] = $internal->user_id;

        // 默认内部账号收货地址
        $address = DB::connection('order')->table('lie_user_address')->where(['user_id' => $info['internal_uid'], 'is_default' => 1])->first();
        
        $address->province_val = $this->getAddress($address->province);
        $address->city_val = $this->getAddress($address->city);
        $address->district_val = $this->getAddress($address->district);
        
        $info['address'] = $address;

        $sale_id = $request->user->userId;
        $info['sale_id'] = $sale_id;

        // 当前登录用户名称
        $userInfo = DB::table('user_info')->where('userId', $sale_id)->select('name')->first(); 
        $info['name'] = $userInfo->name;

        // 当前登录用户内部绑定手机
        $intracode = DB::table('lie_intracode')->where('admin_id', $sale_id)->select('user_id')->first();

        if (!empty($intracode)) {
            $user = DB::connection('order')->table('lie_user_main')->where('user_id', $intracode->user_id)->select('mobile')->first();

            $info['mobile'] = $user ? $user->mobile : '';
        }

        return view('addOffline', $info);
    }  

    // 获取SKU信息
    public function getSku(Request $request)
    {
        if ($request->isMethod('post')) {
            $url = Config('website.search-skuid');
            $data['id'] = $request->input('sku_id');

            $data['k1'] = time();
            $data['k2'] = md5(md5($data['k1']).'fh6y5t4rr351d2c3bryi');

            $response = json_decode(curlApi($url, $data, 'POST'), true); 

            if (!empty($response['data'])) {
                return ['errcode' => 0, 'errmsg' => '', 'data' => $response['data']];
            } else {
                return ['errcode' => -1, 'errmsg' => '未找SKU信息'];
            }
        }
    }

    // 添加到购物车
    public function addCart(Request $request)
    {
        if ($request->isMethod('post')) {        
            $data['uid'] = $request->input('uid');
            $data['id'] = $request->input('id');
            $data['num'] = $request->input('num');
            $data['buy'] = $request->input('buy');
            $data['delivery_place'] = $request->input('delivery_place');
            $data['pf'] = 4;

            $data['k1'] = time();
            $data['k2'] = md5(md5($data['k1']).'fh6y5t4rr351d2c3bryi');

            $url = Config('website.api_domain').'cart/addByOrderSystem';

            $response = json_decode(curlApi($url, $data), true); 
        
            if ($response['err_code'] == 0) {
                return ['errcode' => $response['err_code'], 'errmsg' => $response['err_msg'], 'data'=>$response['data']];
            } else {
                return ['errcode' => $response['err_code'], 'errmsg' => $response['err_msg']];
            }
        }
    }

    // 切换销售类型
    public function switchSaleType(Request $request)
    {
        if ($request->isMethod('post')) {        
            $data['sale_type'] = $request->input('sale_type');
            $data['cart_ids'] = $request->input('cart_ids');

            $data['k1'] = time();
            $data['k2'] = md5(md5($data['k1']).'fh6y5t4rr351d2c3bryi');

            $url = Config('website.api_domain').'cart/switchSaleType';

            $response = json_decode(curlApi($url, $data), true); 

            return ['errcode' => $response['err_code'], 'errmsg' => $response['err_msg']];
        }
    }

    // 获取购物车列表
    public function cartList(Request $request)
    {
        if ($request->isMethod('post')) {        
            $data['uid'] = $request->input('uid');
            $data['type'] = $request->input('type');
            $data['delivery_place'] = $request->input('delivery_place');

            $data['k1'] = time();
            $data['k2'] = md5(md5($data['k1']).'fh6y5t4rr351d2c3bryi');

            $url = Config('website.api_domain').'cart/listsByOrderSystem';

            $response = json_decode(curlApi($url, $data), true); 
         
            if ($response['err_code'] == 0) {
                return ['errcode' => $response['err_code'], 'errmsg' => $response['err_msg'], 'data'=>$response['data']];
            } else {
                return ['errcode' => $response['err_code'], 'errmsg' => $response['err_msg']];
            }
        }
    }

    // 修改购物车商品数量
    public function changeNum(Request $request)
    {
        if ($request->isMethod('post')) {        
            $data['uid'] = $request->input('uid');
            $data['num'] = $request->input('num');
            $data['cart_id'] = $request->input('cart_id');

            $data['k1'] = time();
            $data['k2'] = md5(md5($data['k1']).'fh6y5t4rr351d2c3bryi');

            $url = Config('website.api_domain').'cart/changeNumByOrderSystem';

            $response = json_decode(curlApi($url, $data), true); 
            
            if ($response['err_code'] == 0) {
                return ['errcode' => $response['err_code'], 'errmsg' => $response['err_msg'], 'data'=>$response['data']];
            } else {
                return ['errcode' => $response['err_code'], 'errmsg' => $response['err_msg']];
            }            
        }
    }

    // 删除购物车商品
    public function deleteGoods(Request $request)
    {
        if ($request->isMethod('post')) {        
            $data['uid'] = $request->input('uid');
            $data['cart_id'] = $request->input('cart_id');

            $data['k1'] = time();
            $data['k2'] = md5(md5($data['k1']).'fh6y5t4rr351d2c3bryi');

            $url = Config('website.api_domain').'cart/deleteByOrderSystem';

            $response = json_decode(curlApi($url, $data), true); 
            
            if ($response['err_code'] == 0) {
                return ['errcode' => $response['err_code'], 'errmsg' => $response['err_msg'], 'data'=>$response['data']];
            } else {
                return ['errcode' => $response['err_code'], 'errmsg' => $response['err_msg']];
            }            
        }
    }

    // 确认订单信息
    public function confirm(Request $request) 
    {
        if ($request->isMethod('post')) {  
            $is_online = $request->input('is_online');
            $data['uid'] = $request->input('uid', 0);
            $data['address_id'] = $request->input('address_id', 0);
            $data['cart_id'] = $request->input('cart_ids', '');
            $data['user_coupon_id'] = $request->input('user_coupon_id', 0);
            $data['type'] = !$is_online ? 3 : $request->input('goods_type');

            $data['k1'] = time();
            $data['k2'] = md5(md5($data['k1']).'fh6y5t4rr351d2c3bryi');

            $url = Config('website.api_domain').'cart/confirm';

            $response = json_decode(curlApi($url, $data), true); 
            
            if ($response['err_code'] == 0) {
                return ['errcode' => $response['err_code'], 'errmsg' => $response['err_msg'], 'data'=>$response['data']];
            } else {
                return ['errcode' => $response['err_code'], 'errmsg' => $response['err_msg']];
            }            
        }
    }

    // 检查期货库存
    public function checkStock(Request $request)
    {
        if ($request->isMethod('post')) {  
            $cart_info = json_decode($request->input('cart_info', ''), true);
            $sale_type = $request->input('sale_type', 1);

            $data['k1'] = time();
            $data['k2'] = md5(md5($data['k1']).'fh6y5t4rr351d2c3bryi');

            $url = Config('website.api_domain').'goods/detail';

            $warning_arr = array();

            foreach ($cart_info as $k=>$v) {
                $data['id'] = $v['gid'];

                $response = json_decode(curlApi($url, $data), true); 

                if ($sale_type == 1) {
                    // 现货订单--判断下单数量是否大于库存,若大于则弹出提示信息
                    if ($v['num'] > $response['data']['goods_number']) {
                        $temp['goods_name'] = $response['data']['goods_name']; // 型号
                        $temp['stock'] = $response['data']['goods_number']; // 可用库存
                        $warning_arr[] = $temp;
                        $errmsg = '库存不足,建议设置为期货类型';
                    } 
                } else {
                    // 期货订单--判断下单数量是否小于库存,若小于则弹出提示信息
                    if ($v['num'] < $response['data']['goods_number']) {
                        $temp['goods_name'] = $response['data']['goods_name']; // 型号
                        $temp['stock'] = $response['data']['goods_number']; // 可用库存
                        $warning_arr[] = $temp;
                        $errmsg = '您提交的数量有实际库存,建议直接购买现货';
                    } 
                }
            }

            if (!empty($warning_arr)) {
                return ['errcode' => -1, 'errmsg' => $errmsg, 'data'=>json_encode($warning_arr)];
            }
            
            return ['errcode' => 0, 'errmsg' => ''];           
        }
    }

    // 提交订单
    public function create(Request $request)
    {
        if ($request->isMethod('post')) {        
            $data['uid'] = $request->input('uid');
            $data['sale_id'] = $request->input('sale_id');
            $data['address_id'] = $request->input('address_id');
            $data['cart_id'] = implode(',', $request->input('cart_ids'));
            $data['type'] = $request->input('type');
            $data['remark'] = $request->input('remark');

            if ($data['type'] == 3) { // 自营线下订单
                $data['address_name'] = $request->input('address_name');
                $data['address_mobile'] = $request->input('address_mobile');
            } else { // 联营、自营线上订单
                $data['tax_id'] = $request->input('tax_id');
                $data['user_coupon_id'] = $request->input('user_coupon_id');
            }

            $data['sale_type'] = $request->input('sale_type', ''); // 自营线上选择销售类型

            $data['k1'] = time();
            $data['k2'] = md5(md5($data['k1']).'fh6y5t4rr351d2c3bryi');

            $url = Config('website.api_domain').'order/create';

            $response = json_decode(curlApi($url, $data), true); 
            
            if ($response['err_code'] == 0) {
                return ['errcode' => $response['err_code'], 'errmsg' => $response['err_msg'], 'data'=>['order_id' => $response['data'], 'type' => $data['type']]];
            } else {
                return ['errcode' => $response['err_code'], 'errmsg' => $response['err_msg']];
            }            
        }
    }

    // 提交订单成功页面
    public function success(Request $request)
    {
        $info = $this->getPageInfo($request);

        $order_id = $request->input('order_id');
        $type = $request->input('type');

        if ($type == 1) {
            $title = '新增联营订单';
        } else if ($type == 2) {
            $title = '新增自营线上订单';
        } else {
            $title = '新增自营线下订单';
        }

        $info['title'] = $title;
        $info['paths'] = [["title" => $title, "href" => '#']];
        $info['type'] = $type;

        $order = DB::connection('order')->table('lie_order')->where('order_id', $order_id)->first();

        if ($type != 3) {
            $user = DB::connection('order')->table('lie_user_main')->where('user_id', $order->user_id)->select('mobile')->first();
            $info['user_info'] = $user;
        }

        $info['order_info'] = $order;  

        return view('success', $info);
    }

    // 自营线下订单审核
    public function selfCheck(Request $request)
    {
        if ($request->isMethod('post')) {        
            $order_id = $request->input('order_id');
            $status = $request->input('status');

            // 审核通过推到WMS
            if ($status == 4) {
                $data['order_id'] = $order_id;
                $data['k1'] = time();
                $data['k2'] = md5(md5($data['k1']).'fh6y5t4rr351d2c3bryi');

                $url = Config('website.api_domain').'order/wmsOrder';

                $response = json_decode(curlApi($url, $data), true); 

                if ($response['err_code'] == 0) {
                    $orderInfo = DB::connection('order')->table('lie_order')->where('order_id', $order_id)->first();

                    DB::beginTransaction();
                    try {
                        // 插入到order_price
                        $price['order_id'] = $order_id;
                        $price['order_sn'] = $orderInfo->order_sn;
                        $price['price_type'] = -1;
                        $price['price'] = '-'.$orderInfo->order_amount;
                        $price['create_time'] = time();

                        $priceAdd = DB::connection('order')->table('lie_order_price')->insert($price);

                        // 添加付款记录
                        $pay['user_id'] = $orderInfo->user_id; 
                        $pay['order_id'] = $order_id; 
                        $pay['order_sn'] = $orderInfo->order_sn; 
                        $pay['pay_id'] = 0; // 支付方式ID
                        $pay['pay_name'] = '交通银行'; // 支付方式名
                        $pay['pay_type'] = 1;
                        $pay['pay_amount'] = $orderInfo->order_amount;
                        $pay['is_paid'] = 1;
                        $pay['create_time'] = time();
                        $pay['pay_time'] = time();

                        $payLog = DB::connection('order')->table('lie_pay_log')->insert($pay);

                        // 待发货状态
                        $update = DB::connection('order')->table('lie_order')->where('order_id', $order_id)->update(['status' => $status, 'pay_time' => time(), 'wms_syn' => 1]);

                        if ($update && $priceAdd && $payLog) {
                            DB::commit();
                        }
                    } catch (Exception $e) {
                        DB::rollBack();
                    }   
                } else {
                    return ['errcode' => $response['err_code'], 'errmsg' => $response['err_msg']];
                }

                $event = '自营线下订单审核通过';
            } else {
                $data['order_id'] = $request->input('order_id');
                $data['operator_id'] = $request->user->userId;
                $data['cancel_reason'] = '后台审核不通过';

                $url = Config('website.api_domain').'order/selfCancel';

                $data['k1']  = time();
                $data['k2']  = md5(md5($data['k1']).'fh6y5t4rr351d2c3bryi');
                
                $temp = json_decode(curlApi($url, $data, "POST"), true);

                $event = '自营线下订单审核不通过';

                return array('errcode'=>$temp['err_code'],'errmsg'=>$temp['err_msg']);
            }  
            
            // 操作记录
            $log['order_id'] = $order_id;
            $log['operator_id'] = $request->user->userId;
            $log['operator_type'] = 2;
            $log['event'] = $event;
            $log['ip'] = get_client_ip();
            $log['create_time'] = time();
            $actionLog = DB::connection('order')->table('lie_order_action_log')->insert($log);

            if (!$actionLog){
                errorLog(Error::E_ADD_FAILED, '添加操作记录失败');
                return ['errcode'=>Error::E_ADD_FAILED, 'errmsg'=>'添加操作记录失败'];
            } 

            if (!empty($update)) {
                return ['errcode' => 0, 'errmsg' => '操作成功'];
            } else {
                return ['errcode' => -1, 'errmsg' => '操作失败'];
            }            
        }
    }

}