<?php

namespace App\Http\Controllers\Api;

//use BlueCity\Data\Service\GoodsDataService;
use App\Http\Controllers\BaseController;
use App\Inc\OrderInc;
use App\Models\Orders;
use App\Models\SendGoods;
use App\Models\SubmitPlease;
use App\Models\User;
use App\Services\ActionLogService;
use App\Services\AftersaleOrderService;
use App\Services\AfterSaleService;
use App\Services\CommonService;
use App\Services\GoodsService;
use App\Services\InterFaceService;
use App\Services\LabtypeService;
use App\Services\OrderService;
use App\Services\OrderaddService;
use App\Services\PlatformService;
use App\Services\RecycleOrderService;
use App\Services\RefundService;
use App\Services\SendGoodsService;
use App\Services\SubmitPleaseService;
use App\Services\UserService;
//use BlueCity\Core\Controllers\MountingCoreController as Controller;
use BlueCity\Core\Inc\ErrorInc;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use DB;
use Validator;
use PhpParser\Node\Stmt\Foreach_;

class OrdersController extends BaseController
{
    /**
     * @api {post} /api/interface/order/store 订单新增
     * @apiGroup 第三方订单接口
     * @apiName 订单新增
     * @apiVersion 1.0.0
     *
     * @apiDescription 订单新增，如果已经存在则更新订单信息为最新数据
     *
     * @apiParam {String}   order_no 订单系统编号
     * @apiParam {array}   goods     订单商品
     *
     * @apiSuccess {Number} error    状态码，0：请求成功
     * @apiSuccess {String} msg   提示信息
     * @apiSuccess {Object} data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"code":0,"message":"","data":[]}
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常"}
     *
     */
    public function store(Request $request)
    {
        //先看是不是存在
        $orderNO = $request->input('order_no');
        if (empty($orderNO)) {
            $json = file_get_contents("php://input");
            $post = json_decode($json,true);
            if(empty($post['order_no'])) {
                return $this->error('订单编号不能为空', ErrorInc::INVALID_PARAM);
            }else{
                $orderNO = $post['order_no'];
                $request->merge($post);
            }
        }
//        $Validator = InterFaceService::validateOrderStore($request->all());
        $rules = [
            'goods' => 'required|',
            'shr_name' => 'required|',
            'shr_phone' => 'required',
            'shr_sheng' => 'required',
            'shr_shi' => 'required',
            'shr_adress' => 'required',
            'ware_id' => 'required',
            'pt_type' => 'required',
        ];
        $message = [
            'goods.required' => "请选择商品",
            'shr_name.required' => "收件人不能为空",
            'shr_phone.required' => "联系电话不能为空",
            'shr_sheng.required' => "请选择省",
            'shr_shi.required' => "请选择市",
            'shr_adress.required' => "详细地址不能为空",
            'ware_id.required' => '库房不能为空',
            'pt_type.required' => "平台id类型必填",
        ];
        $inputs= $request->all();
        CommonService::addLog('库房添加订单', json_encode($inputs), '','warehouse-beforadd');
        $Validator = Validator::make ( $inputs, $rules, $message );
        if ($Validator->fails ()) {
            $reeor = CommonService::validatorToString($Validator);
            return $this->error ( $reeor, ErrorInc::INVALID_PARAM,[]);
        }
        $db = new SendGoods();
        $warehouse_num['warehouse_num_rlike'] = $orderNO.'-';
        $warehouse_num['warehouse_num'] = $orderNO;
        $pid = CommonService::getMysqlData($db, ['warehouse_num_searchor'=>$warehouse_num,'data_source'=>1],['id'],[],'value');
        if($pid){
            return $this->error ( '补货商品无需添加服务单', ErrorInc::REPEAT_SUBMIT,[]);
        }
        $order = OrderService::getOrderByOrderNumber($orderNO);
//        if ($order) {
//            return $this->error('该订单已存在', ErrorInc::DATA_EXIST);
//        } else {
            $sendgood = 1;
            DB::beginTransaction(); //开启事务
            $orders = new Orders();
            $rea = CommonService::getMysqlData($orders, ['order_num'=>$orderNO],['id','order_status'],['id'=>'DESC'],'first');
            if($rea && $rea['order_status'] == 50){
                $ordernum = $orderNO.'-ZF'.$rea['id'];
                $raa = Orders::where('id',$rea['id'])->where('order_status','50')->update(['order_num'=>$ordernum,'is_delete'=>1]);
                if(!$raa){
                    DB::rollback();
                    return $this->error( '单号变更失败', ErrorInc::MYSQL_FAILED);
                }
                $sendid = SendGoodsService::getSendGoodBy(['warehouse_num'=>$orderNO,'data_source'=>2,'reject'=>1], ['id'],'first');
                if($sendid){
                    $res = SendGoods::where('id',$sendid)->update(['reject'=>2]);
                    if(!$res){
                        $sendgood = 2;
                    }
                }
            }elseif ($rea && $rea['order_status'] != 50){
                return $this->error('该订单已存在', ErrorInc::DATA_EXIST);
            }
            $input = [];
            ////先把订单数据整理下
            $input['order_num'] = $orderNO;
            $input['skb_bh'] = $orderNO;
            $input['sys_bh'] = CommonService::creactSysNum(3);
            $input['pay_type'] = 1;
            $input['order_status'] = OrderInc::STATE_AVAILABLE;
            $input['car_audit'] = 2;

            //用户信息处理
            $input['shr_name'] = $request->input('shr_name');
            $input['shr_phone'] = $request->input('shr_phone');
            $input['shr_sheng'] = $request->input('shr_sheng');
            $input['shr_shi'] = $request->input('shr_shi');
            $input['shr_xian'] = $request->input('shr_xian');
            $input['shr_adress'] = $request->input('shr_adress');
            $input['shr_other'] = $request->input('shr_other');

            //然后整理商品数据
            $goods = $request->input('goods');
            if (empty($goods)) {
                return $this->error('商品数据不能为空', ErrorInc::INVALID_PARAM);
            }

            $goods_name = '';
            $goodsData = [];
            $goods_id = '0';
            $warehouse_good = [];
            foreach ($goods as $key => $value) {
                if (empty($value['goods_id']) || empty($value['goods_num']) || !isset($value['goods_price'])) {
                    return $this->error(' 商品信息格式错误', ErrorInc::INVALID_PARAM);
                }
                $goodsID = $value['goods_id'];//智配传来的是code码
                $goodsNum = $value['goods_num'];
                $goodsPrice = $value['goods_price'];
                if(isset($value['sku_id']) && $value['sku_id']!=''){
                    $goodss = GoodsService::getGoodsByCode($value['sku_id'],2);//这个函数需要完善下
                    $inputs['p_id'] = $goodss['pt_id'];
                }else {
                    $goodss = GoodsService::getGoodsByCode($goodsID,1);//这个函数需要完善下
                }
                if (empty($goodss)) {
                    return $this->error($goodsID . ' 编码的商品无法找到', ErrorInc::INVALID_PARAM);
                }
                if ($goodsNum == 0) {
                    return $this->error($goodss['pg_name'] . '商品的数量不能为0', ErrorInc::INVALID_PARAM);
                }
                if($value['goods_name']!=''){
                    $goodss['good_name'] = $value['goods_name'];
                }
                $goods_id = $goodss['goods_id'];
                $goodsData[] = [
                    'goods_brand' => $goodss['brand_name'],
                    'goods_name' => $goodss['good_name'],
                    'goods_number' => $goodsID,
                    'goods_num' => $goodsNum,
                    'msg_id' => 0,
                    'goods_id' => $goodss['goods_id'],
                    'cd_id' => $goodss['cd_id'],//默认是
                    'goods_price' => $goodsPrice
                ];
                $warehouse_good[] = [
                    'wg_ordernum' => $orderNO,
                    'wg_goodid' => $goods_id,
                    'wg_goodname' => $goodss['good_name'],
                    'wg_goodnum' => $goodsNum,
                    'wg_goodprice' => $goodsPrice,
                    'wg_creactime' => date("Y-m-d H:i:s")
                ];
            }
            if($inputs['pt_type'] == 2) {
                $pt_id = PlatformService::getPtBy('id', $inputs['p_id'], ['id', 'company_id'], 'first');
            }else{
                $pt_id = PlatformService::getPtBy('zp_id', $inputs['p_id'], ['id', 'company_id'], 'first');
            }
            if (!$pt_id) {
                return $this->error('系统异常', ErrorInc::SERVER_FAILED);
            }
            DB::table("warehouse_good")->insert($warehouse_good);
            $input['goods'] = $goodsData;
            //订单数据
            $input['pt_id'] = $pt_id['id'];
            $input['ware_id'] = $request->input('ware_id')??4;
            $input['company_id'] = $pt_id['company_id'];
//            $sj_value = $request->input('new_money');
            $input['new_money'] = $request->input('new_money');
            $input['ser_type'] = $request->input('ser_type') ?? 3;//智配没给
            $input['order_type'] = 1;
            $input['customer_time'] = $request->input('customer_time');//智配没给
            $input['ser_type'] = 1;
            $orderjoin_data["goods_id"] = $goods_id;
            $orderjoin_data["o_sysbh"] = $input['sys_bh'];
            $orderjoin_data["o_skbnum"] = $orderNO;
            $orderjoin_data["sys_bh"] = $input['sys_bh'];
            $orderjoin_data["skb_bh"] = $request->input('primary_num');
            $orderjoin_data["goods_num"] = 1;
            $orderjoin_data["edit_time"] = date("Y-m-d H:i:s");
            $orderjoin_data["is_jdservice"] = 1;
            $joingoods = DB::table("orders_joingoods")->insert($orderjoin_data);
            if(!$joingoods){
                DB::rollback();
                return $this->error( '记录添加失败', ErrorInc::MYSQL_FAILED);
            }
            $session = InterFaceService::getDefaultUser();//默认一个管理账号作为同步数据主账号
            $result = $ordermsg = OrderaddService::addOrder($input, $session, '',2);
            if ($result['ErrorCode'] == 1) {
                if($request->filled('car_not')){
                    $car_not = $request->input('car_not');
                    if(is_array($car_not)){
                        foreach($car_not as $k => $v){
                            CommonService::accMe($input['sys_bh'], '客户车型', $v, '', 2, 7, '系统同步', 1133);
                        }
                    }else{
                        CommonService::accMe($input['sys_bh'], '客户车型', $car_not, '', 2, 7, '系统同步', 1133);
                    }
                }
                if($request->filled('order_not')){
                    $order_not = $request->input('order_not');
                    foreach($order_not as $k => $v){
                        if($v['note_type']=='车型备注'){
                            $public = 2;
                        }else{
                            $public = 1;
                        }
                        if($v['note_content']!='' && $v['note_content']!=null) {
                            CommonService::accMe($input['sys_bh'], $v['note_type'], $v['note_content'], '', $public, 7, $v['note_name'], 1133);
                        }
                    }
                }
                $data['send_num'] = 'F'.uniqid();
                $data['warehouse_num'] = $orderNO;
                $data['send_type'] = 2;
                $data['sys_num']= $input['sys_bh'];
                $data['order_num']= $orderNO;
                $data['stores'] = $input['ware_id'];//库房id需要智配提供
                $data['receiving_store'] =0;
                $data['user']= '系统同步';
                $data['telephone'] = $input['shr_phone'];
                $data['collect_type'] = 2;
                $data['expect_time'] = '';
                $data['name'] = $input['shr_name'];
                $data['category'] = 1;
                $data['create_id'] = 1133;
                $data['create_name'] = 'erp同步';
                $address = '';
                if($input['shr_sheng'] && $input['shr_shi'] && $input['shr_xian']){
                    $address .= $input['shr_sheng'];
                    $address .= $input['shr_shi'];
                    $address .= $input['shr_xian'];
                }
                $address .= $request->input('shr_adress');
                $data['address'] = $address;
                $data['data_source'] = 2;
                if($sendgood ==1) {
                    $res1 = SendGoodsService::createData($data, $input['goods']);
                }else{
                    $res1 = true;
                }
                if(!$res1){
                    DB::rollback();
                    return $this->error( ' 记录发货单异常', ErrorInc::MYSQL_FAILED);
                }
                DB::commit();
                return $this->success('订单新增成功');
            } else {
                DB::rollback();
                return $this->error($result['ErrorMessage'], $result['ErrorCode']);
            }
//        }
    }

