<?php

namespace App\Http\Controllers\Orders;

use App\Http\Controllers\Common\CommonController;
use App\Models\SendGoods;
use App\Models\SettlementList;
use App\Models\SyncStores;
use App\Services\CommonService;
use App\Services\LabtypeService;
use App\Services\OrderaddService;
use App\Services\SendGoodsService;
use App\Services\SysStoresService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Refund;
use App\Http\Controllers\BaseController;
use DB;
use App\Services\RefundService;
use BlueCity\Core\Inc\ErrorInc;
use App\Services\AftercustService;
use App\Services\OrderService;
use App\Models\OrderMsg;
use App\Models\Orders;
use App\Services\SubmitPleaseService;
use App\Models\SetmoneyType;
use App\Services\AftersaleOrderService;
use App\Services\OrderListService;
use App\Models\SubmitPlease;
use App\Models\OrderList;
use App\Models\SettlementThree;

class RefundController extends BaseController
{
	/**
	 * @name  列表页
     * @param 50:待确认 0:未处理;1:跟进中2:电话回访中;3:已回访；4：已审核；5：已驳回
	 * @param Request $request
	 * @return \BlueCity\Core\Controllers\mixed
	 * @author du 2021年8月10日下午3:07:54
	 */
    public function index(Request $request)
    {
        //$params = $request->only('state','pt_id','ser_id','order_status','order_num','shr_name','shr_phone','page','page_size','creact_id','created_at');
        $params = $request->all();
        if (!$request->filled('state')){
           return $this->error('参数错误无state', ErrorInc::FAILED_PARAM);exit;
        }
    	$list = RefundService::getRefundList($params,$request->get('session_token'));

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

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

    /**
     * @name  发起电话沟通
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年8月11日上午8:40:25
     */
    public function telephone(Request $request)
    {
        $params = $request->only('id','order_num','msg_id','content');
        $checkKey = CommonService::checkKey(['id','order_num','msg_id'],$params);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }

        $session = $request->get('session_token');
        $id = intval($params['id']);
        $order_num = $params['order_num'];
        $msg_id = intval($params['msg_id']);
        $content = $params['content']??"";
        $select = ['sys_num','order_num','p_id','ser_id','customer_id','create_time','order_status'];
        $orderArr = OrderService::getOrderBy('order_num',$order_num,$select);
        if(!$orderArr){
        	return $this->error('无此定单信息', ErrorInc::MYSQL_FAILED);exit;
        }
        $msgArr = OrderMsg::where('id',$msg_id)->select('goods_id','goods_num','goods_price','goods_name')->first();
        Db::beginTransaction();
        $res = AftercustService::createAftercust($orderArr['sys_num'], $orderArr['order_num'], $orderArr['p_id'], $orderArr['create_time'], $msgArr['goods_id'], $msgArr['goods_price'],  $msgArr['goods_num'], $orderArr['customer_id'], $orderArr['ser_id'], $session['admin_acc'], $session['id'], $content, $msgArr['goods_name'], $orderArr['order_status'], 2);

        $inf = Refund::where('id',$id)->update(['state'=>2]);
        $rest = CommonService::accMe($orderArr['sys_num'],'申请退款',"发起电话沟通:".$content,'','',$request->get('session_token')['admin_groupnew'],$request->get('session_token')['admin_acc'],$request->get('session_token')['id']);
        if (!$rest){
        	DB::rollback();
        	return $this->error('备注添加失败', ErrorInc::MYSQL_FAILED);exit;
        }
        if ($res && $inf){
	        DB::commit();
	        $this->pushWebDel($orderArr['order_num'],3);
            $this->insertingLog('发起电话沟通，',$orderArr['order_num'],'发起电话沟通，平台单号：'.$orderArr['order_num'],'退款管理',$request->ip(),$request->get('session_token')['admin_acc']);
            return $this->success('操作成功');exit;
        } else{
	        DB::rollback();
	        return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
        }

    }


