<?php

namespace App\Http\Controllers\Orders;
use App\Http\Controllers\BaseController;
use App\Services\PlatformService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use App\Models\Admin;
use App\Models\Orders;
use App\Models\PjGoods;
use App\Models\Region;
use App\Models\OrderMsg;
use App\Models\PreliminaryNote;
use App\Models\User;
use App\Services\OrderService;
use App\Services\OrderaddService;
use App\Services\CommonService;
use BlueCity\Core\Inc\ErrorInc;


class OrderaddController extends BaseController
{

    /**|---------------------------------------------------------------------------------
     * @name 添加订单展示数据
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author he <219/05/20>
     * |---------------------------------------------------------------------------------
     */
    public function beforAddOrder (Request $request)
    {
        $sys_bh ='L'.date("YmdHis").str_pad(rand(0,999),3,'0',STR_PAD_LEFT);
        $session_token = $request->get('session_token');
        $data['ser_type'] = OrderService::showSerType($session_token['admin_groupnew']);
        $data['pay_type'] = OrderService::showPayType($session_token['admin_groupnew']);
        $data['order_type'] = OrderService::showOrderType($session_token['admin_groupnew']);
        $data['default'] = OrderService::getOldpt($session_token['id']);
//        if($data['default']){
//            $pt = PlatformService::getPtBy('id', $data['default']['p_id'],['cd_ids','gs_bids']);
//            $data['default']['cd_ids'] = $pt['cd_ids']??[];
//            $data['default']['gs_bids'] = $pt['gs_bids']??[];
//            if(!$data['default']['cd_ids']){
//                $data['default']['cd_ids'] = [];
//            }else{
//                $data['default']['cd_ids'] = explode(',', $data['default']['cd_ids']);
//            }
//            if(!$data['default']['gs_bids']){
//                $data['default']['gs_bids'] = [];
//            }else{
//                $data['default']['gs_bids'] = explode(',', $data['default']['gs_bids']);
//            }
//        }
        $data['sys_bh'] = $sys_bh;
        $data['admin_name'] = $session_token['admin_acc'];
        return response()->json(['Data'=>$data,'ErrorCode'=>1,'ErrorMessage'=>'成功']);exit;
    }
    /**|-------------------------------------------------------------------------------
     * @name 添加订单
     * @param sys_bh 系统单号
     * @param skb_bh 平台单号
     * @param pt_id  平台id
     * @param ser_type  服务类型 1：上门安装；2：到店服务
     * @param shr_name 客户姓名
     * @param shr_phone 客户电话
     * @param shr_sheng 省
     * @param shr_shi 市
     * @param shr_xian 县
     * @param shr_adress 详细地址
     * @param shr_other  客户留言
     * @param car_audit  已可派单 1：否(默认) 2：是
     * @param order_type  1：正常；10：夜间；15:40分钟；20：60分钟；25:90分钟；30：两小时
     * @param goods (array)
     * @param goods_id 商品id(goods)
     * @param goods_name 商品品牌(goods)
     * @param goods_price 商品价格(goods)
     * @param goods_num 商品数量(goods)
     * @param goods_number 	 商品编号(goods)
     * @return \Illuminate\Http\JsonResponse
     * @author he <2019-04-18>
     * |---------------------------------------------------------------------------------
     */
    public function add_order (Request $request){
	    $input = $request->only('sys_bh','skb_bh','pt_id','ser_type','shr_name','shr_phone','shr_sheng','shr_shi','shr_xian','shr_adress','shr_other','car_audit','goods','order_time','pay_type','car_make','car_line','car_model','car_id','company_id');//指定需获取字段
    	$input['skb_bh'] = CommonService::restrict($input['skb_bh']);//过滤平台单号在复制时产生的回车、制表符等被忽略的特殊符号
        $session = $request->get('session_token');//获取操作人信息
        $return = OrderaddService::addOrder($input, $session, $request->ip());
	    return $this->error($return['ErrorMessage'], $return['ErrorCode']);

    }
    /**|------------------------------------------------------------------
     * @name 返回选中的商品
     * @param goods_id  商品id
     * @param brand_name  品牌
     * @param goods_number 商品型号
     * @param cd_id 商品品类
     * @return \Illuminate\Http\JsonResponse
     * |------------------------------------------------------------------
     */
    public function mate (Request $request)
    {
        if (!$request->filled('goods_id') || !$request->filled('brand_name') || !$request->filled('goods_number') || !$request->filled('cd_id')|| !$request->filled('pp_pid')){
            return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);
        }
        $goods_number = $request->input('goods_number');
        $pt_id_arr = PlatformService::getPtIdByPtType();
        if(in_array($request->input('pp_pid'), $pt_id_arr)){
            $sql = "SELECT goods_price FROM gone_orders as a LEFT JOIN gone_order_msg as b on a.sys_num = b.sys_num where goods_id = '".$request->input('goods_id')."' and p_id = '".$request->input('pp_pid')."'";
            $goods_price = DB::select($sql);
            if($goods_price){
                $goods_price = CommonService::dataToArray($goods_price);
                $goods_price = $goods_price[0]['goods_price'];
            }
        }else {
            $db = new OrderMsg();
            $goods_price = CommonService::getMysqlData($db, ['goods_id' => $request->input('goods_id')], ['goods_price'], ['creator_time' => 'DESC'], 'value');
        }
        $caps['goods_id'] = $request->input('goods_id');
        $caps['goods_brand'] = $request->input('brand_name');
        $caps['goods_number'] = substr($goods_number,strpos($goods_number,"-")+1);
        //$caps['goods_number'] = ltrim($request->input('goods_number'),$caps['goods_brand'].'-');
        $caps['goods_name'] = $request->input('goods_number');
        $caps['goods_num'] = 1;
        $caps['cd_id'] = $request->input('cd_id');

        $now = date('Y-m-d H:i:s');
       //DB::connection()->enableQueryLog();
        $caps['xprice'] = DB::table('pt_prices')->where('pp_pid',$request->input('pp_pid'))->where('pp_gid',$caps['goods_id'])->where('pp_startime','<',$now)->orderBy('pp_id','Desc')->value('pp_price');
       // print_r(DB::getQueryLog());
        $caps['xprice'] = $caps['xprice']??'暂无';
        if($goods_price){
            $caps['goods_price'] = $goods_price;
        }else{
            $caps['goods_price'] = 0;
        }
        $caps = mb_convert_encoding($caps, 'UTF-8', 'UTF-8');
        return $this->success('成功', $caps);
    }

    /**|---------------------------------------------------------------------------------
     * @name 验证平台单号是否存在
     * @param string order_num 订单单号
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/12/2 16:02
     * |---------------------------------------------------------------------------------
    */
    public function validationOrderNum ( Request $request ){
        if($request->filled('order_num')){
            $res = OrderService::getOrderBy('order_num', $request->input('order_num'),['id']);
            if($res){
                return $this->error('单号已存在', ErrorInc::REPEAT_SUBMIT);
            }else{
                return $this->success('单号验证通过');
            }
        }else{
            return $this->error('缺少订单单号', ErrorInc::INVALID_PARAM);
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 拆分指定平台用户信息
     * @param string data 需要拆分信息
     * @param int pt_id 对那个执行平台id
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2022/1/17 17:02
     * |---------------------------------------------------------------------------------
    */
    public function getDataUser ( Request $request ){
        if($request->filled('data') && $request->filled('pt_id')){
            return CommonService::getDataUser($request->input('data'), $request->input('pt_id'));
        }else{
            return $this->error('缺少必要参数', ErrorInc::FAILED_PARAM);
        }
    }
}