    /**
     * @api {post} /api/interface/order/shipping 告诉订单已发货
     * @apiGroup 第三方订单接口
     * @apiName 告诉订单已发货
     * @apiVersion 1.0.0
     *
     * @apiDescription 根据订单NO修改订单已发货状态
     *
     * @apiParam {String}   $order_no 订单系统编号
     * @apiParam {String}      $shipping_code 快递标识
     * @apiParam {String}      $shipping_no   快递单号
     *
     * @apiSuccess {Number} error    状态码，0：请求成功
     * @apiSuccess {String} msg   提示信息
     * @apiSuccess {Object} data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"code":0,"message":"","data":[]}
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常"}
     *
     */
    public function shipping(Request $request)
    {
        //先看是不是存在
        $orderNO = $request->get('order_no');
        if (empty($orderNO)) {
            $json = file_get_contents("php://input");
            $post = json_decode($json,true);
            if(empty($post['order_no'])) {
                return $this->error('订单编号不能为空', ErrorInc::INVALID_PARAM);
            }else{
                $orderNO = $post['order_no'];
                $request->merge($post);
            }
        }
        $shipping_code = $request->get('shipping_code');
        $shipping_no = $request->get('shipping_no');

        $shippingInfo = $input = [];
        $shippingInfo['shipping_code'] = $shipping_code;
        $shippingInfo['shipping_no'] = $shipping_no;
        CommonService::addLog('库房通知发货', json_encode($request->all()), '','warehouse-shipping');
        //用户信息处理
//        $input['shr_name'] = $request->input('shr_name');
//        $input['shr_phone'] = $request->input('shr_phone');
//        $input['shr_sheng'] = $request->input('shr_sheng');
//        $input['shr_shi'] = $request->input('shr_shi');
//        $input['shr_xian'] = $request->input('shr_xian');
//        $input['shr_adress'] = $request->input('shr_adress');
//        $input['shr_other'] = $request->input('shr_other');

//        $order = OrderService::getOrderByOrderNumber($orderNO);
//        if ($order) {
            return SendGoodsService::sysCourierData($orderNO, $shipping_no, $shipping_code);
            //保存订单信息
//            $session = InterFaceService::getDefaultUser();
//            $res = OrderService::saveShipping($orderNO, $input, $session);//需要完善这个函数
//            if ($res) {
//                return $this->success('发货通知已接收');
//            }
//            return $this->error('发货状态修改失败', ErrorInc::MYSQL_FAILED);
//        }else {
//            return $this->error('订单未找到', ErrorInc::DATA_EMPTY);
//        }
    }