    /**
     * @name  手动同步订单状态
     * @param type   1:开始; 2:暂停
     * @param time   时间
     * @param max_id 数据id
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年8月11日上午9:47:10
     */
    public function manualSync(Request $request)
    {
        $params = $request->only('type','time');
        $time = $params['time']??"";
        $type = $params['type']??"";
        if (empty($type)||empty($time)){
            return $this->error('参数错误无type或无time', ErrorInc::FAILED_PARAM);exit;
        }
        if ($type == 1){
            if ($request->input('max_id')){
                $info = Refund::whereIn('state',[0,1,2,3])->where('id','>',$request->input('max_id'))->orderBy('id','ASC')->limit('10')->get();
            } else {
                $info = Refund::whereIn('state',[0,1,2,3])->orderBy('id','ASC')->limit('10')->get();
            }
            if (!$info->isEmpty()){
                $list = $info->toArray();
//                dump($list);
                $ordersinfo = array_column($list, 'order_num');
                $max_arr = array_column($list,'id');
                $orderArrs = OrderService::getOrderBy('order_num',$ordersinfo,['order_status','order_num','ser_id']);
                if(!$orderArrs){
                	return $this->error('无此定单', ErrorInc::MYSQL_FAILED);exit;
                }
                $orderArr = [];
                foreach( $orderArrs as $k => $v ){
                	$orderArr[$v['order_num']] = $v;
                }
                foreach ($list as $ks => $vs){
                    if (isset($orderArr[$vs['order_num']])) {
	                    if($orderArr[$vs['order_num']]['ser_id'] > '0'){
	                        $poss['ser_id'] = $orderArr[$vs['order_num']]['ser_id'];
	                    }else{
		                    $poss['ser_id'] = '0';
	                    }
                        $poss['order_status'] = $orderArr[$vs['order_num']]['order_status'];
                        Refund::where('id',$vs['id'])->update($poss);
                    }
                    if ($orderArr[$vs['order_num']]['order_status'] == 50 || $orderArr[$vs['order_num']]['order_status'] == 55){
                        Refund::where('id',$vs['id'])->update(['state'=>4,'updated_at'=>date("Y-m-d H:i:s")]);
                    }
                }
                $data['data'] = $info->count();
                $data['max_id'] = max($max_arr);
                return $this->success('操作成功',$data);exit;
            }else{
                 return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
            }
        }elseif ($type == 2){
            $data['max_id'] = "";
            $data['data'] = 0;
            return $this->error('暂停成功', ErrorInc::MYSQL_FAILED,$data);exit;
        }else{
        	return $this->error('参数错误', ErrorInc::FAILED_PARAM);exit;
        }
    }


    /**
     * @name  审核
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年8月11日下午4:50:58
     */
    public function applyRefund(Request $request)
    {
        $input = $request->only('msg_id','sys_num','goods_name','goods_price','order_status','pt_id','id','deal_note','sety_id','lt_parent_id');

        DB::beginTransaction();
        $session_token = $request->get('session_token');
        $data = $this->applyRefundAll($input, $session_token);
        $data = $data->original;
        if($data['ErrorCode']==1){
            DB::commit();
        }else {
            DB::rollBack();
        }
        return $data;

    }

    /**
     * @param $input
     * @param $session_token
     * @return mixed
     * @author du
     * @date 2021/9/17
     */
    public function applyRefundAll($input,$session_token){
//        if (!$input['msg_id'] || !$input['sys_num'] || !$input['goods_name'] || !$input['pt_id']){
//            return $this->error('参数错误', ErrorInc::FAILED_PARAM);
//        }
        $checkKey = CommonService::checkKey(['msg_id','sys_num','goods_name','pt_id'],$input);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);
        }
        $input['apply_type'] = Refund::where('id',$input['id'])->value('apply_type');
        $msg_id = explode(',',$input['msg_id']);
        $orderinfo = OrderService::getOrderBy('sys_num',$input['sys_num']);
        if(!$orderinfo){
            return $this->error('无此定单', ErrorInc::MYSQL_FAILED);
        }
