<?php

namespace App\Http\Controllers\Orders;
use App\Http\Controllers\BaseController;
use App\Http\Controllers\Common\CommonController;
use App\Models\Admin;
use App\Models\AdminAddress;
use App\Models\AdminInfor;
use App\Models\EvaluationForm;
use App\Models\GhPrice;
use App\Models\Negotiated;
use App\Models\OrderAfter;
use App\Models\OrderList;
use App\Models\OrderMsg;
use App\Models\OrderTime;
use App\Models\OrderVisit;
use App\Models\Refund;
use App\Models\SerInfor;
use App\Models\SetmoneyType;
use App\Models\SettlementCount;
use App\Models\SettlementList;
use App\Models\SettlementMoney;
use App\Models\SettlementThree;
use App\Models\SubmitPlease;
use App\Models\SyncStores;
use App\Models\Temporary;
use App\Models\User;
use App\Services\AdminService;
use App\Services\AdminsService;
use App\Services\AftercustService;
use App\Services\AfterSaleService;
use App\Services\EvaluationFormService;
use App\Services\EventGiftService;
use App\Services\ExceloutService;
use App\Services\GoodsService;
use App\Services\LabtypeService;
use App\Services\OrderaddService;
use App\Services\OrderListService;
use App\Services\PjBrandsService;
use App\Services\PlatformService;
use App\Services\RecycleOrderService;
use App\Services\RefundService;
use App\Services\SendGoodsService;
use App\Services\SerInforService;
use App\Services\SettlementService;
use App\Services\SettlementThreeService;
use App\Services\SubmitPleaseService;
use App\Services\SupplierPriceService;
use App\Services\SysStoresService;
use App\Services\TicketListService;
use App\Services\UserService;
use App\Services\F6ClaimService; //F6索赔
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use DB;
use App\Models\Orders;
use App\Services\OrderService;//订单服务
use App\Services\CommonService;//通用服务
use App\Services\AftersaleOrderService;//售后服务
use BlueCity\Core\Inc\ErrorInc;
use PhpParser\Node\Stmt\Foreach_;

use BlueCity\Data\Service\ZhiPei\OrderService as zhiPeiOrder;


class OrdersController extends BaseController
{

    protected $rules = array(
        'sys_num' => '系统单号',
        'phone' => '联系电话',
        'name' => '客户姓名',
        'sheng' => '省',
        'shi' => '市',
        'xian' => '县',
        'address' => '详细地址',
        'order_type' => '订单类型',
        'company_name' => '门店名称',
        'orders_id' => '订单数据id',
        'ser_id' => '门店id',
        'user_id' => '用户id',
        'content' => '备注',
        'id' => '订单数据id',
        'msg_id' => '订单详情表id',
        'goods_id' => '新商品id',
        'goods_paid' => '应收金额',
        'goods_price' => '实收金额',
        'goods_state' => '差额处理类型',
        'submit_money' => '差额',
        'pt_id' => '平台',
        'goods_name_new' => '新商品名称',
        'goods_name_old' => '被换商品名称',
        'reminder' => '催单类型',
        'editType'=>'编辑类型',
    );
    protected $sendgood = array(
        'data' => '需发货商品信息',
        'order_num' => '订单单号',
        'sys_num' => '系统单号',
        'delivery_store' => '发货门店',
        'store_id' => '收货门店',
        'send_time' => '期望送达时间',
        'name' => '姓名',
        'telephone' => '电话',
        'collect_type' => '收货人类型',
        'address' => '收货地址',
        'note' => '备注信息',
        'send_type' => '发货部门类型'
    );
	/**|----------------------------------------------------------------------
     * @name 列表页
     * @param state
     * @param shr_name  客户姓名
     * @param shr_phone 客户电话
     * @param shr_sheng 省
     * @param shr_shi   市
     * @param shr_xian  县
     * @param order_num 平台单号
     * @param p_id      平台id
     * @param ser_yycode 用友编号
     * @param creatData 时间
     * @param lock 锁定状态
     * @param goods_number  商品信息
     * @param page      页码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * |-----------------------------------------------------------------------
     */
    public function index ( Request $request ){
        if (!$request->filled('state')) {
            return $this->error('缺少参数', ErrorInc::INVALID_PARAM, []);
        }
        $input = $request->all();
        if(!in_array($input['state'],[0,1,3,5,10,20,6,7,8,21])){
	        return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);
        }
    	$list = OrderService::getList($input,$request->get('session_token'));

        //导出 start
        $session = $request->get('session_token');
        if ($input['is_excel'] == 1) {
            $sqls = $list['sqls'];
            $excel = new CommonController();
            return $excel->getExcelOut($input['Pri_id'], $sqls, $session,200);
        }
        unset($list['sqls']);
        //导出 end

        //商品订单导出 start
        if($input['is_excel']==2){
            if(isset($input['creatData'])){
                $days = (strtotime($input['creatData'][1]) - strtotime($input['creatData'][0]))/3600/24;
                if($days>90){
                    return $this->error('查询时间超过了90天', ErrorInc::FAILED_PARAM);exit;
                }
            }else{
                return $this->error('请输入查询时间',ErrorInc::FAILED_PARAM);exit;
            }

            $sqls2 = $list['sqls2'];
            $exceout = new ExceloutService();
            if(!$sqls2){
                return $this->error('暂无数据或请检查SQL日志是否打开', ErrorInc::MYSQL_FAILED);
            }
            $list = $exceout->getSqls($sqls2)['list'];
            if($list){
                $sql = $exceout->getSqls($sqls2)['sqls'];
                $con_name = '商品订单';//控制器名称
                $action = 'OrdersMsg';//控制器
                $field_data = $exceout->gainFields($session['id'],$action);
                if (empty($field_data)) {
                    return $this->error('您暂时无导出权限', ErrorInc::MYSQL_FAILED);
                }
                return $exceout->createPlan($list,$sql,200,$action,$con_name,$session['id'],$session['admin_acc'], $session['company_id']);
            }else{
                return $this->error('暂无数据', ErrorInc::MYSQL_FAILED);
            }
        }
        //商品订单导出 end

