<?php
/**
 * 添加订单服务
 * 添加订单操作权限
 * @author DouBin
 * @Date: 2021/08/03
 * @Time: 上午10:10
 * @Email: db@sudianwang.com
 * @version 1.0
 * @copyright BlueCity
 */

namespace App\Services;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\Orders\AotuorderController;
use App\Models\PreliminaryNote;
use App\Models\Region;
use App\Models\User;
use BlueCity\Core\Inc\ErrorInc;
use BlueCity\Core\Service\Service;
use BlueCity\Data\Service\ZhiPei\OrderService as zhiPeiOrder;
use Illuminate\Support\Facades\Log;
use App\Models\OrderMsg;
use Validator;
use DB;

class OrderaddService extends Service{
	/**
     * 验证添加订单参数
     * @param string $input 待添加参数
     * @return multitype:string
     * @author dou 2021年7月31日
     */
    public static function  verificationAddData ( $input ,$source){
	    $rules =[
            'sys_bh' =>'required|unique:orders,sys_num',
            'ser_type' =>'required',
            'skb_bh' =>[
            			'required',
            			'regex:/^[0-9a-zA-Z\_\-]+$/',
            			'unique:orders,order_num'
            		],
            'pt_id' =>'required',
//            'order_time' =>'required',
            'shr_name' =>'required',
            'shr_sheng' =>'required',
            'shr_shi' =>'required',
            'shr_adress' =>'required',
            'goods' =>'required',
            'pay_type' =>'required',
        ];
        /*'shr_phone' =>[
            'required',
            'regex:/^[1][1,2,3,4,5,6,7,8,9][0-9]{9}$|^[1][1,2,3,4,5,6,7,8,9][0-9]{9}-[0-9]{4}$|^0\d{2,3}-?\d{7,8}$/'
        ],*/
        $message = [
            'sys_bh.required'=> '登录名不能为空',
            'sys_bh.unique'=> '系统单号已存在',
            'ser_type.required'=> '请选择服务类型',
            'skb_bh.required'=> '平台单号不能为空',
            'skb_bh.regex'=> '平台单号格式错误',
            'skb_bh.unique'=> '平台单号已存在',
            'pt_id.required'=> '请选择销售平台',
//            'order_time.required'=> '创建时间(下单时间)不能为空',
            'shr_name.required'=> '收件人不能为空',
            'shr_sheng.required'=> '请选择省',
            'shr_shi.required'=> '请选择市',
            'shr_adress.required'=> '详细地址不能为空',
            'goods.required'=> '请选择商品',
            'pay_type.required'=> '请选择支付类型',
        ];
        if($source != 2){
            $rules['shr_phone']=[
                'required',
                'regex:/^[1][1,2,3,4,5,6,7,8,9][0-9]{9}$|^[0-9]{3}\*{7}[0-9]|^[1][1,2,3,4,5,6,7,8,9][0-9]{9}-[0-9]{4}$|^0\d{2,3}-?\d{7,8}$/'
            ];
            $message['shr_phone.required'] = '联系电话不能为空';
            $message['shr_phone.regex'] = '手机号格式错误';
        }else{
            $rules['shr_phone'] = 'required';
            $message['shr_phone.required'] = '联系电话不能为空';
        }
        $Validator = Validator::make($input,$rules,$message);
        if($Validator->fails()){
        	$error = CommonService::validatorToString($Validator);
	        return $error;
        }else{
	        return false;
        }
    }
    /**
     * 添加订单商品详情
     * @param array $goods 待添加商品信息
     * @param string $admin_name 操作人
     * @param string $sys_num 操作人
     * @param string $appoint_code 核销码
     * @return multitype:array
     * @author dou 2021年7月31日
     */
    public static function addOrderMsg ( $goods , $admin_name , $sys_num , $appoint_code){
        $goods_name = "";
        $new_money = 0;
        $category = [];
        $good_brand = [];
//        $appoint_code=substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 6);
        foreach ($goods as $k => $value){
            $num='0';
            $new_money += $value['goods_price']*$value['goods_num'];
            $goods_name.=$value['goods_name'];
            $category[] = $value['cd_id'];
            $good_brand[] = $value['goods_brand'];
            $orderMsgData['goods_id'] = $value['goods_id'];
            $orderMsgData['goods_name'] = $value['goods_name'];
            $orderMsgData['sys_num'] = $sys_num;
            $orderMsgData['goods_brand'] = $value['goods_brand'];
            $orderMsgData['goods_number'] = $value['goods_number'];
            $orderMsgData['category'] = $value['cd_id'];
            //$orderMsgData['goods_pic_path'] = $value['goods_pic_path'];
            $orderMsgData['creator'] = $admin_name;
            $orderMsgData['appoint_code'] =$appoint_code;
	        if($value['goods_num']<4){
	            while ($num<$value['goods_num']){
	                $orderMsgData['goods_price'] = $value['goods_price'];//实收/商品单价
	                $orderMsgData['goods_paid'] = $value['goods_price'];//应收
	                $orderMsgData['goods_num'] = 1;
	                $newOrderId = OrderMsg::insert($orderMsgData);
	                if(!$newOrderId){
		                OrderMsg::where('sys_num',$sys_num)->delete();
		                return false;
	                }
	                $num = $num + 1;
	            }
            }else{
                $orderMsgData['goods_price'] = $new_money;//实收/商品单价
                $orderMsgData['goods_paid'] = $new_money;//应收
                $orderMsgData['goods_num'] = $value['goods_num'];
                $newOrderId = OrderMsg::insert($orderMsgData);
                if(!$newOrderId){
	                OrderMsg::where('sys_num',$sys_num)->delete();
	                return false;
                }
                $num = $num + 1;
            }
        }
        $data['goods_name'] = $goods_name;
        $data['new_money'] = $new_money;
        $data['category'] = array_unique($category);
        $data['good_brand'] = array_unique($good_brand);
        $data['appoint_code'] = $appoint_code;
        return $data;
    }