//        if ($orderinfo['order_status']>10 && $input['apply_type'] == 1){
//            $orderListArr['stauas'] = 50;
//            $returnOrderList = OrderList::where('sys_num',$input['sys_num'])->whereIn('order_goods_id',$msg_id)->update($orderListArr);
//        }
        if($orderinfo['category'] == 3){
            $send_orders = DB::table('send_orders')->where('sys_num', $input['sys_num'])->select('recover','type')->get();
            if($send_orders){
                $send_orders = $send_orders->toArray();
                $recover = [];
                $type = [];
                foreach( $send_orders as $k => $v ){
                    $recover[] = $v['recover'];
                    $type[] = $v['type'];
                }
                if((in_array('1',$recover) || in_array('0',$recover)) && !in_array('5',$type)){
                    return $this->error('该单有发货单未处理，不可退款，请先处理发货单', ErrorInc::REQUEST_FORBIDDEN);
                    exit;
                }
            }
        }
        if ($orderinfo['order_status']>10 && $input['apply_type'] == 1){
            OrderList::where('sys_num', $input['sys_num'])->whereIn('order_goods_id',$msg_id)->update(['stauas'=>50]);
        }
        if ($orderinfo['order_status']>20 && $input['apply_type'] == 1){
            // 工单结算状态      sett_status:1:未审核；10：未结算；20：结算中；30：已完成；40：作废;50:已追回
            $sett_status = SettlementList::where(['sys_num'=>$input['sys_num']])->whereIn('msg_id',$msg_id)->value('sett_status');
            if($sett_status>1){
                return $this->error('该单在申请结算中，请与财务联系后再退货！', ErrorInc::MYSQL_FAILED);
            }else{
                $orderSettArr['list_service_type'] = 50;
                $orderSetteArr['list_service_three'] = 50;
                $returnSettlementList = SettlementList::where('sys_num', $input['sys_num'])->whereIn('msg_id',$msg_id)->update($orderSettArr);
                $returnSettlementThree = SettlementThree::where('sys_num', $input['sys_num'])->whereIn('msg_id',$msg_id)->update($orderSetteArr);
            }
        }
        $submit_stauas = SubmitPlease::where(['submit_sys_num'=>$input['sys_num']])->whereIn('msg_id',$msg_id)->orderBy('id','DESC')->value('submit_stauas');
        if ($submit_stauas == 1){
            return $this->error('该单售后差额已在申请中，请向财务核实！', ErrorInc::MYSQL_FAILED);
        }
        $exi = Refund::where('id',$input['id'])->value('state');
        if(!isset($input['refund_id'])) {
            if (!in_array($exi, [0, 2, 3])) {//state :0：未处理；1：跟进中；2：电话回访中；3：已回访；4：已完成；5：已驳回；50：待确认

                return $this->error('该订单状态不正确', ErrorInc::MYSQL_FAILED);
            }
        }
        try{

            if($input['apply_type'] == 1) {
                $orderArr['order_status'] = 50;
                $all_num = OrderMsg::where('sys_num', $input['sys_num'])->count();
                if (count($msg_id) == $all_num) {
                    if($orderinfo['order_status'] != 50) {
                        $returnOrder = Orders::where('sys_num', $input['sys_num'])->update($orderArr);
                    }else{
                        $returnOrder = 1;
                    }
//                    OrderService::sysWarehouseCancel($input['sys_num']);
                } else {
                    $returnOrder = 1;
                }
            }else{
                $returnOrder = 1;
            }
            if ($returnOrder){
                $ret = $this->applyRefundOne($input, $msg_id, $session_token,$orderinfo);
                if($ret==103 || $ret==203){

                    return $this->success('退款成功-'.$ret);
                }else{
                    if(is_array($ret)){
                        $ret = json_encode($ret);
                    }
                    return $this->error('退货失败-'.$ret, ErrorInc::ELASTIC_FAILED);
                }
            }else{
                return $this->error('该单在（订单管理）操作失败，请核实！', ErrorInc::MYSQL_FAILED);
            }
        }catch(\Exception $e){
            return $this->error($e->getMessage(), ErrorInc::MYSQL_FAILED);
        }
    }


    /**
     *
     * @param array $input
     * @param array $msg_id
     * @param array $session_token
     * @return Ambigous <number, \Illuminate\Http\JsonResponse>|number
     * @author du 2021年8月11日上午11:25:57
     */
    public function applyRefundOne($input,$msg_id,$session_token,$orderinfo){
        if($input['apply_type'] == 1) {
            $msgArr['goods_service'] = 2;
        }
    	$msgArr['goods_state'] = 4;
    	$returnMsg = OrderMsg::where(['sys_num'=>$input['sys_num']])->whereIn('id',$msg_id)->update($msgArr);
    	$returnMsg = 1;
    	if ($returnMsg){
    		/*foreach ($msg_id as $k => $v) {
    			$msg_value = OrderMsg::where('id',$v)->first(['goods_name','goods_price']);
    			$returnPle = SubmitPleaseService::createSubmitPlease($session_token['admin_acc'], $input['pt_id'], $input['sys_num'], $msg_value['goods_name'], $msg_value['goods_price'], 2, 2, 2, 0, 2, $v);
    		}*/
    		if(empty($input['sety_id'])){
    			$input['sety_id'] = $input['lt_parent_id'];
    		}
    		$setP = SetmoneyType::where('sety_id',$input['sety_id'])->select('sety_id','lt_parent_id','sety_name')->first();
    		//if ($returnPle){
            if ($orderinfo['order_status'] > 10) {
                //
                $ret = $this->applyReundStatusTen($input, $session_token, $orderinfo, $setP,$msg_id);
                return $ret;
            }else{
                //
                $ret = $this->applyReundStatus($input, $session_token, $orderinfo, $setP,$msg_id);
                return $ret;
            }
    		/*}else{
    			DB::rollback();
    			return 1;//该单在（申请退\收列表）操作失败，请核实！
    		}*/
    	}else{

    		return 2;//该单在（订单商品管理）操作失败，请核实！
    	}

    }
    /**
     *
     * @param array $input
     * @param array $session_token
     * @param array $orderinfo
     * @param array $setP
     * @return number|\Illuminate\Http\JsonResponse
     * @author du 2021年8月11日上午11:26:25
     */
    public function applyReundStatusTen($input,$session_token,$orderinfo,$setP,$msg_id){
        if($input['apply_type'] == 1) {
            $orderListArr['stauas'] = 50;

            OrderList::where(['sys_num' => $input['sys_num']])->whereIn('order_goods_id', $msg_id)->update($orderListArr);

            if ($orderinfo['order_status'] > 20) {
                $settArr['list_service_type'] = 50;
                SettlementList::where(['sys_num' => $input['sys_num']])->whereIn('msg_id', $msg_id)->update($settArr);
            }
        }
    	// 日志
    	if($input['deal_note']){
    		$pos['deal_note'] = $input['deal_note'];
    		$afs_content = "(".$setP['sety_name'].")".$input['deal_note'];
    		CommonService::accMe($input['sys_num'],'退款管理',"同意退款:".$input['deal_note'],'','',$session_token['admin_groupnew'],$session_token['admin_acc'],$session_token['id']);
    	}
    	if(!$input['state'] && !isset($input['refund_id'])){
            $pos['state'] = 4;
        }
    	$pos['lable_type'] = $input['sety_id']??0;
    	$pos['updated_at'] = date("Y-m-d H:i:s");
    	$orderinfo['afs_serial'] = $orderinfo['afs_serial']??'';
   		$upAfs = OrderListService::creatAftersale(2, $orderinfo['order_num'], $orderinfo['afs_serial'], 1, 31, $input['lt_parent_id'], $input['sety_id'], $orderinfo['p_id'],  $orderinfo['ser_id'], $afs_content, $session_token['admin_acc'], $session_token['admin_acc'], $orderinfo['company_id']);

    	if (!$upAfs){
    		return 101;//标签添加失败
    	}
    	$upRuf = Refund::where('id',$input['id'])->update($pos);

    	if ($upRuf){
            OrderService::aftersaleLog($input['msg_id'],$input['goods_name'],"退货",$session_token['admin_acc']);
            $this->insertingLog("退货，",$input['sys_num'],"订单".$input['sys_num'],"退款管理",'',$session_token['admin_acc']);
            if($input['apply_type'] == 1) {
                /***************半径推送******************************/
//                $store = SyncStores::where("ser_id", $orderinfo['ser_id'])->where("type", 2)->value('id');
                $store = CommonService::getSyncStores($orderinfo['ser_id'], $orderinfo['category']);
                if (!empty($store) && $orderinfo['store_type'] == 5) {
                    $returnOrderList = OrderList::where(['sys_num' => $input['sys_num']])->whereIn('order_goods_id', $msg_id)->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'] = 0;
                        } else {
                            $pop['orcl_consent_price'] = 0;
                        }
                        $pop['remark'] = '客户退单';
                        $store = SysStoresService::sysStore($pop, 'recycleOrder',$store);
                        if ($store['ErrorCode'] != 1) {
                            //                        DB::rollBack();
                            return $store;
                        }
                    }
                }
                /***************半径推送******************************/

                // 退货成功

                //    		DB::commit();
                $this->pushWebDel($orderinfo['order_num'], 3);
               /* if ($orderinfo['p_id'] == '23') {
                    $apply_info = DB::table("apply_info")->where("order_num", $orderinfo['order_num'])->value('id');
                    if (!empty($apply_info)) {
                        $refound['id'] = $apply_info;
                        $refound['order_num'] = $orderinfo['order_num'];
                        $resp = $this->request_post('https://web.sudianwang.com/index.php/Rescue/refoundMoney', $refound);
                        $obj = json_decode($resp, true);
                        if ($obj['code'] != '1') {
                            return response()->json(['Data' => '', 'ErrorMessage' => $obj['msg'], 'ErrorCode' => 9]);
                        }
                    }
                }*/
            }
    		return 103;//退货成功