    /**
     * @api {post} /api/interface/order/shippingCancel 订单发货取消
     * @apiGroup 第三方订单接口
     * @apiName 订单发货取消
     * @apiVersion 1.0.0
     *
     * @apiDescription 根据订单NO修改订单已发货状态取消
     *
     * @apiParam {String}   $order_no 订单系统编号
     *
     * @apiSuccess {Number} error    状态码，0：请求成功
     * @apiSuccess {String} msg   提示信息
     * @apiSuccess {Object} data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"code":0,"message":"","data":[]}
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常"}
     *
     */
    public function shippingCancel(Request $request)
    {
        //先看是不是存在
        $orderNO = $request->get('order_no');
        CommonService::addLog('库房取消通知', json_encode($request->all()), $orderNO,'warehouse-warehouseCancel');
        $order = OrderService::getOrderByOrderNumber($orderNO);
        if ($order) {
            if($order['order_status'] == 3) {
                //保存订单信息
                $session = InterFaceService::getDefaultUser();
                $res = OrderService::shippingCancel($order, $session);//需要完善这个函数
                CommonService::accMe($order['sys_num'], '库房同步', '库房编辑取消订单', '', 1, 7, '系统同步', 1133);
                return $this->success('发货取消已接收成功');
            }else{
                return $this->error('订单已发货请联系o2o部门撤销', ErrorInc::INVALID_PARAM);
            }
        }
        return $this->error('订单未找到', ErrorInc::DATA_EMPTY);
    }

