<?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 OrdersTmController 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-Tmadd');
        $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(in_array($value['sku_id'], ['953857604052','953287477741'])){
                    //猫超卡跳过添加
                    continue;
                }
                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'],'',3);//这个函数需要完善下
                    if($value['sku_id']!=$value['goods_id'] && empty($goodss)){
                        $goodss = GoodsService::getGoodsByCode($value['goods_id'],'',3);//这个函数需要完善下
                    }
                    $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 =  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, '系统同步', 164);
                        }
                    }else{
                        CommonService::accMe($input['sys_bh'], '客户车型', $car_not, '', 2, 7, '系统同步', 164);
                    }
                }
                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'], 164);
                        }
                    }
                }
                $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'] = 164;
                $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 = true;//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']);
            }
//        }
    }
    /**
     * @name 退款
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2022/1/11
     */
    public function refundGoods(Request $request){
        $input = $request->all();
        $checkKey = CommonService::checkKey(['tid'],$input);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
            $flag = 1;
            $refundlist = RefundService::getInfoByKeyValue('order_num', $input['tid'], ['state', 'roPreNo']);
            if ($refundlist) {
                return $this->error('已存在退款', '2003');exit;
                $flag = 2;
            }
            if ($flag == 1) {
                $refund['order_num'] = $input['tid'];
                $refund['refund'] = 1;
                $reason = $input['reason']??'';
                $refund['content'] = '平台订单已撤销'.$reason;
                $refund['urgent'] = 1;
                $refund['recycle_type'] = 0;
                $refund['roPreNo'] = $input['tid'];
                $sys_num = OrderService::getOrderBy('order_num', $input['tid'], ['sys_num', 'order_status', 'new_money']);
                if ($sys_num) {
                    $refund['sys_num'] = $sys_num['sys_num'];
                    $msg = OrderService::getOrderMsg($sys_num['sys_num']);
                    if ($msg['orderMsgArr']) {
                        $msg = $msg['orderMsgArr'];
                        $goodsArr = [];
                        foreach ($msg as $ka => $va) {
                            $goodsArr[$ka]['goods_name'] = $va['goods_name'];
                            $goodsArr[$ka]['goods_price'] = $va['goods_price'];
                            $goodsArr[$ka]['msg_id'] = $va['id'];
                            $goodsArr[$ka]['goods_num'] = $va['goods_num'];
                            $goodsArr[$ka]['goods_id'] = $va['goods_id'];
                        }
                        $refund['goodsArr'] = $goodsArr;
                        $refund['goods_state'] = 2;
                        $refund['info_ing'] = '';
                        $refund['info_acc'] = '';
                        $refund['info_name'] = '';
                        $refund['addType'] = 'tmRefund';
                        $refund['allprice'] = $sys_num['new_money'];
                        $session['id'] = '164';
                        $session['admin_acc'] = '系统操作';
                        $session['admin_groupnew'] = 7;
                        $rea = OrderService::lockOrder($refund, $session, '39.105.188.64');
                        return $this->error($rea['ErrorMessage'], $rea['ErrorCode']);exit;
                    } else {
                        return $this->error('无订单商品', '2001');exit;
                    }

                } else {
                    return $this->error('无订单号', '2002');exit;
                }
            }

    }


    /**
     * @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('成功');
        }

    }



}