//    		exit;
    	}else{
//    		DB::rollback();
    		return 102;//退货失败
    	}

    }
    /**
     *
     * @param array $input
     * @param array $session_token
     * @param array $orderinfo
     * @param array $setP
     * @return number|\Illuminate\Http\JsonResponse
     * @author du 2021年8月11日上午11:26:42
     */
    public function applyReundStatus($input,$session_token,$orderinfo,$setP,$msg_id){
    	if($input['deal_note']){
    		$pos['deal_note'] = $input['deal_note'];
    		$afs_content = "(".$setP['sety_name'].")".$input['deal_note'];
    		CommonService::accMe($input['sys_num'],'退款管理',"同意退款:".$input['deal_note'],'','',$session_token['admin_groupnew'],$session_token['admin_acc'],$session_token['id']);
    	}
    	if(!$input['state'] && !isset($input['refund_id'])){
            $pos['state'] = 4;
        }

    	$pos['lable_type'] = $input['sety_id'];
    	$pos['updated_at'] = date("Y-m-d H:i:s");
    	$orderinfo['afs_serial'] = $orderinfo['afs_serial']??'';
    	$upAfs = OrderListService::creatAftersale(2, $orderinfo['order_num'], $orderinfo['afs_serial'], 1, 31, $input['lt_parent_id'], $input['sety_id'], $orderinfo['p_id'],  $orderinfo['ser_id'], $afs_content, $session_token['admin_acc'], $session_token['admin_acc'],$orderinfo['company_id']);
    	if (empty($upAfs)){
//    		DB::rollback();
    		return 201;exit;//标签添加失败
    	}
    	$upRuf = Refund::where('id',$input['id'])->update($pos);
    	// 日志
    	if ($upRuf){
    		OrderService::aftersaleLog($input['msg_id'],$input['goods_name'],"退货",$session_token['admin_acc']);
    		$this->insertingLog("退货，",$input['sys_num'],"订单".$input['sys_num'],"退款管理",'',$session_token['admin_acc']);
            if($input['apply_type'] == 1) {
                // 退货成功

                //    		DB::commit();
                $this->pushWebDel($orderinfo['order_num'], 3);

            }
    		return 203;//退货成功
    	}else{
//    		DB::rollback();
    		return 202;//退货失败
    	}
    }


    /**
     * @name  驳回
     * @param id        数据id
     * @param order_num 平台单号
     * @param content   备注内容
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed|\Illuminate\Http\JsonResponse
     * @author du 2021年8月11日下午4:33:56
     */
    public function applyReject (Request $request)
    {
        $input = $request->only('id','content');
        DB::beginTransaction();
        $data = RefundService::applyReject($request->ip(), $request->get("session_token"),$input);
        if($data['ErrorCode']==1){
            DB::commit();
        }else {
            DB::rollBack();
        }
        return $data;

    }


    /**
     * @name  加急
     * @param id 数据id
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年8月11日下午5:35:46
     */
    public function urgent(Request $request)
    {
        if (!$request->filled('id')||!$request->filled('content')){
        	return $this->error('参数错误无ID或content', ErrorInc::FAILED_PARAM);exit;
        }
        $id = intval($request->input('id'));
        $content = $request->input('content');
        $session = $request->get('session_token');
        $refArr = Refund::where('id',$id)->select('sys_num','urgent_type')->first();
        if ($refArr['urgent_type'] == 1){
        	$upRes = Refund::where('id',$id)->update(['urgent_type'=>2,'updated_at'=>date("Y-m-d H:i:s")]);
        	$rest = CommonService::accMe($refArr['sys_num'],'退款管理',"退款加急：".$content,'','',$session['admin_groupnew'],$session['admin_acc'],$session['id']);
        	if ($upRes){
        		$this->insertingLog('加急，',$refArr['sys_num'],'加急，系统单号：'.$refArr['sys_num'],'退款管理',$request->ip(),$request->get('session_token')['admin_acc']);
        		return $this->success('操作成功');
        	} else{
        		return $this->error('操作失败1', ErrorInc::MYSQL_FAILED);exit;
        	}
        } else{
        	return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
        }

    }



    /**|---------------------------------------------------------------------------------
     * @name  审核获取标签
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * |---------------------------------------------------------------------------------
     */
  /*   public function getlabel(Request $request)
    {
        if ($request->filled('type')){
            $type = $request->input('type');
            if ($type == 1){
                $info = SetmoneyType::where('lt_parent_id',31)->where('lt_statues',1)->select('sety_id','sety_name','lt_statues')->get();
            }elseif ($type == 2){
                if (!$request->filled('sety_id')){
                    return response()->json(['Data' => "", 'ErrorCode' => 3, 'ErrorMessage' => "参数错误"]);
                    exit;
                }
                $sety_id = $request->input('sety_id');

                $info = SetmoneyType::where('lt_parent_id',$sety_id)->select('sety_id','sety_name','lt_statues')->get();
            }

            if (!$info->isEmpty()){
                return response()->json(['Data' => $info->toArray(), 'ErrorCode' => 1, 'ErrorMessage' => "成功"]);
                exit;
            } else{
                return response()->json(['Data' => "", 'ErrorCode' => 2, 'ErrorMessage' => "暂无标签"]);
                exit;
            }
        }
    } */
    /**|---------------------------------------------------------------------------------
     * @name  编辑标签
     * @param id       数据id
     * @param type      公开状态
     * @return \Illuminate\Http\JsonResponse
     * |---------------------------------------------------------------------------------
     */
