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


class AddTmOrderController extends BaseController{
    /**
     * @name 添加天猫订单
     * @param Request $request
     * @return array
     * @author du
     * @date 2024/3/26
     * @Time: 9:01
     */
    public function addOrderByTm(Request $request){
     //   CommonService::addLog('访问', 11, 111,'TmOrder-addOrder');
  		$input = $request->all();
        if(empty($input)){
            $json = file_get_contents("php://input");
            $input = json_decode($json,true);
            CommonService::addLog('获取订单', $json, 111,'TmOrder-addOrder');
        }else{
            CommonService::addLog('获取订单', json_encode($input), 111,'TmOrder-addOrder');
        }

        $p_id = 29;
        $g_id = 10246;
        //workOrderRO  p_id=16
        $arr = [];
        $arr_goods = [];

        $default_addptId = ['1','11'];
        $post = $input;

            if($post['shopName']){
                $p_id = Pt::where('pt_name',$post['shopName'])->value('id');
                if(!$p_id){
                    //创建平台
                    $pt_name = '天猫服务－'.$post['shopName'];
                    $p_id = Pt::where('pt_name',$pt_name)->value('id');
                    if(!$p_id){
                        $p_id = PlatformService::creactPt('T', $pt_name, '天猫服务单自动添加',1,1,2,1,0,0,0,3);
                        $admin_add = AdminService::getAdmins(['company_id_searchin'=>$default_addptId,'admin_groupnew_noteq'=>2],['id','admin_pt_id']);
                        foreach ($admin_add as $key => $val) {
                            $admin_pt_id = trim($val['admin_pt_id'],',');
                            $admin_pt_id .=",".$p_id;
                            Admin::where("id",$val['id'])->update(['admin_pt_id'=>$admin_pt_id]);
                            $k = 'Login'.$val['id'];
                            $token = AdminToken::where("at_adminid",$val['id'])->first();
                            $token = CommonService::dataToArray($token);
                            if($token){
                                $token['at_permissions'] = json_decode($token['at_permissions'],true);

                                $token['at_perm'] = json_decode($token['at_perm']);
                                unset($token['at_perm']);
                                $token['at_permissions']['admindata']['admin_pt_id'] = $admin_pt_id;
                                AdminToken::where("at_adminid",$val['id'])->update(['at_permissions'=>json_encode($token['at_permissions'])]);
                                RedisService::redisSet($k, json_encode($token));
                            }
                        }
                    }


                }
            }


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

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

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

            $arr[$k]['serverCode'] = $post['serverCode']??'';
            $arr[$k]['serverMode'] = $post['serverMode']??'';
            $arr[$k]['serverNum'] = $post['serverNum'];

            $arr[$k]['appointmentTime'] = $post['appointmentTime']??'';

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

        }