    /**
     * @api {post} /api/interface/order/state 订单修改状态（不需要）
     * @apiGroup 第三方订单接口
     * @apiName 订单修改状态（不需要）
     * @apiVersion 1.0.0
     *
     * @apiDescription 根据订单NO修改订单状态
     *
     * @apiParam {String} $order_no 订单系统编号
     * @apiParam {int} $state 订单系统编号
     *
     * @apiSuccess {Number} error    状态码，0：请求成功
     * @apiSuccess {String} msg   提示信息
     * @apiSuccess {Object} data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"code":0,"message":"","data":[]}
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常"}
     *
     */
    public function state(Request $request)
    {
        //先看是不是存在
        $orderNO = $request->get('order_no');
        $state = $request->get('state');
        $order = OrderService::getOrderByOrderNumber($orderNO);
        if ($order) {
            //保存订单信息

            return $this->success('状态变更成功');
        }
        return $this->error('订单未找到', ErrorInc::DATA_EMPTY);
    }


    /**
     * @api {post} /api/interface/order/update 订单修改（不需要）
     * @apiGroup 第三方订单接口
     * @apiName  订单修改（不需要）
     * @apiVersion 1.0.0
     *
     * @apiDescription 根据订单NO修改订单
     *
     * @apiParam {String} $order_no 订单系统编号
     *
     * @apiSuccess {Number} error    状态码，0：请求成功
     * @apiSuccess {String} msg   提示信息
     * @apiSuccess {Object} data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"code":0,"message":"","data":[]}
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常"}
     *
     */
    public function update(Request $request)
    {
        //先看是不是存在
        $orderNO = $request->get('order_no');
        $goods = $request->input('goods');
        $order = OrderService::getOrderByOrderNumber($orderNO);
        if ($order) {
            //保存订单信息

            return $this->success('订单更新成功');
        }
        return $this->error('订单未找到', ErrorInc::DATA_EMPTY);
    }


    /**
     * @api {post} /api/interface/order/retrieve 订单已回收接口
     * @apiGroup 第三方订单接口
     * @apiName 订单已回收接口
     * @apiVersion 1.0.0
     *
     * @apiDescription 根据订单NO通知速电系统该订单已回收
     *
     * @apiParam {String} $order_no 订单系统编号
     *
     * @apiSuccess {Number} error    状态码，0：请求成功
     * @apiSuccess {String} msg   提示信息
     * @apiSuccess {Object} data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"code":0,"message":"","data":[]}
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常"}
     *
     */
    public function retrieve(Request $request)
    {
        CommonService::addLog('库房回收通知', json_encode($request->all()), '','warehouse-shippingCancel');
        //先看是不是存在
        $orderNO = $request->get('order_no');
        $shipping_code = $request->get('shipping_code');
        $shipping_no = $request->get('shipping_no');
        $recycle_num = $request->get('recycle_num');
        $is_abnormal = $request->get('is_abnormal')??'2';
        $session = InterFaceService::getDefaultUser();
        $res = RecycleOrderService::saveRetrieve($orderNO, $shipping_code, $shipping_no, $session,$recycle_num,$is_abnormal);//需要完善这个函数
        return $res;
    }