/*     public function apply_Label(Request $request){
    	if (!$request->filled('id')){
    		return $this->error('参数错误', ErrorInc::FAILED_PARAM);exit;
    	}
        $id = (int)$request->input('id');
        $data['type'] = 1;
        $res=Db::table('preliminary_note')->where('id',$id)->update($data);
        if($res){
           return $this->success('操作成功');
        }else{
           return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
        }
    } */

    /**
     * @name  编辑退款原因
     * @param id       数据id
     * @param refund_reason      退款原因
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年8月11日下午5:40:46
     */
   /* public function editLabel(Request $request){
    	if (!$request->filled('id')){
    		return $this->error('参数错误', ErrorInc::FAILED_PARAM);exit;
    	}
        $id = $request->input('id');
        $data['refund_reason'] = $request->input('refund_reason');
        $res = Refund::where('id',$id)->update($data);
        $this->insertingLog("编辑退款标签，",$input['sys_num'],"订单".$input['sys_num'],"退款管理",$request->ip(),$request->get('session_token')['admin_acc']);
    	if($res){
           return $this->success('操作成功');
        }else{
           return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
        }
    }*/

    /**
     * @name  编辑获取标签
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年8月12日上午9:29:38
     */
    public function editGetlabel(Request $request)
    {
    	if (!$request->filled('id')){
    		return $this->error('参数错误无ID', ErrorInc::FAILED_PARAM);exit;
    	}
        $id = $request->input('id');
        $info = Refund::where('id',$id)->value('lable_type');
        $info = SetmoneyType::where('sety_id',$info)->select('sety_id','sety_name','lt_parent_id')->get()->first();
        if($info['lt_parent_id'] =='31'){
            $info['lt_parent_id'] = $info['sety_id'];
        }
        if ($info){
        	return $this->success('获取成功',$info);
            exit;
        } else{
        	return $this->error('"暂无标签', ErrorInc::DATA_EMPTY);
            exit;
        }
    }

    /**
     * @name  编辑标签处理
     * @param Request $request
     * @param id            数据id
     * @param sety_id       标签id
     * @param note          备注
     * @param sys_num 　　　系统单号
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年8月11日下午5:48:11
     */
    public function editGetlabelDo(Request $request)
    {
    	if (!$request->filled('id')){
    		return $this->error('参数错误无ID', ErrorInc::FAILED_PARAM);exit;
    	}
        $id = $request->input('id');
        $data['lable_type'] = $request->input('sety_id');
        $note = $request->input('note');
        $res = Refund::where('id',$id)->update($data);
        $this->insertingLog("编辑退款标签，",$request->input['sys_num'],"订单".$request->input['sys_num'],$note,$request->ip(),$request->get('session_token')['admin_acc']);
    	if($res){
           return $this->success('操作成功');
        }else{
           return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取工单号（拷贝）
     * @param Request $request
     * @param msg_id 关联msg id
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2020/11/25 17:44>
     * |---------------------------------------------------------------------------------
     */
    public function searchSernum(Request $request){
        if (!$request->filled('msg_id')) {//关联msg id
           return $this->error('参数错误无msg_id', ErrorInc::FAILED_PARAM);exit;
        }
        $msg_id = explode(',',$request->input('msg_id'));
        if(count($msg_id)>5){
        	return $this->error('单号过多', ErrorInc::FAILED_PARAM);exit;
        }
        $list = DB::table("order_list")->whereIn("order_goods_id",$msg_id)->pluck('serial_number')->toarray();
        if($list){
        	$data = implode(',',$list);
        	return $this->success('操作成功',$data);exit;
        }else{
           return $this->error('"暂无数据', ErrorInc::DATA_EMPTY);exit;
        }

    }

    /**
     * @name 便捷退款
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2022/1/5
     */
    public function fastRefund(Request $request){
        $input = $request->all();
        $session = $request->get("session_token");
        $ip = $request->ip();
        $checkKey = CommonService::checkKey(['content','order_num','recycle_type','refund'],$input);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        $orderInfo = OrderService::getOrderBy('order_num', $request->input('order_num'),['sys_num','p_id','id']);
        if(empty($orderInfo)){
            return $this->error('订单不存在', ErrorInc::MYSQL_FAILED); exit;
        }

        $input['ids'] = $orderInfo['id'];
        $input['p_id'] = $orderInfo['p_id'];
        $input['sys_num'] = $orderInfo['sys_num'];

        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 order_num 平台单号
     * @return \Illuminate\Http\JsonResponse
     * |---------------------------------------------------------------------------------
     */
    public function refundGoods(Request $request)
    {
        if ($request->filled('order_num')) {
            $sysInfo= OrderService::getOrderBy('order_num', $request->input('order_num'),['sys_num','category','order_num']);
            if(!$sysInfo){
                return $this->error('单号不存在', ErrorInc::MYSQL_FAILED);exit;
            }

            $va = OrderService::validationLockOrder($sysInfo);
            if($va['ErrorCode']!=1){
                return $va; exit;
            }

            $va2 = OrderService::validationLockByRefund($sysInfo);

            if($va2['ErrorCode']!=1){
                return $va2;
            }

            $res = OrderService::getOrderMsgBy('sys_num', $sysInfo['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 string order_num 订单单号
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2022/2/11 16:48
     * |---------------------------------------------------------------------------------
    */
    public function sysWarehouseRefund ( Request $request ){
        if($request->filled('order_num')){
            $input = $request->all();
            $refund = RefundService::getInfoByKeyValue('order_num', $input['order_num'],[],'first');
            if($refund) {
                $session = $request->get("session_token");
                $zhipei['time'] = $refund['created_at'];//date('Y-m-d H:i:s');
                $zhipei['signature'] = md5($zhipei['time'] . '97e11cbcc29cbd8a538395abce85d569');
                $zhipei['order_num'] = $input['order_num'];
                $zhipei['refund_state'] = $refund['goods_state']??2;
                $dataState = OrderService::getDataState($zhipei['refund_state']);
                $zhipei['refund_state'] = $dataState['goods_state'];
                if (isset($refund['apply_type']) && $refund['apply_type'] != 1) {
                    $zhipei['refund_type'] = 2;
                } else {
                    $zhipei['refund_type'] = 1;
                }
                $zhipei['refund_price'] = $refund['goods_price'];
                $zhipei['remarks'] = $refund['refund_reason'];
//                if (isset($input['info_name'])) {
//                    $zhipei['account_number'] = $input['info_name'];
//                } else {
                    $zhipei['account_number'] = '';
//                }
//                if (isset($input['info_acc'])) {
//                    $zhipei['bank_name'] = $input['info_acc'];
//                } else {
                    $zhipei['bank_name'] = '';
//                }
//                if (isset($input['info_ing'])) {
//                    $zhipei['account_name'] = $input['info_ing'];
//                } else {
                    $zhipei['account_name'] = '';
//                }
                $zhipei['refund_username'] = $session['admin_acc'];
                $zhipei['refund_id'] = $refund['id'];
                $res = CommonService::requestPost('http://jx.bluearp.com/m/index.php/PartyIrderInterfaceThree/AddRefund', json_encode($zhipei), array('Content-Type: application/json'));
                $res = json_decode($res, true);
                $data = json_encode($zhipei) . '---' . json_encode($res);
                CommonService::addLog('通知库发退款', $data, $input['order_num'], 'warehouse-refund');
                if($res['code']!=200){
                    return  ['Data' => '','ErrorMessage'=>'同步智配失败:'.$res['data'],'ErrorCode'=>ErrorInc::TRANSFER_FAILED];
                }else{
                    return $this->success('成功',$res);exit;
                }
            }else{
                return $this->error('无对应退款单', ErrorInc::MYSQL_FAILED);exit;
            }
        }else{
            return $this->error('缺少参数', ErrorInc::FAILED_PARAM);exit;
        }
    }
    /**
     * 发送短信
     * @param Request $request
     * @return array|string|string[]
     * @author du
     * @date 2022/2/11
     */
    public function sendSmsRefundModel(Request $request){
        $input = $request->all();
        $session = $request->get("session_token");
        $ret = CommonService::sendMsgCommonModel($input, $session);
        return $ret;
    }

    /**
     * @name 异步获取发货状态
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2022/2/16
     */
    public function SendGoodsStaue(Request $request){
        $orderNum = $request->input('order_num');
        $list = SendGoods::where('order_num',$orderNum)->select('type','order_num','time','name','telephone')->get()->toarray();
        if(empty($list)){
            return $this->error('暂无数据', ErrorInc::MYSQL_FAILED);exit;
        }else{
            $types = array_column($list, 'type');
           // $types = array_unique($types);
           // dump($types);
            $arr = [5];
            if(in_array(5, $types)){
                if(array_diff($types,$arr)){
                    $data['sendOrderStaue'] = '存在发货定单';
                }else{
                    $data['sendOrderStaue'] = '已驳回';
                }
            }else{
                $data['sendOrderStaue'] = '存在发货定单';
            }
            $stausName = SendGoodsService::getStatusName();//发货状态
            foreach ($list as $k => $v){
                $list[$k]['sendOrderName'] = $stausName[$v['type']];
            }

            $data['list'] = $list;
            return $this->success('获取成功',$data);

        }
        //print_r(DB::getQueryLog());

    }

    /**
     * @name 便捷填单
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2022/3/28
     */
    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']);//过滤平台单号在复制时产生的回车、制表符等被忽略的特殊符号
        $input['refundorder'] = 2;     //单子撤消
        $session = $request->get('session_token');//获取操作人信息
        $return = OrderaddService::addOrder($input, $session, $request->ip());

        return $this->error($return['ErrorMessage'], $return['ErrorCode']);


    }

    /**
     * @name 异步获取下单金额
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2022/4/6
     */
    public function getOrderPrices(Request $request){
        if (!$request->filled('id')){
            return $this->error('参数错误无ID', ErrorInc::FAILED_PARAM);exit;
        }
        $id = $request->input('id');
        $msg_ids = RefundService::getInfoByKeyValue('id', $id,['msg_id']);
        if(!$msg_ids){
            return $this->error('不存在', ErrorInc::MYSQL_FAILED);exit;
        }
        $msg_idarr = explode(',', $msg_ids);
       // dump($msg_idarr);
        $price = OrderMsg::whereIn('id',$msg_idarr)->sum('goods_price');
        //dump($price);
        return $this->success('获取成功',$price);
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取完成标签类型
     * @param int apply_type 退款标签
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2022/6/24 16:25
     * |---------------------------------------------------------------------------------
    */
    public function getAuditLable ( Request $request ){
        if($request->filled('apply_type')){
            $apply_type = $request->input('apply_type');
            $ApplyType = RefundService::getRefundApplyType();
            $ApplyType = array_column($ApplyType, 'sety_id','type');
            $sety_id = $ApplyType[$apply_type]??'';
            if($sety_id){
                $data = LabtypeService::getLable('sety_id',$sety_id);
                if($data){
                    $return['sety_id'] = $data[0]['sety_id'];
                    $return['sety_name'] = $data[0]['sety_name'];
                    $return['lt_parent_id'] = $data[0]['lt_parent_id'];
                    return $this->success('获取成功',$return);

                }else{
                    return $this->error('标签类型未设定1', ErrorInc::INVALID_PARAM);exit;
                }
            }else{
                return $this->error('标签类型未设定', ErrorInc::INVALID_PARAM);exit;
            }
        }else{
            return $this->error('缺少参数', ErrorInc::FAILED_PARAM);exit;
        }
    }


}