    	if($list['list']){
	    	return $this->success('获取成功', $list); exit;
    	}else{
	    	return $this->error('暂无数据', ErrorInc::DATA_EMPTY,$list);exit;
    	}
    }

    /**|----------------------------------------------------------------------
     * @name 列表页
     * @param sys_num  系统单号
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * |-----------------------------------------------------------------------
     */
    public function getNote(Request $request){

	    if (!$request->filled('sys_num')) {
            return $this->error('缺少参数', ErrorInc::INVALID_PARAM, []);
        }
        $sys_num = $request->input('sys_num');
        $noteRes = CommonService::orderRemarks($sys_num,'orders_id',$request->get('session_token')['admin_groupnew'],$request->input('Login_id'));//获取备注信息
        $list=[];
        $orderafterArr = AftersaleOrderService::getAfterData(['sys_num_searchin'=>$sys_num],'sys_num',['status','sys_num'],1);//获取售后信息
        $aftercunst = AftercustService::getAfterCustData(['afc_sys_searchin'=>$sys_num,'afc_state'=>1],'afc_sys',['afc_id','afc_sys'],'1');//获取电话沟通明细
        foreach ($sys_num as $k => $v){
        	$list[$v]['note'] = $noteRes[$v]??[];
        	if(isset($aftercunst[$v])){
                $list[$v]['aftercust'] = 1;//电话沟通中
            }else{
                $list[$v]['aftercust'] = 2;//无沟通
            }
        	if(isset($orderafterArr[$v])){
        		if ($orderafterArr[$v]['status'] == 0) {
                    $list[$v]['aftertype'] = "1";
        			$list[$v]['afterstatus'] = "";//无售后
        		} elseif ($orderafterArr[$v]['status'] >= 1 && $orderafterArr[$v]['status'] < 40) {
                    $list[$v]['aftertype'] = "2";
        			$list[$v]['afterstatus'] = "售后中";
        		} elseif ($orderafterArr[$v]['status'] == 40) {
                    $list[$v]['aftertype'] = "3";
        			$list[$v]['afterstatus'] = "售后已完成";
        		}

        	}else{
                $list[$v]['aftertype'] = "1";
        		$list[$v]['afterstatus'] = "";//无售后
        	}

        }

        $admin_pt_id = $request->get('session_token')['admin_pt_id'];//session('admin_pt_id');
        $lists['list'] = $list;
        $lists['showcount'] = OrderService::getStatusBar($request->get('session_token'),$admin_pt_id,1);
        return $this->success('成功', $lists); exit;
    }

    /**|------------------------------------------------------------------
     * @name 获取申请售后的必要参数
     * @param sys_num 系统单号
     * @return \Illuminate\Http\JsonResponse
     * |-------------------------------------------------------------------
     */
    public function pgNumber(Request $request)
    {
        if(!$request->filled('sys_num')){
            return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);
        }else{
            $data = AftersaleOrderService::pgNumber($request->input('sys_num'));
            if($data){
                return $this->success('成功', $data); exit;
            }else{
                return $this->error('暂无数据', ErrorInc::DATA_EMPTY);exit;
            }
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 申请售后
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/8/7 16:38
     * |---------------------------------------------------------------------------------
    */
    public function qualityAssurance(Request $request)
    {

        DB::beginTransaction();
        $data = AftersaleOrderService::addAfter($request->all(),$request->get('session_token'),$request->ip());
        if($data['code']) {
            DB::commit();
            $this->operatingTime($data['data']['serserial_number'], '申请质保时间', date("Y-m-d H:i:s"), $data['data']['order_num'], $request->get('session_token')['admin_acc']);//订单操作时间
            $this->insertingLog('申请质保，', $data['data']['sys_num'], '订单' . $data['data']['sys_num'], '订单管理', $request->ip(), $request->get('session_token')['admin_acc']);//日志
            return $this->success($data['msg']);
        }else{
            DB::rollBack();
            return $this->error($data['msg'], $data['data']);exit;
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 客户多次下单记录
     * @param int id 数据id
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/8/20 14:01
     * |---------------------------------------------------------------------------------
    */
    public function orderAllCheck(Request $request){
        if ($request->filled('id')) {
            $id = $request->input('id');
            if(is_array($id)){
                $where['id_searchin'] = $id;
            }else{
                $where['id'] = $id;
            }
            $db = new Orders();
            $orderids = CommonService::getMysqlData($db, $where ,['customer_id','new_customer_id','category','clientAccount','order_num'],[],'first');
            if($orderids){
                if($orderids['clientAccount']!=''){
                    $time = date("Y-m-d H:i:s",strtotime('-1 month'));
                    $orders = Orders::leftJoin('user', 'user.id', '=', 'orders.customer_id')->leftJoin('pt', 'pt.id', '=', 'orders.p_id')->select('orders.order_num', 'orders.sys_num', 'order_status', 'ser_id', 'order_account', 'new_money', 'order_time', 'shr_sheng', 'shr_shi', 'shr_xian', 'shr_adress', 'shr_name', 'shr_phone', 'pt_name','orders.id')->where('clientAccount', $orderids['clientAccount'])->orderBy('orders.create_time', 'DESC')->limit('10')->get();//->where('create_time', '>', $time)->where('order_num', '!=', $orderids['order_num'])->where('order_status', '<', 50)
                }else {
                    $uid = [];
                    $uid[] = $orderids['customer_id'];
                    $uid[] = $orderids['new_customer_id'];
                    $user = new User();
                    $phone = CommonService::getMysqlData($user, ['id_searchin' => $uid], ['shr_phone', 'shr_sheng', 'shr_shi', 'shr_xian', 'shr_name']);
                    $after_state = '1';
                    if ($phone) {
                        $where = [];
                        if ($orderids['category'] < 3) {
                            foreach ($phone as $k => $v) {
                                $next_level = 'user' . $k . '_next_level';
                                $where['user_searchor'][$next_level]['shr_sheng'] = $v['shr_sheng'];
                                $where['user_searchor'][$next_level]['shr_shi'] = $v['shr_shi'];
                                $where['user_searchor'][$next_level]['shr_xian'] = $v['shr_xian'];
                                $where['user_searchor'][$next_level]['shr_name'] = $v['shr_name'];
                            }
                        } else {
                            $phone = array_column($phone, 'shr_phone');
                            $where['user_searchor']['shr_phone_searchin'] = $phone;
                        }
                        $where['id_notin'] = $uid;
                        $user = new User();
                        $userids = CommonService::getMysqlData($user, $where, ['id']);
                        if ($userids) {
                            $userids = array_column($userids, 'id');
                            $userids = implode(',', $userids);
                            $orders = Orders::leftJoin('user', 'user.id', '=', 'orders.customer_id')->leftJoin('pt', 'pt.id', '=', 'orders.p_id')->select('orders.order_num', 'orders.sys_num', 'order_status', 'ser_id', 'order_account', 'new_money', 'order_time', 'shr_sheng', 'shr_shi', 'shr_xian', 'shr_adress', 'shr_name', 'shr_phone', 'pt_name','orders.id')->whereRaw('(customer_id in(' . $userids . ') or new_customer_id in(' . $userids . ')) and is_delete = 2')->orderBy('orders.create_time', 'DESC')->orderBy('orders.sys_num', 'DESC')->limit('10')->get();
                        } else {
                            return $this->error('暂无数据', 2);
                            exit;
                        }
                    } else {
                        return $this->error('数据异常请刷新页面重试', ErrorInc::MYSQL_FAILED);
                        exit;
                    }

                }
                if ($orders) {
                    $orders = $orders->toarray();
                    $order_num = array_column($orders, 'order_num');
                    $order_after = AftersaleOrderService::getAfterData(['order_num_searchin' => $order_num, 'status_searchlt' => '40'], 'order_num', ['status', 'order_num'], 1);//获取售后信息
                    $order_status_name = OrderService::getOrderStatusName();//获取订单状态数组
                    foreach ($orders as $ke => $va) {
                        $orders[$ke]['address'] = $va['shr_sheng'] . $va['shr_shi'] . $va['shr_xian'] . $va['shr_adress'];
                        $orders[$ke]['after_state'] = '1';
                        if (!empty($order_after)) {
                            if (in_array($va['order_num'], $order_after)) {
                                $orders[$ke]['after_state'] = '2';
                                $after_state = '2';
                            }
                        }
                        $orders[$ke]['order_status'] = $order_status_name[$va['order_status']] ?? '未确认';
                        $orderMsg = OrderService::getOrderMsg($va['sys_num']);
                        $orders[$ke]['next'] = $orderMsg;
                        $admins = Admin::where('id', $va['ser_id'])->select('company_name', 'admin_name')->first();
                        $orders[$ke]['company_name'] = $admins['company_name'];
                        $orders[$ke]['admin_name'] = $admins['admin_name'];
                    }
                    $list['after_type'] = $after_state;
                    $list['orders'] = $orders;
                    return $this->success('操作成功', $list);
                } else {
                    return $this->error('暂无数据', 2);
                    exit;
                }
            }else{
                return $this->error('暂无数据', 2);exit;
            }
        }else{
            return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 我要派单
     * @param int orders_id 订单id
     * @param int ser_id 门店id
     * @param int user_id 客户数据id
     * @param string sys_num 系统单号
     * @retrun multitype:array
     * @author dou 2021/8/16 17:53
     * |---------------------------------------------------------------------------------
    */
    public function addWorkOrder ( Request $request ){
        $session = $request->get('session_token');
        $input = $request->only('orders_id', 'ser_id', 'user_id', 'sys_num','child_good','service_charge','smart_store','distance');
        $checkKey = CommonService::checkKey(['orders_id', 'ser_id', 'user_id', 'sys_num'],$input,$this->rules);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM, []);
        }
        $res = OrderService::sendOrder($session, $input, $request->ip());
        return $this->error($res['ErrorMessage'], $res['ErrorCode'], $res['Data']);exit;
    }

    /**|---------------------------------------------------------------------------------
     * @name 评价保存
     * @param id 订单id
     * @param content 备注内容
     * @param sys_num 系统单号
     * @param labtype f反馈标签
     * @retrun multitype:array
     * @author dou 2021/8/17 19:06
     * |---------------------------------------------------------------------------------
    */
    public function qualityEvaluate(Request $request){
        $input = $request->only('id', 'content', 'sys_num','labtype','eval_time');
        $checkKey = CommonService::checkKey(['sys_num','id','content','labtype','eval_time'],$input,$this->rules);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        $session = $request->get('session_token');
        $data = EvaluationFormService::addEvaluation($input,$session,$request->ip());
        return $data;
    }
    /**|---------------------------------------------------------------------------------
     * @name 获取可发货商品
     * @param string order_num 订单单号
     * @param string sys_num 系统单号
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/8/18 16:59
     * |---------------------------------------------------------------------------------
    */
    public function selectSendGoods ( Request $request ){
        if($request->filled('order_num')){
            $order_num = $request->input('order_num');
            $order = OrderService::getOrderBy('order_num', $order_num,['sys_num','accoun']);
            $order_nums = [];
            $order_nums[] = $order_num;
            $order_nums[] = $order['accoun'];
            $data = OrderService::selectSendGoods($order_nums, $order['sys_num']);
            if($data){
                return $this->success('操作成功',$data);exit;
            }else{
                return $this->error('无可发货数据', ErrorInc::DATA_EMPTY);exit;
            }
        }else{
            return $this->error('缺少参数', ErrorInc::INVALID_PARAM);exit;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 申请发货
     * @param array data 需发货商品信息 goods_id：商品ID goods_name：商品名称 msg_id：msg表id
     * @param string order_num 订单单号
     * @param string sys_num 系统单号
     * @param string delivery_store 发货门店
     * @param string store_id 收货门店
     * @param string send_time 期望送达时间
     * @param string name 姓名
     * @param string telephone 电话
     * @param int collect_type 收货人类型
     * @param string address 收货地址
     * @param string note 备注信息
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/8/18 11:22
     * |---------------------------------------------------------------------------------
    */
    public function sendGoods(Request $request){
        DB::beginTransaction();
        $return = SendGoodsService::sendGoods($request);
        if($return['ErrorCode'] == '1'){
            DB::commit(); //提交
        }else{
            DB::rollback();//回滚
        }
        return $return;
    }

    /**|---------------------------------------------------------------------------------
     * @name 订单锁定
     * @param string content 锁定备注
     * @param int p_id 平台id
     * @param string order_num 订单单号
     * @param int refund 锁定类型1退款锁定  2普通锁定
     * @param int refund_type 退款类型1全额  2部分
     * @param string sys_num 系统单号
     * @param int ids 数据id
     * @param int urgent 加急类型：1：普通；2：加急
     * @param string allprice 退款单总金额
     * @param int recycle_type 回收类型 0 不回收1门店回收2库房回收
     * @param int store_id 仓库/门店id
     * @param int send_type 发货类型 发货类型1门店发回2客户发货
     * @param int send_id 发出部门id
     * @param string send_name 发货人姓名
     * @param string telephone 发货人电话
     * @param array goodsArr 锁定订单信息
     * @param string goodsArr->goods_name 商品名称
     * @param string goodsArr->goods_price 商品金额
     * @param string goodsArr->msg_id 商品详情表id
     * @param string goodsArr->goods_num 商品数量
     * @param string goodsArr->goods_id 商品id
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/8/23 15:37
     * |---------------------------------------------------------------------------------
    */
    public function lockOrder ( Request $request ){
        $input = $request->all();
        $session = $request->get("session_token");
        $ip = $request->ip();
        $checkKey = CommonService::checkKey(['content','p_id','order_num','refund','sys_num','ids'],$input);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        if(!in_array($input['refund'], [1,2])){
            return $this->error('退款类型错误', ErrorInc::FAILED_PARAM);exit;
        }
     /*   if(!in_array($input['recycle_type'], [0,1,2])){
            return $this->error('回收类型错误', ErrorInc::FAILED_PARAM);exit;
        }
        if($input['recycle_type']!='0') {
            if (!in_array($input['send_type'], [1, 2])) {
                return $this->error('发货类型错误', ErrorInc::FAILED_PARAM);
                exit;
            }
        }*/
        $res = OrderService::lockOrder($input, $session, $ip);
        return $this->error($res['ErrorMessage'], $res['ErrorCode']);exit;
    }

    /**|---------------------------------------------------------------------------------
     * @name 换货
     * @param string sys_num 系统单号
     * @param int msg_id 订单详情表id
     * @param int goods_id  新商品id
     * @param string goods_paid 应收金额
     * @param string goods_price 实收金额
     * @param string goods_state 差额处理类型1抹零2平台3服务中心4财务5红包
     * @param string submit_money 差额
     * @param string pt_id     平台id
     * @param string goods_name_new 新商品名称
     * @param string goods_name_old 被换商品老商品名称
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/8/25 11:42
     * |---------------------------------------------------------------------------------
    */
    public function confirmReplacement ( Request $request ){
        $input = $request->all();
        $session = $request->get("session_token");
        $checkKey=CommonService::checkKey(['sys_num', 'msg_id', 'goods_id', 'goods_paid', 'goods_price', 'goods_state', 'submit_money', 'pt_id', 'goods_name_new', 'goods_name_old'],$input,$this->rules);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        $orderinfo = OrderService::getOrderBy('sys_num',  $input['sys_num'],['order_num', 'order_status','customer_id','ser_id','store_type','p_id','category','company_id']);
        $input['company_id'] = $orderinfo['company_id'];
        $input['ser_id'] = $orderinfo['ser_id'];
        $input['order_num'] = $orderinfo['order_num'];
        $serial = OrderListService::getOrderListBy('sys_num',  $input['sys_num'] ,'first',['serial_number']);
        $input['order_status'] = $orderinfo['order_status'];
        if ($orderinfo['order_status'] >= 50) {
            return $this->error('该单状态不可换货，请核实！', ErrorInc::SERVER_FAILED);exit;
        }
        if ($orderinfo['order_status'] > 20) {
            /*-------------------------------------------验证结算单状态开始--------------------------------------------*/
            // 工单结算状态
            $sett_status = SettlementList::where(['sys_num' => $input['sys_num'], 'msg_id' => $input['msg_id']])->select('sett_status', 'id', 'ser_id','p_id')->first();
            if ($sett_status['sett_status'] > 1) {
                //该单金额已审核，请联系财务！请核实！
                return $this->error('该单金额已审核，请联系财务！请核实！', ErrorInc::SERVER_FAILED);exit;
            }
            /*-------------------------------------------验证结算单状态结束--------------------------------------------*/
        }
        /*-------------------------------------------验证退收款列表信息开始--------------------------------------------*/
        $subList = SubmitPlease::where(['submit_sys_num' => $input['sys_num'], 'msg_id' => $input['msg_id']])->orderBy('id', 'DESC')->first();
        DB::beginTransaction();
        if($subList){
            if ($subList['submit_stauas'] == 2) {
                DB::rollBack();
                return $this->error('该单售后差额已确认，请向财务核实！', ErrorInc::SERVER_FAILED);exit;
            } elseif($subList['submit_stauas'] < 2){
                DB::rollBack();
                return $this->error('存在未处理的差额申请，请向财务核实！', ErrorInc::SERVER_FAILED);exit;
            }/*else {
                DB::rollBack();
                SubmitPlease::where(['submit_sys_num' => $input['sys_num'], 'msg_id' => $input['msg_id']])->delete();
            }*/
        }
        /*-------------------------------------------验证退收款列表信息结束--------------------------------------------*/

        /*-------------------------------------------添加更换后的商品信息开始--------------------------------------------*/
        $resultMsg = OrderService::replaceMsgGood($input);
        /*-------------------------------------------添加更换后的商品信息结束--------------------------------------------*/
        if ($resultMsg) {
            if (!empty($sett_status)) {
                OrderService::updataReplaceMoney($input, $sett_status, $session);
            }
            if (($input['goods_state'] == 3 || $input['goods_state'] == 4 || $input['goods_state'] == 5 ) && $orderinfo['company_id']!=14) {
                $ArrSett['locksel_type'] = 2;//锁定
                $submit_stauas = 1;//差额处理，1申请中
            } else {
                $ArrSett['locksel_type'] = 1;//未锁定
                $submit_stauas = 2;//差额处理，2确认申请
            }
            if(!isset($session['company_id']) || $session['company_id']=='' || $session['company_id']==0){
                $session['company_id'] = $orderinfo['company_id'];
            }
            $returnPlease = SubmitPleaseService::createSubmitPlease($session['admin_acc'],$input['pt_id'],$input['sys_num'],$input['goods_name_new'],$input['submit_money'],$input['goods_state'],4,2,0,$submit_stauas,$input['msg_id'],0,'','',1,0,$session['company_id']);
            if ($returnPlease) {
                if (!empty($sett_status['sett_status'])) {
                    SettlementList::where(['sys_num' => $input['sys_num'], 'msg_id' => $input['msg_id']])->update($ArrSett);
                }
                /****************************同步通知门店***************************/
                if($orderinfo['order_status']>10 && $orderinfo['store_type']==5){
//                    $store=SyncStores::where("ser_id",$orderinfo['ser_id'])->where("type",2)->value('id');
                    $store = CommonService::getSyncStores($orderinfo['ser_id'], $orderinfo['category']);
                    if(!empty($store)){
                        $supply_price = SupplierPriceService::findPrice($sett_status['ser_id'], $input['goods_id'],['supply_price'],$sett_status['p_id']);
                        if(!$supply_price){
                            $supply_price='0.00';
                        }
                        $goo_code = DB::table('pj_goodcode')->where(['pgc_pgid'=>$input['goods_id'],'pgc_type'=>'1'])->first();
                        if(empty($goo_code)){
                            $goo_code['pgc_code']='暂无';
                            $goo_code['new']='暂无';
                        }
                        $pop = [
                            'ord_order_number' => $serial,
                            'goo_id'        => $input['goods_id'],
                            'goo_code'        => $goo_code['pgc_code'],
                            'goo_codenew'        => $goo_code['new'],
                            'goo_name'       => $input['goods_name_new'],
                            'goo_quantity'    => 1,
                            'goo_price'        => $supply_price,
                            'goo_is_recycle'   => 2,
                            'type'             => 2,
                        ];
                        $store = SysStoresService::sysStore($pop, 'editSd',$store);
                        if($store['ErrorCode']!=1){
                            DB::rollBack();
                            return $store;
                        }
                    }
                }
                /****************************同步通知门店***************************/
                // 日志
                $rea = OrderService::aftersaleLog($input['msg_id'], $input['goods_name_old'], "换货", $session['admin_acc']);
                if(!$rea){
                    DB::rollBack();
                    return $this->error('换货记录添加失败', ErrorInc::MYSQL_FAILED);exit;
                }

                DB::commit();
                $this->insertingLog("换货，", $input['sys_num'], "订单" . $input['sys_num'], "订单管理", $request->ip(), $session['admin_acc']);//日志
                // 换货成功
                return $this->success('换货成功');exit;
            } else {
                DB::rollBack();
                return $this->error('该单在（申请退\收表）操作失败，请核实！', ErrorInc::MYSQL_FAILED);exit;
            }
        }else{
            DB::rollBack();
            return $this->error('该单在（订单商品管理）操作失败，请核实！', ErrorInc::MYSQL_FAILED);exit;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 派单编辑地址
     * @param string sys_num 系统单号
     * @param string phone 联系电话
     * @param string sheng 省份
     * @param string shi 城市
     * @param string xian 区县
     * @param string address 详细地址
     * @param string name 客户姓名
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/8/26 15:36
     * |---------------------------------------------------------------------------------
    */
    public function editAddress ( Request $request ){
        $input = $request->all();
        $session = $request->get("session_token");
        if(!in_array($input['editType'], [1,2,3,4])){
            return $this->error('用户编辑类型错误', ErrorInc::INVALID_PARAM);
        }
        if($input['editType']=='4') {
            $checkKey = CommonService::checkKey(['sys_num', 'phone', 'sheng', 'shi', 'xian', 'address', 'name', 'editType'], $input, $this->rules);
            if ($checkKey['code'] != 1) {
                return $this->error('参数' . $checkKey['data'] . '未填写,或值为空', ErrorInc::INVALID_PARAM);
                exit;
            }
        }
        DB::beginTransaction();
        $sys_num = $input['sys_num'];//系统单号
        $rest = OrderService::getOrderBy('sys_num', $input['sys_num'],['order_num', 'customer_id', 'new_customer_id', 'order_status', 'ser_id','store_type','category']);
        $serial = OrderListService::getOrderListBy('sys_num', $input['sys_num'],'first',['serial_number']);
        $old_user = CommonService::getUser('id', $rest['new_customer_id'],['shr_name','shr_phone','shr_sheng','shr_shi','shr_xian','shr_adress','shr_code','car_make','car_line','car_model','car_id','is_jdservice'],'first');
        $arr['shr_name'] = $old_user['shr_name'];//姓名
        $arr['shr_phone'] = $old_user['shr_phone'];//电话
        $arr['shr_sheng'] = $old_user['shr_sheng'];//省
        $arr['shr_shi'] = $old_user['shr_shi'];//市
        $arr['shr_xian'] = $old_user['shr_xian'];//县
        $arr['shr_adress'] = $old_user['shr_adress'];//详细地址
        if($input['editType']=='1'){
            $arr['shr_name'] = $input['name'];//姓名
        }if($input['editType']=='2'){
            $arr['shr_phone'] = $input['phone'];//电话
        }if($input['editType']=='3'){
            $arr['shr_sheng'] = $input['sheng'];//省
            $arr['shr_shi'] = $input['shi'];//市
            $arr['shr_xian'] = $input['xian'];//县
            $arr['shr_adress'] = $input['address'];//详细地址
        }if($input['editType']=='4'){
            $arr['shr_name'] = $input['name'];//姓名
            $arr['shr_phone'] = $input['phone'];//电话
            $arr['shr_sheng'] = $input['sheng'];//省
            $arr['shr_shi'] = $input['shi'];//市
            $arr['shr_xian'] = $input['xian'];//县
            $arr['shr_adress'] = $input['address'];//详细地址
        }
        if ($rest['new_customer_id'] == $rest['customer_id']) {
            $arr['shr_code'] = $old_user['shr_code'];//核销码
            $arr['car_make'] = $old_user['car_make'];//品牌
            $arr['car_line'] = $old_user['car_line'];//车系
            $arr['car_model'] = $old_user['car_model'];//车型
            $arr['car_id'] = $old_user['car_id'];//车辆id
            $arr['is_jdservice'] = $old_user['is_jdservice'];//车辆id
            $list = User::insertGetId($arr);
            $att['new_customer_id'] = $list;
            $chos = Orders::where('sys_num', $sys_num)->update($att);
        } else {
            $chos = User::where('id', $rest['new_customer_id'])->update($arr);
            $list = $rest['new_customer_id'];
        }
        if (!empty($chos)) {
            RefundService::editUserData($rest['order_num'], $arr['shr_name'], $arr['shr_phone'], $arr['shr_sheng'], $arr['shr_shi'], $arr['shr_xian'], $arr['shr_adress'], $list);
            $dress = $old_user['shr_name'] . "," . $old_user['shr_phone'] . "," . $old_user['shr_sheng'] . $old_user['shr_shi'] . $old_user['shr_xian'] . $old_user['shr_adress'] . "<---更换为--->" . $arr['shr_name'] . "," . $arr['shr_phone'] . "," . $arr['shr_sheng'] . $arr['shr_shi'] . $arr['shr_xian'] . $arr['shr_adress'];
            if ($rest['order_status'] > 10) {
                $poss['customer_phone'] = $arr['shr_phone'];
                $poss['customer_id'] = $list;
                OrderList::where('sys_num', $sys_num)->update($poss);//编辑工单信息
                if ($rest['order_status'] > 20) {
                    SettlementList::where('sys_num',$sys_num)->update(['customer_id'=>$list]);//编辑结算但信息
                }

                if ($rest['order_status'] >= 30 && $rest['category']<3) {
                    $serid = Admin::whereRaw("FIND_IN_SET(" . $rest['ser_id'] . ",children_id)")->value('id');
                    if (!empty($serid)) {
                        $weixin['ser_id'] = $serid;
                    } else {
                        $weixin['ser_id'] = $rest['ser_id'];
                    }
                    $weixin['type'] = '变更客户信息';
                    $weixin['order_num'] = $rest['order_num'];
                    $weixin['data'] = $dress;
                    $weixin['serial_number'] = $serial;
                    CommonService::requestPost('http://weixin.sudianwang.com/index.php/BindingAccount/editInform', $weixin);
                }
                /****************************同步通知门店开始***************************/
//                $store=DB::table('sync_stores')->where("ser_id",$rest['ser_id'])->where("type",2)->value('id');
                $store = CommonService::getSyncStores($rest['ser_id'], $rest['category']);
                if(!empty($store) && $rest['store_type']==5 && $rest['category']<3){
                    $pop = [
                        'ord_order_number' => $serial,
                        'orcl_name'        => $arr['shr_name'],
                        'orcl_phone'       => $arr['shr_phone'],
                        'orcl_province'    => $arr['shr_sheng'],
                        'orcl_city'        => $arr['shr_shi'],
                        'orcl_county'      => $arr['shr_xian'],
                        'orcl_address'     => $arr['shr_adress'],
                        'type'             => 1,
                    ];
                    $store = SysStoresService::sysStore($pop, 'editSd',$store);
                    if($store['ErrorCode']!=1){
                        DB::rollBack();
                        return $store;
                    }
                }
                /****************************同步通知门店结束***************************/
            }

            DB::commit();
            $content = $rest['order_num'] . "订单，地址:".$dress;
            $this->insertinglog('编辑地址，', $rest['sys_num'], $content, '订单管理', $request->ip(), $session['admin_acc']);//日志
            return $this->success('操作成功');exit;
        } else {
            DB::rollBack();
            return $this->error('操作失败',ErrorInc::MYSQL_FAILED);exit;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 更换平台
     * @param string sys_num    系统单号
     * @param int pt_id      新平台
     * @param int change_pid 原平台
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/8/26 18:03
     * |---------------------------------------------------------------------------------
    */
    public function changePt(Request $request){
        $input = $request->all();
        $session = $request->get("session_token");
        $checkKey=CommonService::checkKey(['sys_num', 'change_pid', 'pt_id'],$input);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        $msg = OrderService::getOrderMsgBy('sys_num',$input['sys_num'],['goods_id'],'pluck');
        if(in_array('5912', $msg)){
            return $this->error('特殊订单请联系管理处理', ErrorInc::REQUEST_FORBIDDEN);exit;
        }
        $poss['p_id'] = $input['pt_id'];
        $order_num = OrderService::getOrderBy('sys_num', $input['sys_num'] , ['order_num']);
        $orders = Orders::where('sys_num', $input['sys_num'])->update($poss);
        $orderlist = OrderList::where('sys_num', $input['sys_num'])->update($poss);
        $settlement = SettlementList::where('sys_num', $input['sys_num'])->update($poss);
        SubmitPlease::where('submit_sys_num', $input['sys_num'])->update(['submitr_pt'=>$input['pt_id']]);
        Refund::where('sys_num',$input['sys_num'])->update(['pt_id'=>$input['pt_id']]);
        $this->insertinglog('替换平台，', $input['sys_num'], $input['change_pid'] . '->' . $input['pt_id'] . "更换平台订单", '订单管理', $request->ip(), $session['admin_acc']);
        if (!empty($orders)) {
            return $this->success('操作成功');exit;
        } else {
            return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 订单延期 （动作）
     * @param string sys_num      系统单号
     * @param string note_content 备注内容
     * @param string day_time     延期时间
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/8/26 18:18
     * |---------------------------------------------------------------------------------
    */
    public function delayOrder(Request $request){
        $input = $request->all();
        $session = $request->get("session_token");
        $checkKey=CommonService::checkKey(['sys_num', 'day_time', 'note_content'],$input);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        $order_num = Orders::where('sys_num', $input['sys_num'])->select("order_num",'p_id')->first();
        $order_num = OrderService::getOrderBy('sys_num', $input['sys_num'],['order_num','p_id']);
        $rest = CommonService::accMe($input['sys_num'], '订单管理', "延期，" . $input['note_content'], '', '', $request->get('session_token')['admin_groupnew'], $request->get('session_token')['admin_acc'], $request->get('session_token')['id']);//添加备注
        if ($rest) {
            DB::beginTransaction(); //开启事务
            $arr['day_time'] = $input['day_time'];//延期日期
            $return = Orders::where('sys_num', $input['sys_num'])->update($arr);
            $resultOrderList = OrderList::where('sys_num', $input['sys_num'])->update($arr);
            if ($return) {

                DB::commit();
                $this->insertingLog("订单延期，", $input['sys_num'], "订单延期，订单号：" . $order_num['order_num'], "订单管理", $request->ip(), $session['admin_acc']);
                return $this->success('操作成功');exit;
                exit;
            } else {
                DB::rollback();
                return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
            }
        } else {
            return $this->error('备注添加失败', ErrorInc::MYSQL_FAILED);exit;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 订单加急
     * @param int order_type 加急标签 15,20,25,30
     * @param string sys_num 系统单号
     * @param string content 备注内容
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/8/26 18:41
     * |---------------------------------------------------------------------------------
    */
    public function orderUrgent(Request $request)
    {
        if ($request->filled('sys_num') && $request->filled('order_type')) {
            $sys_num = $request->input('sys_num');
            $order_type = $request->input('order_type');
            $res = OrderService::getOrderBy('sys_num', $sys_num,['order_status','order_type']);
            if ($res && $res['order_status'] < '34' && $res['order_type'] == '1') {
                if ($res['order_status'] == '30') {
                    $serial_number = OrderList::where('sys_num', $sys_num)->value("serial_number");
                    $time = OrderTime::where(['serial_number' => $serial_number, 'is_type' => '接单时间'])->value("create_time");
                    if ((strtotime(date("Y-m-d H:i:s") - strtotime($time))) > 900) {
                        return $this->error('接单已超过15分钟，请催单', ErrorInc::REQUEST_FORBIDDEN);exit;
                    }
                }
                $data['order_type'] = $order_type;
                $ress = Orders::where('sys_num', $sys_num)->update(['order_type' => $order_type]);
                $session = $request->get('session_token');
                if ($request->filled('content')) {//备注
                    CommonService::accMe($sys_num, "订单管理", $request->input('content'), '', 1, $session['admin_groupnew'], $session['admin_acc'], $session['id']);
                }
                if ($ress) {
                    if ($res['order_status'] == '30' || $res['order_status'] == '20') {
                        OrderList::where('sys_num', $sys_num)->update(['orli_type' => $order_type]);
                    }
                    $this->insertingLog('订单加急，', $sys_num, '订单加急:' . $sys_num, '订单管理', $request->ip(), $session['admin_acc']);//日志
                    return $this->success('操作成功');exit;
                }
            }
        } else {
            return $this->error('参数错误', ErrorInc::INVALID_PARAM);exit;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 催单展示
     * @param sys_num 系统单号
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/8/26 19:35
     * |---------------------------------------------------------------------------------
    */
    public function reminderInfo( Request $request ){
        if (!$request->filled('sys_num')) {
            return $this->error('参数错误', ErrorInc::INVALID_PARAM);exit;
        }
        $sys_num = $request->input('sys_num');
        $data = SerInforService::remindInfo($sys_num);
        return $data;
    }

    /**|---------------------------------------------------------------------------------
     * @name 催单
     * @param string sys_num 系统单号
     * @param string order_num 平台单号
     * @param string ser_id 服务商id
     * @param string reminder 是否催单 1：是；2：否
     * @param string content 备注
     * @param string pic
     * @return \Illuminate\Http\JsonResponse
     * @author dou 2021/8/26 19:55
     * |---------------------------------------------------------------------------------
     */
    public function reminder( Request $request ){
        $input = $request->all();
        $session = $request->get("session_token");
        $ip = $request->ip();
        $data = SerInforService::remind($input, $session, $ip);
        return $data;
    }

    /**|---------------------------------------------------------------------------------
     * @name 更换单号
     * @param int id 订单id号
     * @param string old_order 被换系统单号
     * @param string new_order 新的系统单号
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/8/28 10:45
     * |---------------------------------------------------------------------------------
    */
    public function changeOrder(Request $request){
        $input = $request->all();
        $session = $request->get("session_token");
        $checkKey=CommonService::checkKey(['id', 'old_order', 'new_order'],$input,$this->rules);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        $input['old_order'] = CommonService::restrict($input['old_order']);
        $old_id = Orders::where('order_num', $input['old_order'])->value('id');
        if(!$old_id){
            return  $this->error('旧单号不存在', ErrorInc::REQUEST_FORBIDDEN);exit;
        }
        $new_id = Orders::where('order_num', $input['new_order'])->value('id');
        if(!$new_id){
            return  $this->error('新单号不存在', ErrorInc::REQUEST_FORBIDDEN);exit;
        }

        $old_order_info = OrderService::getOrderBy('order_num', $input['old_order'],['order_status']);
        //print_r($old_order_info);
        if($old_order_info<30 || $old_order_info>40){
            return  $this->error('旧单号状态不可换单', ErrorInc::REQUEST_FORBIDDEN);exit;
        }
        $data_source = SendGoodsService::getInfoBy('order_num', $input['old_order'],['send_type'],'first');
        //print_r($data_source);
        if($data_source==2&&$input['source_type']==1){
           // return  $this->error('是库房发货换单，是否确认？', ErrorInc::REQUEST_FORBIDDEN);exit;
            return response()->json(['ErrorCode' => 77, 'ErrorMessage' => '是库房发货换单，是否确认？']);
            exit;
        }


        DB::beginTransaction();
        $order_status = OrderService::getOrderBy('order_num', $input['new_order'],['order_status','sys_num']);
        if ($order_status['order_status'] > 20) {
            return  $this->error('该单号已下派', ErrorInc::REQUEST_FORBIDDEN);exit;
        }

        $data_source_new = SendGoodsService::getInfoBy('order_num', $input['new_order'],['send_type'],'first');

        if($data_source==2 && $data_source_new!=2){
            return  $this->error('旧单是库发货但新单号不是库房发货,不能换单', ErrorInc::REQUEST_FORBIDDEN);exit;
        }

        $poss['order_num'] = $input['old_order'].'-';
        $poss['accoun'] = $input['new_order'];
        $poss['order_status'] = 50;
        $res = Orders::where('id',$new_id)->update($poss);
        if (!$res) {
            return  $this->error('操作失败2', ErrorInc::MYSQL_FAILED);exit;
        }
        $orderArr = Orders::where('id', $old_id)->update(['order_num' => $input['new_order'], 'accoun' => $input['old_order']]);
        $orderlistArr = OrderList::where('order_num', $input['old_order'])->update(['order_num' => $input['new_order']]);
        $settlementArr = SettlementList::where('order_num', $input['old_order'])->update(['order_num' => $input['new_order']]);
        $res = Orders::where('id', $new_id)->update(['order_num' => $input['old_order']]);
        if ($res && $orderArr) {
            DB::commit();
            $this->insertingLog("更换单号，", $order_status['sys_num'], "原单号：" . $input['old_order'] . "=>" . $input['new_order'], "订单管理", $request->ip(), $session['admin_acc']);
            return $this->success('操作成功');exit;
        } else {
            DB::rollback();
            return  $this->error('操作失败3', ErrorInc::MYSQL_FAILED);exit;
        }

    }

    /**|---------------------------------------------------------------------------------
     * @name 电话沟通
     * @param int type 1：展示数据；2：提交数据
     * @param string sys_num 系统单号
     * @param int afc_id  订单表id
     * @param int goods_id   商品id
     * @param string goods_price  商品价格
     * @param string goods_name  商品名称
     * @param string num         商品数量
     * @param string afc_content 备注内容
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/8/28 11:33
     * |---------------------------------------------------------------------------------
    */
    public function afterCusmer(Request $request)
    {
        $input = $request->all();
        $session = $request->get("session_token");
        if (!$request->filled('type')) {
            return $this->error('参数错误', ErrorInc::FAILED_PARAM);exit;
        }
        $sys_num = $request->input('sys_num');
        if ($request->input('type') == 1) {
            $res = AftercustService::getAfterCustData(['afc_state_noteq'=>4,'afc_sys'=>$sys_num],'',['afc_id']);
            if ($res) {
                return  $this->error('存在未完成追踪单', ErrorInc::REQUEST_FORBIDDEN);exit;
            } else {
                $rea = OrderService::searchMsgNum($sys_num,['goods_id', 'goods_name', 'goods_price','goods_num']);
                //dd($rea);
                if ($rea) {
                    $rea = CommonService::resetListKey($rea);
                    return $this->success('操作成功',$rea);
                } else {
                    return  $this->error('存在未完成追踪单', ErrorInc::DATA_EMPTY);exit;
                }
            }
        } elseif ($request->input('type') == 2) {
            $checkKey=CommonService::checkKey(['afc_id', 'goods_id', 'goods_price','num','goods_name','afc_content'],$input);
            if($checkKey['code']!=1){
                return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
            }
            $afc_id = $input['afc_id'];
            $goods_id = $input['goods_id'];
            $goods_price = $input['goods_price'];
            $num = $input['num'];
            $goods_name = $input['goods_name'];
            $order = OrderService::getOrderBy('id', $afc_id);
            $res = AftercustService::getAfterCustData(['afc_state_noteq'=>4,'afc_sys'=>$sys_num],'',['afc_id']);
            if ($res) {
                return  $this->error('存在未完成追踪单', ErrorInc::REQUEST_FORBIDDEN);exit;
            } else {
                $rea = AftercustService::createAftercust($order['sys_num'], $order['order_num'], $order['p_id'], $order['create_time'], $goods_id, $goods_price, $num, $order['new_customer_id'], $order['ser_id'], $session['admin_acc'], $session['id'], $input['afc_content'], $goods_name, $order['order_status'], 1);
                if ($rea) {
                    $rest = CommonService::accMe($order['sys_num'], '电话沟通申请', $input['afc_content'], '', 1, $session['admin_groupnew'], $session['admin_acc'], $session['id']);
                    $this->insertingLog("电话沟通，", $order['sys_num'], "订单", "订单管理", $request->ip(), $session['admin_acc']);//日志
                    return $this->success('操作成功');exit;
                } else {
                    return  $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
                }
            }
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 自动派单
     * @param int type 1:获取可派订单 2：执行派单
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/8/28 15:26
     * |---------------------------------------------------------------------------------
    */
    public function autoOrder(Request $request)
    {
        if ($request->input('type') == 1) {
            $info = DB::table('time_type')->where('t_type', 1)->value('tstart_time');
            $time1 = date("Y-m-d") . $info;
            $time2 = date("Y-m-d H:i:s", strtotime($time1 . " -1 day"));
            $rea = Orders::where('create_time', '>', $time2)->where('create_time', '<', $time1)->where('distype', 1)->where('order_status', 10)->count('id');
            if ($rea) {
                return $this->success('操作成功',$rea);exit;
            } else {
                return  $this->error('操作失败', ErrorInc::DATA_EMPTY);exit;
            }
        } elseif ($request->input('type') == 2) {
            $session = $request->get('session_token');
            $info = DB::table('time_type')->where('t_type', 1)->value('tstart_time');
            $time1 = date("Y-m-d") . $info;
            $time2 = date("Y-m-d H:i:s", strtotime($time1 . " -1 day"));
            $db = new Orders();
            $rea =CommonService::getMysqlData($db, ['create_time_searchgt'=>$time2,'create_time_searchlt'=>$time1,'distype'=>1,'order_status'=>10],[],[],'get','5');
            $num = 0;
            if ($rea) {
                $id = '';
                foreach ($rea as $k => $v) {
                    if (!in_array($v['p_id'], [95, 111, 112, 131, 134, 136])) {//95,112,131,134
                        //include_once('AutomaticAction.class.php');
                        $Autom = new AotuorderController();
                        $info = $Autom->Distrib($v['sys_num'], $request->ip());
                        if ($info == 2) {
                            continue;
                        } else {
                            $num++;
                        }
                    }
                    $id = $v['id'];
                }
                $data['data'] = $num;
                $data['id'] = $id;
                return response()->json(['Data' => $data, 'ErrorCode' => 1, 'ErrorMessage' => '操作成功']);exit;
            } else {
                $data['data'] = $rea;
                return  $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
            }
        } else {
            return  $this->error('操作失败', ErrorInc::REQUEST_FORBIDDEN);exit;
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 恢复 、撤销
     * @param string sys_num 系统单号
     * @param string order_num 平台单号
     * @param int p_id 平台id
     * @param int type 操作类型  1恢复2撤销
     * @param array labtype 拒单标签
     * @param string subsidy_money 补贴金额
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author he <2019-07-02 08:55>
     * |---------------------------------------------------------------------------------
     */
    public function undoIve(Request $request)
    {
        $refArr = Refund::where('order_num', $request->input('order_num'))->where('state', '!=', 5)->first();
        if($refArr){
            return  $this->error('退款订单锁定不能操作', ErrorInc::REQUEST_FORBIDDEN);exit;
        }
        $input = $request->all();
        $session = $request->get("session_token");
        $checkKey=CommonService::checkKey(['sys_num', 'order_num', 'p_id','type'],$input);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        if ($request->input('type') == 1) {
            $order_find = OrderService::getOrderBy('sys_num', $input['sys_num'],['order_status', 'id','ser_id','sys_num','store_type','category']);;
            $order_status = $order_find['order_status'];
            $orderArr['lock_type'] = 1;
            $orderListArr['locklist_type'] = 1;
            $orderSettArr['locksel_type'] = 1;
            $orderSetteArr['locksee_type'] = 1;
            try {
                DB::beginTransaction();
                $a = SettlementList::where('sys_num', $input['sys_num'])->update($orderSettArr);
                $b = Orders::where('sys_num', $input['sys_num'])->update($orderArr);
                $c = OrderList::where('sys_num', $input['sys_num'])->update($orderListArr);
                $d = SettlementThree::where('sys_num', $input['sys_num'])->update($orderSetteArr);
                if ($b) {

                    /****************************同步通知门店***************************/
                    if($order_find['order_status']>10 && $order_find['store_type']=='5'){
//                        $store=SyncStores::where("ser_id",$order_find['ser_id'])->where("type",2)->value('id');
                        $store = CommonService::getSyncStores($order_find['ser_id'], $order_find['category']);
                        if(!empty($store)){
                            $returnOrderList = OrderList::where('sys_num', $order_find['sys_num'])->select('serial_number')->get()->toArray();
                            foreach ($returnOrderList as $k => $v) {
                                $pop = [
                                    'order_num' => $v['serial_number'],
                                    'type' => 2
                                ];
                                $store = SysStoresService::sysStore($pop, 'lockUrl',$store);
                                if ($store['ErrorCode'] != 1) {
                                    DB::rollBack();
                                    return $store;
                                }
                            }
                        }
                    }
                    /******************************同步通知门店*************************/

                    //恢复改已驳回2019/10/8
                    Refund::where('order_num', $input['order_num'])->update(['state' => 5]);
                    $content = "恢复订单" . $input['sys_num'];
                    $this->insertingLog('恢复，', $input['sys_num'], $content, '订单管理', $request->ip(), $request->get('session_token')['admin_acc']);
                    DB::commit();
                    return $this->success('操作成功');exit;
                    exit;
                } else {
                    DB::rollback();
                    return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
                }
            } catch (\Exception $e) {
                DB::rollback();
                return $this->error($e->getMessage(), ErrorInc::MYSQL_FAILED);exit;
            }
        } elseif ($request->input('type') == 2) {
            if (!$request->filled('labtype')) { // || !$request->filled('subsidy_money')
                return $this->error('参数错误', ErrorInc::FAILED_PARAM);exit;
            }
            DB::beginTransaction(); //开启事务
            $submit_stauas = SubmitPleaseService::getSubmitPleaseBy('submit_sys_num', $input['sys_num'],['submit_stauas'],'value');
            // 该单售后差额在申请中，请核实！
            if ($submit_stauas == 1) {
                return  $this->error('该单售后差额在申请中，请核实！', ErrorInc::REQUEST_FORBIDDEN);exit;
            }
            $restSelist = SettlementService::getSettlementListBy('sys_num', $input['sys_num']);

            $restSethree = SettlementThreeService::getSettlementThreeBy('sys_num', $input['sys_num']);
            // 该单金额在结算中
            if ($restSelist) {
                foreach ($restSelist as $k => $v) {
                    if ($v['sett_status'] == 20 || ($v['wat_num'] != "" && $v['sett_status'] != 30)) {
                        DB::rollback();
                        return  $this->error('该订单申请结算中，请与财务联系后再操作！', ErrorInc::REQUEST_FORBIDDEN);exit;
                    }
                }
            }
            if ($restSethree) {
                // 该单金额在收款中
                foreach ($restSethree as $kk => $vv) {
                    if ($vv['three_status'] == 20) {
                        DB::rollback();
                        return  $this->error('该订单申请收款中，请与财务联系后再操作！', ErrorInc::REQUEST_FORBIDDEN);exit;
                    }
                }
            }
            /*------------------------------------------同步第三方平台开始-----------------------------------------------*/
            $syspt = OrderService::sysPtThree( $input , 50);
            if($syspt['ErrorCode']!=1){
                return $syspt;
            }
            /*------------------------------------------同步第三方平台结束-----------------------------------------------*/
            //补油费
            $moneys = SetmoneyType::where("sety_id",4)->value('sety_price');
            $moneys = explode(',',$moneys);
            $orcl_consent_price = 0;
            if (in_array($input['subsidy_money'],$moneys)) {
                $orcl_consent_price = $input['subsidy_money'];
                $orderArr['order_status'] = 55;
                $orderListArr['stauas'] = 55;
                $orderListArr['feeds_time'] = date('Y-m-d H:i:s');
                $orderSettArr['list_service_type'] = 55;
                $orderSettArr['subsidy_money'] = $input['subsidy_money'];
                $orderSettArrs['list_service_type'] = 50;
                $orderSetteArr['list_service_three'] = 55;
                $res = SettlementList::where('sys_num', $input['sys_num'])->get()->toArray();
                foreach ($res as $kr => $vr) {
                    if ($kr == 0) {
                        SettlementList::where('id', $vr['id'])->update($orderSettArr);
                        SettlementService::createSettMoney($vr['id'], $input['sys_num'], $input['subsidy_money'], $session['admin_acc'], 4);
                    } else {
                        SettlementList::where('id', $vr['id'])->update($orderSettArrs);
                    }
                }
            } else {//if ($input['subsidy_money'] == "无补贴")
                $orderArr['order_status'] = 50;
                $orderListArr['stauas'] = 50;
                $orderSettArr['list_service_type'] = 50;
                $orderSetteArr['list_service_three'] = 50;
                $returnSettlementList = SettlementList::where('sys_num', $input['sys_num'])->update($orderSettArr);
            }
            /****/
            $data['ov_show'] = 5;
            $retu = OrderVisit::where('ov_sys', $input['sys_num'])->update($data);
            $returnOrderList = OrderList::where('sys_num',$input['sys_num'])->update($orderListArr);
            $returnOrder = Orders::where('sys_num', $input['sys_num'])->update($orderArr);
            $returnSettlementThree = SettlementThree::where('sys_num', $input['sys_num'])->update($orderSetteArr);
            $get['status'] = 50;
            OrderAfter::where('sys_num', $input['sys_num'])->where('status', '<', 40)->update($get);
            $older = OrderService::getOrderBy('sys_num', $input['sys_num'],['order_status', 'sys_num', 'order_num', 'create_time', 'p_id','ser_id','store_type','category','company_id']);
            if ($returnOrder) {
                $ser_id = $older['ser_id'];
                if (!empty($ser_id) && $ser_id != 0) {
                    $serial_number = OrderList::where('sys_num', $input['sys_num'])->orderBy('id', 'DESC')->limit(1)->value("serial_number");
                    //**************
                    if (empty($serial_number)) {
                        $serial_number = '无';
                        $older['serial_number'] = '';
                    } else {
                        $older['serial_number'] = $serial_number;
                        $slid = SettlementService::getSettlementListBy('list_id', $serial_number,['id','wat_num'],'first');
                        $older['slid'] = $slid['id']??'';
                        $older['wat_num'] = $slid['wat_num']??'';
                    }
                } else {
                    $older['serial_number'] = '';
                    $serial_number = '无';
                }
                AfterSaleService::insertData($input['labtype'], $older, $session);//添加标签相关信息
            }
            if ($returnOrder) {
                /***************半径推送******************************/
                if($older['order_status']>10){
//                    $store=SyncStores::where("ser_id",$older['ser_id'])->where("type",2)->value('id');
                    $store = CommonService::getSyncStores($older['ser_id'], $older['category']);
                    if(!empty($store) && $older['store_type']=='5'){
                        $returnOrderList = OrderList::where('sys_num', $older['sys_num'])->select('serial_number')->get()->toArray();
                        foreach( $returnOrderList as $k => $v )
                        {
                            $pop['ord_order_number'] = $v['serial_number'];
                            $pop['type'] = 1;
                            if($k==0){
                                $pop['orcl_consent_price']=$orcl_consent_price;
                            }else{
                                $pop['orcl_consent_price'] = 0;
                            }
                            $pop['remark'] = '客户退单';
                            $store = SysStoresService::sysStore($pop, 'recycleOrder',$store);
                            if($store['ErrorCode']!=1){
                                DB::rollBack();
                                return $store;
                            }
                        }
                    }
                }
                /***************半径推送******************************/
                /*******************************************撤销订单回收库存*****************************************/
                if($older['order_status']>10) {
                    $goodid = DB::table('order_msg')->where('sys_num', $older['sys_num'])->whereNotIn('goods_service', [2, 3])->select('goods_id', 'goods_num')->get()->toArray();
                    //库存有关
                    if ($goodid) {
                        $gsql = "";
                        $sql = "INSERT INTO `gone_invenrecor`( `iv_serid`, `iv_goodid`, `iv_num`,`iv_serial`,`iv_ordernum`,`iv_company_id`) VALUES";
                        foreach ($goodid as $kgi => $vgi) {
                            $gsql .= "UPDATE `gone_inventory` SET `inv_num`=`inv_num`+" . $vgi['goods_num'] . " WHERE `inv_serid`='" . $older['ser_id'] . "' and `inv_goodid`='" . $vgi['goods_id'] . "' and `inv_company_id`='" . $older['company_id'] . "';";
                            $sql .= "('" . $older['ser_id'] . "','" . $vgi['goods_id'] . "','+" . $vgi['goods_num'] . "','" . $older['serial_number'] . "','" . $older['order_num'] . "','" . $older['company_id'] . "'),";
                        }

                        $sql = trim($sql, ',');
                        DB::insert($sql);
                        DB::update($gsql);
                    }
                }
                /*******************************************撤销订单回收库存*****************************************/
                DB::commit();
//                OrderService::sysWarehouseCancel($input['sys_num']);
                if ($older['order_status'] < 20) {
                    $goodsArr = OrderMsg::where('sys_num', $older['sys_num'])->select('goods_id')->get()->toArray();
                    $goodsArr = OrderService::getOrderMsgBy('sys_num', $older['sys_num'],['goods_id']);
                    $inArr = [];
                    foreach ($goodsArr as $k => $v) {
                        $inArr[$k]['sys_num'] = $older['sys_num'];
                        $inArr[$k]['order_num'] = $older['order_num'];
                        $inArr[$k]['order_time'] = $older['create_time'];
                        $inArr[$k]['order_state'] = $orderArr['order_status'];
                        $inArr[$k]['update_time'] = date("Y-m-d H:i:s");
                        $inArr[$k]['revocation_time'] = date("Y-m-d H:i:s");
                        $inArr[$k]['p_id'] = $older['p_id'];
                        $inArr[$k]['cancle_id'] = $session['id'];
                        $inArr[$k]['cancel_person'] = $session['admin_acc'];
                        //$inArr[$k]['goods_id'] = $v['goods_id'];
                        $inArr[$k]['company_id'] = $session['company_id'];
                        $inArr[$k]['category'] = 3;//退单
                    }
                    Temporary::insert($inArr);
                } elseif ($older['order_status'] >= 20) {
                    Temporary::where('order_num', $older['order_num'])->where('category', 1)->update(['order_state' => $orderArr['order_status'], 'update_time' => date("Y-m-d H:i:s"), 'category' => 3, 'revocation_time' => date("Y-m-d H:i:s"), 'cancle_id' => $session['id'], 'cancel_person' => $session['admin_acc']]);
                }
                //撤销改已审核2019/10/8
                Refund::where('order_num', $input['order_num'])->update(['state' => 4]);
                $this->insertingLog('撤销，', $input['sys_num'], "订单：" . $input['sys_num'], '订单管理', $request->ip(), $session['admin_acc']);//日志
                return $this->success('操作成功');exit;
            } else {
                DB::rollback();
                return $this->error('操作失败',ErrorInc::MYSQL_FAILED);exit;
            }
        }else{
            return $this->error('操作失败',ErrorInc::FAILED_PARAM);exit;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 申请协商价格
     * @param int type 1:展示协商价格的商品；2:提交
     * @param int sys_num 系统单号
     * @param string negotiated_price 价格
     * @param int goods_id 商品id
     * @param string goods_name 商品名称
     * @param string negotiated_reason 申请原因
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/8/28 17:30
     * |---------------------------------------------------------------------------------
    */
    public function negotiated ( Request $request ){
        if ($request->filled('sys_num') && $request->filled('type')) {
            $sys_num = $request->input('sys_num');
            $session = $request->get('session_token');
            if ($request->input('type') == 1) {//展示商品
                $msgArr = OrderService::getOrderMsgBy('sys_num', $sys_num, ['goods_name', 'goods_id','id']);
                if ($msgArr) {
                    return $this->success('成功', $msgArr);
                    exit;
                } else {
                    return $this->error('暂无数据', ErrorInc::DATA_EMPTY);
                    exit;
                }
            } elseif ($request->input('type') == 2) {
                $input = $request->all();
                $checkKey=CommonService::checkKey(['goods_id', 'goods_name', 'negotiated_price','negotiated_reason'],$input);
                if($checkKey['code']!=1){
                    return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
                }
                //
                $msg_id = $request->input('msg_id')??0;
                $goods_id = $request->input('goods_id');
                $negotiated_reason = $request->input('negotiated_reason');
                $negotiated_price = $request->input('negotiated_price');
                $goods_name = $request->input('goods_name');
                $supply_price = $request->input('supply_price');
                $orderArr = OrderService::getOrderBy('sys_num', $sys_num);
                $userArr = CommonService::getUser('id', $orderArr['new_customer_id'],['shr_name', 'shr_phone', 'shr_sheng', 'shr_shi', 'shr_xian', 'shr_adress']);
                //return $orderArr;exit;
                if($msg_id){
                    $is_exist = Negotiated::where('sys_num', $orderArr['sys_num'])->where('msg_id', $msg_id)->where('state', 0)->first();
                }else{
                    $is_exist = Negotiated::where('sys_num', $orderArr['sys_num'])->where('goods_id', $goods_id)->where('state', 0)->first();
                }

                if ($is_exist) {
                    return $this->error('存在未处理的协商价申请，请先处理！', ErrorInc::REQUEST_FORBIDDEN);exit;
                }
                $wat_num = SettlementService::getSettlementListBy('sys_num', $orderArr['sys_num'],['wat_num'],'first');
                if ($wat_num != "") {
                    return $this->error('该订单已结款，无法协商价格！', ErrorInc::REQUEST_FORBIDDEN);exit;
                }
                //供货价
                $company_name = Admin::where('id', $orderArr['ser_id'])->value("company_name");
                //return $supply_price;exit;
                $poss['sys_num'] = $orderArr['sys_num'];
                $poss['order_num'] = $orderArr['order_num'];
                $poss['goods_id'] = $goods_id;
                $poss['msg_id'] = $msg_id;
                $poss['goods_name'] = $goods_name;
                $poss['supply_price'] = $supply_price??0;
                //$poss['negotiated_person'] = $session['admin_acc'];
                $poss['negotiated_reason'] = $negotiated_reason;
                $poss['ser_id'] = $orderArr['ser_id'];
                $poss['company_name'] = $company_name??"暂未派单";
                $poss['order_status'] = $orderArr['order_status']; //订单状态
                $poss['p_id'] = $orderArr['p_id'];
                $poss['negotiated_price'] = $negotiated_price;//申请结算金额
                $poss['state'] = 0; //未处理
                $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['creator'] = $session['admin_acc'];//申请人
                $poss['created_at'] = date('Y-m-d H:i:s');//申请时间
                $poss['updated_at'] = date('Y-m-d H:i:s');
                $poss['company_id'] = $session['company_id'];

                $rest = CommonService::accMe($orderArr['sys_num'], '订单管理', "申请协商价格，" . $negotiated_reason, '', '', $session['admin_groupnew'], $session['admin_acc'], $session['id']);//添加备注
                if (!$rest) {
                    return $this->error('添加备注失败', ErrorInc::MYSQL_FAILED);exit;
                }
                $poss['company_id'] = $session['company_id'];
                $res = Negotiated::insert($poss);
                if ($res) {
                    $this->insertingLog('协商价格，', $orderArr['sys_num'], "订单：" . $orderArr['order_num']."结算金额：".$negotiated_price, '订单管理', $request->ip(), $session['admin_acc']);//日志
                    return $this->success('操作成功');exit;
                } else {
                    return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
                }
            }
        }else{
            return $this->error('参数错误', ErrorInc::FAILED_PARAM);exit;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name  退款锁定商品展示
     * @param string sys_num 系统单号
     * @return \Illuminate\Http\JsonResponse
     * |---------------------------------------------------------------------------------
     */
    public function refundGoods(Request $request)
    {
        if ($request->filled('sys_num')) {
            $sys_num = $request->input('sys_num');
            $res = OrderService::getOrderMsgBy('sys_num', $sys_num,['id', 'goods_id', 'goods_name', 'goods_price' , 'goods_num']);
            if ($res) {
                return $this->success('成功',$res);exit;
            } else {
                return $this->error('暂无数据', ErrorInc::MYSQL_FAILED);exit;
            }
        } else {
            return $this->error('参数错误', ErrorInc::FAILED_PARAM);exit;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name  协商价格获取原结算金额
     * @param order_num  平台单号
     * @param goods_id   商品id
     * @return \Illuminate\Http\JsonResponse
     * @author he <2019/09/26>
     * |---------------------------------------------------------------------------------
     */
    public function getSupply(Request $request)
    {
        if ($request->filled(['order_num', 'goods_id'])) {
            $input = $request->only('order_num', 'goods_id');
            $orderArr = OrderService::getOrderBy('order_num', $input['order_num'],['order_status','ser_id','p_id']);
            if ($orderArr['order_status'] >= 30) {
                $supply_price = SettlementService::getSettlementListBy('order_num', $input['order_num'],['all_price'],'first');
            } else {
                $supply_price = SupplierPriceService::findPrice($orderArr['ser_id'], $input['goods_id'],['supply_price'],$orderArr['p_id']);
            }
            $data['supply_price'] = $supply_price??0;
            return $this->success('操作成功',$data);exit;
        } else {
            return $this->error('参数错误', ErrorInc::FAILED_PARAM);exit;
        }
    }

    /**
     * @name 申请罚单前获取单号
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author dou 2021年8月31日下午1:32:43
     */
    public function beforAddTickt (Request $request)
    {
        $til_ticnum = TicketListService::creactTicktNumber();
        return $this->success('获取成功', $til_ticnum); exit;
    }

    /**|---------------------------------------------------------------------------------
     * @name  申请罚款
     * @param type
     * @return \Illuminate\Http\JsonResponse
     * @author he <2019/10/11>
     * |---------------------------------------------------------------------------------
     */
    public function applicatIonfines(Request $request)
    {
        $input = $request->only('til_ticnum', 'til_ornum', 'til_sysnum' ,'til_price', 'til_cause', 'til_sernum', 'til_watnum', 'til_wats', 'til_serid', 'til_type', 'sety_id');
        $checkKey=CommonService::checkKey(['til_ticnum', 'til_ornum', 'til_sysnum','til_cause','til_serid'],$input,$this->rules);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        $session = $request->get('session_token');
        $orderinfo = OrderService::getOrderBy('order_num', $input['til_ornum'],['new_customer_id','order_num','ser_id','p_id','company_id']);
        $customer_id = $orderinfo['new_customer_id'];
        $userArr = CommonService::getUser('id', $customer_id);
        DB::beginTransaction();//开启事务
        $rest = CommonService::accMe($input['til_sysnum'], '处罚原因', $input['til_cause'], '', '2', $session['admin_groupnew'], $session['admin_acc'], $session['id']);
        $poss['til_dress'] = $userArr['shr_sheng'] . $userArr['shr_shi'] . $userArr['shr_xian'] . $userArr['shr_adress'];
        if (!$rest) {
            DB::rollBack();
            return $this->error('备注添加失败', ErrorInc::MYSQL_FAILED);exit;
        }
        //aftersale表添加标签
        $lable = array(array('sety_id'=>'231','sublevel'=>array($input['sety_id'])));
        $orderinfo['serial_number'] = $input['til_sernum'];
        $aftRes = AfterSaleService::insertData($lable, $orderinfo, $session,$input['til_cause']);
        if ($request->filled('pic') && $request->input('pic') != []) {
            $til_data = 2;
        } else {
            $til_data = 1;
        }
        $res = TicketListService::createTicket($input['til_ornum'], $input['til_sernum'], $input['til_watnum'], $input['til_wats'], $input['til_serid'], $input['til_price'], 1, $input['til_cause'], $session['admin_acc'],$input['til_ticnum'],$input['til_type'],$til_data,$input['sety_id'],231,$userArr['shr_name'],$userArr['shr_phone'],$poss['til_dress'],$orderinfo['company_id']);
        if ($res) {
            if ($request->filled('pic') && $request->input('pic') != []) {
                $pic = $request->input('pic');
                $picArr = [];
                foreach ($pic as $key => $value) {
                        $picArr[] = $value;
                }
                TicketListService::createTicketData(implode(',', $picArr), '', $res, $session['id'], $session['admin_acc'], $input['til_cause'], 2);
            }
            if ($request->filled('sound')) {
                TicketListService::createTicketData('', $request->input('sound'), $res, $session['id'], $session['admin_acc'], $input['til_cause'], 3);
            }
            $sys_num = OrderListService::getOrderListBy('order_num', $input['til_ornum'],'first',['sys_num']);
            DB::commit();//成功则提交
            $this->insertingLog("添加，", $input['til_sysnum'], "添加罚单，" . $input['til_ticnum'], "罚单管理", $request->ip(), $session['admin_acc']);//日志
            return $this->success('添加成功');exit;
        } else {
            DB::rollback();//不成功，则回滚
            return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 电子发票
     * @param int id 数据id
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/8/29 23:27
     * |---------------------------------------------------------------------------------
    */
    public function electronicInvoice(Request $request)
    {
        if ($request->filled('id')) {
            $id = $request->input('id');
            $ret = OrderService::getOrderBy('id', $id,['return_num']);
            if ($ret == 15) {
                return $this->error('该订单已开电子发票，无需重复开启', ErrorInc::ELASTIC_FAILED);exit;
            }
            $res = Orders::where('id', $id)->update(['return_num' => 15]);
            if ($res) {
                return $this->success('操作成功');exit;
            } else {
                return $this->error('参数错误', ErrorInc::MYSQL_FAILED);exit;
            }
        } else {
            return $this->error('参数错误', ErrorInc::FAILED_PARAM);exit;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 编辑协商价格
     * @param string sys_num  系统单号
     * @param int type   1:获取要编辑的数据；2：编辑提交
     * @param int msg_id   msg数据id
     * @param string goods_price   商品价格
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/8/29 23:49
     * |---------------------------------------------------------------------------------
    */
    public function editPrice (Request $request)
    {
        if ($request->filled('sys_num')) {
            if ($request->input('type') == 1) {
                $list = OrderService::getOrderMsgBy('sys_num', $request->input('sys_num'),['id as msg_id','goods_name','goods_price','goods_num']);
                if ($list) {
                    foreach ($list as $k => $v) {
                        $list[$k]['all_price'] = $v['goods_price']*$v['goods_num'];
                    }
                    return $this->success('操作成功',$list);exit;
                }
            } elseif ($request->input('type') == 2) {
                if ($request->filled('msg_id','goods_price')) {
                    $result = OrderMsg::where('id',$request->input('msg_id'))->update(['goods_price' => $request->input('goods_price')]);
                    if ($result) {
                        return $this->success('操作成功');exit;
                    } else {
                        return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
                    }
                }else{
                    return $this->error('缺少参数', ErrorInc::INVALID_PARAM);exit;
                }
            }else{
                return $this->error('参数type错误', ErrorInc::FAILED_PARAM);exit;
            }

        } else {
            return $this->error('缺少参数', ErrorInc::INVALID_PARAM);exit;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name  反馈日志
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author he <2019-09-05>
     * |---------------------------------------------------------------------------------
     */
    public function feedbackLog(Request $request)
    {
        if ($request->filled('sys_num')) {
            $sys_num = $request->input('sys_num');
            $ids = OrderList::where('sys_num', $sys_num)->pluck('id');
            if ($ids) {
                $list = DB::table('feedback')->whereIn('gl_id', $ids)->select('feedback_pic', 'install_time')->get();
                if (!$list->isEmpty()) {
                    $list = $list->toArray();
                    $info = [];
                    foreach ($list as $k => $v) {
                        if ($v['feedback_pic']) {
                            $info[$k]['feedback_pic'] = $this->picurl($v['feedback_pic']);
                        }
                    }
                    if ($info) {
                        return $this->success('成功',$info);exit;
                    } else {
                        return $this->error('暂无图片', ErrorInc::MYSQL_FAILED);exit;
                    }
                } else {
                    return $this->error('暂无图片fkb', ErrorInc::MYSQL_FAILED);exit;
                }
            } else {
                return $this->error('暂无图片oli', ErrorInc::MYSQL_FAILED);exit;
            }
        } else {
            return $this->error('缺少参数', ErrorInc::INVALID_PARAM);exit;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name  售后图片
     * @param order_num       订单单号
     * @return \Illuminate\Http\JsonResponse
     * @author hzc <2020/08/25>
     * |---------------------------------------------------------------------------------
     */
    public function salePhoto(Request $request){
        $sys_num = $request->input('sys_num');
        $order_after = Db::table('order_after')->where('sys_num',$sys_num)->orderBy('create_time','DeSC')->select('create_time','id','after_num')->get()->toArray();
        if(empty($order_after)){
            return $this->error('无售后', ErrorInc::DATA_EMPTY);exit;
        }
        $gl_ids = array_column($order_after, 'id');

        $pics = Db::table('feedsales')->whereIn('gl_id',$gl_ids)->pluck('feedback_pic')->toarray();
        if($pics){
            return $this->success('操作成功',$pics);exit;
        }else{
            return $this->error('暂无图片', ErrorInc::DATA_EMPTY);exit;
        }
    }


    /**|---------------------------------------------------------------------------------
     * @name 获取订单关联信息
     * @param string order_num 订单单号
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/9/14 9:58
     * |---------------------------------------------------------------------------------
    */
    public function searchRele (Request $request)
    {
        $input = $request->only('order_num');
        $data = TicketListService::searchRele($input,1);
        if($data['ErrorCode']!=1){
            return $data;exit;
        }else {
            return $this->success('获取成功', $data['Data']);
            exit;
        }

    }

    /**|---------------------------------------------------------------------------------
     * @name 获取订单详情
     * @param int id 订单数据id
     * @param string order_num 订单单号
     * @param string sys_num 系统单号
     * @param string type 查询数据类型
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/9/23 13:45
     * |---------------------------------------------------------------------------------
    */
    public function getDetail ( Request $request ){
        $input = $request->only('id', 'order_num', 'sys_num','type');
        $checkKey=CommonService::checkKey(['id', 'order_num', 'sys_num','type'],$input,array('id'=>'订单id','order_num'=>'平台单号','sys_num'=>'系统单号','type'=>'查询类型'));
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        $type = ['User','Remark','Evaluation','OrderList','SendOrder','OrderAfter','SerInfor','RecycleOrders'];
        if(in_array($input['type'], $type)){
            switch ( $input['type'] ){
                case 'User'://客户信息
                    $order = OrderService::getOrderBy('id', $input['id'],['customer_id','new_customer_id']);
                    $data['customer'] = CommonService::getUser('id', $order['customer_id']);
                    if($order['customer_id'] != $order['new_customer_id']){
                        $data['new_customer'] = CommonService::getUser('id', $order['new_customer_id']);
                    }else{
                        $data['new_customer'] = '';
                    }
                    break;
                case 'Remark'://备注
                    $data = CommonService::orderRemarks($input['sys_num'],'',$request->get('session_token')['admin_groupnew'],$request->input('Login_id'));//获取备注信息
                    break;
                case 'Evaluation'://评价
                    $id = EvaluationFormService::getInfoBy('plat_number', $input['order_num'],['eva_id']);
                    if($id) {
                        $data = EvaluationFormService::listEvaluation($id);
                    }else{
                        $data = [];
                    }
                    break;
                case 'OrderList'://工单
                    $data = OrderListService::getDetailByOrder($input['order_num']);
                    break;
                case 'SendOrder'://发货单
                    $data = SendGoodsService::getDetailByOrder($input['order_num']);
                    break;
                case 'OrderAfter'://售后单
                    $data = AftersaleOrderService::getDetailByOrder($input['order_num']);
                    break;
                case 'SerInfor'://催单
                    $data = SerInforService::getInfoByKeyValue('sin_ordernum', $input['order_num'],['sin_creacter','sin_serid','sin_creactime','sin_dealtime','creact_centent','sin_num','sin_dealer','sin_dealtime','sin_state']);
                    break;
                case 'RecycleOrders'://退货单
                    $data = RecycleOrderService::getDetailByOrder($input['order_num']);
                    break;
            }
            if($data){
                return $this->success('操作成功',$data);
            }else{
                return $this->error('暂无数据', ErrorInc::DATA_EMPTY);
            }
        }else{
            return $this->error('参数错误type', ErrorInc::FAILED_PARAM);
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 派单获取服务商品
     * @param string order_num 订单单号
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/10/28 15:28
     * |---------------------------------------------------------------------------------
    */
    public function getChildgoods ( Request $request ){
        if($request->filled('order_num') && $request->filled('ser_id')){
            $sys_num = OrderService::getOrderBy('order_num', $request->input('order_num'),['sys_num']);
            if($sys_num){
                $good_id = OrderService::getOrderMsgBy('sys_num', $sys_num,['goods_id','goods_name']);
                if($good_id){
                    $good_ids = [];
                    $data = CommonService::jointArrayKey($good_id, 'goods_id');
                    $good_id = array_column($good_id, 'goods_id');
                    if($request->filled('type')) {
                        if($request->input('type')==2) {
                            foreach ($good_id as $k => $v) {
                                if (in_array($v, ['5912'])) {
                                    unset($good_id[$k]);
                                }
                            }
                            $good_ids = $good_id;
                        }elseif($request->input('type')==1) {
                            foreach ($good_id as $k => $v) {
                                if (in_array($v, ['5912'])) {
                                    $good_ids[] = $good_id[$k];
                                }
                            }
                        }
                        $good_ids = CommonService::resetListKey($good_ids);
                        $good_id = CommonService::resetListKey($good_id);
                    }
                    if($good_ids) {
                        $good = GoodsService::getGoodsBy(['pg_parentid_searchin' => $good_ids], ['pg_id', 'brand_name', 'pg_series', 'version', 'cd_id', 'pg_parentid']);
                    }else{
                        $good = false;
                    }
                    if(!$good_id && !$good_ids){
                        return $this->error('无数据', ErrorInc::DATA_EMPTY);exit;
                    }
                    $ser_id = $request->input('ser_id');
                    if($good) {
                        $location = OrderService::getOrderMsgLocationBy('oml_sysnum', $sys_num,['oml_goodsid']);
                        if($location){
                            $location = array_column($location, 'oml_goodsid');
                        }else{
                            $location = [];
                        }
                        $pg_id = array_column($good, 'pg_id');
                        if($good_id) {
                            $pg_id = array_merge($pg_id, $good_id);
                        }
                        $sql = 'SELECT supply_price,ser_id,goods_id FROM gone_gh_price AS a right JOIN ( SELECT MAX(id) as id FROM `gone_gh_price` WHERE `goods_id` IN ('.implode(",", $pg_id).') AND `ser_id` IN ('.$ser_id.', 0) GROUP BY `goods_id`, ser_id ORDER BY `id` DESC ) as b on a.id = b.id';
                        $supply_prices = DB::select($sql);
//                        $supply_prices = GhPrice::whereIn("goods_id",$pg_id)->whereIn("ser_id",[$ser_id,'0'])->orderBy('id','DESC')->select('supply_price','ser_id','goods_id')->groupBy('goods_id')->get();
                        $supply_prices = OrderService::dealGoodPrice($supply_prices);
                        foreach($good as $k => $v){
                            $good[$k]['supply_price'] = $supply_prices[$ser_id][$v['pg_id']]['supply_price']??'';
                            if(!$good[$k]['supply_price']){
                                $good[$k]['supply_price'] = $supply_prices[0][$v['pg_id']]['supply_price']??'';
                                if(!$good[$k]['supply_price']){
                                    $good[$k]['supply_price'] = '0';
                                }
                            }
                            if(in_array($v['pg_id'], $location)){
                                $good[$k]['check'] = true;
                            }else {
                                $good[$k]['check'] = false;
                            }
                        }
                        $goods = CommonService::jointArrayKey($good, 'pg_parentid', 2);
                        foreach ($data as $k => $v) {
                            $data[$k]['supply_price'] = $supply_prices[$ser_id][$v['goods_id']]['supply_price']??'';
                            if(!$data[$k]['supply_price']){
                                $data[$k]['supply_price'] = $supply_prices[0][$v['goods_id']]['supply_price']??'';
                                if(!$data[$k]['supply_price']){
                                    $data[$k]['supply_price'] = '0';
                                }
                            }
                            $data[$k]['goods'] = $goods[$v['goods_id']];
                        }
                        $data = CommonService::resetListKey($data);
                        return $this->success('操作成功', $data);
                        exit;
                    }else{
                        $sql = 'SELECT supply_price,ser_id,goods_id FROM gone_gh_price AS a right JOIN ( SELECT MAX(id) as id FROM `gone_gh_price` WHERE `goods_id` IN ('.implode(",", $good_id).') AND `ser_id` IN ('.$ser_id.', 0) GROUP BY `goods_id`, ser_id ORDER BY `id` DESC ) as b on a.id = b.id';
                        $supply_prices = DB::select($sql);
                        $supply_prices = OrderService::dealGoodPrice($supply_prices);
                        foreach ($data as $k => $v) {
                            $data[$k]['supply_price'] = $supply_prices[$ser_id][$v['goods_id']]['supply_price']??'';
                            if(!$data[$k]['supply_price']){
                                $data[$k]['supply_price'] = $supply_prices[0][$v['goods_id']]['supply_price']??'';
                                if(!$data[$k]['supply_price']){
                                    $data[$k]['supply_price'] = '0';
                                }
                            }
                            $data[$k]['check'] = true;
                            $data[$k]['goods'] = [];
                        }
                        $data = CommonService::resetListKey($data);
                        return $this->success('操作成功', $data);
                        exit;
                        return $this->error('无数据', ErrorInc::DATA_EMPTY);exit;
                    }
                }else{
                    return $this->error('数据异常', ErrorInc::DATA_EMPTY);exit;
                }
            }else{
                return $this->error('单号错误', ErrorInc::INVALID_PARAM);exit;
            }
        }else{
            return $this->error('单号/服务商编号必填', ErrorInc::FAILED_PARAM);exit;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 活动处理
     *
         * @param array add_type 添加类型 1:礼物;2:退款 (type = 2)
     *
     * @param type        1:获取客户信息；2：添加
     * @param order_num   平台单号
     * @param goods_info  礼品信息
     * @param gift_type   数据类型（单品，多次，终身）
     * @param shr_phone   客户电话
     * @param shr_name    客户姓名
     * @param shr_sheng   地址省
     * @param shr_shi     地址市
     * @param shr_xian    地址县
     * @param shr_address 详细地址
     * @param customer_id 用户id
     *
     * @param string note_content 锁定备注
     * @param int p_id 平台id
     * @param string order_num 订单单号
     * @param int apply_type 退款申请类型
     * @param int refund 锁定类型1退款锁定(默认)
     * @param string sys_num 系统单号
     * @param int ids 数据id
     * @param int urgent 加急类型：1：普通；2：加急
     * @param string allprice 退款单总金额
     * @param array goodsArr 锁定订单信息
     * @param string goodsArr->goods_name 商品名称
     * @param string goodsArr->goods_price 商品金额
     * @param string goodsArr->msg_id 商品详情表id
     * @param string goodsArr->goods_num 商品数量
     * @param string goodsArr->goods_id 商品id
     * @param Request $request
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/11/2 18:28
     * |---------------------------------------------------------------------------------
    */
    public function dealActivity ( Request $request ){
        if(!$request->filled('type')){
            return $this->error('缺少必要参数', ErrorInc::FAILED_PARAM);exit;
        }
        if ($request->input('type') == 1) {
            return EventGiftService::giftAdd($request);
        }else {
            $input = $request->all();
            if(!$request->filled('add_type') || !is_array($input['add_type'])){
                return $this->error('缺少添加类型或类型错误', ErrorInc::FAILED_PARAM);exit;
            }
            DB::beginTransaction();
            if (in_array(1, $input['add_type'])) {
                $giftAdd = EventGiftService::giftAdd($request);
                if($giftAdd['ErrorCode']!='1'){
                    DB::rollBack();
                    return $giftAdd;
                }
            }
            $input['refund'] = 1;
            if (in_array(2, $input['add_type']) || in_array(3, $input['add_type'])) {
                if(!$request->filled('apply_type')){
                    DB::rollBack();
                    return $this->error('缺少退款申请类型', ErrorInc::FAILED_PARAM);exit;
                }
                $order = OrderService::getOrderBy('sys_num', $input['sys_num'],['ser_id', 'order_num', 'order_status','store_type','create_time','new_customer_id','category']);
                foreach($order as $k => $v){
                    $input[$k] = $v;
                }
                $session = $request->get("session_token");
                $ip = $request->ip();
                $userArr = CommonService::getUser('id', $order['new_customer_id']);
                $input['recycle_type'] = 0;
                $applyType = RefundService::getRefundApplyType(true,false,3);
                $note_content = '退款：（'.$applyType[$input['apply_type']].'）'.$input['content'];
                $input['note_content'] = $note_content;
                if(in_array(3, $input['add_type'])){
                    $input['attribute'] = 3;
                }
                $return = OrderService::lockByRefund($input, $session ,$userArr);
                if($return['ErrorCode']!='1'){
                    DB::rollBack();
                    return  $return;
                }
                $rest = CommonService::accMe($input['sys_num'], '订单管理', $note_content, '', '', $session['admin_groupnew'], $session['admin_acc'], $session['id']);
                $this->insertingLog('退款,', $input['sys_num'], "订单" . $input['order_num'].'退款', '订单管理', $ip, $session['admin_acc']);//日志
            }
            DB::commit();
            return $this->success('操作成功');
        }
    }


    /**
     * @name 添加技术，服务评分(车模订单已派单)
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2021/12/8
     */
    public function addServiceScore(Request $request){
        if($request->filled('ser_id')&& $request->input('ser_id')>0){
            $input = $request->all();
            $checkKey = CommonService::checkKey(['sysnum','sety_id','cou_brand','score','lt_parent_id'],$input);
            if($checkKey['code']!=1){
                return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
            }
            $info = SettlementCount::where('cou_synum',$input['sysnum'])->where('cou_type',$input['sety_id'])->where('cou_serid',$input['ser_id'])->value('cou_status');
            if($info){
                if($info==2){
                    $res = SettlementCount::where('cou_serid',$input['ser_id'])->where('cou_synum',$input['sysnum'])->where('cou_type',$input['sety_id'])->update(['cou_status'=>1]);
                }else{
                    $res = 1;
                }
            }else{
                //添加
                $arr['cou_synum'] = $input['sysnum'];//系统单号
                $arr['cou_price'] = LabtypeService::getLable('sety_id', $input['sety_id'])[0]['lt_score']??0;//分数
                $arr['cou_type'] = $input['sety_id'];//标签ID
                $arr['cou_creacter'] = $request->get('session_token')['admin_acc'];//添加人
                $arr['cou_createtime'] = date('Y-m-d H:i:s');//添加时间
                $arr['cou_createtimeym'] = date('Y-m-d');//添加年月日
                $arr['cou_serid'] = $input['ser_id'];//服务商ID
                $arr['cou_parent_type'] = $input['lt_parent_id']??0;//父标签ID
                $arr['cou_brand'] = $input['cou_brand'];//品牌
                $res = SettlementCount::insert($arr);
            }
            if ($res) {
                $ser_name = AdminsService::getAdminsBy('id', $input['ser_id'],['company_name']);
                $this->insertingLog("添加评分，", $input['sys_num'], "添加评分：" . $input['score'].'->服务商：'.$ser_name, "订单列表", $request->ip(), $request->get('session_token')['admin_acc']);
                return $this->success('添加成功');exit;
            }else{
                return $this->error('添加失败', ErrorInc::MYSQL_FAILED);exit;
            }

        }else{
            return $this->error('服务商ID必传', ErrorInc::FAILED_PARAM);
        }

    }

    /**
     * @name 删除技术服务评分
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2021/12/8
     */
    public function delServiceScore(Request $request){
        $input = $request->all();
        $checkKey = CommonService::checkKey(['sysnum','sety_id','score','ser_id'],$input);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        $info = SettlementCount::where('cou_serid',$input['ser_id'])->where('cou_synum',$input['sysnum'])->where('cou_type',$input['sety_id'])->value('cou_status');
        if($info){
            if($info==1){
                $res = SettlementCount::where('cou_serid',$input['ser_id'])->where('cou_synum',$input['sysnum'])->where('cou_type',$input['sety_id'])->update(['cou_status'=>2]);
            }else{
                $res = 1;
            }
            if ($res) {
                $ser_name = AdminsService::getAdminsBy('id', $input['ser_id'],['company_name']);
                $this->insertingLog("删除评分，", $input['sys_num'], "删除评分：" . $input['score'].'->服务商：'.$ser_name, "订单列表", $request->ip(), $request->get('session_token')['admin_acc']);
                return $this->success('删除成功');exit;
            }else{
                return $this->error('删除失败', ErrorInc::MYSQL_FAILED);exit;
            }
        }else{
            return $this->error('不存在',ErrorInc::MYSQL_FAILED);

        }
    }

    /**
     * name 获取选中标签ID
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2021/12/8
     */
    public function getServiceScoreLabs(Request $request){
        $input = $request->all();
        $checkKey = CommonService::checkKey(['sysnum','ser_id'],$input);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }

        $sety_ids = SettlementCount::where('cou_serid',$input['ser_id'])->where('cou_synum',$input['sysnum'])->where('cou_status',1)->pluck('cou_type')->toarray();
       // dump($sety_ids);
        if($sety_ids){
            return $this->success('获取成功',CommonService::strToint($sety_ids));
        }else{
            return $this->error('暂无数据', ErrorInc::MYSQL_FAILED);
        }

    }

    /**|---------------------------------------------------------------------------------
     * @name 同步智配仓库服务单信息
     * @param string order_num 订单单号
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2022/1/18 19:06
     * |---------------------------------------------------------------------------------
    */
    public function sysZhipeiOrder( Request $request ){
        if($request->filled('order_num')){
            $order = OrderService::getOrderBy('order_num', $request->input('order_num'));
            if($order && $order['category']>2){
                /*------------------------------------------通知库房服务单完成-----------------------------------------------*/

                $order_num = $order['order_num'];
                $pt = PlatformService::getPtBy('id', $order['p_id'], ['pt_name','zp_id']);
                $zhipei['pt_name'] = $pt['pt_name'];
                $zhipei['pt_id'] = $pt['zp_id'];
//                $zhipei['pt_name'] = PlatformService::getPtBy('id', $order['p_id'], ['pt_name']);
                $ordermsg = OrderService::getOrderMsgBy('sys_num', $order['sys_num']);
                $zhipei['order_price'] = $order['new_money'];
                $company_name = AdminService::getAdminBy('id', $order['ser_id'], ['company_name']);
                if($company_name==''){
                    $company_name = '无';
                }
                $zhipei['store_name'] = $company_name;
                $zhipei['wholestore_name'] = $company_name;
                $user = UserService::getUserBy('id', $order['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'] = '无';
                }
                $feeds_time = OrderListService::getOrderListBy('order_num', $order['order_num'], 'get', ['feeds_time']);
                if($feeds_time ==''){
                    $feeds_time = date("Y-m-d H:i:s");
                }
                $zhipei['construction_date'] = $feeds_time;
                $zhipei['car_brand'] = $user['car_make'];
                $zhipei['car_frame'] = '';
                $zhipei['order_status'] = $order['order_status'];//订单状态
                foreach ($ordermsg as $k => $v) {
                    //$['cd_id']  商品所属类型
                    $zhipeigoods['goods_name'] = $v['goods_name'];
                    $zhipeigoods['goods_number'] = GoodsService::getGoodsByKey('pg_id', $v['goods_id'], ['general_version']);
                    $zhipeigoods['goods_num'] = $v['goods_num'];
                    $zhipeigoods['goods_brand'] = $v['goods_brand'];
                    $zhipeigoods['goods_price'] = $v['goods_price'];
                    $zhipeigood[$k] = $zhipeigoods;
                }
//                $zhipeigoods['goods_name'] = $ordermsg['goods_name'];
//                $zhipeigoods['goods_number'] = GoodsService::getGoodsByKey('pg_id', $ordermsg['goods_id'], ['general_version']);
//                $zhipeigoods['goods_num'] = $ordermsg['goods_num'];
//                $zhipeigoods['goods_brand'] = $ordermsg['goods_brand'];
//                $zhipeigoods['goods_price'] = $ordermsg['goods_price'];
//                $zhipeigood[0] = $zhipeigoods ;
                //print_r($zhipeiuser);
                $res = zhiPeiOrder::complete($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), $order_num,'warehouse-service');
                if($res['code']!='200'){
                    return $this->error('同步失败:'.$res['data'], ErrorInc::TRANSFER_FAILED);exit;
                }else{
                    return $this->success('同步成功');
                }
                /*------------------------------------------通知库房服务单完成-----------------------------------------------*/
            }else{
                return $this->error('未匹配到对那个车膜类订单',ErrorInc::DATA_EMPTY);
            }
        }else{
            return $this->error('缺少参数',ErrorInc::FAILED_PARAM);
        }
    }

    /**
     * 添加F6索赔
     * @author dongchunyu
     * @created 2022/2/8
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function addF6Claim(Request $request)
    {
        try{
            $alldata = $request->all();
            /**
             * 参数都不为空
             * order_id 订单id
             * goods_name array 商品名称
             * p_id 平台id
             * label array 标签
             * remark 索赔备注
             * claim_amount 索赔金额
             */
            $params = $alldata['order_id'] != '' && !empty($alldata['goods_name']) && $alldata['p_id'] != '' && !empty($alldata['label']) && $alldata['remark'] != '' && $alldata['claim_amount'] != '';
            if(!$params){
                return $this->error('添加参数有误', ErrorInc::INVALID_PARAM, []);
            }
            $res = F6ClaimService::insertData($alldata);
            if(!$res){
                return $this->error('添加失败',ErrorInc::MYSQL_FAILED);exit;
            }
            //日志
            $this->insertingLog('添加F6索赔',$alldata['order_id'], '索赔备注：'.$alldata['remark'], 'F6索赔', $request->ip(), $request->get('session_token')['admin_acc']);
            return $this->success('添加成功');exit;
        }catch(\Exception $e){
            return $this->error($e->getMessage(), ErrorInc::MYSQL_FAILED);exit;
        }
    }

    /**
     * @name用户车型
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2022/2/21
     */
    public function userCarInfo(Request $request){
        $input = $request->all();
        $checkKey = CommonService::checkKey(['sys_num','type'],$input);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        $type = $request->input('type');
        $sys_num = $request->input('sys_num');
        $carInfo = CommonService::getUserCar($sys_num,true);
        if($type==1){ //获取用户车型信息
            if($carInfo){
                return $this->success('获取成功',$carInfo);exit;
            }else{
                return $this->error('暂无数据',ErrorInc::MYSQL_FAILED);exit;
            }
        }else{//更新用户车型信息
            if(!isset($input['car_infor']) || $input['car_infor'] == '') {
                $checkKey = CommonService::checkKey(['car_make', 'car_line', 'car_model', 'car_id'], $input);
                if ($checkKey['code'] != 1) {
                    return $this->error('参数' . $checkKey['data'] . '未填写,或值为空', ErrorInc::INVALID_PARAM);
                    exit;
                }
            }
            $car_infor = $input['car_infor']??'';
           $ret = CommonService::addUserCar($sys_num, $input['car_make'], $input['car_line'], $input['car_model'], $input['car_id'],$car_infor);
           if($ret){
               //日志
               if($car_infor!=''){
                   $info = $car_infor;
               }else {
                   $info = $input['car_make'] . $input['car_line'] . $input['car_model'];
               }
               $this->insertingLog('用户车型更新',$sys_num, '更新前车型：'.$carInfo.';更新后车型：'.$info, '订单管理', $request->ip(), $request->get('session_token')['admin_acc']);
               return $this->success('更新成功');exit;
           }else{
               return $this->error('操作失败',ErrorInc::MYSQL_FAILED);exit;
           }

        }
    }

    /**
     * @name 快捷添单前数据展示
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2022/3/7
     */
  /*  public function fastAddOrderBefor(Request $request){
        if(!$request->filled('id')){
            return $this->error('参数错误订单ID不能为空', ErrorInc::FAILED_PARAM, []);exit;
        }
        $id = intval($request->input('id'));
        $orderInfo = OrderService::getOrderBy('id', $id);
        if(!$orderInfo){
            return $this->error('数据异常', ErrorInc::MYSQL_FAILED);exit;
        }
        $orderInfo['sys_bh'] = 'L'.date("YmdHis").str_pad(rand(0,999),3,'0',STR_PAD_LEFT);
        $userInfo = UserService::getUserBy('id', $orderInfo['new_customer_id'],['shr_name','shr_phone','shr_sheng','shr_shi','shr_xian','shr_adress','car_make','car_line','car_model','car_id']);
        $orderInfo['userInfo'] = $userInfo;

        $session_token = $request->get('session_token');
        $orderInfo['ser_type'] = OrderService::showSerType($session_token['admin_groupnew']);
        $orderInfo['pay_type'] = OrderService::showPayType($session_token['admin_groupnew']);
        $orderInfo['order_type'] = OrderService::showOrderType($session_token['admin_groupnew']);
        $orderInfo['default'] = OrderService::getOldpt($session_token['id']);

        //商品
        $goodpic = PjBrandsService::getAllPic('name');//获取商品品牌图片
        $orderMsg = OrderService::getOrderMsg($orderInfo['sys_num'],$goodpic);
        $orderInfo['goods'] = $orderMsg['orderMsgArr'];

        return $this->success('获取成功',$orderInfo);
    }*/

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

    /**
     * @name 添加订单(返回选中的商品)
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2022/1/26
     */
    public function mate (Request $request)
    {
        if (!$request->filled('goods_id') || !$request->filled('brand_name') || !$request->filled('goods_number') || !$request->filled('cd_id')){
            return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);
        }
        $goods_number = $request->input('goods_number');
        $db = new OrderMsg();
        $goods_price = CommonService::getMysqlData($db,['goods_id'=>$request->input('goods_id')],['goods_price'],['creator_time'=>'DESC'],'value');
        $caps['goods_id'] = $request->input('goods_id');
        $caps['goods_brand'] = $request->input('brand_name');
        $caps['goods_number'] = substr($goods_number,strpos($goods_number,"-")+1);
        //$caps['goods_number'] = ltrim($request->input('goods_number'),$caps['goods_brand'].'-');
        $caps['goods_name'] = $request->input('goods_number');
        $caps['goods_num'] = 1;
        $caps['cd_id'] = $request->input('cd_id');

        if($goods_price){
            $caps['goods_price'] = $goods_price;
        }else{
            $caps['goods_price'] = 0;
        }
        $caps = mb_convert_encoding($caps, 'UTF-8', 'UTF-8');
        return $this->success('成功', $caps);
    }

    /**|---------------------------------------------------------------------------------
     * @name 超时处理
     * @param string id 订单id
     * @param string remark 处理备注
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2024/11/19 18:00
     * |---------------------------------------------------------------------------------
    */
    public function dealTimeOut ( Request $request ){
        $input = $request->all();
        $session = $request->get("session_token");
        if ($request->filled('type') && $input['type']==1 ){
            return $this->success('操作成功',['已联系门店']);exit;
        }
            $checkKey=CommonService::checkKey(['id', 'remark'],$input);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        $order_num = OrderService::getOrderBy('id', $input['id'],['order_num','sys_num']);
        DB::beginTransaction(); //开启事务
        $rest = CommonService::accMe($order_num['sys_num'], '订单管理', "超时未接单处理，" . $input['remark'], '', '', $session['admin_groupnew'], $session['admin_acc'], $session['id']);//添加备注
        $return = Orders::where('id', $input['id'])->update(['distype'=>2]);
        if ($rest && $return) {
            DB::commit();
                $this->insertingLog("接单超时处理，", $input['sys_num'], "接单超时，订单号：" . $order_num['order_num'], "订单管理", $request->ip(), $session['admin_acc']);
                return $this->success('操作成功');exit;
        } else {
            DB::rollback();
            return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
        }
    }

    /**
     * @name 快捷添加定单
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2022/3/7
     */
   /* public function fastAddOrder(Request $request){
        $input = $request->only('sys_bh','skb_bh','pt_id','ser_type','shr_name','shr_phone','shr_sheng','shr_shi','shr_xian','shr_adress','shr_other','car_audit','order_type','goods','order_time','pay_type');//指定需获取字段 ,'car_make','car_line','car_model','car_id'
        $input['skb_bh'] = CommonService::restrict($input['skb_bh']);//过滤平台单号在复制时产生的回车、制表符等被忽略的特殊符号
        $session = $request->get('session_token');//获取操作人信息
        $return = OrderaddService::addOrder($input, $session, $request->ip());
        return $this->error($return['ErrorMessage'], $return['ErrorCode']);
    }*/

}