    /**
     * @api {post} /api/interface/order/show 单个订单获取接口（不需要）
     * @apiGroup 第三方订单接口
     * @apiName 单个订单获取接口（不需要）
     * @apiVersion 1.0.0
     *
     * @apiDescription 根据订单NO获取单个订单信息
     *
     * @apiParam {String} $order_no 订单系统编号
     *
     * @apiSuccess {Number} error    状态码，0：请求成功
     * @apiSuccess {String} msg   提示信息
     * @apiSuccess {Object} data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"code":0,"message":"","data":[]}
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常"}
     *
     */
    public function show(Request $request)
    {
        //先看是不是存在
        $orderNO = $request->get('order_no');
        $order = OrderService::getOrderByOrderNumber($orderNO);
        if ($order) {
            //保存订单信息

            return $this->success('成功', $order);
        }
        return $this->error('订单未找到', ErrorInc::DATA_EMPTY);
    }

    /**
     * @api {post} /api/interface/order/cancel 订单取消接口
     * @apiGroup 第三方订单接口
     * @apiName 订单取消接口
     * @apiVersion 1.0.0
     *
     * @apiDescription 根据订单NO取消订单
     *
     * @apiParam {String} $order_no 订单系统编号
     *
     * @apiSuccess {Number} error    状态码，0：请求成功
     * @apiSuccess {String} msg   提示信息
     * @apiSuccess {Object} data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"code":0,"message":"","data":[]}
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常"}
     *
     */
    public function cancel(Request $request)
    {
        //先看是不是存在
        $orderNO = $request->get('order_no');
        CommonService::addLog('库房取消通知订单', json_encode($request->all()), $orderNO,'warehouse-warehouseCancel');
        if (empty($orderNO)) {
            return $this->error('order_no订单编号不能为空', ErrorInc::INVALID_PARAM);
        }
        $order = OrderService::getOrderByOrderNumber($orderNO);
        if ($order) {
            if($order['order_status'] == 3) {

                //保存订单信息
                $res = (new OrderService())->update(['order_status' => OrderInc::STATE_CANCEL], $order['id']);
                if ($res) {
                    $this->insertingLog('取消订单，',$order['sys_num'],'订单：'.$orderNO,'库房取消订单',$request->ip(), '库房同步');//日志
                }
                return $this->success('订单取消成功');
            }else{
                return $this->error('订单已发货请联系o2o部门撤销', ErrorInc::INVALID_PARAM);
            }
        }

        return $this->error('订单取消失败', ErrorInc::MYSQL_FAILED);
    }

    /**
     * 库房备注同步
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2021/12/21
     */
    public function synRemark(Request $request){
        $time = $request->get('time');
        $signature = $request->get('signature');
        if (empty($time) || empty($signature)) {
            return $this->error('time或 signature 不能为空', ErrorInc::INVALID_PARAM);
        }
        //校验token
        $token = md5($time.'97e11cbcc29cbd8a538395abce85d569');

        if($signature !== $token) return $this->error('秘钥错误', ErrorInc::INVALID_PARAM);

        $orderNO = $request->get('order_no');
        if (empty($orderNO)) {
            return $this->error('order_no订单编号不能为空', ErrorInc::INVALID_PARAM);
        }
        $car_not = $request->input('car_not');
        $create_name = $request->input('create_name');
        if (empty($create_name)) {
            return $this->error('创建人不能为空', ErrorInc::INVALID_PARAM);
        }
        $note = $request->input('note');
        if(empty($car_not) && empty($note) ){
            return $this->error('车型或备注内容必填其一', ErrorInc::INVALID_PARAM);
        }
        $sys_num = OrderService::getOrderBy('order_num', $orderNO,['sys_num','customer_id','new_customer_id']);
        if(!$sys_num){
            return $this->error('订单不存在', ErrorInc::MYSQL_FAILED);exit;
        }
        $flag = 2;
        if($request->filled('car_not')){
            if(is_array($car_not)){
                foreach($car_not as $k => $v){
                    $res = CommonService::accMe($sys_num['sys_num'], '客户车型', $v, '', 2, 7, $create_name, 1133);
                }
                if($res){
                    $flag = 1;
                }
                $car_note = $car_not[0];
            }else{
                $res = CommonService::accMe($sys_num['sys_num'], '客户车型', $car_not, '', 2, 7, $create_name, 1133);
                if($res){
                    $flag = 1;
                }
                $car_note = $car_not;
            }
            User::whereIn('id',[$sys_num['customer_id'],$sys_num['new_customer_id']])->update(['car_infor'=>$car_note]);

        }
        if($request->filled('note')){
            $res = CommonService::accMe($sys_num['sys_num'], '库房同步', $note, '', 2, 7, $create_name, 1133);
            if($res){
                $flag = 1;
            }
        }
        if($flag==1){
            return $this->success('同步成功');
        }else{
            return $this->error('同步失败', ErrorInc::MYSQL_FAILED);
        }
    }

