<?php
/**
 * 文件名称（添加天猫定单）
 * @author Du
 * @Date: 2024/03/25
 * @Time: 14:56
 * @version 1.0
 * @copyright BlueCity
 */
namespace App\Http\Controllers\Api;
use App\Http\Controllers\BaseController;
use App\Http\Controllers\Common\CommonController;
use App\Models\Admin;
use App\Models\JdBound;
use App\Models\OrderList;
use App\Models\Orders;
use App\Models\PjGoods;
use App\Models\ServicePointsmonth;
use App\Models\SetmoneyType;
use App\Models\SettlementCount;
use App\Services\CommonService;
use App\Services\OrderaddService;
use Illuminate\Http\Request;
use DB;
use BlueCity\Core\Inc\ErrorInc;


class AddTmOrderController extends BaseController{
    public function addOrderByTm(Request $request){
        $input = $request->all();
        if(empty($input)){
            $json = file_get_contents("php://input");
            $input = json_decode($json,true);
        }
        CommonService::addLog('获取订单', json_encode($input), 111,'TmOrder-addOrder');
        $p_id = 16;
        $g_id = 4;
        //workOrderRO  p_id=16
        $arr = [];
        $arr_goods = [];
        foreach ($input['workOrderRO'] as $k =>$v){
            $sku_ids = array_unique(array_column($v['items'], 'skuId'));
            // DB::connection()->enableQueryLog();
            $goods_ids = DB::table('tm_bound')->whereIn('sku_id',$sku_ids)->pluck('goods_id','sku_id');
            //print_r(DB::getQueryLog());
            // dump($goods_ids);
            $goods_ids = CommonService::dataToArray($goods_ids);
            // dump($goods_ids);
            if(empty($goods_ids)){
                CommonService::addLog('SKU_all_no',json_encode($sku_ids) , '1111','TmOrder-SKU_no');
                $goods_ids = $g_id;
            }
            $goods_idss = DB::table('tm_bound')->whereIn('sku_id',$sku_ids)->pluck('goods_id');
            $goods_idss = CommonService::dataToArray($goods_idss);
            if(empty($goods_idss)){
                $goods_idss = $g_id;
               // echo 1;
                $goods = PjGoods::where('pg_id',$goods_idss)->select('pg_id','brand_name','pg_series','version','goods_pic_path','national_version')->first();
            }else{
                $goods = PjGoods::whereIn('pg_id',$goods_idss)->select('pg_id','brand_name','pg_series','version','goods_pic_path','national_version')->get();
                $goods = CommonService::jointArrayKey($goods, 'pg_id');
            }

         //   $goods = PjGoods::whereIn('pg_id',$goods_idss)->select('pg_id','brand_name','pg_series','version','goods_pic_path','national_version')->get();


            //存订单
            $eisit_jd = DB::table('tm_proprietary')->where('order_id',$v['workOrderId'])->value('id');
            // dump($arr);
            if(!$eisit_jd){
                if(in_array($v['workOrderId'], array_column($arr, 'order_id'))){
                    unset($arr[$k]);
                    // echo 2;echo '---'.$v['orderId'].'---';
                }
                $arr[$k]['order_id'] = $v['workOrderId'];
                $arr[$k]['admin_acc'] = '系统';
                $arr[$k]['pt_id'] = $p_id;
                $arr[$k]['pay_type'] = '在线支付';
                $arr[$k]['shopName'] = $v['shopName'];
                $arr[$k]['appKey'] = $v['appKey'];
                $arr[$k]['serverName'] = $v['serverName'];
                $arr[$k]['order_remark'] = json_encode($v['orderNotes']);
                $arr[$k]['order_start_time'] = $v['createTime'];//date('Y-m-d H:i:s',$v['createTime']/1000);
                $arr[$k]['parentNo'] = $v['parentNo'];

                $arr[$k]['queryFailCount'] = $v['queryFailCount'];

                $arr[$k]['serverOrderId'] = $v['serverOrderId'];//

                $arr[$k]['serverCode'] = $v['serverCode'];
                $arr[$k]['serverMode'] = $v['serverMode'];
                $arr[$k]['serverNum'] = $v['serverNum'];

                $arr[$k]['appointmentTime'] = $v['appointmentTime'];

                $arr[$k]['userPhone'] = $v['userPhone'];
                $arr[$k]['receiveAddress'] = $v['receiveAddress'];
                $arr[$k]['extJson'] = $v['extJson'];
                $arr[$k]['is_show'] = 1;
                $arr[$k]['channel'] = 0;
                $arr[$k]['tmWorkOrderId'] = $v['tmWorkOrderId'];
                $arr[$k]['parent_orderid'] = 0;
                DB::table('tm_proprietary')->insert($arr[$k]);
                unset($arr[$k]);

            }

            //存商品
            //`gone_jdgoods` (`order_id`,`pt_id`,`sku_id`,`sku_name`,`item_total`,`jd_price`,`jd_cost`)
            $resjdgoods = DB::table('tmgoods')->where("order_id",$v['workOrderId'])->value('id');
            if(!$resjdgoods){
                if(in_array($v['workOrderId'], array_column($arr_goods, 'order_id'))){
                    unset($arr_goods[$k]);
                    // echo 1;echo '---'.$v['orderId'].'---';
                }
                foreach($v['items'] as $kk => $vv){
                    $arr_goods[$kk]['order_id'] = $v['workOrderId'];
                    $arr_goods[$kk]['pt_id'] = $p_id;
                    $arr_goods[$kk]['sku_id'] = $vv['skuId'];
                    $arr_goods[$kk]['itemNumber'] = $vv['itemNumber'];
                    $arr_goods[$kk]['skuCode'] = $vv['skuCode'];
                    $arr_goods[$kk]['model'] = $vv['model'];
                    $arr_goods[$kk]['brandName'] = $vv['brandName'];
                    DB::table('tmgoods')->insert($arr_goods[$kk]);
                    unset($arr_goods[$kk]);

                    $goodid = $goods_ids[$vv['skuId']]??4;
                    $goods_res = $goods[$goodid];
                    //    dd($goods_res);
                    if ($goods_res['pg_series'] == '') {
                        $type = $goods_res['version'];
                    } else {
                        $type = $goods_res['pg_series'] . "-" . $goods_res['version'];
                    }
                    $goods_name = $goods_name . $goods_res['brand_name'] . "," . $type . "," . $goods_res['general_version'] . ",";
                    $good_brand[] = $goods_res['brand_name'];

                    $orderMsgData[$kk]['goods_id'] = $goodid;
                    $orderMsgData[$kk]['goods_name'] = $vv['brandName'] . "-" . $vv['model'];
                    $orderMsgData[$kk]['goods_price'] = 0;//实收/商品单价
                    $orderMsgData[$kk]['goods_paid'] = 0;
                    $orderMsgData[$kk]['goods_num'] = $vv['itemNumber'];
                    $orderMsgData[$kk]['goods_brand'] = $vv['brandName'];
                    $orderMsgData[$kk]['goods_number'] = $vv['model'];
                    $orderMsgData[$kk]['cd_id'] = 1;

                }
            }

            $exsit = Orders::where('order_num',$v['workOrderId'])->value('id');
            if(!$exsit){
                $sys_num = 'L'.date("YmdHis").str_pad(rand(0,999),3,'0',STR_PAD_LEFT);
                $orders[$k]['sys_bh'] = $sys_num;
                $orders[$k]['skb_bh'] = $v['workOrderId'];
                $orders[$k]['pt_id'] = $p_id;
                $orders[$k]['ser_type'] = 1;//服务类型：1上门安装，2到店服务
                $orders[$k]['shr_name'] = $v['userName']??'空';
                $orders[$k]['shr_phone'] = $v['userPhone'];//
                $orders[$k]['shr_sheng'] = $v['receiveAddress'];//
                $orders[$k]['shr_shi'] = $v['receiveAddress'];//
                $orders[$k]['shr_xian'] = $v['receiveAddress'];//
                $orders[$k]['shr_adress'] = $v['receiveAddress'];//
                $orders[$k]['shr_other'] = '接单后10分钟内务必联系客户核实车型跟安装时间！不断电安装、如果无法完成 请立刻反馈我们处理~！';
                $orders[$k]['car_audit'] = 3;//1:新订单；2：可派单；3：处理中
                $orders[$k]['order_type'] = 1;//订单类型：1：普通；20加急；10：夜间
                $orders[$k]['order_time'] = $v['createTime'];//date('Y-m-d H:i:s',$v['createTime']/1000);
                $orders[$k]['pay_type'] = 1;//支付方式：1在线支付；2货到付款
                $orders[$k]['goods'] = $orderMsgData;
                //   $session = $request->get('session_token');//获取操作人信息
                $session['admin_groupnew'] = 7;
                $session['admin_acc'] = '系统录入';
                $session['id'] = 1133;
                $orders['company_id'] = 1;
                // dump($orders[$kk]);
                $ip = $_SERVER["REMOTE_ADDR"];
                $return = OrderaddService::addOrder($orders[$k], $session, $ip);
                return $return;
                //if($return['ErrorCode']==1)
                //    dump($return);
                CommonService::addLog('添加定单', json_encode($return), $v['orderId'],'jdAPI_addOrder');
            }else{
                return $this->error('已存在', ErrorInc::MYSQL_FAILED);
            }

        }


    }

}