    /**|---------------------------------------------------------------------------------
     * @name 添加订单
     * @param array $input 订单信息
     * @param array $session 操作人信息
     * @param string $ip 操作设备ip
     * @param string $source 订单来源1本系统 2 库存系统
     * @retrun /multitype:array
     * @author dou 2021/9/9 13:45
     * |---------------------------------------------------------------------------------
    */
    public static function addOrder ( $input , $session , $ip , $source = 1 ){
        $Validator = OrderaddService::verificationAddData($input,$source);
        if($Validator){
            return ['Data' => [], 'ErrorMessage' => $Validator, 'ErrorCode' => ErrorInc::FAILED_PARAM];
        }
     /*   if($input['pt_id']=='148' && $input['pay_type']!='2'){
            return ['Data' => [], 'ErrorMessage' => '400电话只可选择货到付款', 'ErrorCode' => ErrorInc::FAILED_PARAM];
        }*/
        $goods = $input['goods'];
        DB::beginTransaction(); //开启事务
        $appoint_code = OrderService::creactCode($input['pt_id']);
        $ordermsg = OrderaddService::addOrderMsg($goods,$session['admin_name'],$input['sys_bh'],$appoint_code);
        if(!$ordermsg){
            DB::rollback();
            return ['Data' => [], 'ErrorMessage' => '商品订单添加失败', 'ErrorCode' => ErrorInc::MYSQL_FAILED];
        }
        $goods_name = $ordermsg['goods_name'];
        $new_money = $ordermsg['new_money'];
        $reg_citylevel = Region::whereRaw("reg_citylevel!='' and (reg_name='".$input['shr_sheng']."' or reg_alias like '%".$input['shr_sheng']."，%' or reg_name='".$input['shr_shi']."' or reg_alias like '%".$input['shr_shi']."，%')")->value("reg_citylevel");
        if($reg_citylevel){
            $input['shr_stype'] = $reg_citylevel;
        }else{
            $input['shr_stype']="0";
        }
        if (isset($input['shr_other'])){
            CommonService::accMe($input['sys_bh'],'客户留言',$input['shr_other'],'','',$session['admin_groupnew'],$session['admin_acc'],$session['id']);
        }
        $userArr['skb_xm'] = $input['shr_phone'];
        $userArr['shr_name'] = CommonService::restrict($input['shr_name']);
        $userArr['shr_phone'] = $input['shr_phone'];
        $userArr['shr_sheng'] = $input['shr_sheng'];
        $userArr['shr_shi'] = $input['shr_shi'];
        $userArr['shr_xian'] = $input['shr_xian'];
        $userArr['shr_adress'] = CommonService::restrict($input['shr_adress']);
        $userArr['shr_other'] = $input['shr_other'];
        $userArr['sys_num'] = $input['sys_bh'];
        $userArr['create_time'] = date('Y-m-d H:i:s');
        $userArr['shr_code'] = $ordermsg['appoint_code'];
        $userArr['car_make'] = $input['car_make']??'';
        $userArr['car_line'] = $input['car_line']??'';
        $userArr['car_model'] = $input['car_model']??'';
        $userArr['car_id'] = $input['car_id']??'';
        $car_infor = '';
        if($userArr['car_make']!=''){
            $car_infor .= $userArr['car_make'];
        }if($userArr['car_line']!=''){
            $car_infor .= ' '.$userArr['car_line'];
        }if($userArr['car_model']!=''){
            $car_infor .= ' '.$userArr['car_model'];
        }
        $userArr['car_infor'] = $input['car_infor']??$car_infor;
        $customer_id = User::insertGetId($userArr);
        if(!$customer_id){
            DB::rollback();
            return ['Data' => [], 'ErrorMessage' => '添加人员信息失败', 'ErrorCode' => ErrorInc::MYSQL_FAILED];
        }
        if($userArr['car_id']!='' || $userArr['car_line']!=''){
            $car = $userArr['car_make']." ".$userArr['car_line']." ".$userArr['car_model'];
            CommonService::accMe($input['sys_bh'],'车型备注',$car,'','2',$session['admin_groupnew'],$session['admin_acc'],$session['id']);
            $input['car_audit'] = 2;
        }
        if ($input['car_audit'] == 1){
            $data['order_status'] = 1;
        }elseif ($input['car_audit'] == 2){
            $data['order_status'] = 10;
        }elseif ($input['car_audit'] == 3){
            $data['order_status'] = 3;//等待库房发货
        }else{
            $data['order_status'] = 1;
        }
        $refundorder = $input['refundorder']??1;
        if($refundorder == 2){
            $data['order_status'] = 3;//退单用
        }

        $company_id = $input['company_id']??$session['company_id'];
        $input['order_type'] = 1;
        $input['accoun'] = $input['accoun']??'';
        $newOrder = OrderService::insertOrder($data['order_status'], $goods_name, $input['pt_id'], $input['skb_bh'], $input['sys_bh'], $customer_id, $new_money, $session, $input['ser_type'], $input['order_type'], $input['order_time'],$input['pay_type'],$ordermsg['category'],$ordermsg['good_brand'],$company_id,$input['accoun']);//添加订单表信息
        if ($newOrder){
            DB::commit();
           /* if(in_array('3', $ordermsg['category']) && $source != 2) {
                $pt = PlatformService::getPtBy('id', $input['pt_id'], ['pt_name','zp_id']);
                $zhipei['pt_name'] = $pt['pt_name'];
                $zhipei['pt_id'] = $pt['zp_id'];
//                $zhipei['pt_name'] = PlatformService::getPtBy('id', $input['pt_id'], ['pt_name']);
                $zhipei['order_price'] = $new_money;
                $zhipei['store_name'] = '无';
                $zhipei['wholestore_name'] = '无';
                if ($userArr['shr_name']) {
                    $zhipeiuser['shr_name'] = $userArr['shr_name'];
                } else {
                    $zhipeiuser['shr_name'] = '无';
                }

                $zhipeiuser['shr_phone'] = $userArr['shr_phone'];
                $zhipeiuser['shr_sheng'] = $userArr['shr_sheng'];
                $zhipeiuser['shr_shi'] = $userArr['shr_shi'];
                //                $zhipeiuser['shr_xian'] = $user['shr_xian'];
                if ($userArr['shr_xian'] != '') {
                    $zhipeiuser['shr_xian'] = $userArr['shr_xian'];
                } else {
                    $zhipeiuser['shr_xian'] = '无';
                }
                if ($userArr['shr_adress'] != '') {
                    $zhipeiuser['shr_adress'] = $userArr['shr_adress'];
                } else {
                    $zhipeiuser['shr_adress'] = '无';
                }

                $zhipei['construction_date'] = date("Y-m-d H:i:s");
                $zhipei['car_brand'] = $userArr['car_make'];
                $zhipei['car_frame'] = '';
                $zhipei['order_status'] = $data['order_status'];//订单状态
                $zhipeigood = [];
                foreach ($goods as $k => $v) {
                    //$['cd_id']  商品所属类型
                    $zhipeigoods['goods_name'] = $v['goods_name'];
                    $zhipeigoods['goods_number'] = GoodsService::getGoodsByKey('pg_id', $v['goods_id'], ['general_version']);
                    $zhipeigoods['goods_num'] = $v['goods_num'];
                    $zhipeigoods['goods_brand'] = $v['goods_brand'];
                    $zhipeigoods['goods_price'] = $v['goods_price'];
                    $zhipeigood[$k] = $zhipeigoods;
                }
                //print_r($zhipeiuser);
                $res = zhiPeiOrder::complete($input['skb_bh'], $zhipei, $zhipeigood, $zhipeiuser);
                //$res['code'] = 200;
                $inputs['data']['zhipei'] = $zhipei;
                $inputs['data']['zhipeigood'] = $zhipeigood;
                $inputs['data']['zhipeiuser'] = $zhipeiuser;
                $inputs['return'] = $res;
                CommonService::addLog('库房添加服务订单', json_encode($inputs), $input['skb_bh'],'warehouse-service');
            }*/
            $preliminary_note = PreliminaryNote::where('order_num',trim($input['skb_bh']))->select('remarks','user','creactid','type','id')->get()->toArray();
            if(!empty($preliminary_note)) {
                foreach( $preliminary_note as $k => $v ){
                    CommonService::accMe($input['sys_bh'],'预添加备注',$v['remarks'],'',$v['type'],$session['admin_groupnew'],$v['user'],$v['creactid']);
                    $tb_type['tb_type'] = 2;
                    PreliminaryNote::where('id',$v['id'])->update($tb_type);
                }
            }
            //$this->add_pt_order(trim($input['skb_bh']));
            $BaseController = new BaseController();
            $BaseController->insertingLog("添加订单，",$input['sys_bh'],"添加订单","添加订单",$ip,$session['admin_acc']);
            if ($input['car_audit'] == 2){
                $Autom = new AotuorderController();
                $info = $Autom->Distrib($input['sys_bh'], $ip);
            }
            return ['Data' => [], 'ErrorMessage' => '添加成功', 'ErrorCode' => 1];
        } else {
            DB::rollback();
            return ['Data' => [], 'ErrorMessage' => '添加失败', 'ErrorCode' => ErrorInc::MYSQL_FAILED];
        }
    }
}
