<?php
/**
 * 文件名称（同步服务单接口）
 * 文件简单描述（用于同步第三方服务单）
 * @author DouBin
 * @Date: 2021/9/27
 * @Time: 14:39
 * @Email: db@sudianwang.com
 * @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\AdminToken;
use App\Models\JdSynchronous;
use App\Models\OrderList;
use App\Models\OrderMsg;
use App\Models\Orders;
use App\Models\SettlementList;
use App\Models\User;
use App\Services\AdminService;
use App\Services\CommonService;
use App\Services\GoodsService;
use App\Services\JdBoundService;
use App\Services\JdSynchronousService;
use App\Services\OrderaddService;
use App\Services\OrderService;
use App\Services\PlatformService;
use App\Services\RedisService;
use App\Services\UserService;
use BlueCity\Data\Service\ZhiPei\OrderService as zhiPeiOrder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use DB;
use BlueCity\Core\Inc\ErrorInc;
use PhpParser\Node\Stmt\Foreach_;


class AddServiceOrderController extends BaseController
{
    /**|---------------------------------------------------------------------------------
     * @name 添加服务单接口
     * @param json data 平台同步数据
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/9/27 14:44
     * |---------------------------------------------------------------------------------
    */
    public function add_order ( Request $request ){
        // 开始处理获取的数据，
        // 最终的目的是让 $ar 等于 请求的serviceBills参数
//        $inputdata = $request->input('data');
        $filename = 'OT2SX'.date('Ym');
//        $inputdata = self::getTestData();
        $inputdata = $request->input('data');
        CommonService::addLog('添加京东服务单', $inputdata, '无','addservicedata');
        $post_arr = json_decode($inputdata,true);
        $order_list = $post_arr['serviceBills'];
        $default_addptId = ['670','1663'];
        $bc_flag = 0;//用于生成系统单号累加使用确保循环中系统单号不重复
        $flag = 1;
        foreach($order_list as $ord_k => $ord_v){
            $pt_name = (string)$ord_v['shopName'];
            if($pt_name == ""){
                //平添不存在时添加日志需了解
                CommonService::addLog('获取平台名称失败', $ord_v, $ord_v['orderId'],$filename);
//                logRecord(['msg'=>'获取平台名称失败','data'=>$ord_v,'time'=>date("Y-m-d H:i:s")],'Filminstall'.date("Ym"));
                continue;
            }
            $new_customer_id = OrderService::getOrderBy('order_num', $ord_v['orderId'],['new_customer_id']);
            $userphone = UserService::getUserBy('id', $new_customer_id,['shr_phone']);
            if($userphone){
                $is_jdservice=1;
                $ord_v['consMobile']=$userphone;
                $ord_v['consTel']=$userphone;
            }else{
                $is_jdservice=2;
                $res_phone=$this->GetJDtempPhone($ord_v['orderId']);
                if($res_phone){
                    $ord_v['old_consMobile']=$ord_v['consMobile'];
                    $ord_v['old_consTel']=$ord_v['consTel'];
                    $ord_v['consMobile']=$res_phone;
                    $ord_v['consTel']=$res_phone;
                }
            }
            $sku_arr = array_column($ord_v['goods'],'goodId');
            if($pt_name == '京东商城'){
                // $pt_id=11;
                $pt_id = JdBoundService::getBoundBy('sku_id', $sku_arr, ['pt_id'],'first');
                if(!$pt_id){
                    $pt_id = PlatformService::getPtBy('pt_name', $pt_name, ['id'],'first');
                }else{
                    $pt_id = DB::table('pt_terrace')->where("id",$pt_id)->value('ter_pt_id');
                }
            }else{
                $pt_id = PlatformService::getPtBy('pt_name', $pt_name, ['id'],'first');
                if($pt_id && $pt_id == 216){
                    $pt_id = 214;
                }
            }
            $shujudata['sys_bh'] = CommonService::creactSysNum(3);
            $db = DB::table("orders_joingoods");
            $data = CommonService::getMysqlData($db, ['skb_bh'=>$ord_v['orderId']],['o_skbnum','sys_bh']);
            if($data){
                $data[]=['o_skbnum'=>$ord_v['orderId']];
                $shujudata['sys_bh']=(string)$data[0]['sys_bh'];
                $sys_num = array_column($data,'sys_bh');
                $db = new Orders();
                $orders_data = CommonService::getMysqlData($db, ['sys_num_searchin'=>$sys_num],['sys_num','order_num','p_id','order_status','customer_id','new_customer_id']);
                $shr_phone=(string)$ord_v['consTel']??$ord_v['consMobile'];
                $is_jdservice=2;
                $order_status=1;
                if(!empty($orders_data)){
                    $is_jdservice=1;
                    // 如果之前已经添加过了，那么将之前的平台id 赋值给现在的数据；
                    if(empty($pt_id)){
                        $pt_id=$orders_data[0]['p_id'];
                    }

                    foreach ($orders_data as $key => $val) {
                        if($val['order_status']<50) {
                            if ($val['order_status'] > $order_status) {
                                $order_status = $val['order_status'];
                            }
                        }
                    }
                    if($order_status >= 40){
                        CommonService::addLog('安装已完成', json_encode($ord_v), $ord_v['orderId'],$filename);
    //                    logRecord(['msg'=>'安装已完成','data'=>$ord_v,'time'=>date("Y-m-d H:i:s")],'Filminstall'.date("Ym"));
                        continue;
                    }
                    // 将之前的数据删除掉；
                    foreach ($orders_data as $key => $val) {
                        $customer_id[] = $val['customer_id'];
                        $customer_id[] = $val['new_customer_id'];
                        User::whereIn('id',$customer_id)->delete();
                        Orders::where("sys_num",$val['sys_num'])->delete();
                        OrderList::where("sys_num",$val['sys_num'])->delete();
                        SettlementList::where("sys_num",$val['sys_num'])->delete();
                        OrderMsg::where("sys_num",$val['sys_num'])->delete();
                    }
                }
            }else{
                $db = new Orders();
                $order_nums = $ord_v['orderId']."-";
//                $orders_data = CommonService::getMysqlData($db, ['order_num_rlike'=>$order_nums],['sys_num','order_num','p_id','order_status','customer_id','new_customer_id']);
                if($order_nums == '' || $order_nums =='-'){
                    CommonService::addLog('单号异常', $ord_v, $ord_v['orderId'],$filename);
                    //                    logRecord(['msg'=>'安装已完成','data'=>$ord_v,'time'=>date("Y-m-d H:i:s")],'Filminstall'.date("Ym"));
                    continue;
                }
                $orders_data = Orders::whereRaw("order_num = '".$ord_v['orderId']."' or order_num like '".$order_nums."%'")->select('sys_num','order_num','p_id','order_status','customer_id','new_customer_id','lock_type')->get();
                $orders_data = CommonService::dataToArray($orders_data);
                $shr_phone='';
                $is_jdservice=2;
                $order_status=1;
                if(!empty($orders_data)){
                    $shujudata['sys_bh'] = (string)$orders_data[0]['sys_num'];
                    $is_jdservice=1;
                    // 如果之前已经添加过了，那么将之前的平台id 赋值给现在的数据；
                    if(empty($pt_id)){
                        $pt_id=$orders_data[0]['p_id'];
                    }

                    foreach ($orders_data as $key => $val) {
                        if($val['lock_type']==2){
                            CommonService::addLog('订单已经锁定', $ord_v, $ord_v['orderId'],$filename);
                            //                    logRecord(['msg'=>'安装已完成','data'=>$ord_v,'time'=>date("Y-m-d H:i:s")],'Filminstall'.date("Ym"));
                            continue;
                        }
                        if($val['order_status'] >$order_status){
                            $order_status=$val['order_status'];
                        }
                    }
                    if($order_status >= 40){
                        CommonService::addLog('安装已完成', $ord_v, $ord_v['orderId'],$filename);
                        //                    logRecord(['msg'=>'安装已完成','data'=>$ord_v,'time'=>date("Y-m-d H:i:s")],'Filminstall'.date("Ym"));
                        continue;
                    }
                    // 将之前的数据删除掉；
                    $customer_id = [];
                    foreach ($orders_data as $key => $val) {
                        $shr_phone = UserService::getUserBy('id', $val['new_customer_id'],['shr_phone']);
                        $customer_id[] = $val['customer_id'];
                        $customer_id[] = $val['new_customer_id'];
                        User::whereIn('id',$customer_id)->delete();
                        Orders::where("sys_num",$val['sys_num'])->delete();
                        OrderList::where("sys_num",$val['sys_num'])->delete();
                        SettlementList::where("sys_num",$val['sys_num'])->delete();
                        OrderMsg::where("sys_num",$val['sys_num'])->delete();
                    }
                }
            }
            DB::table("orders_joingoods")->where("skb_bh",$ord_v['orderId'])->delete();
//            if(empty($pt_id) || $pt_id >186){
//                $is_jdservice=2;
//            }else{
//                $is_jdservice=1;
//            }
            if(empty($pt_id)){
                // 默认添加平台数据，并且给拥有的人赋权
                $pt_id = PlatformService::creactPt('C', $pt_name, '服务单自动添加',1,1,2,1);
                if(!$pt_id){
                    continue;
                }

                $admin_add = AdminService::getAdmins(['id_searchin'=>$default_addptId],['id','admin_pt_id']);
                foreach ($admin_add as $key => $val) {
                    $admin_pt_id=trim($val['admin_pt_id'],',');
                    $admin_pt_id .=",".$pt_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();
                    if($token){
                        $token['at_permissions'] = json_decode($token['at_permissions']);
                        $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));
                    }
                }
            }
            $shujudata['skb_bh']=$ord_v['orderId'];
            $Incre_key=0;
            $orderId = JdSynchronous::where('order_id',$ord_v['orderId'])->value('id');
            if(!$orderId) {
                $res = JdSynchronousService::creactJdSynchronous($ord_v['consName'], $ord_v['consMobile'], $ord_v['consMobile'], $ord_v['provinceName'], $ord_v['cityName'], $ord_v['countyName'], $ord_v['consAddress'], '系统录入', $pt_id, $ord_v['orderId'], 1, 0, 0, 0, 1, 4, 2, '', $ord_v['outBoundDate']);
            }
            $goods_id = JdBoundService::getBoundBy('sku_id', $sku_arr, ['goods_id','sku_id']);
            $goods_id = false;
            if($goods_id) {
                $goods_id = array_column($goods_id, 'goods_id', 'sku_id');
                $goodsid = array_column($goods_id, 'goods_id');
                $pj_good = GoodsService::getGoodsBy(['pg_id_searchin'=>$goodsid],['pg_id','brand_name','pg_series','version','cd_id','pg_position']);
                $pj_good = CommonService::jointArrayKey($pj_good, 'pg_id');
            }
            foreach($ord_v['goods'] as $k => $v){
                if(!$orderId) {
                    $ress = JdSynchronousService::creactJdGood($pt_id, $ord_v['orderId'], $v['goodId'], $v['goodName'], $v['goodCount'], 0, 0, json_encode($v['verCodeList']), $v['storeName']);
                }
                for ($i=1; $i <=$v['goodCount']; $i++) {
                    if($Incre_key==0){
                        $sys_bh = $shujudata['sys_bh'];
                        $order_num = trim($shujudata['skb_bh']);
                    }else{
                        // 除第一个商品后之后的订单，系统单号后面加值，原始单号后面直接加-1  -2
                        $sys_bh = CommonService::creactSysNum(3,$shujudata['sys_bh'],$Incre_key);
                        $order_num = trim($shujudata['skb_bh']).'-'.$Incre_key;
                    }
                    $user_data=[];
                    $user_data['shr_name'] = (string)$ord_v['consName'];
                    if($shr_phone!=''){
                        $user_data['shr_phone'] = $shr_phone;
                    }else {
                        $user_data['shr_phone'] = $ord_v['consTel'] ?? $ord_v['consMobile'];
                    }
                    $user_data['shr_sheng'] = (string)$ord_v['provinceName'];
                    $user_data['shr_shi'] = (string)$ord_v['cityName'];
                    $user_data['shr_xian'] = (string)$ord_v['countyName'];
                    $user_data['shr_adress'] = (string)$ord_v['consAddress'];
                    $address_len = mb_strlen($user_data['shr_sheng'].$user_data['shr_shi'].$user_data['shr_xian'],"utf-8");
                    if(mb_substr($user_data['shr_adress'],0,$address_len,'utf-8') == ($user_data['shr_sheng'].$user_data['shr_shi'].$user_data['shr_xian'])){
                        $user_data['shr_adress'] = mb_substr($user_data['shr_adress'],$address_len,null,'utf-8');
                    }
                    $user_data['sys_num'] = $sys_bh;
                    $user_data['create_time'] = date("Y-m-d H:i:s");
                    $user_data['shr_code'] = $v['verCodeList'][$i-1];
                    $user_data['company_type'] = 1;
                    $user_data['is_jdservice'] = $is_jdservice;
                    $user_id = User::insertGetId($user_data);

                    $orderMsgData=[];
                    $goodid = $goods_id[$v['goodId']]??'';
                    $goods[0]['goods_price'] = 0;
                    $goods[0]['goods_num'] = 1;
                    $goods[0]['goods_name'] = $pj_good[$goodid]['good_name']??$v['goodName'];
                    $goods[0]['cd_id'] = 3;
                    $goods[0]['goods_brand'] = $pj_good[$goodid]['brand_name']??$v['goodBrandName'];
                    $goods[0]['goods_id'] = 5912;
                    $goods[0]['goods_number'] = $v['goodCatName'];
                    $goods[0]['pg_position'] = $pj_good[$goodid]['pg_position']??'';
                    $goods[0]['ort_goodid'] = $v['goodId'];
                    $newOrderId = OrderaddService::addOrderMsg($goods, '系统录入', $sys_bh,$user_data['shr_code']);
                    $goods_name = $newOrderId['goods_name'];
                    $new_money = $newOrderId['new_money'];
                    CommonService::addLog('添加商品', json_encode($goods), $sys_bh,$filename);

                    $orderjoin_data=[];
                    $orderjoin_data["goods_id"] = 5912;
                    $orderjoin_data["o_sysbh"] = $sys_bh;
                    $orderjoin_data["o_skbnum"] = $order_num;
                    $orderjoin_data["sys_bh"] = $shujudata['sys_bh'];
                    $orderjoin_data["skb_bh"] = $shujudata['skb_bh'];
                    $orderjoin_data["goods_num"] = 1;
                    $orderjoin_data["edit_time"] = date("Y-m-d H:i:s");
                    $orderjoin_data["is_jdservice"] = $is_jdservice;
                    DB::table("orders_joingoods")->insert($orderjoin_data);


                    $orders_data=[];
                    if($pt_name=='京东商城'){
                        // 如果是平台是自营的,则判断之前是否有过订单,如果没有则赋值 新订单，如果有则赋值之前的状态；
                        if($is_jdservice==1){
                            // 如果之前有订单则需要判断之前的订单状态
                            if($order_status >= 10){
                                $orders_data['order_status'] =10;
                            }else{
                                $orders_data['order_status'] =1;
                            }
                        }else{
                            // 如果之前没有则默认赋值 新订单
                            $orders_data['order_status'] =1;
                        }

                    }else{
                        $orders_data['order_status'] =10;
                    }
                    if($is_jdservice==2){
                        $orders_data['order_status'] =1;
                    }
                    $storeName=(string)$v['storeName'];
                    if($storeName != ''){
                        $centent = '京东门店:<strong class="red">'.$storeName.'</strong>';
                        CommonService::accMe($sys_bh, '订单备注',$centent , '', 1, '7', '系统录入', '1133');
                    }
                    $session['admin_acc'] = '系统录入';
                    $session['id'] = '1133';
                    $newOrder = OrderService::insertOrder($orders_data['order_status'], $v['goodName'], $pt_id, $order_num, $sys_bh, $user_id, $new_money, $session, 2, 1, date('Y-m-d H:i:s'),1,$newOrderId['category'],$newOrderId['good_brand']);//添加订单表信息
                    if($newOrder){
                        if(in_array('3', $newOrderId['category']) && $session['id']==670) {
                            $pt = PlatformService::getPtBy('id', $pt_id, ['pt_name','zp_id']);
                            $zhipei['pt_name'] = $pt['pt_name'];
                            $zhipei['pt_id'] = $pt['zp_id'];
//                            $zhipei['pt_name'] = PlatformService::getPtBy('id', $pt_id, ['pt_name']);
                            $zhipei['order_price'] = $new_money;
                            $zhipei['store_name'] = '无';
                            $zhipei['wholestore_name'] = '无';
                            if ($user_data['shr_name']) {
                                $zhipeiuser['shr_name'] = $user_data['shr_name'];
                            } else {
                                $zhipeiuser['shr_name'] = '无';
                            }

                            $zhipeiuser['shr_phone'] = $user_data['shr_phone'];
                            $zhipeiuser['shr_sheng'] = $user_data['shr_sheng'];
                            $zhipeiuser['shr_shi'] = $user_data['shr_shi'];
                            //                $zhipeiuser['shr_xian'] = $user['shr_xian'];
                            if ($user_data['shr_xian'] != '') {
                                $zhipeiuser['shr_xian'] = $user_data['shr_xian'];
                            } else {
                                $zhipeiuser['shr_xian'] = '无';
                            }
                            if ($user_data['shr_adress'] != '') {
                                $zhipeiuser['shr_adress'] = $user_data['shr_adress'];
                            } else {
                                $zhipeiuser['shr_adress'] = '无';
                            }

                            $zhipei['construction_date'] = date("Y-m-d H:i:s");
                            $zhipei['car_brand'] = '';
                            $zhipei['car_frame'] = '';
                            $zhipei['order_status'] = $orders_data['order_status'];//订单状态
                            $zhipeigood = [];
                            foreach ($goods as $k => $v) {
                                //$['cd_id']  商品所属类型
                                $zhipeigoods['goods_name'] = $v['goods_name'];
                                $zhipeigoods['goods_number'] = GoodsService::getGoodsByKey('pg_id', $v['goods_id'], ['general_version']);
                                $zhipeigoods['goods_num'] = $v['goods_num'];
                                $zhipeigoods['goods_brand'] = $v['goods_brand'];
                                $zhipeigoods['goods_price'] = $v['goods_price'];
                                $zhipeigood[$k] = $zhipeigoods;
                            }
                            //print_r($zhipeiuser);
                            $res = zhiPeiOrder::complete($order_num, $zhipei, $zhipeigood, $zhipeiuser);
                            $inputs['data']['zhipei'] = $zhipei;
                            $inputs['data']['zhipeigood'] = $zhipeigood;
                            $inputs['data']['zhipeiuser'] = $zhipeiuser;
                            $inputs['return'] = $res;
                            CommonService::addLog('库房添加服务订单', json_encode($inputs), $order_num,'warehouse-service');
                        }
                    }
                    $Incre_key++;

                    $flag=2;
                }
            }
        }
        if($flag==2){
            echo 2;
        }else{
            echo 1;
        }
    }
    /**
     * 获取京东临时手机号
     */
    public function GetJDtempPhone($orderId){
        $filename = 'OT2SX'.date('Ym');
        $url="116.196.75.172/index.php/JdjxApi/sysUserPhones";
        $data['orderId']=$orderId;
        $res_data = CommonService::requestPost($url, $data);
//        $res_data=$this->https_post($url,$data);

        $res_arr=json_decode($res_data,true);

        if(!is_array($res_arr) || !isset($res_arr['jingdong_getUserVerPhoneByOrderId_search_responce']['response']['data'])){
            CommonService::addLog('获取京东客户的临时手机号失败', $res_data, $orderId,$filename);
            return false;
        }

        $res_arrtwo=$res_arr['jingdong_getUserVerPhoneByOrderId_search_responce']['response']['data'];

        if(!isset($res_arrtwo['verMobil']['tenantCode'])){
            CommonService::addLog('获取京东客户的临时手机号失败', $res_data, $orderId,$filename);
            return false;
        }
        CommonService::addLog('获取京东客户的临时手机号成功', $res_data, $orderId,$filename);

        if(isset($res_arrtwo['verMobil']['extno'])){
            return $res_arrtwo['verMobil']['tenantCode']."-".$res_arrtwo['verMobil']['extno'];
        }

        return $res_arrtwo['verMobil']['tenantCode'];

    }


    /**|---------------------------------------------------------------------------------
     * @name 列表页
     * @param string ju_ordernum 订单单号
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2021/9/30 8:55
     * |---------------------------------------------------------------------------------
    */
    public static function getTestData ( ){
        // 赋值默认数据
         $post_data=[
              "resultCode" => 1,
              "resultMsg" => "OK",
              "serviceBillsSize" =>1,
              "serviceBills" => [
                    [
                        "provinceId" => 1,
                        "cityId" => 2810,
                        "outBoundDate" =>  "2021-01-05 15:07:10",
                        "orderDate" =>  "2021-01-05 14:53:47",
                        "cityName" => "天津",
                        "goods" => [
                                [
                                    "goodCatName" =>  "汽车贴膜",
                                    "serviceName" =>  "贴膜（全车）",
                                    "serviceBillId" =>  "e0692193cd5eada9",
                                    "servicerTel" =>  "022-82939932",
                                    "goodCount" => 1,
                                    "goodBrandName" => "米其林",
                                    "installId" => 10353134,
                                    "goodCatId" => 13979,
                                    "goodName" => "3M 车膜1111111",
                                    "serviceNum" => 1,
                                    "verCodeList" =>["BH975555558"],
                                    "storeName" =>  "北京博瑞2222222222222",
                                    "verValidDate" => 16253000000,
                                    "goodBrandId" => 32,
                                    "goodId" => 897567496,
                                    "serviceInfoId" =>  "33813_10353134_24580551_14043_223543_25554096097_21439644_1_100154",
                                    "serviceItemFee" => "0.0",
                                    "storeFullAddress" =>  "北京朝阳区建外街道通惠河北路20号",
                                    "storeId" => 24580551
                                ],[
                                    "goodCatName" =>  "汽车贴膜",
                                    "serviceName" =>  "贴膜（全车）",
                                    "serviceBillId" =>  "e0692193cd5eada9",
                                    "servicerTel" =>  "022-82939932",
                                    "goodCount" => 1,
                                    "goodBrandName" => "米其林",
                                    "installId" => 10353134,
                                    "goodCatId" => 13979,
                                    "goodName" => "3M   车膜2222222",
                                    "serviceNum" => 1,
                                    "verCodeList" =>["BH9744444477"],
                                    "storeName" =>  "北京博11111111111111",
                                    "verValidDate" => 162228000000,
                                    "goodBrandId" => 32,
                                    "goodId" => 897567496,
                                    "serviceInfoId" =>  "33813_10353134_24580551_14043_223543_25554096097_21439644_1_100154",
                                    "serviceItemFee" => "0.0",
                                    "storeFullAddress" =>  "北京朝阳区建外街道通惠河北路20号",
                                    "storeId" => 24580551
                                ]
                        ],
                        "venderId" => 763130,
                        "townId" =>0,
                        "provinceName" => "天津",
                        "consName" => "孔圣寅",
                        "carryId" => "1274",
                        "countyName" =>  "武清区",
                        "consMobile" =>  "15030028256",
                        "consTel" =>  "15030028256",
                        "shopName" =>  "京东商城",
                        "consAddress" => "科创四街中国梦谷3号楼5楼",
                        "orderId" => 230701146334,
                        "countyId" => 51081,
                        "venderName" =>  "3M中国有限公司"
                    ]
              ]
         ];
         return json_encode($post_data);
    }
}
