<?php
/**
 * 订单服务
 * 订单基础操作服务
 * @author lixiaolin
 * @Date: 2021/4/2
 * @Time: 下午13:50
 * @Email: lixiaolin@bluearp.com
 * @version 1.0
 * @copyright BlueCity
 */

namespace App\Services;

use App\Factory\OrderFactory;
use App\Http\Controllers\PushController;
use App\Http\Controllers\PushxmController;
use App\Inc\OrderInc;
use App\Models\AdminAddress;
use App\Models\Bserviss;
use App\Models\Disareanew;
use App\Models\GhPrice;
use App\Models\GhXPrice;
use App\Models\InstallPerson;
use App\Models\Leadsubsidie;
use App\Models\Management;
use App\Models\OrderAfter;
use App\Models\OrderMsg;
use App\Models\OrderMsgLocation;
use App\Models\Orders;
use App\Models\PjGoods;
use App\Models\Pt;
use App\Models\RecycleGoods;
use App\Models\RecycleOrders;
use App\Models\Refund;
use App\Models\Region;
use App\Models\Arcover;
use App\Models\AdminInfor;
use App\Models\SettlementList;
use App\Models\SettlementMoney;
use App\Models\SettlementThree;
use App\Models\SubmitPlease;
use App\Models\Supportacti;
use App\Models\OrderList;
use App\Models\OrderSendflow;
use App\Models\OrderVisit;
use App\Models\SyncStores;
use App\Models\Temporary;
use App\Models\User;
use App\Models\OrderLog;
use App\Models\Aftercust;
use App\Models\Admin;
use BlueCity\Core\Service\Service;
use BlueCity\Core\Inc\ErrorInc;
use BlueCity\Data\Service\ZhiPei\OrderService as zhiPeiOrder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\BaseController;
use DB;
use App\Services\OrderDeductionFeeService;

class OrderService extends Service
{
   // private static $instance;
    public $modelMain = null;

    public function __construct()
    {
        if (!$this->modelMain) $this->modelMain = new Orders();
    }

    /**
     * @return mixed
     */
    public static function getInstance()
    {
       /*  if (is_null(static::$instance)) {
            static::$instance = new static;
        }
        return static::$instance; */
    }
    /**|---------------------------------------------------------------------------------
     * @name 参数说明
     * @retrun /multitype:array
     * @author dou 2021/8/17 18:40
     * |---------------------------------------------------------------------------------
     */
    public static function rulesShow (  ){
        return array(
            'sys_num' => '系统单号',
            'sheng' => '省',
            'shi' => '市',
            'xian' => '县',
            'address' => '详细地址',
            'order_type' => '订单类型',
            'company_name' => '门店名称',
            'company_id' => '所属公司id',
            'orders_id' => '订单数据id',
            'ser_id' => '门店id',
            'user_id' => '用户id',
        );
    }

    /**|---------------------------------------------------------------------------------
     * @name 添加订单
     * @param string ju_ordernum 订单单号
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2021/9/9 11:58
     * |---------------------------------------------------------------------------------
    */
    public static function insertOrder ( $order_status , $goods_name , $p_id , $order_num , $sys_num , $customer_id , $new_money , $session , $ser_type , $order_type = 1 , $customer_time , $pay_type = 1 , $category , $good_brand,$company_id=1,$accoun='',$clientAccount = ''){
        $data['order_status'] = $order_status;//订单状态
        $data['goods_name'] = $goods_name;//商品名称
        $data['p_id'] = $p_id;//平台id
        $data['order_num'] = trim($order_num);//平台编号
        $data['order_time'] = date('Y-m-d H:i:s');//下单时间
        $data['create_time'] = date('Y-m-d H:i:s');//创建时间
        $data['sys_num'] = $sys_num;//系统编号
        $data['customer_id'] = $customer_id;//客户信息
        $data['new_customer_id'] = $customer_id;//安装联系人
        $data['order_account'] = $new_money;//订单金额
        $data['new_money'] = $new_money;//实收
        $data['handled_by'] = $session['admin_acc'];//创建人
        $data['admin_id'] = $session['id'];//创建人id
        $data['ser_type'] = $ser_type;//服务类型 1：上门安装；2：到店服务
        $data['order_type'] = $order_type;//订单类型 1：正常；10：夜间；15:40分钟；20：60分钟；25:90分钟；30：两小时
        $data['customer_time'] = $customer_time;//客户下单时间
        $data['pay_type'] = $pay_type;//付款方式 1：线上付款 2：货到付款
        $data['category'] = implode(',',$category);//商品类型
        $data['goods_brand'] = implode(',',$good_brand);//商品品牌
        $data['company_id'] = $company_id;
        $data['accoun'] = $accoun??'';
        $data['clientAccount'] = $clientAccount??'';
        $newOrder = Orders::insert($data);
        return $newOrder;
    }
    /**
     * 获取订单列表
     * @param array $params
     * @return array|mixed
     */
    public function getOrders($params)
    {
        return Orders::where($params)->get();
    }

    /**获取订单详细内容
     * @param int $sysNumber 订单ID
     * @return array|mixed
     */
    public static function getOrderBySysNumber($sysNumber)
    {
        return Orders::where('sys_num',$sysNumber)->first();
    }

    /**获取订单详细内容
     * @param int $sysNumber 订单ID
     * @return array|mixed
     */
    public static function getOrderMsgBySysNumber($sysNumber)
    {
        return OrderMsg::where('sys_num',$sysNumber)->first();
    }

    /**获取订单详细内容
     * @param int $orderNumber 订单ID
     * @return array|mixed
     */
    public static function getOrderByOrderNumber($orderNumber)
    {
        return Orders::where('order_num',$orderNumber)->first();
    }