    /**
     * @name 获取售后位置
     * @param Request $request
     * @return array|array[]|\Illuminate\Http\JsonResponse
     * @author du
     * @date 2022/1/6
     */
    public function getAfterSalesSite(Request $request){
        $data = $this->checkedToken($request->input('time'), $request->input('signature'));
        if($data->original['ErrorCode']!=1) return $data->original;
        $res = AftersaleOrderService::getDerail();
        return $this->success('获取成功',$res);

    }

    /**
     * @name 获取售后标签
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2022/1/6
     */
    public function getAfterSalesLabs(Request $request){
        $data = $this->checkedToken($request->input('time'), $request->input('signature'));
        if($data->original['ErrorCode']!=1) return $data->original;

        if($request->filled('sety_id')){
            $sety_id = $request->input('sety_id');
        }else{
            $sety_id = 511;
        }
        $key = 'lt_parent_id';
        $list = LabtypeService::getLable($key,$sety_id,'',1);

        foreach ($list as $k =>$v){
            $res[$k]['sety_id'] = $v['sety_id'];
            $res[$k]['sety_name'] = $v['sety_name'];
            $res[$k]['lt_parent_id'] = $v['lt_parent_id'];
        }
        if($res){
            return $this->success('获取成功', $res);
        }else{
            return $this->error('无数据', ErrorInc::DATA_EMPTY, []);
        }
    }

    /**
     * @name 添加售后
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2022/1/6
     */
    public function addAfterSales(Request $request){
        $data = $this->checkedToken($request->input('time'), $request->input('signature'));
        if($data->original['ErrorCode']!=1) return $data->original;

        if(!$request->filled('order_no')){
            return $this->error('参数错误 平台单号未填写,或值为空', ErrorInc::FAILED_PARAM, []);
        }
        $ip = ($_SERVER["HTTP_VIA"]) ? $_SERVER["HTTP_X_FORWARDED_FOR"] : $_SERVER["REMOTE_ADDR"];
        $ip = ($ip) ? $ip : $_SERVER["REMOTE_ADDR"];
        $input = $request->all();
        $session['id'] = 0;
        $session['admin_groupnew'] = 0;
        $session['admin_acc'] = $input['create_name'];

        $oinfo = OrderService::getOrderBy('order_num',$input['order_no'],['category','id']);//获取订单信息
        if($oinfo['category']!=3){
            return $this->error('单号不存在', ErrorInc::MYSQL_FAILED);exit;
        }
        $input['id'] = $oinfo['id'];
        $input['Pri_id'] = 145;
        DB::beginTransaction();
        CommonService::addLog('添加售后', json_encode($input), $input['order_no'],'apiAddAfter');
        $data = AftersaleOrderService::addAfter($input,$session,$ip);
        if($data['code']) {
            DB::commit();
            $this->operatingTime($data['data']['serserial_number'], '申请售后时间', date("Y-m-d H:i:s"), $data['data']['order_num'], $input['create_name']);//订单操作时间
            $this->insertingLog('添加售后(同步)，', $data['data']['sys_num'], '订单' . $data['data']['sys_num'], '售后管理', $ip, $input['create_name']);//日志
            return $this->success($data['msg']);
        }else{
            DB::rollBack();
            return $this->error($data['msg'], $data['data']);exit;
        }
    }

    /**
     * @name 获取申诉类型
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2022/1/6
     */
    public function getAfterSalesType(Request $request){
        $data = $this->checkedToken($request->input('time'), $request->input('signature'));
        if($data->original['ErrorCode']!=1) return $data->original;

        $data = AftersaleOrderService::getAfterAppealType();
        return $this->success('获取成功', $data);
    }


    /**
     * @name 获取售后信息
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2022/1/6
     */
    public function getAfterSalesDetail(Request $request){
        $data = $this->checkedToken($request->input('time'), $request->input('signature'));
        if($data->original['ErrorCode']!=1) return $data->original;

        if(!$request->filled('order_no')){
            return $this->error('参数错误 平台单号未填写,或值为空', ErrorInc::FAILED_PARAM, []);
        }

        $data = AftersaleOrderService::getDetailByOrder($request->input('order_no'));
        if($data){
            return $this->success('获取成功', $data);
        }else{
            return $this->error('暂无数据', ErrorInc::MYSQL_FAILED);
        }
    }

    /**
     * @name 退款
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2022/1/11
     */
    public function refundGoods(Request $request){
        $data = $this->checkedToken($request->input('time'), $request->input('signature'));
        if($data->original['ErrorCode']!=1) return $data->original;

        $input = $request->all();
        $checkKey = CommonService::checkKey(['content','order_no','recycle_type','refund','pgc_code','create_name'],$input);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }

       // $sys_num = OrderService::getOrderBy('order_num', $request->input('order_no'),['sys_num']);
        $orderInfo = OrderService::getOrderBy('order_num', $request->input('order_no'),['sys_num','p_id','id']);
        if(empty($orderInfo)){
            return $this->error('订单不存在', ErrorInc::MYSQL_FAILED); exit;
        }
        $goods_id = DB::table('pj_goodcode')->whereIn('pgc_code',$request->input('pgc_code'))->select('pgc_pgid')->get();
        if(!$goods_id){
            return $this->error('商品不存在', ErrorInc::MYSQL_FAILED);exit;
        }

