<?php

namespace App\Http\Controllers\Extend;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use App\Http\Controllers\Publics\getBsSignController;
//use App\Http\Controllers\payment\alipaywap\wappay\payRefund;
header('content-type:application/json;charset=utf8');
class BsApiController extends Controller
{
    /**|---------------------------------------------------------------------------------
     * @name 添加日志
     * @param $admin 操作人
     * @param $model 操作模块名称
     * @param $type 创建类型
     * @param $content 操作内容
     * @param $num 平台单号
     * @param $ip 访问ip
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2020/8/24 15:38>
     * |---------------------------------------------------------------------------------
     */
    function AddCzrz($admin,$model,$type,$content,$num,$ip){
        $data['czrz_name'] = $admin;//登录者
        $data['czrz_ip'] = $ip?$ip:"0.0.0.0";//操作ip
        $data['czrz_czsj'] = date("Y-m-d H:i:s");//创建时间
        $data['test_data'] = $model;//操作模块名称
        $data['czrz_czlx'] = $type;//创建类型
        $data['czrz_number'] = $num;//平台单号
        $data['czrz_czxq'] = $content;//操作内容
        $rest=DB::table('czrz')->insert($data);
        if(!empty($rest)){
            return 1;
        }else{
            return 2;
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name  订单数据入口
     * @param sign 签名
     * @param api_name 访问接口名称
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2020/8/24 17:32>
     * |---------------------------------------------------------------------------------
     */
    public function orderApi ( Request $request ){
        $ip = $request->getClientIp();
        $input = $request->all();
        if(empty($input['orderBillCode'])){
            $json = file_get_contents("php://input");
            $input=json_decode($json,true);
        }
        self::addLog('orderApi', json_encode($input), $input['orderBillCode'], 'boshiadd');
        if (!empty($input['orderBillCode']) && !empty($input['item'])) {
	        $getBsSign = new getBsSignController;
            $queryMap = $getBsSign->getQueryMap();
            $api=['taobao.pos.weborder.sync','qimen.taobao.pos.weborder.add'];
            if(!in_array($queryMap['method'],$api)){
                return response()->json(['message' => '', 'flag' => '接口名称错误', 'code' => 3]);
                exit;
            }else {//getSignService::checkSign4TextRequest(file_get_contents("php://input"),'300ca3f62e9051bfbcf4550dcd98b8f1')
                if (true) {
	                $ptId = [];
	                $ptId['ps_pid'] = '81';
                    if($queryMap['method'] == 'taobao.pos.weborder.sync' || $queryMap['method'] == 'qimen.taobao.pos.weborder.add'){
	                    if($input['th_act']==1){
                    		return $this->weblChange($input,$ptId,$ip);
                		}else{
	                		return $this->weblCreadd($input,$ptId,$ip);
                		}
                	}
                } else {
                    return response()->json(['message' => '', 'flag' => '安全效验失败', 'code' => 2]);
                    exit;
                }
            }
        }else{
            return response()->json(['message' => $input, 'flag' => '访问参数错误', 'code' => 4]);
            exit;
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name  添加订单
     * @param $input 请求参数
     * @param $ptId 平台id
     * @param $ip 访问ip
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2020/8/24 15:53>appoint_num
     * |---------------------------------------------------------------------------------
     */
    public function weblCreadd( $input,$ptId,$ip ){
	    $ptId=$ptId['ps_pid'];
        if(!isset($input['orderBillCode']) || !isset($input['orderWebCod']) || !isset($input['name']) || !isset($input['phone'])){
	        return response()->json(['message' => '', 'flag' => 'order访问参数错误', 'code' => 4]);
            exit;
        }
        $order_num=$input['orderBillCode'];
        $info=$input['item'];
        if(!is_array($info)){
            $info = stripslashes($info);
            $info=json_decode($info,true);
            if(!is_array($info)) {
                return response()->json(['message' => '', 'flag' => '商品数据异常', 'code' => 5]);
                exit;
            }
        }
        $shr_name=$input['name'];
        $shr_phone=$input['phone'];
        $shr_sheng=$input['province'];
        $shr_shi=$input['city'];
        $shr_xian=$input['district'];
        $adress=$input['addres'];
        $shr_adress=$input['shippingAddress'];
        //if(!empty($input['order_time'])){
        //    $order_time=$input['order_time'];
        //}else{
        $order_time=date('Y-m-d H:i:s');
        //}
        $order_content=$input['note'];
        if(!empty($input['day_time'])){
            $order_content='客户预约安装时间为：'.$input['day_time'].";".$order_content;
        }
        if(!empty($input['gkly'])){
            $order_content .= ';客户留言：'.$input['gkly'];
        }
        if(!empty($input['kfbz'])){
            $order_content .= ';客服备注：'.$input['kfbz'];
        }
        $rsnum=DB::table('orders')->where("order_num",$order_num)->value('id');
        if(!empty($rsnum)){
            return response()->json(['message' => '', 'flag' => '平台订单号已存在', 'code' => 5]);
            exit;
        }else{
	        DB::beginTransaction(); //开启事务
            $sys_num='L'.date("Ymdhis").str_pad(rand(0,999),3,'0',STR_PAD_LEFT);
            $goods_names="";
            $good_brand = [];
            $order_account=0;
            $new_money=0;
            $appoint_code=substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 6);
            foreach($info as $k=>$v){
	            $goods = DB::table('pj_goods')->where('brand_name','博世')->where('version',$v['skuCode'])->first();
	            if($goods['pg_series'] == ''){
		            $version = $goods['pg_series']."-".$goods['version'];
	            }else{
		            $version = $goods['version'];
	            }
	            if($goods){
	            	$goods = self::dataToArray($goods);
	                while($num<$v['quantity']){
	                    $msg['goods_id']=$goods['pg_id'];//商品id
	                    $msg['goods_name']=$goods['brand_name'].'-'.$version;//商品名称
	                    $msg['goods_num']=1;//商品数量
	                    $msg['goods_number']=$version;//商品型号
	                    $msg['goods_brand']=$goods['brand_name'];//商品品牌
	                    $msg['goods_price']=$v['price']*1;//商品单价
	                    $msg['goods_paid']=$v['price']*1;//应收
	                    $msg['sys_num'] = $sys_num;//系统单号
	                    $msg['appoint_code'] =$appoint_code;
	                    $num=$num+1;
	                    $rest_msg=DB::table('order_msg')->insert($msg);
			            if(empty($rest_msg)){
				            DB::rollback();//回滚
			                return response()->json(['message' => '', 'flag' => '系统异常-1001', 'code' => 500]);
			                exit;
			            }
	                }
	                $new_money = $new_money+$v['quantity']*$v['price'];
	                $good_brand[] = $goods['brand_name'];
	                $goods_names.=$goods['brand_name'].",".$version.",";
                }else{
	                DB::rollback();//回滚
	                return response()->json(['message' => '', 'flag' => '系统异常-1002', 'code' => 500]);
	                exit;
                }
            }
            $tom['shr_name']=$shr_name;//客户名称
            $tom['shr_phone']=$shr_phone;//客户电话
            $tom['shr_sheng']=$shr_sheng;//省
            $tom['shr_shi']=$shr_shi;//市
            $tom['shr_xian']=$shr_xian;//县
            $tom['county']=$adress;//县
            $tom['shr_adress']=$adress.$shr_adress;//详细地址
            $tom['sys_num']=$sys_num;//系统单号
            $user_id=DB::table("user")->insertGetId($tom);
            if(empty($user_id)){
	            DB::rollback();//回滚
                return response()->json(['message' => '', 'flag' => '系统异常-1003', 'code' => 500]);
                exit;
            }
            $arr['handled_by']="研发";
            $arr['admin_id']="670";
            $arr['order_status']="10";
            if($order_content!=''){
	            $noteArr['orders_id']=$sys_num;
	            $noteArr['note_name']='系统同步';
	            $noteArr['note_content']=$order_content;
	            $noteArr['note_time']=$order_time;
	            $noteArr['note_type']='客户备注';
	            DB::table('note')->insert($noteArr);
            }

            $time=date("Y-m-d");
            $time1=date("Y-m-d",strtotime("+1 day"));
            $reaa=DB::table('kefu')->where("kf_day",$time)->where("kf_day",$time1)->where('disable',1)->where("kef_pd",2)->orderBy('fp_time','asc')->get();
            if(!empty($reaa)){
	            $reaa = self::dataToArray($reaa);
                $arr['kef_id']=$reaa['kf_id'];//分配客服id
            }
            $arr['goods_name'] = $goods_names;//商品名称
            $arr['sys_num']=$sys_num;//系统单号
            $arr['order_num']=$order_num;//平台单号
            $arr['p_id']=$ptId;//平台id
            $arr['ser_type']=1;//服务类型
            $arr['ser_id']=0;//接单中心id
            $arr['order_time']=$order_time;//下单时间
            $arr['customer_id']=$user_id;//客户id
            $arr['new_customer_id']=$user_id;//安装联系人id
            $arr['order_account']=$new_money;//订单金额
            $arr['new_money']=$new_money;//实收金额
            $arr['goods_brand'] = implode(',',array_unique($good_brand));//商品品牌
            $retust=DB::table("orders")->insert($arr);
            if(!empty($retust)){

                if(!empty($reaa)){
                    $poss['number']=$reaa['number']+1;
                    $poss['fp_time']=date("Y-m-d H:i:s");
                    DB::table('kefu')->where("id",$reaa['id'])->update($poss);
                }
                $this->AddCzrz('博世同步',"添加订单(博世)","添加，","订单",$sys_num,$ip);
                DB::commit();
                return response()->json(['message' => '', 'flag' => '订单添加成功', 'code' => 1]);
                exit;
            }else{
	            DB::rollback();//回滚
                return response()->json(['message' => '', 'flag' => '订单添加失败', 'code' => 500]);
                exit;
            }
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 变更状态通知接口
     * @param $input 请求参数
     * @param $ptId 平台id
     * @param $ip 访问ip
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2020/8/27 17:41>
     * |---------------------------------------------------------------------------------
     */
    public function weblChange(	$input,$ptId,$ip){
	    $ptId=$ptId['ps_pid'];
        $rest=DB::table("orders")->where("order_num",$input['orderBillCode'])->select('order_status','id','sys_num','wx_id','order_num','new_money','is_delete','p_id','ser_id','customer_id','create_time','new_customer_id')->first();
        //$rest=DB::table("orders")->where("order_num",$input['order_num'])->select('order_status','id','sys_num')->first();
        if(!empty($rest)){
			$rest = self::dataToArray($rest);
            $resa=DB::table('refund')->where("order_num",$rest['order_num'])->where("ser_state",'!=','10')->value('id');
            if(empty($resa)){
	            DB::beginTransaction(); //开启事务
	            if($input['note']){
	                $noteArr['orders_id']=$rest['sys_num'];
	                $noteArr['note_name']='接口撤销';
	                $noteArr['note_content']=$input['note'];
	                $noteArr['note_time']=date("Y-m-d H:i:s");
	                $noteArr['note_type']='客户留言';
	                DB::table('note')->insert($noteArr);
	            }else{
		            $noteArr['orders_id']=$rest['sys_num'];
	                $noteArr['note_name']='接口撤销';
	                $noteArr['note_content']='平台客户发起退款';
	                $noteArr['note_time']=date("Y-m-d H:i:s");
	                $noteArr['note_type']='客户留言';
	                DB::table('note')->insert($noteArr);
	            }
	            $userArr=DB::table("user")->where("id",$rest['new_customer_id'])->select('shr_name','shr_phone','shr_sheng','shr_shi','shr_xian','shr_adress')->first();
                $order_msg=DB::table("order_msg")->where("sys_num",$rest['sys_num'])->select('id','goods_name','goods_id','goods_price')->first();
                $order_msg=json_decode(json_encode($order_msg), true);
                $userArr=json_decode(json_encode($userArr), true);
                //退款单信息
                $refunds['sys_num'] = $rest['sys_num'];
                $refunds['order_num'] = $rest['order_num'];
                $refunds['pt_id'] = $rest['p_id'];
                $refunds['goods_name'] = $order_msg['goods_name'];
                $refunds['goods_id'] = $order_msg['goods_id'];
                $refunds['goods_price'] = $order_msg['goods_price'];
                $refunds['ser_id'] = $rest['ser_id'];
                $refunds['msg_id'] = $order_msg['id'];
                $refunds['user_id'] = $rest['customer_id'];
                $refunds['shr_name'] = $userArr['shr_name'];
                $refunds['shr_phone'] = $userArr['shr_phone'];
                $refunds['shr_sheng'] = $userArr['shr_sheng'];
                $refunds['shr_shi'] = $userArr['shr_shi'];
                $refunds['shr_xian'] = $userArr['shr_xian'];
                $refunds['shr_adress'] = $userArr['shr_adress'];
                $refunds['state'] = 0;//待审核
                $refunds['order_status'] = $rest['order_status'];
                $refunds['refund_reason'] = '平安客户退款';
                $refunds['refund_note'] = $input['note'];
                $refunds['order_time'] = $rest['create_time']; //下单时间
                $refunds['created_at'] = date("Y-m-d H:i:s");
                $refunds['urgent_type'] = 1;
                $res=DB::table('refund')->insert($refunds);
                if($res){
	                $order=DB::table('orders')->where("order_num",$rest['order_num'])->update(['lock_type'=>2]);
	                $order_list=DB::table('order_list')->where("order_num",$rest['order_num'])->update(['locklist_type'=>2]);
	                DB::table('settlement_list')->where("order_num",$rest['order_num'])->update(['locked'=>2]);
	                if(!$order){
		                DB::rollback();//回滚
		                return response()->json(['message' => '', 'flag' => '状态变更失败', 'code' => 0]);
	                }
	                $pt_name=DB::table('pt')->where('id',$ptId)->value('pt_name');
                	$this->AddCzrz($pt_name,"订单管理","撤销，","订单",$input['orderBillCode'],$ip);
	                DB::commit();
	                return response()->json(['message' => '', 'flag' => '状态变更成功', 'code' => 1]);
                }else{
	                DB::rollback();//回滚
	                return response()->json(['message' => '', 'flag' => '状态变更失败', 'code' => 0]);
                	exit;
                }
            }else{
                return response()->json(['message' => '', 'flag' => '状态变更失败', 'code' => 0]);
            	exit;
            }
        }else{
            return response()->json(['message' => '', 'flag' => '订单不存在', 'code' => 5]);
            exit;
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 变更状态通知接口
     * @param $input 请求参数
     * @param $ptId 平台id
     * @param $ip 访问ip
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2020/8/27 17:41>
     * |---------------------------------------------------------------------------------
     */
    public function weblChanges($input,$ptId,$ip){
	    $ptId=$ptId['ps_pid'];
        $rest=DB::table("orders")->where("order_num",$input['order_num'])->select('order_status','id','sys_num','wx_id','order_num','new_money')->first();
        if(!empty($rest)){
	        $rest=json_decode(json_encode($rest), true);
            if($rest['order_status']==1 || $rest['order_status']==5 || $rest['order_status']==10){
	            DB::beginTransaction(); //开启事务
	            if($input['centent']){
	                $noteArr['orders_id']=$rest['sys_num'];
	                $noteArr['note_name']='接口撤销';
	                $noteArr['note_content']=$input['centent'];
	                $noteArr['note_time']=date("Y-m-d H:i:s");
	                $noteArr['note_type']='客户留言';
	                DB::table('note')->insert($noteArr);
	            }
                $arr['order_status']=50;
                $list=DB::table("orders")->where("id",$rest['id'])->update($arr);
                if(!empty($list)){
	                $pt_name=DB::table('pt')->where('id',$ptId)->value('pt_name');
	                $this->AddCzrz($pt_name,"订单管理","撤销，","订单",$input['order_num'],$ip);
                    //if($ptId=="86" || $ptId=="123"){
                    //    $this->AddCzrz("乐车邦","订单管理","撤销，","订单",$input['order_num'],$ip);
                    //}else if($ptId=="102"){
                    //    $this->AddCzrz("畅通车友会","订单管理","撤销，","订单",$input['order_num'],$ip);
                    //}else{
                    //    $this->AddCzrz("汽车超人","订单管理","撤销，","订单",$input['order_num'],$ip);
                    //}
                    DB::commit();
                    return response()->json(['Data' => '', 'ErrorMessage' => '状态变更成功', 'code' => 0]);
                    exit;
                }else{
	                DB::rollback();//回滚
                    return response()->json(['Data' => '', 'ErrorMessage' => '状态变更失败', 'code' => 1]);
                    exit;
                }
            }else{
	            $post['WIDout_trade_no']=$rest['order_num'];
	            $post['WIDtrade_no']=$rest['wx_id'];
	            $post['WIDrefund_amount']=$rest['new_money'];
	            $post['WIDrefund_reason']='客户退款';
	            $post['WIDout_request_no']=$rest['order_num'];
				require dirname ( __FILE__ ).DIRECTORY_SEPARATOR.'./../payment/alipaywap/wappay/payRefund.php';
	            $refund =  new \payRefund();
	            $res=$refund->alipayRefund($post);
	            //print_r($res);
                return response()->json(['Data' =>$res , 'ErrorMessage' => '状态变更失败', 'code' => 1]);
                exit;
            }
        }else{
            return response()->json(['Data' => '', 'ErrorMessage' => '订单不存在', 'code' => 5]);
            exit;
        }
    }
     /**|---------------------------------------------------------------------------------
     * @name 查询订单状态
     * @param $input 请求参数
     * @param $ptId 平台id
     * @param $ip 访问ip
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2020/12/22 14:00>
     * |---------------------------------------------------------------------------------
     */
    public function searchState ($input,$ptId,$ip){
    	$ptId=$ptId['ps_pid'];
        $rest=DB::table("orders")->where("order_num",$input['order_num'])->where("p_id",$ptId)->select('order_status','is_delete','day_time','wx_id')->first();
        if(!empty($rest)){
	        $rest=json_decode(json_encode($rest), true);
	        if($rest['is_delete']=='1' && $rest['order_status']<50){
		        $state='01';//待付款
	        }else{
		        $res=DB::table('refund')->where("order_num",$input['order_num'])->where("ser_state",'!=','10')->value('id');
		        if(!empty($res) && $rest['order_status']<50){
			        $state='08';//待审核
		        }else{
			        if($rest['order_status']<'34' && $rest['day_time']!=''&& $rest['day_time']!='0'){
				        $state='04';//已预约
			        }else{
				        switch ( $rest['order_status'] ){
				        	case 1:
				        		$state='02';//待派遣
				        		break;
				        	case 5:
				        		$state='02';//待派遣
				        		break;
				        	case 10:
				        		$state='02';//待派遣
				        		break;
				        	case 20:
				        		$state='03';//已调派
				        		break;
				        	case 30:
				        		$state='03';//已调派
				        		break;
				        	case 34:
				        		$state='07';//已服务
				        		break;
			        		case 40:
				        		$state='07';//已服务
				        		break;
				        	case 50:
				        		if($rest['wx_id']!=''){
				        			$state='10';//已取消(已支付)
			        			}else{
				        			$state='09';//已取消（未支付）
			        			}
				        		break;
			        		case 55:
				        		if($rest['wx_id']!=''){
				        			$state='10';//已取消(已支付)
			        			}else{
				        			$state='09';//已取消（未支付）
			        			}
				        		break;
				        	default:
				        		$state='12';//待服务
				        		break;
				        }
			        }
		        }
	        }
	        $data['state']=$state;
	        return response()->json(['Data' => $data, 'ErrorMessage' => '获取成功', 'code' => 0]);
        }else{
	        return response()->json(['Data' => '', 'ErrorMessage' => '订单不存在', 'code' => 5]);
            exit;
        }
    }
    /**
     * 将参数拼接为url: key=value&key=value
     * @param   $params
     * @return  string
     */
    function getSign($params,$privateKey ){
		ksort($params);
		$content = $privateKey;
		if( !empty($params) ){
			$array = array();
			foreach( $params as $key => $value ){
				$content .= $key.$value;
			}
		}
		$content .= $privateKey;
		$string=  md5($content);

     return $string;
    }

    /**|---------------------------------------------------------------------------------
     * @name 添加日志记录文件
     * @param string $msg 错误信息
     * @param string $data 错误信息
     * @param string $number 单号
     * @param string $filename 数据文件名称
     * @author dou 2021/12/8 16:15
     * |---------------------------------------------------------------------------------
    */
    public static function addLog ( $msg ,  $data , $number , $filename = '' ){
        if(!$filename){
            $filename = 'DataLog'.date('Ym');
        }else{
            $time = date('Ym');
            if(strpos($filename,$time) !== false){
            }else{
                $filename = $filename.$time;
            }
        }
        $file_path = "./filedata/".$filename.".txt";
        if(!is_dir('./filedata')){
            mkdir(iconv("UTF-8", "GBK", './filedata'),0777,true);
        }
        $myfile = fopen($file_path, "a");
        $txt = $msg.":".$data."--".$number.'--'.date("Y-m-d H:i:s")."\r\n";
        fwrite($myfile, $txt);
        fclose($myfile);
    }

    /**|---------------------------------------------------------------------------------
     * 外层数组内层对象转数组
     * @param array $list   带转化数据
     * @return array
     * @author dou <2021/07/16>
     * |---------------------------------------------------------------------------------
     */
     public function dataToArray ( $list ){
     	return json_decode(json_encode($list),true);
     }
}