    /**获取订单详细内容(暂时没用到，以后肯定会用到抽象工厂)
     * @param Order $order 订单数据模型
     * @return mixed
     */
    public function makeOrderRepository(Orders $order)
    {
        $orderType = $order->getAttribute('order_type');

        $repository = OrderFactory::make($orderType);

        return $repository;
    }
    /**|---------------------------------------------------------------------------------
     * @name 获取详情表明细
     * @param string $key 查询键
     * @param string $value 查询值
     * @param array $select 待查询参数
     * @param string $type 查询类型
     * @retrun /multitype:array
     * @author dou 2021/8/17 19:35
     * |---------------------------------------------------------------------------------
    */
    public static function getOrderMsgBy ($key, $value, $select = [] , $type = 'get'){
       $db = new OrderMsg();
       if($key == 'id'){
           $type = 'first';
       }
       if($type == 'first'){
           if(count($select) == 1){
               $type = 'value';
           }
       }
        $list = CommonService::getMysqlData($db,[$key=>$value],$select,[],$type);
        return $list;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取商品位置详情
     * @param string $key 查询键
     * @param string $value 查询值
     * @param array $select 待查询参数
     * @param string $type 查询类型
     * @retrun /multitype:array
     * @author dou 2021/10/28 18:00
     * |---------------------------------------------------------------------------------
    */
    public static function getOrderMsgLocationBy ($key, $value, $select = [] , $type = 'get'){
        $db = new OrderMsgLocation();
        if($key == 'oml_id'){
            $type = 'first';
        }
        if($type == 'first'){
            if(count($select) == 1){
                $type = 'value';
            }
        }
        $list = CommonService::getMysqlData($db,[$key=>$value],$select,[],$type);
        return $list;
    }

    /**|---------------------------------------------------------------------------------
     * @name 根据指定条件（多条件）获取商品
     * @param array $params 查询条件
     * @param array $select 查询内容
     * @retrun multitype:array
     * @author dou 2021/10/28 18:00
     * |---------------------------------------------------------------------------------
     */
    public static function getOrderMsgLocations ( $params , $select = [] , $type = 'get' ){
        $db = new OrderMsgLocation();
        if($type == 'first') {
            if (count($select) == 1) {
                $type = 'value';
            }
        }
        $list = CommonService::getMysqlData($db, $params,$select,[],$type);
        if($list){
            $list = GoodsService::addGoodsName($list,$select);
        }
        return $list;
    }

    /**获取订单详细内容
     * @param string $key 查询键
     * @param string $value 查询值
     * @param array $select 待查询参数
     * @return array|mixed
     */
    public static function getOrderBy($key, $value, $select = [])
    {
        $db = new Orders();
        $type = 'first';
        if(count($select) == 1){
            $type = 'value';
        }
        if(is_array($value)){
            $type = 'get';
            $key = $key."_searchin";
        }
        $list = CommonService::getMysqlData($db,[$key=>$value],$select,[],$type);
        return $list;
    }
    /**
     * 订单列表
     * @param array $session 用户信息
     * @param array $input 请求数据
     * @return /multitype:array
     * @author dou 2021年8月3日
     */
    public static function getList ( $input , $session )
    {
	    /*---------------------------------------------拼接订单列表查询条件开始-------------------------------------------------------*/
    	$admin_pt_id = $session['admin_pt_id'];//获取当前用户可查看平台权限
        $where = [];
        $where['is_delete'] = 2;//默认获取生效订单

        if(!in_array($session['admin_groupnew'],[7,8])){
            $where['p_id_searchin'] = trim($admin_pt_id);
        }

        $day_time = date('Y-m-d 23:59:59', strtotime('+2day')); //时间
        $Db = new Orders();
        $Db = $Db->leftJoin('user', 'orders.customer_id', '=', 'user.id')->leftJoin('pt', 'orders.p_id', '=', 'pt.id');
        if(isset($input['shr_phone']) || isset($input['shr_name'])){
	        $user = new User();
	        if(isset($input['shr_phone'])){
		        $user = $user->where('shr_phone','like',$input['shr_phone'] . '%');
	        }if(isset($input['shr_name'])){
		        $user = $user->where('shr_name','like',$input['shr_name'] . '%');
	        }
	        $user = $user->pluck('id')->toArray();
	        if(empty($user)){
		        $where['new_customer_id_searchin'] = $user;
	        }else{
		        $searchor = [];
		        $searchor['customer_id_searchin'] = $user;
		        $searchor['new_customer_id_searchin'] = $user;
		        $where['customer_id_searchor'] = $searchor;
	        }
        }
        /*---------------------------------------------状态查询条件开始-------------------------------------------------------*/
        $statuswhere = OrderService::getStatusWhere($input['state'],$day_time);
        foreach( $statuswhere as $k => $v ){
        	$where[$k] = $v;
        }
        /*---------------------------------------------状态查询条件结束-------------------------------------------------------*/
        if(isset($input['order_num'])){//搜索平台单号
            $searchor = [];
            $searchor['order_num_rlike'] = $input['order_num'];
            $searchor['accoun_rlike'] = $input['order_num'];
            $where['order_num_searchor'] = $searchor;
	       // $where['order_num_rlike'] = $input['order_num'];
        }
        if(isset($input['p_id'])){//搜索平台
	        $where['p_id'] = $input['p_id'];
        }
        if(isset($input['shr_sheng'])){//客户地址省
	        $where['shr_sheng_rlike'] = $input['shr_sheng'];
        }
        $bmmc_pids = BmmcService::searchPids($session['admin_groupnew']);

        if(isset($input['admin_id'])){//经手人
	        $where['admin_id'] = $input['admin_id'];
        }
        if(isset($input['shr_shi'])){//市
	        $where['shr_shi_rlike'] = str_replace('市','',$input['shr_shi']);
        }
        if(isset($input['shr_xian'])){//县
	        $where['shr_xian_like'] = $input['shr_xian'];
        }
        if(isset($input['goods_number'])){//商品
	        $where['goods_name_like'] = $input['goods_number'];
        }
        if(isset($input['ser_id'])){//服务商
	        $where['ser_id'] = $input['ser_id'];
        }

        if(isset($input['ser_id_status'])){//1:未派成功订单，2:已派成功订单
            if($input['ser_id_status']==1){
                $where['ser_id'] = 0;
            }else {
                $where['ser_id_searchgt'] = 0;
            }
        }
        if(isset($input['distype'])){//派单方式：2自动；3手动
             $where['distype'] = $input['distype'];
        }


        if(isset($input['shr_code'])){
            $where['shr_code'] = $input['shr_code']; //客户识别码 验证码
        }


        if(isset($input['creatData'])){//创建时间
        	$input['creatData'][1] = date("Y-m-d", strtotime($input['creatData'][1] . " +1 day"));
	        $where['gone_orders.create_time_between'] = $input['creatData'];
        }
//        else{
//           if($input['state']=='2'){
//                $input['creatData'][0] = date("Y-m-d", strtotime(date("Y-m-d") . " +1 day"));
//                $input['creatData'][1] = date("Y-m-d");
//           }
//        }
        if(isset($input['lock'])){//锁定状态
	        $where['lock_type'] = $input['lock'];
	        $where['order_status_notin'] = [50, 55];
        }
        if(isset($input['cd_id'])){//商品品类
            $where['gone_orders.category_findinset'] = $input['cd_id'];
        }

//        if ($session['admin_groupnew'] != 7){//管理员可以看全部 && $session['admin_groupnew'] != 8
        if(!in_array($session['admin_groupnew'],[7,8])) {
            $where['gone_orders.company_id'] = $session['company_id'];
        }
        if(in_array($session['admin_groupnew'],[8])) {
            $where['gone_orders.company_id_searchin'] = $session['all_companys'];
        }

        /*---------------------------------------------拼接订单列表查询条件结束-------------------------------------------------------*/
        $is_excel = $input['is_excel']??'0';
        $where = CommonService::jointWhere($where);
        $page_size = $input['page_size']??10;

        if($is_excel==2){
            DB::connection()->enableQueryLog();#开启执行日志
            $paginate2 = $Db->whereRaw($where)->select('orders.*','order_msg.goods_name','order_msg.goods_number','order_msg.goods_num','order_msg.goods_price','order_msg.goods_service','shr_phone', 'shr_name', 'shr_sheng', 'shr_shi', 'shr_xian', 'shr_adress', 'pt_name', 'distype','bus_type','shr_code')->leftJoin('order_msg', 'orders.sys_num', '=', 'order_msg.sys_num')->orderBy('orders.create_time','ASC')->paginate($page_size);
            $data['sqls2'] = DB::getQueryLog()[1];
        }

        if ($is_excel == 1) {
            DB::connection()->enableQueryLog();#开启执行日志
        }
        $paginate = $Db->whereRaw($where)->select('orders.*', 'shr_phone', 'shr_name', 'shr_sheng', 'shr_shi', 'shr_xian', 'shr_adress', 'pt_name', 'distype','bus_type','shr_code')->orderBy('orders.create_time','ASC')->paginate($page_size);

        //导出所需语句
        $data['sqls'] = DB::getQueryLog()[1];

        $data['showcount'] = OrderService::getStatusBar($session,$admin_pt_id,1);//获取操作权限可展示订单状态栏
        $all_button = BmmcService::whereButton($input['token'],$input['Pri_id']);
        $export = BmmcService::getTopButton('export,auto_order,exportOrdersMsg','',$all_button);
        $data['button_top'] = $export['button_top']??[];//顶部按钮
        $data['button_search'] = $export['button_search']??[];//搜索栏按钮
        $data['smartStore'] = self::getSmartStoreName();//获取是否为F6
        //获取是否有 订单详情
        $group = $session['admin_groupnew'];
        $bmmc_pids = BmmcService::searchPids($group);
        /*if(in_array('112',$bmmc_pids) || in_array('104',$bmmc_pids)|| in_array('8',$bmmc_pids)){
            $data['orderDetail'] = '';
        }else{*/
            $data['orderDetail'] = '订单详情';
       // }
        $list = CommonService::dataToArray($paginate->items());
        if($list){
            $list = OrderService::jointListData($input,$session,$list,$day_time,$all_button);//获取列表信息明细说明
            $data['list'] = $list;
        }else{
            $data['list'] = [];
        }
        $data['page'] = [
            'count' => $paginate->total(),
            'page'=>$paginate->currentPage(),
            'page_size'=>$page_size,
            'allPage'=>$paginate->lastPage()
        ];
        return $data;

    }
     /**
     * 获取指定状态所需必要查询条件
     * @param string $status 状态栏参数
     * @param string $day_time 延期时间
     * @return /multitype:array
     * @author dou 2021年8月4日
     */
     public static function getStatusWhere ( $status , $day_time = '' )
     {
	    $where = [];
		if(!$day_time){
			$day_time = date('Y-m-d 23:59:59', strtotime('+2day')); //时间
		}
     	 if(in_array($status,[1,3,5,10])){
	        $where['order_status'] = $status;
	        $where['day_time_searchlt'] = $day_time;
        }else if($status == 20){
	        $where['order_status'] = $status;
        }else if($status == 21){
             $where['order_status'] = 20;
             $where['distype'] = 5;
         }else if($status == 6){
	        $where['order_status_searchlt'] = 20;
	        $where['day_time_searchgt'] = $day_time;
        }else if($status == 7){
	        $where['tracking_state'] = 2;
        }else if($status == 8){
	        $where['order_status_searchin'] = ['50','55'];
        }
        return $where;
     }
     /**
     * 获取操作权限可展示订单状态栏信息
     * @param string $group 操作人权限
     * @param string $admin_pt_id 可操作平台信息
     * @param string $type 是否查询数据量1是
     * @return /multitype:array
     * @author dou 2021年8月4日
     */
     public static function getStatusBar ( $session , $admin_pt_id = '' , $type = '2'){
         $group = $session['admin_groupnew'];

        $showcount = [
            ['showname' => "全部", 'shownum' => '--','status'=>0],
          //  ['showname' => "等待发货", 'shownum' => '--','status'=>3],
            ['showname' => "新订单", 'shownum' => '--','status'=>1],
            ['showname' => "处理中", 'shownum' => '--','status'=>5],
            ['showname' => "可派单", 'shownum' => '--','status'=>10],
            ['showname' => "已派单", 'shownum' => '--','status'=>20],
            ['showname' => "超时未接单", 'shownum' => '--','status'=>21],
           // ['showname' => "延期订单", 'shownum' => '--','status'=>6],
          //  ['showname' => "订单追踪", 'shownum' => '--','status'=>7],
            ['showname' => "撤销订单", 'shownum' => '--','status'=>8]
        ];

        if( $type == '1'){
	        foreach( $showcount as $k => $v ){
	        	$showcount[$k]['shownum'] = OrderService::getStatusNum($v['status'],$admin_pt_id,$session);
	        }
        }
        return $showcount;
     }
     /**
     * 获取指定状态订单数量
     * @param string $status 状态栏参数
     * @param string $admin_pt_id 可操作平台信息
     * @return /multitype:array
     * @author dou 2021年8月4日
     */
     public static function getStatusNum ( $status , $admin_pt_id ,$session = ''){

	    if(in_array($status,[1,3,5,10,20,6,7,21])){
		    $db = new Orders();
		    $where['is_delete'] = '2';
            if(!in_array($session['admin_groupnew'],[7,8])) {
                $where['p_id_searchin'] = $admin_pt_id;
            }

            if(!in_array($session['admin_groupnew'],[7,8])) {
                $where['company_id'] = $session['company_id'];
            }
            if(in_array($session['admin_groupnew'],[8])) {
                $where['company_id_searchin'] = $session['all_companys'];
            }

	     	$statuswhere = OrderService::getStatusWhere($status);
	        foreach( $statuswhere as $k => $v ){
	        	$where[$k] = $v;
	        }
			$num = CommonService::getMysqlData($db,$where,[],[],'count');
			$num = $num??'0';
			return $num;
        }else{
	        return '--';
        }
     }
     /**
     * 拼接列表数据
     * @param string $session 用户信息
     * @param array $input 请求数据
     * @param array $list 订单数据
     * @param string $day_time 延期展示时间
     * @param array $all_button 按钮信息
     * @return /multitype:array
     * @author dou 2021年8月3日
     */
    public static function jointListData ( $input , $session , $list , $day_time , $all_button ){
        $admin_groupnew = $session['admin_groupnew'];//获取操作人所属部门
	     /*---------------------获取订单中出现的服务商id开始-----------------------------*/
        $serId = [];
        foreach ($list as $ke => $ve) {
            $serId[] = $ve['ser_id'];
        }
        //排除未接单状态
        $companyData = [];
        if(!in_array($input['state'],[1,5,10,20])){
            $db = new Admin();
            $companyData = CommonService::getMysqlData($db,['id_searchin'=>$serId],['company_name', 'id','is_lidao','owner']);
            $companyList = CommonService::jointArrayKey($companyData,'id');
        }
         /*---------------------获取订单中出现的服务商id结束-----------------------------*/
        $order_status_name = OrderService::getOrderStatusName();//获取订单状态数组
        $smartStoreName = self::getSmartStoreName(true);//获取是否为F6
        $order_type = OrderService::showOrderType('',1);//获取订单类型
        $goodpic = PjBrandsService::getAllPic('name');//获取商品品牌图片 放在此处减少循环调取次数
        foreach( $list as $k => $v ){
            $buttonData = [];
            $buttonData[] = 'addF6Claim,editInfo,fastAddOrderBefor'; //添加F6索赔 dong
            if(!in_array($v['order_status'],[50,55]) && $v['lock_type'] != 1){
                $buttonData[] = 'undo_ive';
            }else {
                if(!in_array($v['order_status'],[50,55])) {
                    if (($v['order_status'] < 20) && ($v['day_time'] > $day_time)) {
                        $buttonData[] = 'quality_evaluate,AddRemarks,quality_assurance';
                    } else {
                        $buttonData[] = 'quality_assurance,Aftercusmer,consulting,change_pt,quality_evaluate,AddRemarks';
                    }
                    if ($v['order_status'] > 10) {//我要编辑
                        $buttonData[] = 'WorkOrder';
                    }
                    if ($v['order_status'] == 3) {//我要编辑
                        $buttonData[] = 'WorkOrder';
                    }
                    if ($v['order_status'] <= 10 && $v['order_status'] != 3) {//我要派单
                        $buttonData[] = 'addWorkOrder';
                    }
                    if ($v['order_status'] <= 10 && $v['order_status'] != 3 && $v['bus_type'] == 2) {
                        $buttonData[] = 'edit_price';
                    }
                    if ($v['order_status'] == 20 && $v['distype'] == 5) {
                        $buttonData[] = 'dealTimeOut';
                    }
                    if (in_array($v['order_status'], [1, 5, 10, 20, 30])) {//订单延期
                        $buttonData[] = 'delay_order';
                    }
                    if (in_array($v['order_status'], [1, 5, 10, 20, 30, 34, 40])) {
                        $buttonData[] = 'negotiated,gift_add,electronic_invoice';
                    }
                    if (in_array($v['order_status'], [1, 3 , 5, 10, 20, 30, 34, 40])) {
                        $buttonData[] = 'dealActivity';
                    }
                    if (in_array($v['order_status'], [50]) && $v['category'] == 3) {
                        $buttonData[] = 'dealActivity';
                    }
                    if (($v['order_type'] == 1 || $v['order_type'] == 10) && ($v['order_status'] == 20 || $v['order_status'] == 30)) {
                        $buttonData[] = 'order_urgent';
                    }
                    if ($v['order_status'] == 20 || $v['order_status'] == 30) {//我要催单,申请罚单
                        $buttonData[] = 'reminder,Applicationfines';
                    }
                    if ($v['order_status'] > 20) {
                        if ($v['category'] == 3) {
                            $buttonData[] = 'addServiceScore';
                        }
                        $buttonData[] = 'change_order';
                    }
                    if ($v['lock_type'] == 1 && ($v['order_status'] < 34 || $admin_groupnew == 7 || $admin_groupnew == 79)) {
                        $buttonData[] = 'lockorder';
                    }
                }else{
                    if ($v['category'] == 3) {
                        $buttonData[] = 'dealActivity';
                    }
                }
            }
            if (in_array($v['order_status'],[34,40,50,55])) {
                $buttonData[] = 'feedbackLog';
            }

            //同步智配仓库服务单信息
            if ($v['category'] == 3 && $v['order_status']!=50) {
                $buttonData[] = 'sysZhipeiOrder';
            }

            if($v['order_status']!=3) {
                if(!in_array($v['order_status'],[50,55])) {
                    $buttonData[] = 'sendGoods';
                }
                $buttonData[] = 'salePhoto,AddRemarks';
            }
        	$button = BmmcService::getListButton($buttonData,$all_button);
            $list[$k]['button_one'] = $button['button_one']??[];
            $list[$k]['button_two'] = $button['button_two']??[];
            $list[$k]['button_three'] = $button['button_three']??[];
            $list[$k]['order_status_name'] = $order_status_name[$v['order_status']]??'未确认';
            if ($v['order_status'] == 20 && $v['distype'] == 5) {
                $list[$k]['order_status_name'] = '超时未接单';
            }
            $list[$k]['smartStoreName'] = $smartStoreName[$v['smart_store']]??'未确认';
            $list[$k]['order_type_name'] = $order_type[$v['order_type']]??'未确认';
            if ($v['order_status'] >= 20 && $admin_groupnew != 2) {
                if (isset($companyList[$v['ser_id']])) {
                    $list[$k]['service_name'] = $companyList[$v['ser_id']]['company_name'];
                    $list[$k]['is_lidao'] = $companyList[$v['ser_id']]['is_lidao'];
                    $list[$k]['owner'] = $companyList[$v['ser_id']]['owner'];
                } else {
                    $list[$k]['service_name'] = '';
                }
            } else {
                $list[$k]['service_name'] = '';
            }
            if ($v['order_status'] < 20) {
                $list[$k]['status_name'] = "暂未派单！";
            } else if ($v['order_status'] == 20) {
                $list[$k]['status_name'] = "暂未接单！";
            } else {
                $list[$k]['status_name'] = "";
            }
            $list[$k]['pd_time'] = "";
            if ($v['order_status'] > 10) {
                $db = new OrderList();
            	$orderlistRes = CommonService::getMysqlData($db,['sys_num'=>$v['sys_num']],['creater', 'create_time'],[],'first');
                $list[$k]['creater_name'] = $orderlistRes['creater'];
                if ($v['order_status'] == 20) {
                    $list[$k]['pd_time'] = $orderlistRes['create_time'];
                }
            } else {
                //if($request->get('session_token')['admin_groupnew'] != 7){
                $list[$k]['creater_name'] = "***";
                //}
            }
            if ($v['after_type'] == "") {
                $list[$k]['after_type'] = "质保售后";
            }

            $list[$k]['cd_name'] = CategoryService::getNameByCdId($v['category']);//订单类型

            /*---------------------------------------判定并获取联系人变更信息开始----------------------------------------------------*/
            if ($v['new_customer_id'] != $v['customer_id']) {//当订单联系人不等于安装联系人
            	$db = new User();
            	$new_user = CommonService::getMysqlData($db,['id'=>$v['new_customer_id']],['shr_name', 'shr_phone', 'shr_sheng', 'shr_shi', 'shr_xian', 'shr_adress', 'shr_other'],[],'first');
                if (!empty($new_user)) {
                    $list[$k]['shr_name_new'] = $new_user['shr_name'];
                    $list[$k]['shr_phone_new'] = $new_user['shr_phone'];
                    $list[$k]['shr_sheng_new'] = $new_user['shr_sheng'];
                    $list[$k]['shr_shi_new'] = $new_user['shr_shi'];
                    $list[$k]['shr_xian_new'] = $new_user['shr_xian'];
                    $list[$k]['shr_adress_new'] = $new_user['shr_adress'];
                    $list[$k]['shr_other_new'] = $new_user['shr_other'];
                    $list[$k]['new_address_type'] = 1;
                } else {
                    $list[$k]['new_address_type'] = 2;//不展示新地址
                }
            } else {
                $list[$k]['new_address_type'] = 2;//不展示新地址
            }
            /*---------------------------------------判定并获取联系人变更信息结束----------------------------------------------------*/

            //获取订单类型
            $list[$k]['cd_name'] = CategoryService::getNameByCdId($v['category']);



            /*---------------------------------------获取订单商品明细信息开始----------------------------------------------------------*/
			$orderMsg = OrderService::getOrderMsg($v['sys_num'],$goodpic);
			if($v['shr_code']!==''){
                $list[$k]['appoint_code'] = $v['shr_code'];
            }else {
                $list[$k]['appoint_code'] = $orderMsg['appoint_code'];
            }
            $list[$k]['send_sms'] = $orderMsg['send_sms'];
            $list[$k]['orderMsgArr'] = $orderMsg['orderMsgArr'];
            /*---------------------------------------获取订单商品明细信息结束----------------------------------------------------------*/
            //电话沟通
//            $db = new Aftercust();
//            $aftercust = CommonService::getMysqlData($db,['afc_sys'=>$v['sys_num'],'afc_state'=>1],['afc_id'],[],'value');
//            if ($aftercust) {
//                $list[$k]['aftercust'] = 1;//电话沟通
//            } else {
                $list[$k]['aftercust'] = 2;
//            }
            $list[$k]['afterstatus'] = "";//无售后
            $list[$k]['mess'] = [];
            // }
            $list[$k]['type'] = 1;
            unset($list[$k]['user']);
            unset($list[$k]['pt']);
            unset($list[$k]['ordermsg']);
        }
        return $list;
    }
     /**
     * 获取订单商品明细
     * @param string $sys_num 系统单号
     * @param array $goodpic 商品品牌图片
     * @param int $id 数据id
     * @return /multitype:array
     * @author dou 2021年8月3日
     */
 	public static function getOrderMsg ( $sys_num = '' , $goodpic = [] , $id = '' ){
	 	$db = new OrderMsg();
        $location = OrderService::getOrderMsgLocationBy('oml_sysnum', $sys_num,['oml_goodsid','oml_parentid','oml_goodsname']);
        if($location){
            $location = CommonService::jointArrayKey($location, 'oml_parentid',2);
        }
	 	if($id != ''){
		 	$orderMsgArr = CommonService::getMysqlData($db,['id'=>$id],['id', 'goods_id' ,'beihuan_id', 'goods_name', 'goods_num', 'goods_service', 'goods_number', 'goods_price', 'goods_paid', 'goods_state', 'goods_difference', 'goods_brand' ,'appoint_code', 'send_sms' ,'code_state','category'],[],'first');
		 	if ($orderMsgArr['goods_service'] == 4) {
	            $db = new OrderLog();
	            $orderMsgArr['goods_name_log'] = CommonService::getMysqlData($db,['msg_id'=>$orderMsgArr['id']],['goods_name'],['id'=>'DESC'],'value');
            } else {
                $orderMsgArr['goods_name_log'] = 1;
            }
            $orderMsgArr['goods_pic_path'] = $goodpic[$orderMsgArr['goods_brand']]['path']??'';
		 	if($orderMsgArr['goods_pic_path']==''){
		 	    switch ( $orderMsgArr['category'] ){
		 	        case 3:
                        $orderMsgArr['goods_pic_path'] = $goodpic['车膜']['path'];
		 	            break;
		 	        default:
		 	            ;
		 	            break;
		 	    }
            }
            $orderMsgArr['child_good'] = $location[$orderMsgArr['goods_id']]??[];
            $data = $orderMsgArr;
	 	}else{
	 		$orderMsgArr = CommonService::getMysqlData($db,['sys_num'=>$sys_num,'goods_service_searchin'=>[1,2,4]],['id', 'goods_id' ,'beihuan_id', 'goods_name', 'goods_num', 'goods_service', 'goods_number', 'goods_price', 'goods_paid', 'goods_state', 'goods_difference', 'goods_brand' ,'appoint_code', 'send_sms' ,'code_state','category']);
		 	$data['appoint_code'] = $orderMsgArr[0]['appoint_code']??"暂无";
	        $data['send_sms'] = $orderMsgArr[0]['send_sms']??'1';
		 	if($orderMsgArr){
		        foreach ($orderMsgArr as $kk => $vv) {
		            if ($vv['goods_service'] == 4) {
			            $db = new OrderLog();
			            $orderMsgArr[$kk]['goods_name_log'] = CommonService::getMysqlData($db,['msg_id'=>$vv['id']],['goods_name'],['id'=>'DESC'],'value');
		            } else {
		                $orderMsgArr[$kk]['goods_name_log'] = 1;
		            }
                    $orderMsgArr[$kk]['child_good'] = $location[$vv['goods_id']]??[];
		            $orderMsgArr[$kk]['goods_pic_path'] = $goodpic[$vv['goods_brand']]['path']??$goodpic['logo']['path'];
                    if($orderMsgArr[$kk]['goods_pic_path']==''){
                        switch ( $vv['category'] ){
                            case 3:
                                $orderMsgArr[$kk]['goods_pic_path'] = $goodpic['车膜']['path'];
                                break;
                            default:
                                ;
                                break;
                        }
                    }
		        }
	        }
	        $data['orderMsgArr'] = $orderMsgArr;
 		}
        return $data;
 	}
    /**
     * 获取定单状态名
     * @return /multitype:array
     * @author du 2021年7月30日下午2:00:40
     */
    public static function getOrderStatusName( $type = true)
    {
        $data = [['type'=>1,'name'=>'新订单'],['type'=>3,'name'=>'等待发货'],['type'=>5,'name'=>'处理中'],['type'=>10,'name'=>'可派单'],['type'=>20,'name'=>'已调派（未接单）'],['type'=>30,'name'=>'安装中'],['type'=>34,'name'=>'待完成'],['type'=>40,'name'=>'已完成'],['type'=>50,'name'=>'已撤销'],['type'=>55,'name'=>'已撤销(补油费)']];
        if($type){
            $data = array_column($data, 'name','type');
        }
    	return $data;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取是否为F6
     * @retrun /multitype:array
     * @author dou 2021/12/14 2:55
     * |---------------------------------------------------------------------------------
    */
    public static function getSmartStoreName ( $type = false){
        $data = [['type'=>1,'name'=>'正常订单','color'=>''],['type'=>2,'name'=>'F6订单','color'=>'red'],['type'=>3,'name'=>'蓝领订单','color'=>'blue'],['type'=>4,'name'=>'任务单','color'=>'']];
        if($type){
            $data = array_column($data, 'name','type');
        }
        return $data;
    }

    /**
     * @name 获取订单商品类型
     * @return string[]
     * @author du
     * @date 2021/9/7
     */
    public static function getGoodsServiceName(){
        $data = array("0"=>'追加','1'=>'正常','2'=>'退货','3'=>'换货','4'=>'换新');
        return $data;
    }
    /**
     * 获取服务类型
     * @param $group 请求权限
     * @return /multitype:array
     * @author dou 2021年7月31日
     */
    public static function showSerType( $group = '' , $type = '' ){
	    if(!$group){
		    $show = [];
	    }else{
		    $show = [];
	    }
    	$showdata = array(array("type"=>1,"name"=>'上门安装'),array("type"=>2,"name"=>'到店安装'),array("type"=>3,"name"=>'物流快递'));
    	if($show){
	    	foreach( $showdata as $k => $v ){
				if(in_array($k,$show)){
					$data[] = $v;
				}
			}
		}else{
			$data = $showdata;
		}
		if( $type =='1'){
			$data = array_column($data, 'name' , 'type');
		}
		return $data;
    }
    /**
     * 获取付款类型
     * @param $group 请求权限
     * @return /multitype:array
     * @author dou 2021年7月31日
     */
    public static function showPayType( $group = '' , $type = '' ){
	    if(!$group){
		    $show = [];
	    }else{
            $bmmc_pids = BmmcService::searchPids($group);
            if(in_array('112',$bmmc_pids)||in_array('8',$bmmc_pids)){
                $show = [1];
            }else{
                $show = [];
            }
	    }
    	$showdata = array(array("type"=>1,"name"=>'在线支付'),array("type"=>2,"name"=>'货到付款'));
    	if($show){
            $showdata = CommonService::jointArrayKey($showdata, 'type');
	    	foreach( $showdata as $k => $v ){
				if(in_array($k,$show)){
					$data[] = $v;
				}
			}
		}else{
			$data = $showdata;
		}
		if( $type =='1'){
			$data = array_column($data, 'name' , 'type');
		}
		return $data;
    }
    /**
     * 获取订单类型
     * @param $group 请求权限
     * @return /multitype:array
     * @author dou 2021年7月31日
     */
    public static function showOrderType( $group = '' , $type = '' ){
	    if(!$group){
		    $show = [];
	    }else{
            $bmmc_pids = BmmcService::searchPids($group);
            if(in_array('104',$bmmc_pids)||in_array('112',$bmmc_pids)||in_array('8',$bmmc_pids)){
                $show = [1];
            }else{
                $show = [];
            }
	    }
    	$showdata = array(array("type"=>1,"name"=>'正常'),array("type"=>10,"name"=>'夜间'),array("type"=>15,"name"=>'加急（四十分钟救援）'),array("type"=>20,"name"=>'加急（六十分钟救援）'),array("type"=>25,"name"=>'加急（九十分钟救援）'),array("type"=>30,"name"=>'加急（一百二十分钟救援）'));
    	if($show){
            $showdata = CommonService::jointArrayKey($showdata, 'type');
	    	foreach( $showdata as $k => $v ){
				if(in_array($k,$show)){
					$data[] = $v;
				}
			}

		}else{
			$data = $showdata;
		}
		if( $type =='1'){
			$data = array_column($data, 'name' , 'type');
		}
		return $data;
    }
    /**|---------------------------------------------------------------------------------
     * @name  最近添加订单的平台，服务类型
     * @param string $admin_id 操作人id
     * @return /multitype:array
     * @author dou 2021年8月10日
     * |---------------------------------------------------------------------------------
     */
    public static function getOldpt($admin_id)
    {
        $db = new Orders();
        $res = CommonService::getMysqlData($db,['admin_id'=>$admin_id],['ser_type','p_id'],['create_time'=>'DESC'],'first');
        if(!$res){
            $admin = new Admin();
            $ptid = CommonService::getMysqlData($admin,['id'=>$admin_id],['ptid'],[],'value');
            if($ptid){
                $res['p_id'] = (int)$ptid;
                $res['ser_type'] = 0;
            }
        }
        return $res;
    }


    /**|---------------------------------------------------------------------------------
     * 退换货记录
     * @param $msg_id
     * @param $goods_name
     * @param $is_action
     * @param $admin_acc
     * @return int
     * |---------------------------------------------------------------------------------
     */
    public static function aftersaleLog($msg_id,$goods_name,$is_action,$admin_acc){
    	$data['msg_id'] = $msg_id;
    	$data['goods_name'] = $goods_name;
    	$data['create_name'] = $admin_acc;
    	$data['is_action'] = $is_action;
    	$result = DB::table('order_log')->insert($data);
    	if($result){
    		return 1;
    	}else{
    		return 2;
    	}
    }
    /**|---------------------------------------------------------------------------------
     * @name 订单派遣
     * @param $session 登录用户信息 id:操作人id  admin_acc：操作人名称
     * @param $input 订单信息  orders_id：订单数据id  ser_id：服务商id  user_id：用户id  sys_num：工单号
     * @param $ip 访问ip
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2020/7/10 10:28>
     * |---------------------------------------------------------------------------------
     */
    public static function  sendOrder ($session,$input,$ip ){
        $BaseController = new BaseController;
        $orderinfo = OrderService::getOrderBy('id', $input['orders_id'],['p_id', 'order_num', 'order_status', 'new_customer_id', 'create_time', 'new_money', 'order_type', 'pay_type','category','company_id']);
        if($orderinfo) {
            DB::beginTransaction();
            $shr_code = UserService::getUserBy('id', $orderinfo['new_customer_id'],['shr_code','is_jdservice']);
            if($shr_code['shr_code'] == ''){
                $appoint_code = OrderService::creactCode($orderinfo['p_id']);
                if($appoint_code){
                    $user['shr_code'] = $appoint_code;
                    $rea = User::where("id",$orderinfo['new_customer_id'])->update($user);
                    if(!$rea){
                        DB::rollback();
                        return ['Data' => '', 'ErrorMessage' => '生成客户识别码失败U，请重试！', 'ErrorCode' => ErrorInc::MYSQL_FAILED];
                    }
                }else{
                    DB::rollback();
                    return ['Data' => '', 'ErrorMessage' => '生成客户识别码失败，请重试！', 'ErrorCode' => ErrorInc::MYSQL_FAILED];
                }
            }
            if ($orderinfo['order_status'] > 10) {
                DB::rollback();
                return ['Data' => '', 'ErrorMessage' => '派单失败，该订单状态不正确，请刷新核实！', 'ErrorCode' => ErrorInc::REQUEST_FORBIDDEN];
            } else {
                $sub_types = PlatformService::getFieldsById($orderinfo['p_id'],['bus_type','pcl_id']);
                $pcl_id = $sub_types['pcl_id'];
                $sub_type = $sub_types['bus_type'];
                $msgdb = new OrderMsg();
                $ordermsginfo = CommonService::getMysqlData($msgdb, ['sys_num'=>$input['sys_num'],'goods_service_notin'=>[2,3]],['id', 'goods_brand', 'goods_id', 'goods_name', 'goods_num','neg_price','goods_price','category']);
                if($ordermsginfo){
                    $child_good = $input['child_good']??'';
                    $goodid = array_column($ordermsginfo, 'goods_id');
                    if($child_good){
                        if(is_array($child_good)){
                            $oml_oid = OrderMsgLocation::where("oml_oid",$input['orders_id'])->value('oml_oid');
                            if($oml_oid) {
                                $locationpdelet = OrderMsgLocation::where("oml_oid", $input['orders_id'])->delete();
                                if (!$locationpdelet) {
                                    DB::rollback();
                                    return ['Data' => '', 'ErrorMessage' => '子商品处理失败', 'ErrorCode' => ErrorInc::MYSQL_FAILED];
                                }
                            }
                            foreach($child_good as $k => $v){
                                if(!in_array($v['goodsid'], $goodid)) {
                                    $msglocationp[$k]['oml_oid'] = $input['orders_id'];
                                    $msglocationp[$k]['oml_sysnum'] = $input['sys_num'];
                                    $msglocationp[$k]['oml_ordernum'] = $orderinfo['order_num'];
                                    $msglocationp[$k]['oml_parentid'] = $v['parentid'];
                                    $msglocationp[$k]['oml_goodsid'] = $v['goodsid'];
                                    $msglocationp[$k]['oml_goodsname'] = $v['goodsname'];
                                    $locationpinsert = OrderMsgLocation::insert($msglocationp[$k]);
                                    if (!$locationpinsert) {
                                        DB::rollback();
                                        return ['Data' => '', 'ErrorMessage' => '子商品处理失败1', 'ErrorCode' => ErrorInc::MYSQL_FAILED];
                                    }
                                }
                            }
                        }else{
                            return ['Data' => '', 'ErrorMessage' => '下属商品数据异常', 'ErrorCode' => ErrorInc::INVALID_PARAM];
                        }
                    }
                    if($shr_code['is_jdservice'] == 2 && $pcl_id ==11){
                        if($child_good){
                            $child_id = array_column($child_good, 'goodsid');
                            $pt_data = self::getPtReceamount($orderinfo['p_id'],$child_id);
                        }else{
                            if(in_array('5912', $goodid)){
                                $pt_data = self::getPtReceamount($orderinfo['p_id'],['5912']);
                            }else{
                                DB::rollback();
                                return ['Data' => '', 'ErrorMessage' => '商品异常', 'ErrorCode' => ErrorInc::MYSQL_FAILED];
                            }
                        }
                        if($pt_data['pt_receamount'] <= 0 || $pt_data['pt_prepamount'] < $pt_data['pt_dispamount'] || $pt_data['pt_dispamount'] < $pt_data['pt_receamount']){
                            DB::rollback();
                            return ['Data' => '', 'ErrorMessage' => '平台预充值金额不足,无法派单', 'ErrorCode' => ErrorInc::MYSQL_FAILED];
                        }
                        $get['ol_dispamount'] = $pt_data['pt_dispamount'];
                        $get['ol_receamount'] = $input['service_charge'] = $pt_data['pt_receamount'];
                        $pt_res = DB::update("UPDATE gone_pt set pt_prepamount=pt_prepamount-".$pt_data['pt_dispamount'].",pt_lockamount=pt_lockamount+".$pt_data['pt_dispamount']." where id=? and pt_prepamount >=?",[$orderinfo['p_id'],$pt_data['pt_dispamount']]);
                        $pt_install=[];
                        $pt_install['pi_ptid']=$pt_data['id'];
                        $pt_install['pi_serid']=$input['ser_id'];
                        $pt_install['pi_sysbh']=$input['sys_num'];
                        $pt_install['pi_skbbh']=$orderinfo['order_num'];
                        $pt_install['pi_creatime']=date('Y-m-d H:i:s');
                        $pt_install['pi_conent']='派单';
                        $pt_install['pi_pricetype']=1;
                        $pt_install['pi_companyid']=1;
                        $pt_install['pi_username'] = $session['admin_acc'];
                        $pt_install['pi_price']=0-$pt_data['pt_dispamount'];
                        $pt_install['pi_afterprice']=$pt_data['pt_prepamount']-$pt_data['pt_dispamount'];
                        $pt_install['pi_lockprice']=$pt_data['pt_lockamount'];
                        $pt_install['pi_preprice']=$pt_data['pt_prepamount'];

                        $pt_instData[]=$pt_install;
                        // pi_afterprice
                        $pt_install['pi_pricetype']	=2;
                        $pt_install['pi_preprice']	=$pt_data['pt_prepamount']-$pt_data['pt_dispamount'];
                        $pt_install['pi_price']		=$pt_data['pt_dispamount'];
                        $pt_install['pi_afterprice']=$pt_data['pt_lockamount']+$pt_data['pt_dispamount'];

                        $pt_instData[]=$pt_install;
                        DB::table('pt_installog')->insert($pt_instData);
                    }else{
                        $pt_res = true;
                    }
                    $syspt = OrderService::sysPtThree( $orderinfo , 1);
                    if($syspt['ErrorCode']!=1){
                        DB::rollback();
                        return $syspt;
                    }else{
                        $shr_phone = CommonService::getUser('id', $input['user_id']);
                        $post['ser_id'] = $input['ser_id'];//服务中心id
                        $post['order_status'] = 20;//已派单

                    }
                    $install=InstallPerson::whereRaw("(admin_id='".$input['ser_id']."' or company_id='".$input['ser_id']."') and delet_y=1 and install_state=1 and install_is_type=1 and is_shman=2 and bind_id is not null")->select('id','check_code','install_name','install_phone','bind_id')->first();
                    $push_type=1;
                    $serid = Admin::whereRaw("FIND_IN_SET(" . $input['ser_id'] . ",children_id)")->value('id');
                    $ol_distype = DB::table('order_rejected')->where("or_order_num",$orderinfo['order_num'])->where('or_ser_id',$input['ser_id'])->value('or_id');
                    foreach ($ordermsginfo as $k => $v) {
                        $orderlistIds = OrderList::where(['sys_num' => $input['sys_num'], 'order_goods_id' => $v['id']])->value('id');
                        if ($orderlistIds) {
                            $BaseController->insertingLog("派单，", $input['sys_num'], "订单重复派单", "订单管理", $ip, $session['admin_acc']);//日志;
                            DB::rollback();
                            return ['Data' => '', 'ErrorMessage' => '派单失败，该订单已被派单，请刷新核实！', 'ErrorCode' => ErrorInc::REPEAT_SUBMIT];
                        }else{
                            $number = 'P' . date("Ymdhis") . str_pad(rand(0, 999), 3, '0', STR_PAD_LEFT);
                            /***追溯****/
                            $arr['trace_code'] = $number;//追溯码
                            $arr['code'] = "http://weixin.sudianwang.com/index.php/Management/index?trace_code_select=" . $number . "&";//二维码
                            /***派工单***/

                            $get['stauas'] = 20;
                            $get['goods_brand'] = $v['goods_brand'];//商品品牌
                            $get['serial_number'] = $number;//派工单号
                            $get['p_id'] = $orderinfo['p_id'];//平台id
                            $get['ser_id'] = $input['ser_id'];//服务中心id
                            $get['sys_num'] = $input['sys_num'];//系统单号
                            $get['order_num'] = $orderinfo['order_num'];//平台编号
                            $get['goods_num'] = $v['goods_num'];//派遣商品数量
                            $get['category'] = $v['category'];//商品类型
                            $get['order_goods_id'] = $v['id'];//关联msg_id
                            $get['admin_id'] = $session['id'];//$_SESSION['id'];//创建人id
                            $get['creater'] = $session['admin_acc'];
                            $get['customer_id'] = $orderinfo['new_customer_id'];//用户id
                            $get['customer_phone'] = $shr_phone['shr_phone'];//客户手机号
                            $get['orli_type'] = $orderinfo['order_type'];//订单类型
                            $get['pay_typel'] = $orderinfo['pay_type'];//支付方式
                            if ($sub_type == 2) {
                                $get['goods_price'] = $v['neg_price'];
                            }
                            if($input['service_charge']){
                                $get['goods_price'] = $input['service_charge'];
                                $get['manhourfee'] = $input['service_charge'];
                            }else{
                                $get['goods_price'] = 0;
                                $get['manhourfee'] = 0;
                            }
                            $timed = DB::table('ser_time')->where('ser_id', 0)->first();
                            $date_n = date("Y-m-d", strtotime("+1 day"));
                            $date_s = date("H:i:s");
                            if ($date_s > $timed['start_time'] && $date_s < $timed['end_time']) {
                                $payout_time = date("Y-m-d H:i:s");//接单奖罚起始计时时间
                            } else {
                                if ($date_s < $timed['start_time']) {
                                    $payout_time = date("Y-m-d") . " " . $timed['start_time'];//接单奖罚起始计时时间
                                } else {
                                    $payout_time = $date_n . " " . $timed['start_time'];//接单奖罚起始计时时间
                                }
                            }
                            /***订单操作时间***/
                            $BaseController->operatingTime($number, '下单时间', $orderinfo['create_time'], $orderinfo['order_num'], $session['admin_acc']);//订单操作时间
                            $BaseController->operatingTime($number, '派单时间', date("Y-m-d H:i:s"), $orderinfo['order_num'], $session['admin_acc']);//订单操作时间
                            $BaseController->addThistory($number, 'tih_crecttime', $payout_time, $input['ser_id'], 1);//添加历史时间

                            /***************半径推送******************************/
                            $store = CommonService::getSyncStores($input['ser_id'], $orderinfo['category']);
                            if(!empty($store)){
                                $pt_id_arr = PlatformService::getPtIdByPtType();
                                if(in_array($orderinfo['p_id'], $pt_id_arr)){
                                    $supply_price = GhXPrice::whereRaw("`goods_id`='" . $v['goods_id'] . "' and `ser_id`=0")->orderBy('id', 'DESC')->value('supply_price');
                                }else {
                                    $supply_price = GhPrice::whereRaw("`goods_id`='" . $v['goods_id'] . "' and `ser_id`='".$input['ser_id']."'")->orderBy('id', 'DESC')->value('supply_price');
                                    if(!$supply_price) {
                                        $supply_price = GhPrice::whereRaw("`goods_id`='" . $v['goods_id'] . "' and `ser_id`=0")->orderBy('id', 'DESC')->value('supply_price');
                                    }
                                }
                                if(!$supply_price){
                                    $supply_price='0.00';
                                }
                                $goo_code = DB::table('pj_goodcode')->where(['pgc_pgid'=>$v['goods_id'],'pgc_type'=>'1'])->first();
                                if(empty($goo_code)){
                                    $goo_code['pgc_code']='暂无';
                                    $goo_code['new']='暂无';
                                }

                                $pop['platform_number'] = $orderinfo['order_num'];
                                $pop['ord_order_number'] = $number;
                                $pop['ord_clent_id'] = $input['user_id'];
                                $pop['order_num'] = $orderinfo['order_num'];
                                $pop['orcl_name'] = $shr_phone['shr_name'];
                                $pop['orcl_phone'] = $shr_phone['shr_phone'];
                                $pop['orcl_province'] = $shr_phone['shr_sheng'];
                                $pop['orcl_city'] = $shr_phone['shr_shi'];
                                $pop['orcl_county'] = $shr_phone['shr_xian'];
                                $pop['orcl_address'] = $shr_phone['shr_adress'];
                                $pop['ord_service_shop_id'] = $input['ser_id'];
                                $pop['goo_id'] = $v['goods_id'];
                                $pop['goo_code'] = $goo_code['pgc_code'];
                                $pop['goo_codenew'] = $goo_code['new'];
                                $pop['goo_name'] = $v['goods_name'];
                                $pop['goo_quantity'] = $v['goods_num'];
                                $pop['ord_service_adm_id'] = $install['id']??0;
                                $pop['ord_service_type'] = 1;
                                $pop['ord_client_id'] = $orderinfo['new_customer_id'];
                                $pop['goo_is_recycle'] = 1;
                                $pop['goo_price'] = $supply_price;
                                $pop['company_name'] = CompanyService::getCompanyById($orderinfo['company_id'],['com_name'],'value');
                                $store = SysStoresService::sysStore($pop, 'orderUrl',$store);
                                if($store['ErrorCode']!=1){
                                    DB::rollback();
                                    return $store;
                                }
                                $push_type=2;
                                $get['store_type'] = 5;//派工单状态
                                $post['store_type'] = 5;

                            }else{
                                $get['store_type'] = 1;//派工单状态
                                $post['store_type'] = 1;
                            }
                            /***************半径推送******************************/

                            OrderAfter::where('deal_serid',0)->where('order_num',$orderinfo['order_num'])->update(['deal_serid'=>$input['ser_id'],'ser_id'=>$input['ser_id']]);

                            $get['company_id'] = $orderinfo['company_id'];
                            $get['ol_distype'] = 3;//手动派单
                            if(isset($ol_distype) && !empty($ol_distype)){
                                $get['ol_distype'] = 1;//手动重复派单
                            }
                            $agency_id = DB::table('admin')
                                ->where('id',$input['ser_id'])
                                ->value('company_id');
                            $get['agency_id'] = $agency_id;//代理商id(运营商）
                            $returnOrderList = OrderList::insert($get);//派工单列表
                            $arr['company_id'] = $orderinfo['company_id'];
                            $returnMan = Management::insert($arr);
                            if ($returnOrderList) {
                                $weixin['ser_id'] = $input['ser_id'];
                                $weixin['order_num'] = $orderinfo['order_num'];
                                $weixin['goods_name'] = '安装服务';//$v['goods_name'];
                                $weixin['serial_number'] = $number;
                                $weixin['dress'] = $shr_phone['shr_sheng'].$shr_phone['shr_shi'].$shr_phone['shr_xian'].$shr_phone['shr_adress'];

//                                CommonService::requestPost('http://zptzchat.bluearp.com/m/index.php/BindingAccount/push_order', $weixin);
                                CommonService::push_order($weixin);

                                /*--------------------------添加订单执行统计记录开始------------------------------------*/
                                $relation['sys_num'] = $input['sys_num'];//系统单号
                                $relation['order_num'] = $orderinfo['order_num'];//平台单号
                                $relation['serial_number'] = $number;//派工单号
                                $relation['single_payer'] = $session['admin_acc'];//派单人
                                $relation['order_time'] = $orderinfo['create_time'];//下单时间
                                $relation['payment_time'] = date("Y-m-d H:i:s");//派单时间
                                $relation['ser_id'] = $input['ser_id'];//服务商id
                                $relation['order_goods_id'] = $v['id'];//商品id
                                $relation['p_id'] = $orderinfo['p_id'];//平台id
                                $relation['admin_id'] = $session['id'];
                                $relation['customer_id'] = $orderinfo['new_customer_id'];//用户id
                                $relation['order_state'] = 20;//订单状态（已派单）
                                $relation['update_time'] = date("Y-m-d H:i:s");//更新时间
                                $relation['orli_type'] = $orderinfo['order_type'];//订单类型
                                $relation['category'] = 1;//已派单
                                $relation['company_id'] = $orderinfo['company_id'];
                                Temporary::insert($relation);
                                /*--------------------------添加订单执行统计记录结束------------------------------------*/

                                /*--------------------------添加工单回访记录开始------------------------------------*/
                                $visit_data['ov_serial'] = $number;
                                $visit_data['ov_sys'] = $input['sys_num'];
                                $visit_data['ov_order'] = $orderinfo['order_num'];
                                $visit_data['ov_creatime'] = date('Y-m-d H:i:s');
                                $visit_data['ov_statue'] = 1;
                                $visit_data['ov_show'] = 1;
                                $visit_data['ov_lasttime'] = date("Y-m-d H:i:s", intval(time()));
                                $visit_data['company_id'] = $orderinfo['company_id'];
                                OrderVisit::insert($visit_data);
                                /*--------------------------添加工单回访记录结束------------------------------------*/

                                /*--------------------------添加工单上游记录开始------------------------------------*/
                                $senl['os_serial'] = $number;
                                $senl['os_serid'] = $input['ser_id'];
                                $senl['os_installid'] = $input['ser_id'];
                                $senl['os_parenid'] = '0';
                                $senl['os_ordernum'] = $orderinfo['order_num'];
                                $senl['os_sysnum'] = $input['sys_num'];
                                OrderSendflow::insert($senl);
                                /*--------------------------添加工单上游记录结束------------------------------------*/
                            }
                        }
                    }
                    $post['distype'] = 3;
                    $post['smart_store'] = $input['smart_store']??1;
                    $post['distance'] = $input['distance']??0;//派单门店距离
                    $returnOrder = Orders::where('sys_num', $input['sys_num'])->update($post);
                    // 派单扣除 订单所属公司金额
                    // 扣费
                    $post_data['adm_id'] = $session['admin_id']??0;
                    $post_data['company_id'] = $orderinfo['company_id'];
                    $post_data['order_number'] = $orderinfo['order_num'];
                    $post_data['reo_price'] = -0.5;
                    $post_data['reo_pay_way'] = 4;
                    $reduce_price = OrderDeductionFeeService::deductFee($post_data);
                    if ($reduce_price['code'] != 200) {
                        DB::rollback();
                        return ['Data' => '', 'ErrorMessage' =>$reduce_price['msg'], 'ErrorCode' =>$reduce_price['code']];
                    }
                    if ($returnOrder && $returnOrderList && $returnMan && $pt_res) {

                        DB::commit();
//                        $msgBody['pushtyep'] = 'appointment';
//                        $msgBody['order_num'] = $orderinfo['order_num'];
//                        $msgBody['sys_num'] = $input['sys_num'];
//                        $msgBody['number'] = $number;
//                        $msgBody['id'] = $session['id'];
//                        $msgBody['centent'] = "超15分钟未预约";
//                        $msgBody['admin_acc'] = $session['admin_acc'];
                        //DB::rollBack();
//                        $BaseController->pushRecord($msgBody,date("Y-m-d H:i:s", strtotime('+1 minutes', time())),4,$orderinfo['order_num'],1,1,0 );
                        $BaseController->insertingLog("派单，", $input['sys_num'], "订单" . $input['sys_num'], "订单管理", $ip, $session['admin_acc']);//日志
//                        if($push_type==1){
//                            try {
////                                OrderService::pushApp($orderinfo, $input['ser_id']);
//                            }catch(\Exception $e){
//                                return ['Data' => '', 'ErrorMessage' => '派单成功推送失败', 'ErrorCode' => 1];
//                            }
//                        }

                        return ['Data' => '', 'ErrorMessage' => '派单成功', 'ErrorCode' => 1];

                    }else{
                        DB::rollback();
                        return ['Data' => '', 'ErrorMessage' => '派单失败', 'ErrorCode' => ErrorInc::MYSQL_FAILED];
                    }
                }else{
                    DB::rollback();
                    return ['Data' => '', 'ErrorMessage' => '数据不存在-msg', 'ErrorCode' => ErrorInc::DATA_EMPTY];
                }
            }
        }else{
            return ['Data' => '', 'ErrorMessage' => '数据不存在-order', 'ErrorCode' => ErrorInc::DATA_EMPTY];
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取平台接单金额
     * @param int $pt_id 平台低
     * @param array $type_str 包含位置
     * @retrun /multitype:array
     * @author dou 2021/12/12 22:19
     * |---------------------------------------------------------------------------------
    */
    public static function getPtReceamount ( $pt_id , $type_str ){
        $pt_data = Pt::leftJoin('pt_relation', 'pt_relation.ptj_id', '=', 'pt.id')->where('id',$pt_id)->select('id','pt_name','pt_prepamount','pt_lockamount','pt_warnamount','pt_warnuserid','ptqc_dispamount','ptqc_receamount','ptqd_dispamount','ptqd_receamount','ptcd_dispamount','ptcd_receamount','pthd_dispamount','pthd_receamount','pttc_dispamount','pttc_receamount','ptdtc_dispamount','ptdtc_receamount','ptcj_dispamount','ptcj_receamount')->first();
        $pt_data = CommonService::dataToArray($pt_data);
        $pt_dispamount = 0;
        $pt_receamount = 0;

        $array=$type_str;
        if(count($array)==1 && in_array(5912,$array)){
            $array = [9589];
        }
        if(in_array(9589,$array)){
            $pt_dispamount +=(float)$pt_data['ptqc_dispamount'];
            $pt_receamount +=(float)$pt_data['ptqc_receamount'];
        }

        if(in_array(9583,$array)){
            $pt_dispamount +=(float)$pt_data['ptqd_dispamount'];
            $pt_receamount +=(float)$pt_data['ptqd_receamount'];
        }

        if(in_array(9584,$array)){
            $pt_dispamount +=(float)$pt_data['ptcd_dispamount'];
            $pt_receamount +=(float)$pt_data['ptcd_receamount'];
        }

        if(in_array(9585,$array)){
            $pt_dispamount +=(float)$pt_data['pthd_dispamount'];
            $pt_receamount +=(float)$pt_data['pthd_receamount'];
        }

        if(in_array(9586,$array)){
            $pt_dispamount +=(float)$pt_data['pttc_dispamount'];
            $pt_receamount +=(float)$pt_data['pttc_receamount'];
        }

        if(in_array(9587,$array)){
            $pt_dispamount +=(float)$pt_data['ptdtc_dispamount'];
            $pt_receamount +=(float)$pt_data['ptdtc_receamount'];
        }

        if(in_array(9588,$array)){
            $pt_dispamount +=(float)$pt_data['ptcj_dispamount'];
            $pt_receamount +=(float)$pt_data['ptcj_receamount'];
        }

        $pt_data['pt_dispamount'] = $pt_dispamount;
        $pt_data['pt_receamount'] = $pt_receamount;

        unset($pt_data['ptqc_dispamount']);unset($pt_data['ptqc_receamount']);
        unset($pt_data['ptqd_dispamount']);unset($pt_data['ptqd_receamount']);
        unset($pt_data['ptcd_dispamount']);unset($pt_data['ptcd_receamount']);
        unset($pt_data['pthd_dispamount']);unset($pt_data['pthd_receamount']);
        unset($pt_data['pttc_dispamount']);unset($pt_data['pttc_receamount']);
        unset($pt_data['ptdtc_dispamount']);unset($pt_data['ptdtc_receamount']);
        unset($pt_data['ptcj_dispamount']);unset($pt_data['ptcj_receamount']);

        return $pt_data;
    }

    /**|---------------------------------------------------------------------------------
     * @name 推送消息
     * @param array $orderinfo 订单信息
     * @param int $ser_id 门店id
     * @param string $type 推送类型
     * @retrun /multitype:array
     * @author dou 2021/8/17 17:27
     * |---------------------------------------------------------------------------------
    */
    public static function pushApp ( $orderinfo = [] , $ser_id , $type = '新订单'){
        return 1;
        $admin = Admin::whereRaw("FIND_IN_SET(" . $ser_id . ",children_id) or id='".$ser_id."'")->get(['admin_acc','token','phone_type','id'])->toArray();
        $admin_id = array_column($admin, 'id');
        $admininfor = new AdminInfor();
        $bind = CommonService::getMysqlData($admininfor, ['admin_id_searchin'=>$admin_id],['bind','admin_id']);
        $bind = CommonService::jointArrayKey($bind, 'admin_id');
        if(!empty($admin)){
            if($type == '新订单'){
                if ($orderinfo['order_type'] == 1) {
                    $type = "新订单";
                } elseif ($orderinfo['order_type'] == 10) {
                    $type = "夜间订单";
                } elseif ($orderinfo['order_type'] == 20 || $orderinfo['order_type'] == 15 || $orderinfo['order_type'] == 25 || $orderinfo['order_type'] == 30) {
                    $type = "加急订单";
                }
            }
            foreach( $admin as $k => $v ){
                if(isset($bind[$v['id']]) && $bind[$v['id']]['bind'] == 2) {
                    if ($v['phone_type'] == 'xiaomi') {
                        $Push = new PushxmController();
                        $Push->push($v['token'], $type);
                    } else {
                        $Push = new PushController();
                        $Push->push($v['admin_acc'], $type, 2);
                    }
                }
            }
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 派单同步第三方平台
     * @param array $orderinfo 订单信息
     * @retrun /multitype:array
     * @author dou 2021/8/17 13:37
     * |---------------------------------------------------------------------------------
    */
    public static function sysPtThree ( $orderinfo , $type){
        return ForeignApiService::sysPtThree($orderinfo, $type);
    }
    /**|---------------------------------------------------------------------------------
     * @name 获取系统推荐服务商
     * @param array $input 1:搜索匹配的服务中心; 4:名称匹配服务商
     * @param is_type 1:搜索匹配的服务中心; 4:名称匹配服务商
     * @param sys_num 系统单号（is_type=1）
     * @param sheng   省（is_type=1）
     * @param shi     是（is_type=1）
     * @param xian    县（is_type=1）
     * @param address 详细地址（is_type=1）
     * @param order_type 订单类型 1：普通；10：夜间；20：加急（is_type=1）
     * @param luotuo  是否为骆驼品牌 1：否 2：是（is_type=1）
     * @param
     * @param company_name 服务中心名称（is_type=4）
     * @retrun /multitype:array
     * @author dou 2021/8/17 18:18
     * |---------------------------------------------------------------------------------
    */
    public static function getService ( $input,$session='' ){
        if(isset($input['is_type'])){
            if(isset($input['searchdres']) && $input['searchdres'] == 1){
                $pt_id = 23;
                $category = 3;
                $ser_ids = [];
                $gs_bid = [];
                $cd_id = [];
            }else {
                $checkKey = CommonService::checkKey(['sys_num'], $input, OrderService::rulesShow());
                if ($checkKey['code'] != 1) {
                    return ['Data' => '', 'ErrorMessage' => '参数' . $checkKey['data'] . '未填写,或值为空', 'ErrorCode' => ErrorInc::INVALID_PARAM];
                }
                $order = OrderService::getOrderBy('sys_num', $input['sys_num'], ['category', 'p_id']);
                $pt_id = $order['p_id'];
                $category = $order['category'];
                /*--------------------------------------获取订单中包含的商品信息开始------------------------------------------*/
                $goods = OrderMsg::where("sys_num", $input['sys_num'])->pluck('goods_id')->toarray();
                $goodwhere['pg_id_searchin'] = $goods;
                $list = GoodsService::getGoodsBy($goodwhere, ['gs_bid', 'cd_id', 'brand_name']);
                //获取订单商品包含的品牌
                $gs_bid = array_column($list, 'gs_bid');
                $gs_bid = array_unique($gs_bid);

                $sup_brname = array_column($list, 'brand_name');
                $sup_brname = array_unique($sup_brname);
                //获取订单商品包含的品类
                $cd_id = array_column($list, 'cd_id');
                $cd_id = array_unique($cd_id);
                //获取活动服务中心id
                $time = date("Y-m-d H:i:s");
                $support = new Supportacti();
                $sup_serid = CommonService::getMysqlData($support, ['sup_startime_searchgt' => $time, 'sup_endtime_searchlt' => $time, 'sup_brname_searchin' => $sup_brname], ['sup_serid']);
                //dd($sup_serid);
                if ($sup_serid) {
                    $ser_ids = [];
                    foreach ($sup_serid as $ksu => $vsu) {
                        $serid = trim($vsu['sup_serid'], ',');
                        $ser_id[$ksu] = explode(',', $serid);
                        if ($ser_ids != "") {
                            $ser_ids = array_merge($ser_ids, $ser_id[$ksu]);
                        } else {
                            $ser_ids = $ser_id[$ksu];
                        }
                    }
                    $ser_ids = array_unique($ser_ids);
                } else {
                    $ser_ids = [];
                }
            }
            $brand_service = ServiceProviderService::getBrandService(true);
            /*--------------------------------------获取订单中包含的商品信息结束------------------------------------------*/
            if($input['is_type'] == 1){
                $checkKey = CommonService::checkKey(['sheng','shi','xian','order_type'],$input,OrderService::rulesShow());//,'address'
                if($checkKey['code']!=1){
                    return ['Data' => '', 'ErrorMessage' => '参数'.$checkKey['data'].'未填写,或值为空', 'ErrorCode' => ErrorInc::INVALID_PARAM];
                }
                /*--------------------------------------验证订单客户地址开始------------------------------------------*/
                if($category == 1) {
                    $region = new Region();
                    $shengs = ['北京', '上海', '天津', '重庆'];
                    if (strpos($input['sheng'], '省') !== false) {
                        $sheng = mb_substr($input['sheng'], 0, -1, 'utf-8');
                    } else {
                        $sheng = $input['sheng'];
                    }
                    $shr_sheng = $region->whereRaw("reg_level=1 and (reg_name like '%" . $input['sheng'] . "%' or reg_alias like '%" . $input['sheng'] . "%' or reg_name like '%" . $sheng . "%')")->first();
                    if ($shr_sheng) {
                        if (strstr($input['shi'], "东市")) {
                            $shi = str_replace('东市', '东', $input['shi']);
                        } elseif (strstr($input['shi'], "东")) {
                            $shi = $input['shi'];
                        } else {
                            $shi = mb_substr($input['shi'], 0, mb_strlen($input['shi']) - 1);
                        }
                        $region = new Region();
                        if (in_array($sheng, $shengs)) {
                            $shr_shi = $region->whereRaw("reg_level=2 and (reg_name like '%" . $input['sheng'] . "%' or reg_alias like '%" . $input['sheng'] . "%' or reg_name like '%" . $sheng . "%') and reg_blnum='" . $shr_sheng['reg_num'] . "'")->first();
                        } else {
                            $shr_shi = $region->whereRaw("reg_level=2 and (reg_name like '%" . $input['shi'] . "%' or reg_alias like '%" . $input['shi'] . "%' or reg_name like '%" . $shi . "%') and reg_blnum='" . $shr_sheng['reg_num'] . "'")->first();
                        }
                        if ($shr_shi) {
                            $drid = '';
                            $shiid = '';
                            $region = new Region();
                            if ($input['xian'] != '市、县级市') {
                                $shr_xian = $region->whereRaw("reg_level=3 and (reg_name like '%" . $input['xian'] . "%' or reg_alias like '%" . $input['xian'] . "%') and reg_blnum='" . $shr_shi['reg_num'] . "'")->first();
                                if ($shr_xian) {
                                    $drid = $shr_xian['reg_id'];
                                }
                            } else {
                                $shiid = $shr_shi['reg_id'];
                            }
                        } else {
                            return ['Data' => '', 'ErrorMessage' => '暂无推荐数据si', 'ErrorCode' => ErrorInc::DATA_EMPTY];
                        }
                    } else {
                        return ['Data' => '', 'ErrorMessage' => '暂无推荐数据se', 'ErrorCode' => ErrorInc::DATA_EMPTY];
                    }
                    if (!empty($shiid) || !empty($drid)) {
                        $arcover = new Disareanew();
                        if ($drid) {
                            $dress = $arcover->where(['are_shid' => $shr_sheng['reg_id'], 'are_xid' => $drid])->first();
                            $xian = 1;
                        } else {
                            $dress = $arcover->where(['are_shid' => $shr_sheng['reg_id'], 'are_sid' => $shiid])->first();
                            $xian = 2;
                        }
                        if ($xian == 1) {
                            $serPro = Bserviss::leftJoin('admin','admin.id','=','bservisnew.bs_serid')->whereRaw("find_in_set('" . $dress['are_id'] . "',bs_areid) and bs_status='1' and enable=1 and (company_id = '".$session['company_id']."') or admin_groupnew=3")->get();
                        } else {
                            $serPro = Bserviss::leftJoin('admin','admin.id','=','bservisnew.bs_serid')->whereRaw("bs_sid='" . $dress['are_sid'] . "' and bs_status='1' and enable=1 and (company_id = '".$session['company_id']."') or admin_groupnew=3")->get();
                        }
                        if ($serPro) {
                            $serPro = $serPro->toarray();

                            $admin_id = array_column($serPro, 'bs_serid');
                        } else {
                            return ['Data' => '', 'ErrorMessage' => '暂无推荐数据fw', 'ErrorCode' => ErrorInc::DATA_EMPTY];
                        }
                    } else {
                        //未匹配省市
                        return ['Data' => '', 'ErrorMessage' => '暂无推荐数据qx', 'ErrorCode' => ErrorInc::DATA_EMPTY];
                    }
                }else{
                    $special_city = ['北京市','天津市','上海市','重庆市','北京','天津','上海','重庆'];
                    if (strpos($input['sheng'], '省') !== false) {
                        $input['sheng'] = mb_substr($input['sheng'], 0, -1, 'utf-8');
                    } else {
                        $input['sheng'] = $input['sheng'];
                    }
                    if (strstr($input['shi'], "东市")) {
                        $input['shi'] = str_replace('东市', '东', $input['shi']);
                    } elseif (strstr($input['shi'], "东")) {
                        $input['shi'] = $input['shi'];
                    } else {
                        $input['shi'] = mb_substr($input['shi'], 0, mb_strlen($input['shi']) - 1);
                    }
                    if(in_array($input['sheng'],$special_city)){
                        $admin_id = AdminAddress::where('ad_sheng','like','%'.$input['sheng'].'%')->select("admin_id")->get();
                    }else{
                        $admin_id = AdminAddress::where('ad_sheng','like','%'.$input['sheng'].'%')->where('ad_shi','like','%'.$input['shi'].'%')->select("admin_id")->get();
                    }
                   // print_r($admin_id);
                    $admin_id = CommonService::dataToArray($admin_id);
                    if($admin_id) {
                        $admin_ids = array_column($admin_id, 'admin_id');
                        $admin_idss = array_unique($admin_ids);
                        /*$ids = [];
                        foreach ($admin_idss as $key => $value) {
                            if (!in_array($value, [3, 6, 4, 5, 444, 445, 446, 167, 266, 270, 353, 458])) {
                                $ids[] = $value;
                            }
                        }
                        $admin_id = $ids;*/
                    }else{
                        //未匹配省市
                        return ['Data' => '', 'ErrorMessage' => '暂无推荐数据dz', 'ErrorCode' => ErrorInc::DATA_EMPTY];
                    }
                }
                /*--------------------------------------验证订单客户地址结束------------------------------------------*/

                /*--------------------------------------获取对应服务商信息开始--------------------------------------------*/

                $where = ['id_searchin'=>$admin_id,'enable'=>1,'ad_project_findinset'=>$category];
               // if($pt_id == 453)
                $pt_id_arr = PlatformService::getPtIdByPtType();
                if(in_array($pt_id, $pt_id_arr))
                {
                    $where['service_type_findinset'] = '3';
                }else{
                    if(in_array($category, [1,2])){
                        $where['service_type_findinset'] = '1';
                    }
                }

                if ($session && $session['admin_groupnew'] != 7) {//管理员可以看全部
//                    $where['company_id'] = $session['company_id']; //2022-11-3 获取服务商可不用分公司
//                    $where['company_type'] = 1;
//                    $where['admin_groupnew'] = 2;

                    if($session['company_id']==14){
                        $wherecompany1['company_id'] = $session['company_id'];
                        $wherecompany1['company_type'] = 1;
                        $wherecompany1['admin_groupnew'] = 2;
                        $wherecompany2['id_searchin'] = [91,101];
                        $where['wherecompany_searchor']['wherecompany1_next_level'] = $wherecompany1;
                        $where['wherecompany_searchor']['wherecompany2_next_level'] = $wherecompany2;
                    }else {
                        $where['company_id'] = $session['company_id'];
                        $where['company_type'] = 1;
                        $where['admin_groupnew'] = 2;
                    }
                }

                $list = AdminsService::getAdmins($where,['id','company_name','is_lidao','owner','children_id','ad_brand','ad_project','brand_service'],['is_sord'=>'DESC']);

                if($list){
                    $children_id = [];
                    //if($pt_id != 453)
                    if(!in_array($pt_id, $pt_id_arr))
                    {
                        foreach ($list as $k2 => $v2) {
                            if ($v2['owner'] == '1' && $v2['children_id'] != '') {
                                $children_id[] = $v2['children_id'];
                            }
                        }
                    }
                }else{
                    return ['Data' => '', 'ErrorMessage' => '暂无推荐数据admin', 'ErrorCode' => ErrorInc::DATA_EMPTY];
                }
                if($children_id){
                    $children_id=implode(',',$children_id);
                    $admin_infor = new AdminInfor();
                    $inforsearch = ['admin_id_searchin'=>$children_id,'admin_province_rlike'=>$sheng,'admin_city_rlike'=>$shi];
                    if($input['xian']!='市、县级市'){
                        $inforsearch = array_merge($inforsearch,['admin_county_rlike'=>$input['xian']]);
                    }
                    $children = CommonService::getMysqlData($admin_infor, $inforsearch , ['admin_id']);
                    if($children){
                        $cadmin_id = array_column($children, 'admin_id');
                        $admin_id = array_merge($admin_id,$cadmin_id);
                        $lists = AdminsService::getAdmins($where,['id','company_name','is_lidao','owner','children_id','ad_brand','ad_project','brand_service'],['is_sord'=>'DESC']);
                        if($lists){
                            $list = array_merge($list,$lists);
                        }
                    }
                }
                $admin_infor = new AdminInfor();
                $children = CommonService::getMysqlData($admin_infor, ['admin_id_searchin'=>$admin_id] , ['admin_id','admin_longitude','admin_latitude','admin_province','admin_city','admin_county','admin_dressi','verstorename','verstoreid']);
                $admin_list = [];
                if($children){
                    $admin_list = CommonService::jointArrayKey($children, 'admin_id');
                }

                /*--------------------------------------获取对应服务商信息结束--------------------------------------------*/
                if($list){
                    $lists = [];
                    $jingwei = [];
                    $end = CommonService::jingwei($input['sheng'],$input['sheng'].$input['shi'].$input['xian'].$input['address']);
                    foreach( $list as $kri => $vri ){
                        if(isset($brand_service[$vri['brand_service']])){
                            $brand_serviceshow = "(".$brand_service[$vri['brand_service']].")";
                        }else{
                            $brand_serviceshow = '';
                        }
                        $adminInfo = $admin_list[$vri['id']];
                        $list[$kri]['verstorename'] = $adminInfo['verstorename']??'';
                        $list[$kri]['verstoreid'] = ''; //$adminInfo['verstoreid']??'';
                        $list[$kri]['dress'] = $adminInfo['admin_province']." ".$adminInfo['admin_city']." ".$adminInfo['admin_county']." ".$adminInfo['admin_dressi'];
                        if(in_array($vri['id'], $ser_ids)){
                            $zhichi="支持";
                            if(isset($flag) && $flag=='4'){
                                $zhichi.=":须核实";
                            }
                            $list[$kri]['company_name']=$vri['company_name'].$brand_serviceshow."(".$zhichi.")";
                        }else{
                            $list[$kri]['company_name']=$vri['company_name'].$brand_serviceshow;
                        }
                        $city = $adminInfo['admin_province'];
                        if($adminInfo['admin_longitude'] && $adminInfo['admin_latitude']){
                            $start = $adminInfo['admin_longitude'].','.$adminInfo['admin_latitude'];
                        }else{
                            $address = $adminInfo['admin_dressi'];
                            $start = CommonService::jingwei($adminInfo['admin_province'],$address);
                        }
                        if($adminInfo['admin_dressi']=='' || $start ==''){
                            $list[$kri]['juli'] = '';
                            $list[$kri]['jl'] = 100000;
                            $lists[] = $list[$kri];
                            unset($list[$kri]);continue;
                        }else{
                            $jingwei[] = $start;
                        }
                    }
                    if(!empty($jingwei) && !empty($end)){
                        $jingwei = implode('|', $jingwei);
                        $res = CommonService::juli($jingwei,$end,2);
                    }else{
                        $res = [];
                    }
                    $num_ = 0;
                    foreach ($list as $k => $v) {
                        if (!isset($res[$num_])) {
                            $list[$k]['juli'] = '';
                            $list[$k]['jl'] = 100000;
                        } else {
                            $list[$k]['juli'] = round($res[$num_]['distance']/1000,2) . '公里';
                            $list[$k]['jl'] = round($res[$num_]['distance']/1000,2);
                        }
                        $num_++;
                    }
                    if(!empty($lists) && !empty($list)) {
                        $list = array_merge($list, $lists);
                    }elseif (!empty($lists)){
                        $list = $lists;
                    }
                    $list = CommonService::resetListKey($list);
                    $num = [];
                    foreach($list as $k => $v){
                        $ad_brand = array_intersect(explode(',',trim($v['ad_brand'],',')),$gs_bid);//统计匹配订单商品品牌量
                        $list[$k]['contains_brand'] = array_values($ad_brand);
                        $ad_project = array_intersect(explode(',',trim($v['ad_project'],',')),$cd_id);//统计匹配订单商品品类量
                        $list[$k]['contains_project'] = array_values($ad_project);
                        $brandnum[] = count($ad_brand);
                        $list[$k]['brandnum'] = count($ad_brand);
                        $projectnum[] = count($ad_project);
                        $list[$k]['projectnum'] = count($ad_project);
                        $total[]=$v['is_lidao'];
                        $num[]=$v['jl'];
                        if($v['jl'] == 100000){
                            unset($list[$k]['jl']);
                        }
                    }
                    array_multisort($num, SORT_NUMERIC ,SORT_ASC, $brandnum, SORT_NUMERIC ,SORT_DESC, $projectnum, SORT_NUMERIC ,SORT_DESC, $list);
                    return ['Data' => $list, 'ErrorMessage' => '操作成功', 'ErrorCode' => 1];
                }else{
                    return ['Data' => '', 'ErrorMessage' => '无数据', 'ErrorCode' => ErrorInc::DATA_EMPTY];
                }
            }
            else if($input['is_type'] == 4){
                $checkKey = CommonService::checkKey(['company_name'],$input,OrderService::rulesShow());
                if($checkKey['code']!=1){
                    return ['Data' => '', 'ErrorMessage' => '参数'.$checkKey['data'].'未填写,或值为空', 'ErrorCode' => ErrorInc::INVALID_PARAM];
                }
                $admin_infors = new AdminInfor();
                $verstorename_id = CommonService::getMysqlData($admin_infors, ['verstorename_like'=>$input['company_name']],['admin_id']);
                if($verstorename_id) {
                    $verstorename_id = array_column($verstorename_id, 'admin_id');
                    $company_name_or['id_searchin'] = $verstorename_id;
                }
                $company_name_or['company_name_like'] = $input['company_name'];
                $where = ['company_name_searchor'=>$company_name_or,'enable'=>1,'ad_project_findinset'=>$category];

                $pt_id_arr = PlatformService::getPtIdByPtType();
                if(in_array($pt_id, $pt_id_arr))
                //if($pt_id == 453)
                {
                    $where['service_type_findinset'] = '3';
                }

                if ($session && $session['admin_groupnew'] != 7) {//管理员可以看全部
                    if($session['company_id']==14){
                        $wherecompany1['company_id'] = $session['company_id'];
                        $wherecompany1['company_type'] = 1;
                        $wherecompany1['admin_groupnew'] = 2;
                        $wherecompany2['id_searchin'] = [91,101];
                        $where['wherecompany_searchor']['wherecompany1_next_level'] = $wherecompany1;
                        $where['wherecompany_searchor']['wherecompany2_next_level'] = $wherecompany2;
                    }else {
                        $where['company_id'] = $session['company_id'];
                        $where['company_type'] = 1;
                        $where['admin_groupnew'] = 2;
                    }
                }
                CommonService::startmysql();
                $list = AdminsService::getAdmins($where,['id','company_name','is_lidao','owner','children_id','ad_brand','ad_project','brand_service'],['is_sord'=>'DESC']);
                if($list){
                    $admin_id = array_column($list, 'id');
                    $admin_infor = new AdminInfor();
                    $children = CommonService::getMysqlData($admin_infor, ['admin_id_searchin'=>$admin_id] , ['admin_id','admin_longitude','admin_latitude','admin_province','admin_city','admin_county','admin_dressi','verstorename','verstoreid']);
                    $admin_list = [];
                    if($children){
                        $admin_list = CommonService::jointArrayKey($children, 'admin_id');
                    }
                    $lists = [];
                    $jingwei = [];
                    $end = CommonService::jingwei($input['sheng'],$input['sheng'].$input['shi'].$input['xian'].$input['address']);
                    foreach( $list as $kri => $vri ){
                        if(isset($brand_service[$vri['brand_service']])){
                            $brand_serviceshow = "(".$brand_service[$vri['brand_service']].")";
                        }else{
                            $brand_serviceshow = '';
                        }
                        $adminInfo = $admin_list[$vri['id']];
                        $list[$kri]['verstorename'] = $adminInfo['verstorename']??'';
                        $list[$kri]['verstoreid'] = ''; //$adminInfo['verstoreid']??'';
                        if(in_array($vri['id'], $ser_ids)){
                            $zhichi="支持";
                            if(isset($flag) && $flag=='4'){
                                $zhichi.=":须核实";
                            }
                            $list[$kri]['company_name']=$vri['company_name'].$brand_serviceshow."(".$zhichi.")";
                        }else{
                            $list[$kri]['company_name']=$vri['company_name'].$brand_serviceshow;
                        }
                        $city = $adminInfo['admin_province'];
                        if($adminInfo['admin_longitude'] && $adminInfo['admin_latitude'] && $vri['is_lidao']=='2'){
                            $start = $adminInfo['admin_longitude'].','.$adminInfo['admin_latitude'];
                        }else{
                            $address = $adminInfo['admin_dressi'];
                            $start = CommonService::jingwei($adminInfo['admin_province'],$address);
                        }
                        if($adminInfo['admin_dressi']=='' || $start ==''){
                            $list[$kri]['juli'] = '';
                            $list[$kri]['jl'] = 100000;
                            $lists[] = $list[$kri];
                            unset($list[$kri]);continue;
                        }else{
                            $jingwei[] = $start;
                        }
                    }
                    if(!empty($jingwei) && !empty($end)){
                        $jingwei = implode('|', $jingwei);
                        $res = CommonService::juli($jingwei,$end,2);
                    }else{
                        $res = [];
                    }
                    $num_ = 0;
                    foreach ($list as $k => $v) {
                        if (!isset($res[$num_])) {
                            $list[$k]['juli'] = '';
                            $list[$k]['jl'] = 100000;
                        } else {
                            $list[$k]['juli'] = round($res[$num_]['distance']/1000,2) . '公里';
                            $list[$k]['jl'] = round($res[$num_]['distance']/1000,2);
                        }
                        $num_++;
                    }
                    if(!empty($lists) && !empty($list)) {
                        $list = array_merge($list, $lists);
                    }elseif (!empty($lists)){
                        $list = $lists;
                    }
                    $list = CommonService::resetListKey($list);
                    $num = [];
                    foreach($list as $k => $v){
                        $ad_brand = array_intersect(explode(',',trim($v['ad_brand'],',')),$gs_bid);//统计匹配订单商品品牌量
                        $list[$k]['contains_brand'] = array_values($ad_brand);
                        $ad_project = array_intersect(explode(',',trim($v['ad_project'],',')),$cd_id);//统计匹配订单商品品类量
                        $list[$k]['contains_project'] = array_values($ad_project);
                        $brandnum[] = count($ad_brand);
                        $list[$k]['brandnum'] = count($ad_brand);
                        $projectnum[] = count($ad_project);
                        $list[$k]['projectnum'] = count($ad_project);
                        $total[]=$v['is_lidao'];
                        $num[]=$v['jl'];
                        if($v['jl'] == 100000000){
                            unset($list[$k]['jl']);
                        }
                    }
                    array_multisort($brandnum, SORT_NUMERIC ,SORT_DESC, $projectnum, SORT_NUMERIC ,SORT_DESC, $list);
                    return ['Data' => $list, 'ErrorMessage' => '操作成功', 'ErrorCode' => 1];
                }else{
                    return ['Data' => '', 'ErrorMessage' => '无数据', 'ErrorCode' => ErrorInc::DATA_EMPTY];
                }
            }
            else if($input['is_type'] == 3){
                $checkKey = CommonService::checkKey(['service_id'],$input,OrderService::rulesShow());
                if($checkKey['code']!=1){
                    return ['Data' => '', 'ErrorMessage' => '参数'.$checkKey['data'].'未填写,或值为空', 'ErrorCode' => ErrorInc::INVALID_PARAM];
                }

                $list = AdminsService::getAdmins(['id'=>$input['service_id'],'company_id'=>$session['company_id'],'company_type'=>1],['id','company_name','is_lidao','owner','children_id','ad_brand','ad_project','brand_service'],['is_sord'=>'DESC']);
                if($list){
                    foreach( $list as $kri => $vri ){
                        $ad_brand = array_intersect(explode(',',trim($vri['ad_brand'],',')),$gs_bid);//统计匹配订单商品品牌量
                        $list[$kri]['contains_brand'] = array_values($ad_brand);
                        $ad_project = array_intersect(explode(',',trim($vri['ad_project'],',')),$cd_id);//统计匹配订单商品品类量
                        $list[$kri]['contains_project'] = array_values($ad_project);
                        $brandnum[] = count($ad_brand);
                        $list[$kri]['brandnum'] = count($ad_brand);
                        $projectnum[] = count($ad_project);
                        $list[$kri]['projectnum'] = count($ad_project);
                    }
                    array_multisort($brandnum, SORT_NUMERIC ,SORT_DESC, $projectnum, SORT_NUMERIC ,SORT_DESC, $list);
                    return ['Data' => $list, 'ErrorMessage' => '操作成功', 'ErrorCode' => 1];
                }else{
                    return ['Data' => '', 'ErrorMessage' => '无数据', 'ErrorCode' => ErrorInc::DATA_EMPTY];
                }
            }
            else if($input['is_type'] == 5){
                $checkKey = CommonService::checkKey(['company_id'],$input,OrderService::rulesShow());
                if($checkKey['code']!=1){
                    return ['Data' => '', 'ErrorMessage' => '参数'.$checkKey['data'].'未填写,或值为空', 'ErrorCode' => ErrorInc::INVALID_PARAM];
                }
                $where = ['enable'=>1,'ad_project_findinset'=>$category];

                if(isset($input['company_name']) && !empty($input['company_name'])) {
                    $where['company_name_like'] = $input['company_name'];
                }
                if(isset($session['company_id'])){
                    $where['company_id'] = $session['company_id'];
                }else {
                    $where['company_id'] = $input['company_id'];
                }
                $where['company_type'] = 2;
                $pt_id_arr = PlatformService::getPtIdByPtType();
                if(in_array($pt_id, $pt_id_arr))
                    //if($pt_id == 453)
                {
                    $where['service_type_findinset'] = '3';
                }
                $list = AdminsService::getAdmins($where,['id','company_name','is_lidao','owner'],['is_sord'=>'DESC']);
                if($list){
                    $admin_id = array_column($list, 'id');
                    $admin_infor = new AdminInfor();
                    $children = CommonService::getMysqlData($admin_infor, ['admin_id_searchin'=>$admin_id] , ['admin_id','admin_longitude','admin_latitude','admin_province','admin_city','admin_county','admin_dressi','verstorename','verstoreid']);
                    $admin_list = [];
                    if($children){
                        $admin_list = CommonService::jointArrayKey($children, 'admin_id');
                    }
                    $lists = [];
                    $jingwei = [];
                    $end = CommonService::jingwei($input['sheng'],$input['sheng'].$input['shi'].$input['xian'].$input['address']);
                    foreach( $list as $kri => $vri ){
                        $adminInfo = $admin_list[$vri['id']];
                        $city = $adminInfo['admin_province'];
                        if($adminInfo['admin_longitude'] && $adminInfo['admin_latitude'] && $vri['is_lidao']=='2'){
                            $start = $adminInfo['admin_longitude'].','.$adminInfo['admin_latitude'];
                        }else{
                            $address = $adminInfo['admin_dressi'];
                            $start = CommonService::jingwei($adminInfo['admin_province'],$address);
                        }
                        if($adminInfo['admin_dressi']=='' || $start ==''){
                            $list[$kri]['juli'] = '';
                            $list[$kri]['jl'] = 100000;
                            $lists[] = $list[$kri];
                            unset($list[$kri]);continue;
                        }else{
                            $jingwei[] = $start;
                        }
                    }
                    if(!empty($jingwei) && !empty($end)){
                        $jingwei = implode('|', $jingwei);
                        $res = CommonService::juli($jingwei,$end,2);
                    }else{
                        $res = [];
                    }
                    $num_ = 0;
                    foreach ($list as $k => $v) {
                        if (!isset($res[$num_])) {
                            $list[$k]['juli'] = '';
                            $list[$k]['jl'] = 100000;
                        } else {
                            $list[$k]['juli'] = round($res[$num_]['distance']/1000,2) . '公里';
                            $list[$k]['jl'] = round($res[$num_]['distance']/1000,2);
                        }
                        $num_++;
                    }
                    if(!empty($lists) && !empty($list)) {
                        $list = array_merge($list, $lists);
                    }elseif (!empty($lists)){
                        $list = $lists;
                    }
                    $list = CommonService::resetListKey($list);
                    $num = [];
                    foreach($list as $k => $v){
                        $total[]=$v['is_lidao'];
                        $num[]=$v['jl'];
                        if($v['jl'] == 100000000){
                            unset($list[$k]['jl']);
                        }
                    }
                    array_multisort($num, SORT_NUMERIC ,SORT_ASC, $list);
                    return ['Data' => $list, 'ErrorMessage' => '操作成功', 'ErrorCode' => 1];
                }else{
                    return ['Data' => $list, 'ErrorMessage' => '无数据', 'ErrorCode' => 1];
                }
            }else{
                return ['Data' => '', 'ErrorMessage' => '参数错误-查询类型', 'ErrorCode' => ErrorInc::FAILED_PARAM];
            }
        }else{
            return ['Data' => '', 'ErrorMessage' => '缺少参数-查询类型', 'ErrorCode' => ErrorInc::INVALID_PARAM];
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取订单个商品数量
     * @param string $sys_num 订单单号
     * @param string $select 需获取的参数
     * @retrun /multitype:array
     * @author dou 2021/8/18 20:14
     * |---------------------------------------------------------------------------------
     */
    public static function searchMsgNum ( $sys_num , $select = [] ){
        if(!$select){
            $select = ['goods_name','goods_id','id','goods_num'];
        }
        $msg = OrderService::getOrderMsgBy('sys_num', $sys_num,$select);
        $ordermsg = [];
        foreach($msg as $k => $v){
            if(isset($ordermsg[$v['goods_id']])){
                $ordermsg[$v['goods_id']]['goods_num'] += $v['goods_num'];
                $ordermsg[$v['goods_id']]['id'] .= ','.$v['id'];
            }else{
                $ordermsg[$v['goods_id']] = $v;
                $ordermsg[$v['goods_id']]['recover'] = 0;
            }
        }
        return $ordermsg;
    }
    /**|---------------------------------------------------------------------------------
     * @name 获取可发货商品
     * @param array $order_num 订单单号
     * @param string $sys_num 系统单号
     * @param array $type 是否展示全部商品
     * @retrun /multitype:array
     * @author dou 2021/8/18 16:59
     * |---------------------------------------------------------------------------------
     */
    public static function selectSendGoods ( $order_num , $sys_num , $type = false){
        $ordermsg = OrderService::searchMsgNum($sys_num);
        $sendlist = SendGoodsService::searchSendNum($order_num);
        $data = SendGoodsService::selectSendGoods($ordermsg, $sendlist,$type);
        return $data;
    }

    /**|---------------------------------------------------------------------------------
     * @name 订单锁定处理
     * @param array $input 锁定传输信息
     * @param array $session 登录人信息
     * @param string $ip 操作设备网络ip
     * @retrun /multitype:array
     * @author dou 2021/8/24 8:38
     * |---------------------------------------------------------------------------------
     * @noinspection DuplicatedCode
     */
    public static function lockOrder ( $input , $session , $ip ){
        $order = OrderService::getOrderBy('sys_num', $input['sys_num'],['ser_id', 'order_num', 'order_status','store_type','create_time','new_customer_id','category','p_id','company_id']);
        foreach($order as $k => $v){
            $input[$k] = $v;
        }
        $validationLockOrder = self::validationLockOrder($input);
        if($validationLockOrder['ErrorCode'] != 1){
            return $validationLockOrder;
        }
        DB::beginTransaction();
        $send_good = SendGoodsService::getSendGoodBy(['send_num'=>$input['order_num'],'data_source'=>'2','type'=>1],['id'],'first');
        $input['recycle_id'] = 0;
        $userArr = CommonService::getUser('id', $order['new_customer_id']);
        $refund_id = 0;
        if($input['refund'] == '1'){
            $return = OrderService::lockByRefund($input, $session ,$userArr);
            if($return['ErrorCode']!='1'){
                DB::rollBack();
                return  $return;
            }
            $refund_id = $return['id'];
        }else{
            $return = OrderService::lockByCommon($input);
            if($return['ErrorCode']!='1'){
                DB::rollBack();
                return  $return;
            }
        }
        if ($input['refund'] == 1) {
            $log = "退款锁定：";
            $note_content = $log . $input['content'];
        } else {
            $log = "锁定：";
            $note_content = $log . $input['content'];
        }
        $rest = CommonService::accMe($input['sys_num'], '订单管理', $note_content, '', '', $session['admin_groupnew'], $session['admin_acc'], $session['id']);
        if($rest){
            $returnOrderList = OrderListService::getOrderListBy('sys_num', $input['sys_num'],'get',['serial_number']);
            /*---------------------------------------------判定同步门店锁定通知开始------------------------------------*/
            if($order['order_status']>10 && $order['store_type']==5){
//                $store=SyncStores::where("ser_id",$order['ser_id'])->where("type",2)->value('id');
                $store = CommonService::getSyncStores($order['ser_id'], $order['category']);
                if(!empty($store)){
                    foreach( $returnOrderList as $k => $v )
                    {
                        $pop = [
                            'order_num' => $v['serial_number'],
                            'type'            => 1
                        ];
                        $store = SysStoresService::sysStore($pop, 'lockUrl',$store);
                        if($store['ErrorCode']!=1){
                            DB::rollBack();
                            return $store;
                        }
                    }
                }
            }
            /*---------------------------------------------判定同步门店锁定通知结束------------------------------------*/

            if($input['recycle_type']!='0' && !$send_good) {
                /*-------------------------------------------回收货物流程开始------------------------------------------------*/
                /*$returnRecy = RecycleOrderService::creactRecycle($input, $session , $ip);
                if($returnRecy['ErrorCode']!='1'){
                    DB::rollBack();
                    return  $returnRecy;
                }
                $input['recycle_id'] = $returnRecy['Data']['id'];*/
                /*-------------------------------------------回收货物流程结束------------------------------------------------*/
            }
            $BaseController = new BaseController();
            $BaseController->insertingLog('锁定，', $input['sys_num'], "订单" . $input['order_num'].$log, '订单管理', $ip, $session['admin_acc']);//日志
            DB::commit();
            if($input['recycle_id']>0 && $input['refund'] == '1' && $refund_id>0){
                Refund::where('id',$refund_id)->update(['recycle_id'=>$input['recycle_id']]);
            }
            /*-------------------------------------------判定退款锁定发送微信推送开始------------------------------------------------*/
            if ($input['refund'] == 1 && $order['order_status']>10) {
                foreach( $returnOrderList as $k => $v ){
                    $weixin['ser_id'] = $order['ser_id'];
                    $weixin['shr_name'] = $userArr['shr_name'];
                    $weixin['shr_phone'] = $userArr['shr_phone'];
                    $weixin['serial_number'] = $v['serial_number'];
                    $weixin['goods_name'] = $goods_name_res[$k]??'';
//                    CommonService::requestPost('http://weixin.sudianwang.com/index.php/BindingAccount/refundPush', $weixin);
                }
            }
            /*-------------------------------------------判定退款锁定发送微信推送结束------------------------------------------------*/
            return ['Data' => '', 'ErrorMessage' => '操作成功', 'ErrorCode' => 1];
        }else{
            DB::rollBack();
            return ['Data' => '', 'ErrorMessage' => '操作失败', 'ErrorCode' => ErrorInc::MYSQL_FAILED];
            exit;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 锁定前状态验证
     * @param array $input 锁定传输信息
     * @retrun /multitype:array
     * @author dou 2021/11/4 17:30
     * |---------------------------------------------------------------------------------
    */
    public static function validationLockOrder ( $input ){
//        $send_orders = SendGoodsService::getInfoBy('sys_num', $input['sys_num'],['recover','type']);
//        if($send_orders){
//            $recover = array_column($send_orders, 'recover');
//            $type = array_column($send_orders, 'type');
//            if(in_array('1',$recover) && !in_array('5',$type)){
//                return  ['Data' => '','ErrorMessage'=>'该单有发货单未处理，不能锁定，请先处理发货单','ErrorCode'=>ErrorInc::REQUEST_FORBIDDEN];
//            }
//
//        }

        if($input['category'] == 3){
            $send_orders = DB::table('send_orders')->where('sys_num', $input['sys_num'])->select('recover','type')->get();
            if($send_orders){
                $send_orders=$send_orders->toArray();
                $recover=[];
                $type=[];
                foreach( $send_orders as $k => $v ){
                    $recover[]=$v['recover'];
                    $type[]=$v['type'];
                }
                if((in_array('1',$recover) || in_array('0',$recover)) && !in_array('5',$type)){
                    return ['Data' => '', 'ErrorMessage' => '该单有发货单未处理，不能锁定，请先处理发货单', 'ErrorCode' => 6];
                    exit;
                }
            }
        }
        /*----------------------------------------订单退收款记录验证开始-------------------------------------------------*/
        $submit_stauas = SubmitPleaseService::getSubmitPleaseBy('submit_sys_num', $input['sys_num'], ['submit_stauas'], 'firsts');
        if ($submit_stauas == 1) {
            return  ['Data' => '','ErrorMessage'=>'该单售后差额在申请中，请核实','ErrorCode'=>ErrorInc::REQUEST_FORBIDDEN];
        }
        /*----------------------------------------订单退收款记录验证结束-------------------------------------------------*/
        /*----------------------------------------工单结算流程验证开始-------------------------------------------------*/
        $restSelist = SettlementService::getSettlementListBy('sys_num', $input['sys_num'],['sett_status']);
        if ($restSelist) {
            foreach ($restSelist as $k => $v) {
                if ($v['sett_status'] == 20 || $v['sett_status'] == 65 || $v['sett_status'] == 10) {
                    return  ['Data' => '','ErrorMessage'=>'该单金额在结算中','ErrorCode'=>ErrorInc::REQUEST_FORBIDDEN];
                }
            }
        }
        /*----------------------------------------工单结算流程验证结束-------------------------------------------------*/
        /*----------------------------------------第三方结算流程验证开始-------------------------------------------------*/
        $restSethree = SettlementThreeService::getSettlementThreeBy('sys_num', $input['sys_num'],['three_status']);
        if ($restSethree) {
            // 该单金额在收款中
            foreach ($restSethree as $kk => $vv) {
                if ($vv['three_status'] == 20) {
                    return  ['Data' => '','ErrorMessage'=>'该单金额在收款中','ErrorCode'=>ErrorInc::REQUEST_FORBIDDEN];
                }
            }
        }
        /*----------------------------------------第三方结算流程验证结束-------------------------------------------------*/
        return  ['Data' => '','ErrorMessage'=>'验证通过','ErrorCode'=>1];
    }

    /**|---------------------------------------------------------------------------------
     * @name 退款锁定
     * @param array $input 锁定传输信息
     * @param array $session 操作人信息
     * @retrun /multitype:array
     * @author dou 2021/8/24 14:43
     * |---------------------------------------------------------------------------------
    */
    public static function lockByRefund ( $input , $session , $userArr){
        if(!isset($input['allprice'])){
            return  ['Data' => '','ErrorMessage'=>'请填写退款金额','ErrorCode'=>ErrorInc::FAILED_PARAM];
        }

        $goodsArr = $input['goodsArr'];
        $msg_ids = array_column($goodsArr,'msg_id');//获取订单明细表数据id
        $r_goods_price = OrderMsg::whereIn('id',$msg_ids)->pluck('goods_price')->toarray();
        $r_all_goods_price = array_sum($r_goods_price);
        if($r_all_goods_price>0 && $input['allprice']==0){
            return  ['Data' => '','ErrorMessage'=>'退款金额错误:商品价格不为0请核实','ErrorCode'=>ErrorInc::FAILED_PARAM];
        }
        if(!isset($input['goods_state']) || !in_array($input['goods_state'], [2,4])){
            return  ['Data' => '','ErrorMessage'=>'请确认差额处理类型','ErrorCode'=>ErrorInc::FAILED_PARAM];
        }
        $submit_stauas = SubmitPleaseService::getSubmitPleaseBy('submit_sys_num', $input['sys_num'],['submit_stauas','refund_id']);
//        $submit_stauas = array_column($submit_stauas, 'submit_stauas');
        $refund_id = [];
        foreach($submit_stauas as $k => $v){
            if($v['submit_stauas'] !=2 && $v['submit_stauas'] !=3){
                $refund_id[] = $v['refund_id'];
            }
        }
//        $submit_stauas = CommonService::resetListKey($submit_stauas);
//        if($submit_stauas){
//            return  ['Data' => '','ErrorMessage'=>'存在未处理的财务退收款记录，请联系管理员','ErrorCode'=>ErrorInc::REQUEST_FORBIDDEN];
//        }
        $refArr = RefundService::getInfoByKeyValue('order_num', $input['order_num'],['state','apply_type','id']);
//        if(!isset($input['apply_type']) || $input['apply_type'] == 1) {
//            foreach($refArr as $k => $v){
//                if($v['apply_type'] == 1 && $v['state'] ==4){
//                    return  ['Data' => '','ErrorMessage'=>'该订单已经退款并撤销，请核实','ErrorCode'=>ErrorInc::REQUEST_FORBIDDEN];
//                }
//                if($v['state']<4){
//                    $state[] = $v['state'];
//                }
//            }
//        }else{
//            $state = array_column($refArr, 'state');
            $state = [];
            $apply_type = [];
            $refund_num = 0;
            foreach($refArr as $k => $v){
                if($v['state'] !=5){
                    $refund_num++;
                }
                if($v['apply_type'] == 1 && $v['state'] ==4){
                    if($input['apply_type']!=10) {
                        return ['Data' => '', 'ErrorMessage' => '该订单已经退款并撤销，请核实', 'ErrorCode' => ErrorInc::REQUEST_FORBIDDEN];
                    }
                }
                if($refund_id){
                    if ($v['state'] < 4 || in_array($v['id'], $refund_id)) {
                        $state[] = $v['state'];
                        $apply_type[] = $v['apply_type'];
                    }
                }else {
                    if ($v['state'] < 4) {
                        $state[] = $v['state'];
                        $apply_type[] = $v['apply_type'];
                    }
                }
            }
//        }
//        $state = CommonService::resetListKey($state);
        if($apply_type && in_array($input['apply_type'], $apply_type)){
            return  ['Data' => '','ErrorMessage'=>'存在未处理的申请类型退款','ErrorCode'=>ErrorInc::REQUEST_FORBIDDEN];
        }
//        if($state){
//            return  ['Data' => '','ErrorMessage'=>'存在未处理的平台退款记录，请联系管理员','ErrorCode'=>ErrorInc::REQUEST_FORBIDDEN];
//        }



        $orderArr['lock_type'] = 2;
        $orderListArr['locklist_type'] = 2;
        $orderSettArr['locksel_type'] = 2;
        $orderSetteArr['locksee_type'] = 2;

        $goods_name_res = array_column($goodsArr,'goods_name');//获取待退款商品组
        $goods_price_res = array_column($goodsArr,'goods_price');//获取退款商品金额
        $goods_price_res = array_sum($goods_price_res);
        $goods_id_res = array_column($goodsArr,'good_id');//退款商品组
        if(!isset($input['apply_type']) || $input['apply_type'] == 1) {
            $returnOrder = Orders::where('sys_num', $input['sys_num'])->update($orderArr);//订单锁定操作
            if ($returnOrder) {
                if ($input['order_status'] > '10') {
                    $returnOrderList = OrderList::where('sys_num', $input['sys_num'])->whereIn('order_goods_id', $msg_ids)->update($orderListArr);//工单锁定操作
                    if ($returnOrderList) {
                        if ($input['order_status'] >= '30') {
                            $returnSettlementList = SettlementList::where('sys_num', $input['sys_num'])->whereIn('msg_id', $msg_ids)->update($orderSettArr);//门店结算单锁定操作
                            $returnSettlementThree = SettlementThree::where('sys_num', $input['sys_num'])->whereIn('msg_id', $msg_ids)->update($orderSetteArr);//第三方结算单锁定操作
                            if (!$returnSettlementList) {
                                return ['Data' => '', 'ErrorMessage' => '操作失败stlist', 'ErrorCode' => ErrorInc::MYSQL_FAILED];
                            }
                        }
                    } else {
                        return ['Data' => '', 'ErrorMessage' => '操作失败olist', 'ErrorCode' => ErrorInc::MYSQL_FAILED];
                    }
                }
            } else {
                return ['Data' => '', 'ErrorMessage' => '操作失败order', 'ErrorCode' => ErrorInc::MYSQL_FAILED];
            }
            $poss['apply_type'] = 1;
        }else{
            $poss['apply_type'] = $input['apply_type'];
        }
        $dataState = self::getDataState($input['goods_state']);
        if(!$dataState){
            return  ['Data' => '','ErrorMessage'=>'差额处理异常','ErrorCode'=>ErrorInc::FAILED_PARAM];
        }else{
            $poss['state'] = $dataState['state'];//待审核
            $pleArr['submit_stauas'] = $dataState['submit_stauas'];
        }
        $centent = $input['note_content']??$input['content'];
        $poss['sys_num'] = $input['sys_num'];
        $poss['order_num'] = $input['order_num'];
        $poss['pt_id'] = $input['p_id'];
        $poss['goods_name'] = implode(',',$goods_name_res);
        $poss['goods_id'] = implode(',',$goods_id_res);
        $poss['goods_price'] = $input['allprice'];
        $poss['ser_id'] = $input['ser_id'];
        $poss['msg_id'] = implode(',',$msg_ids);
        $poss['user_id'] = $input['new_customer_id'];
        $poss['shr_name'] = $userArr['shr_name'];
        $poss['shr_phone'] = $userArr['shr_phone'];
        $poss['shr_sheng'] = $userArr['shr_sheng'];
        $poss['shr_shi'] = $userArr['shr_shi'];
        $poss['shr_xian'] = $userArr['shr_xian'];
        $poss['shr_adress'] = $userArr['shr_adress'];
//        $poss['state'] = 0;//待审核
        $poss['order_status'] = $input['order_status'];
        $poss['refund_reason'] = $centent;
        $poss['order_time'] = $input['create_time']; //下单时间
        $poss['created_at'] = date("Y-m-d H:i:s");
        $poss['urgent_type'] = 1;
        $poss['creact_id'] = $session['id'];
        $poss['creactor'] = $session['admin_acc'];
        $poss['goods_state'] = $input['goods_state'];
        $poss['attribute'] = $input['attribute']??'1';//申请属性 1服务退款，2商品退款，3业务收款
        $poss['category'] = $input['category']??'0';//订单商品服务类型
        $poss['recycle_id'] = $input['recycle_id']??'0';//回收单id
        $poss['refund_num'] = $refund_num;//退款次数
        $poss['roPreNo'] = $input['roPreNo']??'';//平台同步退款单号
        if(isset($input['add_type']) && in_array(3, $input['add_type'])){
            $pleArr['submit_stauas'] = 7;
            $allprice = '-'.$input['allprice'];//申请金额
        }else{
            $allprice = $input['allprice'];//申请金额
        }
        $poss['company_id'] = $input['company_id']??$session['company_id'];
        $refund = RefundService::createRefund($poss);
        if(!$refund){
            return  ['Data' => '','ErrorMessage'=>'操作失败rf','ErrorCode'=>ErrorInc::MYSQL_FAILED];
        }
        if(isset($input['info_ing']) && isset($input['info_acc']) && isset($input['info_name'])){
            $pleArr['customer_info'] = "开户行/第三方：".$input['info_ing']."<br/>帐号：".$input['info_acc']."<br/>姓名：".$input['info_name'];
        }else{
            $pleArr['customer_info'] = '';
        }


        $returnPle = SubmitPleaseService::createSubmitPlease($session['admin_acc'], $input['p_id'], $input['sys_num'], implode(',',$goods_name_res), $allprice, $input['goods_state'], 2, 2, 0, $pleArr['submit_stauas'], implode(',',$msg_ids),$refund,$pleArr['customer_info'],$centent,$poss['attribute'],$refund_num,$session['company_id']);
        if(!$returnPle){
            return  ['Data' => '','ErrorMessage'=>'操作失败sbp','ErrorCode'=>ErrorInc::MYSQL_FAILED];
        }
        $msgBody['pushtyep'] = 'refund';
        $msgBody['order_num'] = $input['order_num'];
        $msgBody['goods_id'] = $goods_id_res[0];
        $msgBody['goods_price'] = $goods_price_res;
        $msgBody['concent'] = $centent;
        $msgBody['goods_num'] = '1';
        $msgBody['goods_name'] = implode(',',$goods_name_res);
        $msgBody['session_id'] = $session['id'];
        $msgBody['session_acc'] = $session['admin_acc'];
        $BaseController = new BaseController();
//        $BaseController->pushRecord($msgBody,date("Y-m-d H:i:s", strtotime('+15 minutes', time())),3,$orderArr['order_num'],1,1,0 );

        return  ['Data' => $refund,'ErrorMessage'=>'操作成功','ErrorCode'=>1];
    }


    /**
     * 退单锁定验证
     * @param $input
     * @return array
     * @author du
     * @date 2022/1/24
     */
    public static function validationLockByRefund($input){
        $submit_stauas = SubmitPleaseService::getSubmitPleaseBy('submit_sys_num', $input['sys_num'],['submit_stauas']);
        $submit_stauas = array_column($submit_stauas, 'submit_stauas');
        foreach($submit_stauas as $k => $v){
            if($v==2 || $v==3){
                unset($submit_stauas[$k]);
            }
        }
        $submit_stauas = CommonService::resetListKey($submit_stauas);
        if($submit_stauas){
            return  ['Data' => '','ErrorMessage'=>'存在未处理的财务退收款记录，请联系管理员','ErrorCode'=>ErrorInc::REQUEST_FORBIDDEN];
        }
        $refArr = RefundService::getInfoByKeyValue('order_num', $input['order_num'],['state','apply_type']);
        $state = [];
        foreach($refArr as $k => $v){
            if($v['apply_type'] == 1 && $v['state'] ==4){
                return  ['Data' => '','ErrorMessage'=>'该订单已经退款并撤销，请核实','ErrorCode'=>ErrorInc::REQUEST_FORBIDDEN];
            }
            if($v['state']<4){
                $state[] = $v['state'];
            }
        }
        if($state){
            return  ['Data' => '','ErrorMessage'=>'存在未处理的平台退款记录，请联系管理员','ErrorCode'=>ErrorInc::REQUEST_FORBIDDEN];
        }

        return  ['Data' => '','ErrorMessage'=>'验证通过','ErrorCode'=>1];
    }



    /**|---------------------------------------------------------------------------------
     * @name 判定退款差额处理类型对应数据状态
     * @param int $goods_state 差额处理类型
     * @retrun /multitype:array
     * @author dou 2021/9/16 17:16
     * |---------------------------------------------------------------------------------
    */
    public static function getDataState ( $goods_state ){
        switch ( $goods_state ){
            case 2://平台
                $data['submit_stauas'] = 2;
                $data['state'] = 0;
                $data['goods_state'] = 1;
                break;
            case 4://财务
                $data['submit_stauas'] = 1;
                $data['state'] = 4;
                $data['goods_state'] = 2;
                break;
            default:
                return false;
                break;
        }
        return $data;
    }

    /**|---------------------------------------------------------------------------------
     * @name 普通锁定
     * @param array $input 锁定传输信息
     * @retrun /multitype:array
     * @author dou 2021/8/24 16:06
     * |---------------------------------------------------------------------------------
    */
    public static function lockByCommon( $input ){
        $orderArr['lock_type'] = 2;
        $orderListArr['locklist_type'] = 2;
        $orderSettArr['locksel_type'] = 2;
        $orderSetteArr['locksee_type'] = 2;
        $returnOrder = Orders::where('sys_num', $input['sys_num'])->update($orderArr);
        if($returnOrder){
            if($input['order_status'] > '10'){
                $returnOrderList = OrderList::where('sys_num', $input['sys_num'])->update($orderListArr);
                if($returnOrderList){
                    if($input['order_status'] >= '30'){
                        $returnSettlementList = SettlementList::where('sys_num', $input['sys_num'])->update($orderSettArr);
                        $returnSettlementThree = SettlementThree::where('sys_num', $input['sys_num'])->update($orderSetteArr);
                        if(!$returnSettlementList){
                            return  ['Data' => '','ErrorMessage'=>'操作失败stlist','ErrorCode'=>ErrorInc::MYSQL_FAILED];
                        }else{
                            return  ['Data' => '','ErrorMessage'=>'操作成功','ErrorCode'=>1];
                        }
                    }else{
                        return  ['Data' => '','ErrorMessage'=>'操作成功','ErrorCode'=>1];
                    }
                }else{
                    return  ['Data' => '','ErrorMessage'=>'操作失败olist','ErrorCode'=>ErrorInc::MYSQL_FAILED];
                }
            }else{
                return  ['Data' => '','ErrorMessage'=>'操作成功','ErrorCode'=>1];
            }
        }else{
            return  ['Data' => '','ErrorMessage'=>'操作失败order','ErrorCode'=>ErrorInc::MYSQL_FAILED];
        }

    }

    /**|---------------------------------------------------------------------------------
     * @name 换货对应的订单详情表操作
     * @param array $input 请求数据
     * @retrun /multitype:array
     * @author dou 2021/8/25 18:26
     * |---------------------------------------------------------------------------------
    */
    public static function replaceMsgGood ( $input ){
        $goodsInfo = GoodsService::getGoodsByKey('pg_id',$input['goods_id'],['brand_name', 'version','pg_series']);
        $arr['goods_id'] = $input['goods_id'];//商品id
        $arr['goods_name'] = $goodsInfo['good_name'];//商品名称
        $arr['goods_service'] = 4;//换新
        $brand_name = $goodsInfo['brand_name'].'-';
        $arr['goods_number'] = mb_ereg_replace($brand_name,"",$goodsInfo['good_name']);//商品型号
        $arr['goods_price'] = $input['goods_price'];//实收
        $arr['goods_paid'] = $input['goods_paid'];//应收
        $arr['goods_state'] = $input['goods_state'];//差额处理1抹零2平台3服务中心4财务5红包
        $arr['goods_difference'] = $input['submit_money'];//差额
        $arr['goods_brand'] = $goodsInfo['brand_name'];//品牌名称
        if($input['order_status'] > 10){
            OrderList::where('sys_num',$input['sys_num'])->where('order_goods_id',$input['msg_id'])->update(['goods_brand'=>$goodsInfo['brand_name']]);
            if($input['order_status'] > 20){
                SettlementList::where('sys_num',$input['sys_num'])->where('msg_id',$input['msg_id'])->update(['goods_brand'=>$goodsInfo['brand_name']]);
            }
        }
        DB::connection()->enableQueryLog();#开启执行日志
        $resultMsg = OrderMsg::where('id', $input['msg_id'])->where('sys_num',$input['sys_num'])->update($arr);
        return $resultMsg;
    }
    /**|---------------------------------------------------------------------------------
     * @name 换货商品金额计算
     * @param array $input 换货请求参数
     * @param array $sett_status 结算单信息
     * @param array $session 操作人信息
     * @retrun /multitype:array
     * @author dou 2021/8/26 9:31
     * |---------------------------------------------------------------------------------
    */
    public static function updataReplaceMoney ( $input , $sett_status , $session ){
        $save = false;
        $saves = false;
        $sav = false;
        $sava = false;
        $price = SupplierPriceService::findPrice($sett_status['ser_id'], $input['goods_id'],['supply_price'],$sett_status['p_id']);
        if ($price) {
            $pri['sem_price'] = $price;
            SettlementMoney::where(['sem_slid' => $sett_status['id'], 'sem_type' => 1])->update($pri);
            $order_price['order_price'] = $price;
            $sava = SettlementList::where('id', $sett_status['id'])->update($order_price);
        }
        $ld_price = Leadsubsidie::where('ld_goodid', $input['goods_id'])->where('ld_type', 1)->where('ld_release', 1)->select('ld_price', 'le_setyid')->get();
        $Leadsubsidie = new Leadsubsidie();
        $ld_price = CommonService::getMysqlData($Leadsubsidie, ['ld_goodid'=>$input['goods_id'],'ld_type'=>1,'ld_release'=>1],['ld_price', 'le_setyid']);
        if ($ld_price) {
            foreach ($ld_price as $kld => $vld) {
                $sem_ids = SettlementMoney::where(['sem_slid' => $sett_status['id'], 'sem_type' => $vld['le_setyid']])->select('sem_id', 'sem_price')->first();
                if ($sem_ids) {
                    $moneyqj['sem_price'] = $vld['ld_price'];
                    $sav = SettlementMoney::where('sem_id', $sem_ids['sem_id'])->update($moneyqj);
                } else {
                    $saves = SettlementService::createSettMoney($sett_status['id'], $input['sys_num'], $vld['ld_price'], $session['admin_acc'], $vld['le_setyid']);
                }
            }
        } else {
            $sem_ids = SettlementMoney::whereRaw("sem_slid='" . $sett_status['id'] . "' and (sem_type=14 or sem_type=19)")->select('sem_id', 'sem_price')->first();
            if ($sem_ids) {
                $sav = SettlementMoney::where('sem_id', $sem_ids['sem_id'])->delete();
            }
        }
        $OrderList = new OrderList();
        $tim = CommonService::getMysqlData($OrderList, ['sys_num'=>$input['sys_num'],'order_goods_id'=>$input['msg_id']],['create_time'],[],'value');
        if($tim) {
            $brand_name = GoodsService::getGoodsByKey('pg_id', $input['goods_id'], ['brand_name']);
            $sup_price = DB::table('support')->whereRaw("sup_serid like '%," . $sett_status['ser_id'] . ",%' and sup_brname='" . $brand_name . "' and sup_startime<'" . $tim . "' and sup_endtime>'" . $tim . "'")->value('sup_price');
        }else{
            $sup_price = false;
        }
        if ($sup_price) {
            $sem_id = SettlementMoney::where(['sem_slid' => $sett_status['id'], 'sem_type' => 12])->select('sem_id', 'sem_price')->first();
            if ($sem_id) {
                $money['sem_price'] = "-" . $sup_price;
                $save = SettlementMoney::where('sem_id', $sem_id['sem_id'])->update($money);
            } else {
                $sup_price = "-" . $sup_price;
                $saves = SettlementService::createSettMoney($sett_status['id'], $input['sys_num'], $sup_price, $session['admin_acc'], 12);
            }
        } else {
            $sem_id = SettlementMoney::where(['sem_slid' => $sett_status['id'], 'sem_type' => 12])->select('sem_id', 'sem_price')->first();
            if ($sem_id) {
                SettlementMoney::where('sem_id', $sem_id['sem_id'])->delete();
            }
        }
        if ($save || $saves || $sav || $sava) {
            if ($sav) {
                $sul['sul_msgid'] = $input['msg_id'];
                $sul['sul_price'] = $sem_ids['sem_price'];
                $sul['sul_creacter'] = $session['admin_acc'];
                $sul['sul_type'] = "14";
                DB::table('support_log')->insert($sul);
            }
            if ($save) {
                $sul['sul_msgid'] = $input['msg_id'];
                $sul['sul_price'] = $sem_id['sem_price'];
                $sul['sul_creacter'] = $session['admin_acc'];
                $sul['sul_type'] = "12";
                DB::table('support_log')->insert($sul);
            }
            $all_price['all_price'] = SettlementMoney::where('sem_slid', $sett_status['id'])->sum('sem_price');
            return SettlementList::where('id', $sett_status['id'])->update($all_price);
        }
    }

    public static function shippingCancel($order, $session = []) {
        $orderID = $order['id'];
        if ($orderID) {
            $res = Orders::where('id', $orderID)->where('order_status', 3)->update(['order_status'=>50,'lock_type'=>2]);
            if ($res) {
                return  ['Data' => '','ErrorMessage'=>'操作成功','ErrorCode'=>1];
            }else{
                return  ['Data' => '','ErrorMessage'=>'操作失败','ErrorCode'=>ErrorInc::MYSQL_FAILED];
            }
        }else{
            return  ['Data' => '','ErrorMessage'=>'系统异常','ErrorCode'=>ErrorInc::SERVER_FAILED];
        }
        return true;
    }

    /**
     * 将发货信息修改到订单里
     * @param string $orderNO 订单NO
     * @param array $shippingInfo 发货信息
     * @param array $session  操作人
     * @return bool
     */
    public static function saveShipping($orderNO, $shippingInfo, $session = []) {
        $data = ['order_status'=>OrderInc::STATE_AVAILABLE];
        $res = Orders::where('order_num', $orderNO)->update($data);
        if ($res) {
//                ActionLogService::createActionLog('orders', 'cancelShipping', $order['order_nim'], '系统同步取消发货', '', $session);
        }
        return true;
    }


    /**|---------------------------------------------------------------------------------
     * @name 设置派单获取的商品价格结构
     * @param array $supply_prices 商品金额信息
     * @param Boolean $ser_id 是否排列整理服务商
     * @param Boolean $goods_id 是否排列整理商品
     * @retrun /multitype:array
     * @author dou 2021/12/4 10:49
     * |---------------------------------------------------------------------------------
     */
    public static function dealGoodPrice ( $supply_prices , $ser_id = true , $goods_id = true ){

        if($supply_prices) {
            if ($ser_id) {
                $supply_prices = CommonService::jointArrayKey($supply_prices, 'ser_id', 2);
                if ($goods_id) {
                    foreach ($supply_prices as $k => $v) {
                        $supply_prices[$k] = CommonService::jointArrayKey($v, 'goods_id');
                    }
                }
            } else {
                $supply_prices = CommonService::jointArrayKey($supply_prices, 'goods_id');
            }
        }
        return $supply_prices;
    }

    /**|---------------------------------------------------------------------------------
     * @name 发送短信  给门店发送短信
     * @param int $p_id 平台id
     * @param string $sys_num 系统单号
     * @param int $customer_id 用户id
     * @param int $order_goods_id 商品id
     * @param int $ser_id 门店id
     * @param int $order_num 订单单号
     * @retrun /multitype:array
     * @author dou 2021/12/1 10:32
     * |---------------------------------------------------------------------------------
    */
//    发送短信  给门店发送短信
    public static function server_order($p_id,$sys_num,$customer_id,$order_goods_id,$ser_id,$order_num='',$session){
//        return 1000;
        $pt = new Pt();
        $user = new User();
        $order_msg = new OrderMsg();
        $admin_infor = new AdminInfor();
        $info = UserService::getUserBy('id', $customer_id,['shr_name','shr_phone','shr_sheng','shr_shi','shr_xian','shr_adress']);
        $order_info = self::getOrderMsgBy('id', $order_goods_id,['goods_name','goods_brand']);
        $pt_info = PlatformService::getPtBy('id', $p_id,['pt_name','sms_name','sms_password','signature']);
        $admininfor = new AdminInfor();
        $phones = CommonService::getMysqlData($admininfor, ['admin_id'=>$ser_id],['phone','head_phone'],[],'first');
        $phone = $phones['phone']??$phones['head_phone'];
        $brand_service = AdminService::getAdminBy('id', $ser_id,['brand_service']);
        if(($p_id==211 || $p_id==212 || $p_id==214 || $p_id==216 || $p_id==208 || $p_id==304 || $p_id==319 || $p_id==320 || $p_id==310 || $p_id==367) && ($brand_service==2 || $brand_service==7) && $order_info['goods_brand']=="3M"){
            $weixin="3M车膜官方账号";
            $weiphone="010-5947-9483";
        }else{
            $weixin="极限光合技师服务号";
            $weiphone="400-615-2060";
        }
        if($p_id==319 || $p_id==320){
            $weiphone="18518950080";
        }
        $sms_number=$sys_num;
        if($order_num!=''){
            $sms_number=$order_num;
        }

        if($pt_info && $pt_info['sms_password']!=''){
            if($p_id=='294'){
                $contents="订单：".$sms_number."  已指派到您的门店：客户姓名：".$info['shr_name']." 联系方式：".$info['shr_phone']." 地址：".$info['shr_sheng'].$info['shr_shi'].$info['shr_xian'].$info['shr_adress']." 车膜型号：".$order_info['goods_name']."，请及时到“".$weixin."”承接订单，完工后请提醒客户出示验证码，在微信公众号“".$weixin."”提交10位验证码上传图片申请完工，请您主动联系车主预约安装，提醒安装技师施工前务必核对产品及车况，无异常后方可施工，严禁学徒工施工，严禁对产品负面评价或鉴定言论，严禁向客户推销店内其他产品，产品有问题请致售后服务热线：".$weiphone."，感谢您的支持！";
            }else{
                $contents="订单：".$sms_number."已指派到您的门店：客户姓名：".$info['shr_name']." 联系方式：".$info['shr_phone']." 地址：".$info['shr_sheng'].$info['shr_shi'].$info['shr_xian'].$info['shr_adress']." 车膜型号：".$order_info['goods_name']."，请及时到“".$weixin."”承接订单，完工后请提醒客户出示验证码，在微信公众号“".$weixin."”提交10位验证码上传图片申请完工，请您主动联系车主，提醒安装技师施工前务必核对产品及车况，无异常后方可施工，严禁学徒工施工，严禁对产品负面评价或鉴定言论，产品有问题请致售后服务热线：".$weiphone."，感谢您的支持！";
            }
            $file_name="OrderviewSendnote".date("Ym");
            CommonService::addLog('派单发送短信通知门店', json_encode(['phone'=>$phone,'explain'=>'send_start']), $sys_num,$file_name);
            // 如果是能膜和龙膜的话则添加智配贴装几个字。
            if(in_array($p_id,[387,389,390,391])){
                $contents="智配贴装:".$contents;
            }
            // 如果签名是 xzadmin 的话则将平台名称设置为签名
            if($pt_info['sms_name']=='zptzadmin'){
                if( $pt_info['signature'] !='' && $pt_info['signature'] !=null ){
                    $contents = "【" . $pt_info['signature'] . "】" . $contents;
                }else {
                    $contents = "【" . $pt_info['pt_name'] . "】" . $contents;
                }
            }
            if(!empty($pt_info['sms_name']) && !empty($pt_info['sms_password'])){
                $res=CommonService::senSms($phone,$contents,'',$pt_info['sms_name'],$pt_info['sms_password'],$session['admin_acc']);
            }else{
                $res="-102";
            }
            CommonService::addLog('派单发送短信通知门店', json_encode(['phone'=>$phone,'explain'=>'send_end','code'=>$res,'content'=>$contents]), $sys_num,$file_name);
        }else{
            $res="-101";
        }
        if($res>0){
        }else{
            CommonService::smsinfo($p_id,$sys_num,"派单",$res,$phone,$contents,$session);
        }
        return $res;
    }

    /**|---------------------------------------------------------------------------------
     * @name 发送短信，接单发送短信给客户
     * @param string $p_id 平添id
     * @param string $customer_id 用户id
     * @param string $ser_id 门店id
     * @param string $istall_id 技师id
     * @param string $sys_num 系统单号
     * @param string $order_num 平台单号
     * @retrun /multitype:array
     * @author dou 2021/12/9 8:45
     * |---------------------------------------------------------------------------------
    */
    public static function instArr_order($p_id,$customer_id,$ser_id,$istall_id,$sys_num,$order_num,$session){
//        return 1000;
        $user_info = UserService::getUserBy('id', $customer_id,['shr_name','shr_phone','shr_code']);
        $admins = AdminService::getAdminBy('id', $ser_id,['company_name']);
        $company_name = explode('-',$admins);
        $instArr = InstallPersonService::getInstallPersonById($istall_id,['install_name','install_phone','install_address','install_storename']);
        $admininfor = new AdminInfor();
        $admin_infors = CommonService::getMysqlData($admininfor, ['admin_id'=>$ser_id],['phone','head_phone','admin_dressi'],[],'first');
        $pt_info = PlatformService::getPtBy('id', $p_id,['pt_name','sms_name','sms_password','sms_content','signature']);
        if($pt_info){
            $pt_info['sms_content']=str_replace("\$shr_phone",$user_info['shr_phone'],$pt_info['sms_content']);
            $pt_info['sms_content']=str_replace("\$shr_name",$user_info['shr_name'],$pt_info['sms_content']);
            $pt_info['sms_content']=str_replace("\$shr_code",$user_info['shr_code'],$pt_info['sms_content']);
            $pt_info['sms_content']=str_replace("\$order_number",$order_num,$pt_info['sms_content']);
            // 如果是天知门店，则替换技师的信息。
            if($ser_id==6682){
                $pt_info['sms_content']=str_replace("\$company_name",$instArr['install_name'],$pt_info['sms_content']);
                $pt_info['sms_content']=str_replace("\$instArr",$instArr['install_storename'],$pt_info['sms_content']);
                $pt_info['sms_content']=str_replace("\$phone",$instArr['install_phone'],$pt_info['sms_content']);
                $pt_info['sms_content']=str_replace("\$address",$instArr['install_address'],$pt_info['sms_content']);
            }else{
                $pt_info['sms_content']=str_replace("\$company_name",$company_name['0'],$pt_info['sms_content']);
                $pt_info['sms_content']=str_replace("\$instArr",$instArr['install_name'],$pt_info['sms_content']);
                if(!empty($admin_infors['head_phone'])){
                    $phone=$admin_infors['head_phone'];
                }else{
                    $phone=$admin_infors['phone'];
                }
                $pt_info['sms_content']=str_replace("\$phone",$phone,$pt_info['sms_content']);
                $pt_info['sms_content']=str_replace("\$address",$admin_infors['admin_dressi'],$pt_info['sms_content']);
            }
            if(strstr($user_info['shr_phone'],"-")){
                $shr_phone=explode("-",$user_info['shr_phone']);
                $pt_info['sms_content']="#".$shr_phone[1]."#".$pt_info['sms_content'];
                $user_info['shr_phone']=$shr_phone[0];
            }else{
                $user_info['shr_phone']=$user_info['shr_phone'];
            }
            if($pt_info['sms_name']=='zptzadmin'){
                if( $pt_info['signature'] !='' && $pt_info['signature'] !=null ){
                    $pt_info['sms_content'] = "【" . $pt_info['signature'] . "】" . $pt_info['sms_content'];
                }else {
                    $pt_info['sms_content'] = "【" . $pt_info['pt_name'] . "】" . $pt_info['sms_content'];
                }
            }
            if(!empty($pt_info['sms_name']) && !empty($pt_info['sms_password']) && !empty($pt_info['sms_content'])){
                $res=CommonService::senSms($user_info['shr_phone'],$pt_info['sms_content'],'',$pt_info['sms_name'],$pt_info['sms_password'],$session['admin_acc']);
            }else{
                $res="-102";
            }
        }else{
            $res="-101";
        }
        if($res>0){
//            SmsService::createSmsRecord($pt_info['sms_content'], $user_info['shr_phone'], '系统添加', 3,$res);
        }else{
            CommonService::smsinfo($p_id,$sys_num,"接单",$res,$user_info['shr_phone'],$pt_info['sms_content'],$session);
        }
        return $res;
    }

    /**|---------------------------------------------------------------------------------
     * @name 生成订单核销码
     * @param int $p_id 平台id
     * @retrun /multitype:array
     * @author dou 2021/12/8 17:48
     * |---------------------------------------------------------------------------------
    */
    public static function creactCode ( $p_id , $num = 0 ){
        $shr_code = DB::table('code')->where('pt_id',$p_id)->orderBy('code','DESC')->value('code');
        $shr_codes['pt_id'] = $p_id;
        if($shr_code){
            $shr_codes['code']=(int)$shr_code+rand(1,9);
        }else{
            $shr_codes['code'] = '11010668';
        }
        $shr_res=DB::table('code')->insert($shr_codes);
        if($shr_res) {
            $shr_code_data = str_pad(((int)$p_id), 2, '0', STR_PAD_LEFT) . str_pad(((int)$shr_codes['code']), 8, '0', STR_PAD_LEFT);
            return $shr_code_data;
        }else{
            if($num >= 4){
                return '';
            }else{
                $num++;
                return self::creactCode($p_id,$num);
            }
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 同步库房订单撤销
     * @param string $sys_num 系统单号
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2022/1/13 17:57
     * |---------------------------------------------------------------------------------
    */
    public static function sysWarehouseCancel ( $sys_num ){
        $orders = self::getOrderBy('sys_num', $sys_num);
        $category = explode(',', $orders['category']);
        if(in_array('3', $category)) {
            $pt = PlatformService::getPtBy('id', $orders['p_id'], ['pt_name','zp_id']);
            $zhipei['pt_name'] = $pt['pt_name'];
            $zhipei['pt_id'] = $pt['zp_id'];
//            $zhipei['pt_name'] = PlatformService::getPtBy('id', $orders['p_id'], ['pt_name']);
            $ordermsg = self::getOrderMsgBy('sys_num', $orders['sys_num']);
            $zhipei['order_price'] = $orders['order_account'];
            $company_name = AdminService::getAdminBy('id', $orders['ser_id'], ['company_name']);
            $zhipei['store_name'] = $company_name ?? '无';
            $zhipei['wholestore_name'] = $company_name ?? '无';
            $user = UserService::getUserBy('id', $orders['new_customer_id'], ['id', 'shr_name', 'shr_phone', 'shr_sheng', 'shr_shi', 'shr_xian', 'shr_adress', 'car_make']);
            if ($user['shr_name']) {
                $zhipeiuser['shr_name'] = $user['shr_name'];
            } else {
                $zhipeiuser['shr_name'] = '无';
            }

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

            $zhipei['construction_date'] = date("Y-m-d H:i:s");
            $zhipei['car_brand'] = $user['car_make'];
            $zhipei['car_frame'] = '';
            $zhipei['order_status'] = 50;//订单状态
            $zhipeigood = [];
            foreach ($ordermsg as $k => $v) {
                $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($orders['order_num'], $zhipei, $zhipeigood, $zhipeiuser);
            $inputs['data']['zhipei'] = $zhipei;
            $inputs['data']['zhipeigood'] = $zhipeigood;
            $inputs['data']['zhipeiuser'] = $zhipeiuser;
            $inputs['return'] = $res;
            CommonService::addLog('库房撤销服务订单', json_encode($inputs), $orders['order_num'], 'warehouse-service');
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 获取京东订单状态
     * @param string status 订单状态
     * @param string orderId 订单单号
     * @param string pt_id 平台id
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2025/2/17 10:56
     * |---------------------------------------------------------------------------------
    */
    public static function getJdOrderStatus ( $orderId , $pt_id , $status = 204 ){
        $token = DB::table('jdpop_token')->where('pt_id',$pt_id)->select('app_key','app_secret','access_token','pt_id','auth_key','type')->first();
        if($token['type'] == 2) {
            $url = "http://116.196.75.172/index.php/SaasApiGetOrder/getDataByOrder?orderId=" . $orderId . "&status=" . $status;
            $urls = $url."&authKey=".$token['auth_key']."&access_token=".$token['access_token']."&app_key=".$token['app_key']."&app_secret=".$token['app_secret'];
            $BaseController = new BaseController();
            $res = $BaseController->http_get($urls);
            $data = json_decode($res, true);
            $result = $data['jingdong_omnic_order_query_orderList_responce']['result'];
            $result = json_decode($result, true);
            CommonService::addLog('获取取消订单', $urls.'---'.$res, $pt_id, 'orderService-getOrderCancelByJd');
            if (isset($result['success'])&&$result['success'] == true) {
                $order_data = $result['data'];
                if (!empty($order_data)) {
                    $order_data = $order_data['data'];
                    foreach ($order_data as $kkk => $vvv) {
                        if($vvv['orderInfo']['salesChannelOrderId'] == $orderId && $vvv['orderInfo']['status']==204){
                            $flag = 1;
                            $refundlist = RefundService::getInfoByKeyValue('order_num', $vvv['orderInfo']['salesChannelOrderId'], ['state', 'roPreNo']);
                            if ($refundlist) {
                                $rea = '退款已存在';
                                $flag = 2;
                            }
                            if ($flag == 1) {
                                $refund['order_num'] = $vvv['orderInfo']['salesChannelOrderId'];
                                $refund['refund'] = 1;
                                $refund['content'] = '平台订单已撤销';
                                $refund['urgent'] = 1;
                                $refund['recycle_type'] = 0;
                                $refund['roPreNo'] = $vvv['orderInfo']['salesChannelOrderId'];
                                $sys_num = OrderService::getOrderBy('order_num', $vvv['orderInfo']['salesChannelOrderId'], ['sys_num', 'order_status', 'new_money']);
                                if ($sys_num) {
                                    $refund['sys_num'] = $sys_num['sys_num'];
                                    if ($sys_num['order_status'] > 10) {
                                        $msg = OrderService::getOrderMsg($sys_num['sys_num']);
                                    } else {
                                        $msg = OrderService::getOrderMsg($sys_num['sys_num']);
                                    }
                                    if ($msg['orderMsgArr']) {
                                        $msg = $msg['orderMsgArr'];
                                        $goodsArr = [];
                                        foreach ($msg as $ka => $va) {
                                            $goodsArr[$ka]['goods_name'] = $va['goods_name'];
                                            $goodsArr[$ka]['goods_price'] = $va['goods_price'];
                                            $goodsArr[$ka]['msg_id'] = $va['id'];
                                            $goodsArr[$ka]['goods_num'] = $va['goods_num'];
                                            $goodsArr[$ka]['goods_id'] = $va['goods_id'];
                                        }
                                        $refund['goodsArr'] = $goodsArr;
                                        $refund['goods_state'] = 2;
                                        $refund['info_ing'] = '';
                                        $refund['info_acc'] = '';
                                        $refund['info_name'] = '';
                                        $refund['addType'] = 'jdRefund';
                                        $refund['allprice'] = $sys_num['new_money'];
                                        $session['id'] = '1133';
                                        $session['admin_acc'] = '系统操作';
                                        $session['admin_groupnew'] = 7;
                                        $session['company_id'] = Pt::where('id',$pt_id)->value('company_id');
                                        $rea = OrderService::lockOrder($refund, $session, '39.105.188.64');
                                    } else {
                                        $rea = '无订单商品';
                                    }

                                } else {
                                    $rea = '无订单号';
                                }
                            }
                            $return[$kkk]['lockOrder'] = $rea;
                            $return[$kkk]['order_num'] = $vvv['orderInfo']['salesChannelOrderId'];
                            CommonService::addLog('添加退款单', json_encode($return), $pt_id, 'orderService-addOrderCancels');
                            return  ['Data' => $order_data,'ErrorMessage'=>'订单已撤销','ErrorCode'=>ErrorInc::BUSINESS_FORBID];
                        }
                    }
                }
            }
            return  ['Data' => $result,'ErrorMessage'=>'数据正常','ErrorCode'=>1];
        }else{
            return  ['Data' => $token,'ErrorMessage'=>'数据正常','ErrorCode'=>1];
        }
    }
}