        if(!isset($post['items'])){
            $item = json_decode($post['extJson'],true);
            $post['items'] = json_decode($item['goodsInfo'],true);
           // dd($post['items']);
            $items[] = $post['items'];
            $sku_ids = array_unique(array_column($items, 'goodsId'));
        }else{
            $sku_ids = array_unique(array_column($post['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 = JdBound::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');
            }

            //存商品
            //`gone_jdgoods` (`order_id`,`pt_id`,`sku_id`,`sku_name`,`item_total`,`jd_price`,`jd_cost`)
            $resjdgoods = DB::table('tmgoods')->where("order_id",$post['workOrderId'])->value('id');
            if(!$resjdgoods){
                if(isset($items)){
                    foreach($items as $kk => $vv){
                        if(in_array($post['workOrderId'], array_column($arr_goods, 'order_id'))){
                            unset($arr_goods[$kk]);
                        }
                        $arr_goods[$kk]['order_id'] = $post['workOrderId'];
                        $arr_goods[$kk]['pt_id'] = $p_id;
                        if(isset($vv['skuId'])){
                            $arr_goods[$kk]['sku_id'] = $vv['skuId'];
                            $arr_goods[$kk]['itemNumber'] = $vv['itemNumber'];
                            $arr_goods[$kk]['model'] = $vv['model'];
                        }else{
                            $arr_goods[$kk]['sku_id'] = $vv['goodsId'];
                            $arr_goods[$kk]['itemNumber'] = $vv['saleNum'];
                            $arr_goods[$kk]['model'] = $vv['goodsName'];
                        }

                        $arr_goods[$kk]['skuCode'] = $vv['skuCode']??'';

                        $arr_goods[$kk]['brandName'] = $vv['brandName']??'';

                        DB::table('tmgoods')->insert($arr_goods[$kk]);
                        unset($arr_goods[$kk]);
                    }
                }else{
                    foreach($post['items'] as $kk => $vv){
                        if(in_array($post['workOrderId'], array_column($arr_goods, 'order_id'))){
                            unset($arr_goods[$kk]);
                        }

                        $arr_goods[$kk]['order_id'] = $post['workOrderId'];
                        $arr_goods[$kk]['pt_id'] = $p_id;
                        if(isset($vv['skuId'])){
                            echo 1;
                            $arr_goods[$kk]['sku_id'] = $vv['skuId'];
                            $arr_goods[$kk]['itemNumber'] = $vv['itemNumber'];
                            $arr_goods[$kk]['model'] = $vv['model'];
                        }else{
                            echo $vv['goodsId'];
                            $arr_goods[$kk]['sku_id'] = $vv['goodsId'];
                            $arr_goods[$kk]['itemNumber'] = $vv['saleNum'];
                            $arr_goods[$kk]['model'] = $vv['goodsName'];
                        }

                        $arr_goods[$kk]['skuCode'] = $vv['skuCode']??'';

                        $arr_goods[$kk]['brandName'] = $vv['brandName']??'';

                        DB::table('tmgoods')->insert($arr_goods[$kk]);
                        unset($arr_goods[$kk]);
                    }
                }


            }

            if(isset($items)){
                foreach ($items as $kkk =>$vvv){
                    if(isset($vvv['skuId'])){
                        $goodid = $goods_ids[$vvv['skuId']]??4;
                    }else{
                        $goodid = $goods_ids[$vvv['goodsId']]??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'];

                    if(!isset($vvv['model'])){
                        $vvv['model'] = $vvv['goodsName'];
                        $vvv['itemNumber'] = $vvv['saleNum'];
                    }

                    if($goodid==4){
                        $orderMsgData[$kkk]['goods_name'] = $vvv['brandName'] . "-" . $vvv['model'];
                        $orderMsgData[$kkk]['goods_brand'] = $vvv['brandName']??'';
                        $orderMsgData[$kkk]['goods_number'] = $vvv['model'];

                    }else{
                        $orderMsgData[$k]['goods_name'] = $goods_res['brand_name'] . "-" . $type;
                        $orderMsgData[$k]['goods_brand'] = $goods_res['brand_name'];
                        $orderMsgData[$k]['goods_number'] = $type;
                    }
                    $orderMsgData[$kkk]['goods_id'] = $goodid;
                    $orderMsgData[$kkk]['goods_price'] = 0;//实收/商品单价
                    $orderMsgData[$kkk]['goods_paid'] = 0;
                    $orderMsgData[$kkk]['goods_num'] = $vvv['itemNumber'];
                    $orderMsgData[$kkk]['cd_id'] = 1;

                }
            }else{
                foreach ($post['items'] as $kkk =>$vvv){
                    if(isset($vvv['skuId'])){
                        $goodid = $goods_ids[$vvv['skuId']]??4;
                    }else{
                        $goodid = $goods_ids[$vvv['goodsId']]??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'];

                    if(!isset($vvv['model'])){
                        $vvv['model'] = $vvv['goodsName'];
                        $vvv['itemNumber'] = $vvv['saleNum'];
                    }

                    if($goodid==4){
                        $orderMsgData[$kkk]['goods_name'] = $vvv['brandName'] . "-" . $vvv['model'];
                        $orderMsgData[$kkk]['goods_brand'] = $vvv['brandName']??'';
                        $orderMsgData[$kkk]['goods_number'] = $vvv['model'];

                    }else{
                        $orderMsgData[$k]['goods_name'] = $goods_res['brand_name'] . "-" . $type;
                        $orderMsgData[$k]['goods_brand'] = $goods_res['brand_name'];
                        $orderMsgData[$k]['goods_number'] = $type;
                    }
                    $orderMsgData[$kkk]['goods_id'] = $goodid;
                    $orderMsgData[$kkk]['goods_price'] = 0;//实收/商品单价
                    $orderMsgData[$kkk]['goods_paid'] = 0;
                    $orderMsgData[$kkk]['goods_num'] = $vvv['itemNumber'];
                    $orderMsgData[$kkk]['cd_id'] = 1;

                }
            }


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

                // dump($orders[$kk]);
                $ip = $_SERVER["REMOTE_ADDR"];
                $return = OrderaddService::addOrder($orders[$k], $session, $ip);
                CommonService::addLog('添加定单', json_encode($return), $post['orderId'],'jdAPI_addOrder');
                return $return;
                //if($return['ErrorCode']==1)
                //    dump($return);

            }else{
                return $this->error('已存在', ErrorInc::MYSQL_FAILED);
            }

     //   }


    }

    /**
     * @name 取消订单
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2024/3/26
     * @Time: 14:44
     */
    public function CancelOrder(Request $request){
/*
        $arr_up['workOrderId'] = '256485555';
        $arr_up['code'] = '89562';
        $arr_up['timestamp'] = time().'000';


        if($_SERVER["HTTP_HOST"]=='zptz.bluearp.com') {
            $arr_up['appKey'] = '';
            $arr_up['app_key'] = '';
            $arr_up['sign'] = $this->getSign($arr_up,'');
            $url = 'https://opengw.ncarzone.com/api/workorder/uploadworker?';
        }else{
            $arr_up['appKey'] = '2024032216801'; //b1e5c75530052abf221bfc9f3d2a591bdfa4ed7f
            $arr_up['app_key'] = '2024032216801';
            $arr_up['sign'] = $this->getSign($arr_up,'b1e5c75530052abf221bfc9f3d2a591bdfa4ed7f');
            $url = 'https://opensandbox.ncarzone.com/api/workorder/uploadworker?';
        }
         ksort($arr_up);
        foreach( $arr_up as $k => $post ){
            if(strpos($v,' ')){
                $urldata[] = $k."=".urlencode ($v);
            }else{
                $urldata[] = $k."=".$v;
            }
        }
        $urldata = implode("&",$urldata);

       // $url = $url.$urldata;
       // echo $url;
        $url = 'https://opensandbox.ncarzone.com/api/workorder/verifyV2';

      //  CommonService::addLog('接单', $url, $orderListArr['order_num'],'TmOrder-get5Order');
        //$ret_up = $this->http_get($url);
         $ret_up = CommonService::requestPost($url, $urldata);

       // CommonService::addLog('接单', $ret_up.'---'.json_encode($arr_up).'---'.$url,1111,'TmOrder-getOrder');
        return $ret_up;



        exit;*/
        $input = $request->all();
        if(empty($input)){
            $json = file_get_contents("php://input");
            $input = json_decode($json,true);
        }
        CommonService::addLog('取消订单', json_encode($input), 111,'TmOrder-CancelOrder');


            $input['appKey'] = '2024032216801'; //b1e5c75530052abf221bfc9f3d2a591bdfa4ed7f
            $input['app_key'] = '2024032216801';
            $sign = $this->getSign($input,'b1e5c75530052abf221bfc9f3d2a591bdfa4ed7f');

        $order_num = $input['workOrderId'];
        $info = Orders::where('order_num',$order_num)->first();
        $info = CommonService::dataToArray($info);
        if(empty($info)){
            CommonService::addLog('无此订单', json_encode($input), $order_num,'TmOrder-CancelOrder');
            return $this->error('无此订单', ErrorInc::MYSQL_FAILED);
        }
        if($info['order_status']<=20){
            Orders::where('order_num',$order_num)->update(['order_status'=>50,'lock_type'=>2]);
            OrderList::where('order_num',$order_num)->update(['stauas'=>50,'locklist_type'=>2]);
        }else{
            $data['allprice'] = $info['new_money'];
            $goods_arr = OrderMsg::where('sys_num',$info['sys_num'])->get(['id as msg_id','goods_name','goods_price','goods_id as good_id']);

            $data['goodsArr'] = CommonService::dataToArray($goods_arr);
            $data['goods_state'] = 2;//2:平台; 4:财务
            $data['sys_num'] = $info['sys_num'];
            $data['order_num'] = $info['order_num'];
            $data['apply_type'] = 1;
            $data['content'] = $input['cancelReason']??'无';
            $data['p_id'] = $info['p_id'];
            $data['ser_id'] = $info['ser_id'];
            $data['new_customer_id'] = $info['new_customer_id'];
            $data['order_status'] = $info['order_status'];
            $data['create_time'] = $info['create_time'];
            $userArr = User::where('id',$info['new_customer_id'])->first();
            $session['admin_groupnew'] = 7;
            $session['admin_acc'] = '系统录入';
            $session['id'] = 1133;
            $session['company_id'] = 1;

            $ret = OrderService::lockByRefund($data , $session , $userArr);
            CommonService::addLog('锁定退单', json_encode($ret), $order_num,'TmOrder-CancelOrder');
            return $ret;

        }


    }

    private function getSign($params,$sec) {
        if ($params != null) { // 所有请求参数按照字母先后顺序排序
            ksort($params);
            // 定义字符串开始 结尾所包括的字符串
            $stringToBeSigned = $sec;//'eb229319be99494583fe87810b608123';//'8de8b7903e7740abb9ac6ec39f22c0e5';
            // 把所有参数名和参数值串在一起
            foreach ($params as $k => $v) {
                $stringToBeSigned .= "$k$v";
            }
            unset($k, $v);

            // 把venderKey加在字符串的两端
            $stringToBeSigned .= $sec;//'eb229319be99494583fe87810b608123';//'8de8b7903e7740abb9ac6ec39f22c0e5';
        } else {
            // 定义字符串开始 结尾所包括的字符串
            $stringToBeSigned = $sec;//'eb229319be99494583fe87810b608123';//'8de8b7903e7740abb9ac6ec39f22c0e5';
            // 把venderKey加在字符串的两端
            $stringToBeSigned .= $sec;//'eb229319be99494583fe87810b608123';//'8de8b7903e7740abb9ac6ec39f22c0e5';
        }
        // 使用MD5进行加密，再转化成大写

        // return strtoupper(md5($stringToBeSigned));
        // 使用MD5进行加密，再转化成小写
        return strtolower(md5($stringToBeSigned));
    }

    /**
     * @name 拆分地址
     * @param $address
     * @return array
     * @author du
     * @date 2024/3/26
     * @Time: 9:13
     */
    public function disAdderss($address){
        preg_match('/(.*?(省|自治区|北京市|天津市))/', $address, $matches);
        if (count($matches) > 1) {
            $province = $matches[count($matches) - 2];
            $address = str_replace($province, '', $address);
        }
        preg_match('/(.*?(市|自治州|地区|区划|县))/', $address, $matches);
        if (count($matches) > 1) {
            $city = $matches[count($matches) - 2];
            $address = str_replace($city, '', $address);
        }
        preg_match('/(.*?(区|县|镇|乡|街道))/', $address, $matches);
        if (count($matches) > 1) {
            $area = $matches[count($matches) - 2];
            $address = str_replace($area, '', $address);
        }

        return [
            'province' => isset($province) ? $province : '无',
            'city' => isset($city) ? $city : $province,
            'area' => isset($area) ? $area : '无',
            'address' => isset($address) ? $address : '',
        ];
    }

}