        $goodsArr = DB::table('order_msg')->where('sys_num',$orderInfo['sys_num'])->whereIn('goods_id',$goods_id)->select('id as msg_id','goods_id', 'goods_name','goods_price','goods_num')->get()->toarray();

        if(!$goodsArr){
            return $this->error('订单商品不存在', ErrorInc::MYSQL_FAILED);exit;
        }
        $input['goodsArr'] = $goodsArr;
        $ip = ($_SERVER["HTTP_VIA"]) ? $_SERVER["HTTP_X_FORWARDED_FOR"] : $_SERVER["REMOTE_ADDR"];
        $ip = ($ip) ? $ip : $_SERVER["REMOTE_ADDR"];

        $session['id'] = 0;
        $session['admin_groupnew'] = 0;
        $session['admin_acc'] = $input['create_name'];

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

        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;

    }

    /**
     * 获取售后图文
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2022/1/14
     */
    public function  getImgContent(Request $request){
        $data = $this->checkedToken($request->input('time'), $request->input('signature'));
        if($data->original['ErrorCode']!=1) return $data->original;

        if(!$request->filled('afid')||(intval($request->input('afid'))<=0)){
            return $this->error('参数错误售后ID不能这空', ErrorInc::FAILED_PARAM, []);exit;
        }
        $id = intval($request->input('afid'));
        $ret = DB::table('order_after_content')->where('afid',$id)->first();
        if($ret){
            return $this->success('获取成功', $ret); exit;
        }else{
            return $this->error('暂无数据', ErrorInc::DATA_EMPTY);exit;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 查询退款信息
     * @param string order_num 订单单号
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2022/1/27 14:31
     * |---------------------------------------------------------------------------------
    */
    public function getRefund ( Request $request ){
//        $data = $this->checkedToken($request->input('time'), $request->input('signature'));
//        if($data->original['ErrorCode']!=1) return $data->original;
        if(!$request->filled('order_num')){
            return $this->error('参数错误订单单号不能为空', ErrorInc::FAILED_PARAM, []);exit;
        }
        $refund = RefundService::getInfoByKeyValue('order_num', $request->input('order_num'),['goods_price','state']);
        if($refund){
            $data['list'] = $refund;
            $allprice = 0;
            foreach($refund as $k => $v){
                if($v['state']!=5){
                    $allprice = $allprice+$v['goods_price'];
                }
            }
            $data['allprice'] = $allprice;
            return $this->success('获取成功', $data); exit;
        }else{
            return $this->error('暂无数据', ErrorInc::DATA_EMPTY);exit;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 添加或编辑商品信息
     * @param string time 时间
     * @param string signature 校验码
     * @param string zp_id 数据id
     * @param string brand_name 品牌名称
     * @param string pg_series 系列名称
     * @param string version 型号名称
     * @param string pg_goodsname 商品全名
     * @param string good_code 商品编号
     * @param string is_delect 是否下架1在售  2下架
     * @param string cd_id 品类ID
     * @param string gs_id 系列id
     * @param string gs_bid 品牌ID
     * @param string pieces 单位
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2022/2/17 14:54
     * |---------------------------------------------------------------------------------
    */
    public function updateGood ( Request $request ){
        $data = $this->checkedToken($request->input('time'), $request->input('signature'));
        if($data->original['ErrorCode']!=1) return $data->original;
        $input = $request->all();
        $checkKey = CommonService::checkKey(['zp_id', 'brand_name','version','pg_goodsname','good_code','is_delect','cd_id','gs_id','gs_bid','pieces'],$input);
        if($checkKey['code'] != 1){
            return ['Data' => [], 'ErrorMessage' => '参数'.$checkKey['data'].'未填写,或值为空', 'ErrorCode' => ErrorInc::INVALID_PARAM];
        }
        CommonService::addLog('库房添加/编辑商品', json_encode($input), '','warehouse-updatagood');
        if($input['zp_id']<1){
            return $this->error('商品id错误', ErrorInc::INVALID_PARAM);exit;
        }
        unset($input['time']);
        unset($input['signature']);
        $session = InterFaceService::getDefaultUser();//默认一个管理账号作为同步数据主账号
        $result = GoodsService::updateWarehouseGood($input,$session);
        return $this->error($result['ErrorMessage'], $result['ErrorCode']);exit;
    }


    /**
     * @name 获取凭证图片
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2022/3/1
     */
    public function getPicByRefundId(Request $request){
        $data = $this->checkedToken($request->input('time'), $request->input('signature'));
        if($data->original['ErrorCode']!=1) return $data->original;

        if(!$request->filled('refund_id')||(intval($request->input('refund_id'))<=0)){
            return $this->error('参数错误退款ID不能这空', ErrorInc::FAILED_PARAM, []);exit;
        }
        $refundId = $request->input('refund_id');
        $info = SubmitPlease::where('refund_id',$refundId)->select('id','submit_sys_num')->first();
        if(!$info)
        {
            return $this->error('不存在', ErrorInc::MYSQL_FAILED);
        }
        $order_num = OrderService::getOrderBy('sys_num', $info['submit_sys_num'],['order_num']);

        $res = Db::table('pictures')->where('sett_wat_num',$info['submit_sys_num'])->where('sp_id',$info['id'])->value('upload_pictures');

        if($res){
            $ret['refund_id'] = $refundId;
            $ret['order_num'] = $order_num;
            $ret['pic'] = $res;
            return $this->success('获取成功',$ret);exit;
        }else{
            return $this->error('暂无数据', ErrorInc::MYSQL_FAILED);exit;
        }

    }

    /**|---------------------------------------------------------------------------------
     * @name 添加库存sku绑定
     * @param string goods_id 商品id
     * @param string sku_id 平台商品id
     * @param string tm_goodn 天猫商品名
     * @param string tm_state 1启用  2停用
     * @param string pt_id 平台id
     * @param string goods_name 品牌/系列/商品名称
     * @param string goods_number 商品编号
     * @param string company_type 所属公司类别：1极限2其他
     * @param string admin_name 操作人
     * @param string time 请求时间
     * @param string signature 签名字段
     * @param string tb_selfprice sku绑定的价格
     * @param string company_id 公司id
     * @param string tm_position sku绑定车膜的部位
     * @param string tm_type 绑定商品类型：1正常；2赠品；
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2022/5/11 13:54
     * |---------------------------------------------------------------------------------
    */
    public function addTmBound ( Request $request ){
        $data = $this->checkedToken($request->input('time'), $request->input('signature'));
//        if($data->original['ErrorCode']!=1) return $data->original;
        $input = $request->all();
        CommonService::addLog('库房添加绑定sku', json_encode($input), '','warehouse-boundsku');
        $array = ['goods_id', 'sku_id','tm_goodn','tm_state','pt_id','goods_name','goods_number','company_type','admin_name','time','signature','tb_selfprice','company_id','tm_position','tm_type'];
        $checkKey = CommonService::checkKey($array,$input);
        if($checkKey['code'] != 1){
            return ['Data' => [], 'ErrorMessage' => '参数'.$checkKey['data'].'未填写,或值为空', 'ErrorCode' => ErrorInc::INVALID_PARAM];
        }
        unset($array[array_search('signature',$array)]);
        unset($array[array_search('pt_id',$array)]);
        $array = CommonService::resetListKey($array);
        DB::beginTransaction(); //开启事务
        $sku_id = DB::table('tm_bound')->where("sku_id",$input['sku_id'])->first();
        if($sku_id){
            $raa = DB::table('tm_bound')->where("sku_id",$input['sku_id'])->delete();
            if(!$raa){
                DB::rollback();
                return $this->error('操作失败tmd',ErrorInc::MYSQL_FAILED);
            }
        }
        $pt_ids = PlatformService::getPtBy('zp_id', $input['pt_id'],['id','pt_name'],'first');
        if($pt_ids){
            $pt_id = DB::table('pt_terrace')->where("ter_pt_id",$pt_ids['id'])->value('id');
            if(!$pt_id){
                $poss['ter_tmall_name'] = $pt_ids['pt_name'];
                $poss['ter_pt_id'] = $pt_ids['id'];
                $poss['ter_company_type'] = $input['company_type'];
                $poss['ter_admin_name'] = $input['admin_name'];
                $poss['ter_time'] = $input['time'];
                $poss['company_id'] = $input['company_id'];
                $pt_id = DB::table('pt_terrace')->insertGetId($poss);
            }
            if(!$pt_id){
                DB::rollback();
                return $this->error('操作失败te',ErrorInc::MYSQL_FAILED);
            }
            foreach($input as $k => $v){
                if(in_array($k, $array)){
                    $tm[$k] = $v;
                }
            }
            $tm['pt_id'] = $pt_id;
            $res = DB::table('tm_bound')->insertGetId($tm);
            if($res){
                DB::commit();
                return $this->success('操作成功');
            }else{
                DB::rollback();
                return $this->error('操作失败tm',ErrorInc::MYSQL_FAILED);
            }
        }else{
            return $this->success('操作成功');
        }
    }

    /**
     * @name 检查token
     * @param $time
     * @param $signature
     * @return mixed
     * @author du
     * @date 2022/1/6
     */
    public function checkedToken($time,$signature){
        if (empty($time) || empty($signature)) {
            return $this->error('time或 signature 不能为空', ErrorInc::INVALID_PARAM);
        }
        //校验token
        $token = md5($time.'97e11cbcc29cbd8a538395abce85d569');

        if($signature !== $token){
            return $this->error('秘钥错误', ErrorInc::INVALID_PARAM);
        }else{
            return $this->success('成功');
        }

    }



}
