<?php
/**
 * 通用服务
 * 系统通用操作权限
 * @author DouBin
 * @Date: 2021/07/14
 * @Time: 下午17:20
 * @Email: db@sudianwang.com
 * @version 1.0
 * @copyright BlueCity
 */

namespace App\Services;

use App\Models\Admin;
use App\Models\AdminInfor;
use App\Models\AdminToken;
use App\Models\ApplyNote;
use App\Models\Company;
use App\Models\Czrz;
use App\Models\Department;
use App\Models\Functions;
use App\Models\NoteDetail;
use App\Models\OrderAfter;
use App\Models\Orders;
use App\Models\Permissions;
use App\Models\SmsTemplate;
use App\Models\SyncStores;
use App\OtherModels\SmsRecord;
use BlueCity\Core\Service\Service;
use Illuminate\Support\Facades\Log;
use BlueCity\Core\Sdk\MiscSapi;
use App\Inc\VerificationCodeInc;
use App\Models\Note;
use App\Models\User;
use DB;
use phpDocumentor\Reflection\Types\Integer;
use phpDocumentor\Reflection\Types\Self_;

class CommonService extends Service{
   /**|---------------------------------------------------------------------------------
     * @name 验证函数
     * @param $check 需要校验参数
     * @param $parameter 传输参数
     * @param $rules 验证参数对应中文注释
     * @return \Illuminate\Http\JsonResponse
     * @author Dou <2021/04/25>
     * |---------------------------------------------------------------------------------
     */
    public static function checkKey ( $check , $parameter , $rules = [] ){
	    $flag['code'] = 1;
	    $flag['data'] = [];
	    $paramet = [];
	    foreach( $parameter as $k => $v ){
	        if($v!=='') {
                $paramet[] = $k;
            }
	    }
    	foreach( $check as $k => $v ){
    		if(!in_array($v,$paramet)){
	    		$flag['code'] = 2;
	    		$flag['data'][] = $rules[$v]??$v;
    		}else{
	    		if($parameter[$v] === '' || $parameter[$v] === null){
		    		$flag['code'] = 2;
	    			$flag['data'][] = $rules[$v]??$v;
	    		}
    		}
    	}
    	if($flag['code'] == 2){
	    	$flag['data'] = implode(",",$flag['data']);
    	}
    	return $flag;
    }
    /**|---------------------------------------------------------------------------------
     * @name 系统验证函数结果转化为字符串
     * @param array $Validator 验证结果
     * @return \Illuminate\Http\JsonResponse
     * @author Dou <2021/07/21>
     * |---------------------------------------------------------------------------------
     */
     public static function validatorToString ( $Validator ){
     	$Validator = $Validator->errors()->toArray();
     	$data = [];
     	foreach( $Validator as $k => $v ){
     		$data[] = $v[0];
     	}
     	return implode(',',$data);
    }
    /**|---------------------------------------------------------------------------------
     * @name  发送短信
     * @param string $phone 电话号码
     * @param string $content 发送内容
     * @param string $auth 用户身份 SuDianPaw 速电   DianPingPaw 电瓶安装
     * @param string $admin_acc 发送内容
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2021/07/14>
     * |---------------------------------------------------------------------------------
     */
     public static function senSms ( $phone , $content , $auth = '' , $username = '' , $pwd = '' , $admin_acc = '未设定' ){
        if($username!='' && $pwd!=''){
        }else {
            $accountinfor = config('auth.passwords.' . $auth);
            $username = $accountinfor['account'];
            $pwd = $accountinfor['password'];
        }
        $password = md5($username."".md5($pwd));

        $url = "http://www1.jc-chn.cn/smsSend.do?";
        //dump($content);
        //exit;
        $param =
        array(
            'username'=>$username,
            'password'=>$password,
            'mobile'=>$phone,
             //'content'=>iconv("GB2312","UTF-8",$content)
            'content'=>$content
        );

        //$MiscSapi = new MiscSapi();
        //$result = $MiscSapi->httpPost($url,$param,'http_build_query');
        $rea = CommonService::requestPost($url, $param);
        $phone = explode(',',$phone);
        foreach( $phone as $k => $v ){
            SmsService::createSmsRecord($content, $v, $admin_acc,$username,$rea);
        }
        return $rea;
    }

    /**|---------------------------------------------------------------------------------
     * @name 记录多心发送失败记录
     * @param string $pid 平台id
     * @param string $sys_num 系统单号
     * @param string $order_status 订单状态
     * @param string $sms 失败码
     * @param string $phone 手机号
     * @param string $contents 短信内容
     * @retrun /multitype:array
     * @author dou 2021/12/8 15:37
     * |---------------------------------------------------------------------------------
    */
    public static function smsinfo($pid,$sys_num,$order_status,$sms,$phone,$contents,$session){
        $messinfo = DB::table('messinfo');
        $create_content="其他";
        switch ($sms) {
            case '-1':
                $create_content="账号未注册";
                break;
            case '-2':
                $create_content="其他错误";
                break;
            case '-3':
                $create_content="密码错误";
                break;
            case '-4':
                $create_content="手机号格式不对";
                break;
            case '-5':
                $create_content="短信余量不足";
                break;
            case '-6':
                $create_content="定时发送时间不是有效的时间格式";
                break;
            case '-101':
                $create_content="平台不存在";
                break;
            case '-102':
                $create_content="短信账号密码含空值";
                break;
            default:
                break;
        }
        $data['sms']=$sms;
        $data['create_content']=$create_content;
        $data['status']=2;
        $data['pid']=$pid;
        $data['createtime']=date("Y-m-d H:i:s");
        $data['sys_num']=$sys_num;
        $data['order_status']=$order_status;
        $data['creat_admin']=$session['admin_acc'];
        $data['content']=$create_content;
        $data['admin']=$session['admin_acc'];
        $rest=$messinfo->insert($data);
        if($rest){
            $datar['phone']=$phone;
            $datar['content']=$contents;
            $datar['sys_num']=$sys_num;
            $datar['p_id']=$pid;
            $datar['code']=$sms;
            $datar['code_info']=$create_content;
            $datar['createtime']=date("Y-m-d H:i:s");
            $datar['creator']=$session['admin_acc'];
            $datar['company_type']=1;
            DB::table('retransmission')->insert($datar);
            return true;
        }else{
            return false;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @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/".date('Ym')."/".$filename.".txt";
        if(!is_dir('./filedata')){
            mkdir(iconv("UTF-8", "GBK", './filedata'),0777,true);
        }
        if(!is_dir("./filedata/".date('Ym'))){
            mkdir(iconv("UTF-8", "GBK", "./filedata/".date('Ym')),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);
    }

    /**|---------------------------------------------------------------------------------
     * @name 模拟post请求
     * @param string $url 请求链接
     * @param array $param 请求参数
     * @param array $header 请求头
     * @retrun multitype:array
     * @author dou 2021/8/9 19:35
     * |---------------------------------------------------------------------------------
    */
    public static function requestPost($url,$param,$header='') {
        /*$header = array(
            'Content-Type: application/json',
        );*/
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        if($header!=''){
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        // https 请求//如果地址是https协议，且CURLOPT_SSL_VERIFYPEER和CURLOPT_SSL_VERIFYHOST打开了，则需要加载证书
        if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https") {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        if (is_array($param) && 0 < count($param)) {
            $postMultipart = false;
            foreach ($param as $k => $v) {
                if ('@' == substr($v, 0, 1)) {
                    $postMultipart = true;
                    break;
                }
            }
            unset($k, $v);
            if ($postMultipart) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $param);// post传输数据
            } else {
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($param));
            }
        }else{
            curl_setopt($ch, CURLOPT_POSTFIELDS, $param);// post传输数据
        }
        $response = curl_exec($ch);
        curl_close($ch);
        return trim($response);
    }
    public static function ToUrlencode($arr)
    {

        $temp = array();
        if (is_array($arr))
        {
            foreach ($arr AS $key => $row)
            {
                $temp[$key] = $row;
                if (is_array($temp[$key]))
                {
                    $temp[$key] = self::ToUrlencode($temp[$key]);
                }
                else
                {
                    $temp[$key] = urlencode($row);
                }
            }
        }
        else
        {
            $temp = $arr;
        }
        return $temp;
    }
    /**|---------------------------------------------------------------------------------
     * @name 模拟form表单提交
     * @param string $url 请求链接
     * @param array $data 请求数据
     * @retrun multitype:array
     * @author dou 2021/8/17 14:40
     * |---------------------------------------------------------------------------------
     */
    public static function requestForm($url, $data)
    {
        $postdata = http_build_query($data);
        $options = array('http' => array('method' => 'POST', 'header' => 'Content-type:application/x-www-form-urlencoded', 'content' => $postdata, 'timeout' => 15 * 60));
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return $result;
    }
    /**|---------------------------------------------------------------------------------
     * @name 模拟get请求
     * @param string $url 请求链接
     * @param string $ssl 是否使用ssl证书
     * @retrun multitype:array
     * @author dou 2021/8/16 14:10
     * |---------------------------------------------------------------------------------
    */
    public static function requestGet( $url , $ssl = FALSE ){
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        if($ssl)
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
            curl_setopt($curl, CURLOPT_SSLVERSION, 3);
        }
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            //var_dump(curl_error($curl));
            return FALSE;
        }
        curl_close($curl); // 关闭CURL会话
        return $tmpInfo; // 返回数据
    }
    /**|---------------------------------------------------------------------------------
     * @name  获取验证法类型编号
     * @param string $send_type 类型名称
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2021/07/15>
     * |---------------------------------------------------------------------------------
     */
     public static function aginCodeType ( $send_type ){
     	switch ( $send_type ){
			case 'TYPE_LOGIN_PC':
				return VerificationCodeInc::TYPE_LOGIN_PC;
				break;
			default:
				return 'error';
				break;
		}
     }

     /**
     * 获取
     * @param db $db 数据库
     * @param array $params where条件
     * @param array $select 查询字段
     * @param array $orderby 排序规则
      * @param array $type 查询方式
      * @param array $limit 查询数量
     * @return array|mixed
     */
    public static function getMysqlData( $db , $params , $select = [] , $orderby = [] , $type = 'get' , $limit ='')
    {
	    //$db = new Admin();
	    if($params){
	    	$where = CommonService::jointWhere($params);
		   	$db = $db->whereRaw($where);
	    }
	    if($orderby){
		    foreach( $orderby as $k => $v ){
		    	$db = $db->orderBy($k,$v);
		    }
	    }
        if($limit){
            $db = $db->limit($limit);
        }
	    if($type == 'value'){
		    $list = $db->value($select[0]);
	    }elseif ( $type == 'count' ){
	    	$list = $db->count();
	    }elseif ( $type == 'pluck' ){
            $list = $db->pluck($select[0]);
            if( $list ){
                $list = CommonService::dataToArray($list);
            }
        }else{
		    if($select){
		    	$db = $db->select($select);
		    }
		    if($type == 'first'){
		        $list = $db->first();
	        }else{
		        $list = $db->get();
	        }
	        if( $list ){
		        $list = CommonService::dataToArray($list);
	        }
	    }
        return $list;
    }

     /**|---------------------------------------------------------------------------------
     * @name  拼接查询语句
     * @param array $params 待拼接参数
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2021/07/26>
     * |---------------------------------------------------------------------------------
     */
	public static function jointWhere ( $params ){
		$condition = [];
		foreach( $params as $k => $v ){
			if(strpos($k,'_noteq')){//不等于
				$key_length = strlen($k);
				$range_length = strlen('_noteq');
				$k = substr($k,0,$key_length-$range_length);
				$condition[] = $k." != '".$v."'";
			}elseif ( strpos($k,'_llike') ){//左包含
				$key_length = strlen($k);
				$range_length = strlen('_llike');
				$k = substr($k,0,$key_length-$range_length);
				$condition[] = $k." like '%".$v."'";
			}elseif ( strpos($k,'_rlike') ){//右包含
				$key_length = strlen($k);
				$range_length = strlen('_rlike');
				$k = substr($k,0,$key_length-$range_length);
				$condition[] = $k." like '".$v."%'";
			}elseif ( strpos($k,'_like') ){//包含
				$key_length = strlen($k);
				$range_length = strlen('_like');
				$k = substr($k,0,$key_length-$range_length);
				$condition[] = $k." like '%".$v."%'";
			}elseif ( strpos($k,'_between') ){//区间取值
				$key_length = strlen($k);
				$range_length = strlen('_between');
				$k = substr($k,0,$key_length-$range_length);
				$condition[] = $k." between '".$v[0]."' and '".$v[1]."'";
			}elseif ( strpos($k,'_searchin') ){//在数据内in
				$key_length = strlen($k);
				$range_length = strlen('_searchin');
				$k = substr($k,0,$key_length-$range_length);
				if(is_array($v)){
					$condition[] = $k." in ('".implode("','",$v)."')";
				}else{
					$condition[] = $k." in (".$v.")";
				}
			}elseif ( strpos($k,'_notin') ){//不在在数据内in
				$key_length = strlen($k);
				$range_length = strlen('_notin');
				$k = substr($k,0,$key_length-$range_length);
				if(is_array($v)){
					$condition[] = $k." not in ('".implode("','",$v)."')";
				}else{
					$condition[] = $k." not in (".$v.")";
				}
			}elseif ( strpos($k,'_searchgt') ){//大于
				$key_length = strlen($k);
				$range_length = strlen('_searchgt');
				$k = substr($k,0,$key_length-$range_length);
				$condition[] = $k." > '".$v."'";
			}elseif ( strpos($k,'_searcheqgt') ){//大于等于
                $key_length = strlen($k);
                $range_length = strlen('_searcheqgt');
                $k = substr($k,0,$key_length-$range_length);
                $condition[] = $k." >= '".$v."'";
            }elseif ( strpos($k,'_searchlt') ){//小于
				$key_length = strlen($k);
				$range_length = strlen('_searchlt');
				$k = substr($k,0,$key_length-$range_length);
				$condition[] = $k." < '".$v."'";
			}elseif ( strpos($k,'_searcheqlt') ){//小于等于
                $key_length = strlen($k);
                $range_length = strlen('_searcheqlt');
                $k = substr($k,0,$key_length-$range_length);
                $condition[] = $k." <= '".$v."'";
            }elseif ( strpos($k,'_findinset') ){
                $key_length = strlen($k);
                $range_length = strlen('_findinset');
                $k = substr($k,0,$key_length-$range_length);
                $condition[] = "FIND_IN_SET(".$v.",".$k.")";
            }elseif ( strpos($k,'_isnull') ){//是空的
                $key_length = strlen($k);
                $range_length = strlen('_isnull');
                $k = substr($k,0,$key_length-$range_length);
                $condition[] = $k." is null";
            }elseif ( strpos($k,'next_level') ){//下一级拆分
//				$key_length = strlen($k);
//				$range_length = strlen('_searchor');
//				$k = substr($k,0,$key_length-$range_length);
                $condition[] = CommonService::joinnext($v);
            }elseif ( strpos($k,'_searchor') ){//或关系查询
//				$key_length = strlen($k);
//				$range_length = strlen('_searchor');
//				$k = substr($k,0,$key_length-$range_length);
				$condition[] = CommonService::jointOr($v);
			}else{
				$condition[] = $k." = '".$v."'";
			}
		}
		return implode(' and ',$condition);
	}

	 /**|---------------------------------------------------------------------------------
     * @name  拼接查询or语句
     * @param array $params 待拼接参数
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2021/80/02>
     * |---------------------------------------------------------------------------------
     */
    public static function jointOr ( $params ){
	    $condition = [];
	    foreach( $params as $k => $v ){
            if ( strpos($k,'next_level') ){
                $data = [];
                foreach($v as $ka => $va){
                    $data[$ka] = $va;
                }
                $condition[]= "(".CommonService::jointWhere($data).")";
            }else {
                $data = [];
                $data[$k] = $v;
                $condition[]= CommonService::jointWhere($data);
            }
	    }
	    return "(".implode(' or ',$condition).")";
    }

    /**|---------------------------------------------------------------------------------
     * @name 拼接多重查询
     * @param array $params 待拼接参数
     * @return \Illuminate\Http\JsonResponse
     * @author dou 2022/1/8 10:48
     * |---------------------------------------------------------------------------------
     */
    public static function joinnext ( $params ){
        $condition = [];
        foreach( $params as $k => $v ){
            $data = [];
            $data[$k] = $v;
            $condition[]= CommonService::jointWhere($data);
        }
        return implode(' and ',$condition);
    }
	 /**|---------------------------------------------------------------------------------
     * @name  提取二维数字键值做主键所有参数保留
     * @param array $data 数组数据
     * @param string $key 提取键值
     * @param string $type 提取键值在数据中是否唯一  1唯一 2不唯一
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2021/07/27>
     * |---------------------------------------------------------------------------------
     */
     public static function jointArrayKey ( $data , $key , $type = '1'){
	    if($type == '1'){
	     	$key = array_column($data,$key);
	     	$data = array_combine($key,$data);
     	}else{
	     	$list = [];
	     	foreach( $data as $k => $v ){
	     		$list[$v[$key]][] = $v;
	     	}
	     	$data = $list;
     	}
     	return $data;
     }

    /**
     * 获取指定权限可操作数据
     *
     * @param array $ids 可操作id组
     * @param array $allData 数据组
     * @param array $key 主键
     *
     * @return mixed $data
     */
     public static function filterIds ( $ids = [] , $allData = [] , $key = '' ){
     	$data = [];
     	if($ids){
	     	$allData = CommonService::jointArrayKey($allData,$key);
	     	foreach( $ids as $k => $v ){
	     		if(isset($allData[$v])){
		     		$data[] = $allData[$v];
	     		}
	     	}
     	}else{
	     	$data = $allData;
     	}
     	return $data;
     }

     /**
     * 获取符合字段和字段值的数组集合
     * @param array $data 待过滤数组
     * @param array $conditions 检索条件
     * @return array 返回所有符合要求的数组集合
     */
    public static function arrayFilterFieldValue( $data, $conditions )
    {
	    $field = array_keys($conditions[0])[0];
	    $value = array_values($conditions[0])[0];
        $data = array_filter($data, function ($row) use ($field, $value) {
            if (isset($row[$field])) {
                if(is_array($value)){
                    return in_array($row[$field], $value);
                }else {
                    return $row[$field] == $value;
                }
            }
        });
        unset($conditions[0]);
        $conditions = array_values($conditions);
        if($conditions){
	        return CommonService::arrayFilterFieldValue($data,$conditions);
        }else{
        	return $data;
    	}
    }

    /**
     *@name 添加备注
     * @param $sys_num 系统单号
     * @param $note_type 备注类型
     * @param $note_content 备注内容
     * @param $send_num 派工单号
     * @param $public_state 安装点是否可见 1：可见；2：不可见
     * @param $admin_groupnew
     * @param $admin_acc
     * @param $id
     * @return number
     * @author du 2021年7月28日下午4:04:42
     */
    public static function accMe ($sys_num,$note_type,$note_content,$send_num,$public_state,$admin_groupnew,$admin_acc,$id)
    {
        if($send_num){
            $note_content = $note_content."(".$send_num.")";
        }
        if($admin_groupnew==2){//设置服务中心添加的备注为可见
            $data['public_state'] = 2;
        }else{
            if($public_state){
                $data['public_state'] = $public_state;
            }
        }
        $noteLong = self::verificationNoteLong($note_content);
        $data['orders_id'] = $sys_num;
        $data['note_name'] = $admin_acc;
        $data['note_content'] = $noteLong['content'];
        $data['note_time'] = date("Y-m-d H:i:s");
        $data['note_type'] = $note_type;
        $data['note_adid'] = $id;//添加人id
        $data['note_group'] = $admin_groupnew;//备注类型
        $data['note_mumtype'] = $noteLong['code'];//备注字数类型
        $rest = Note::insertGetId($data);
        if(strpos($note_type,"售后") >= 0){
            $after_num = AftersaleOrderService::getAfterData(['sys_num'=>$sys_num],[],['p_id','order_num'],'first'); //DB::table("order_after")->where('sys_num',$sys_num)->select('p_id','order_num')->first();
            $data['order_num'] = $after_num['order_num'];

        }
        if($rest){
            if($noteLong['code'] == 2){
                NoteDetail::insert(['ntd_nid'=>$rest,'ntd_content'=>$note_content]);
            }
            $order = OrderService::getOrderBy('sys_num', $sys_num,['category','order_num']);
    /*        if($order && $order['category']==3) {
                $zhipei['time'] = date('Y-m-d H:i:s');
                $zhipei['signature'] = md5($zhipei['time'] . '97e11cbcc29cbd8a538395abce85d569');
                $zhipei['order_num'] = $order['order_num'];
                $zhipei['content'] = $data['note_content'];
                $zhipei['type'] = $note_type;
                $zhipei['creator'] = $admin_acc;
                $zhipei['create_time'] = date("Y-m-d H:i:s");
                $res = CommonService::requestPost('http://jx.bluearp.com/m/index.php/PartyIrderInterfaceThree/AddRemarks', json_encode($zhipei), array('Content-Type: application/json'));
                $res = json_decode($res,true);
                $data = json_encode($zhipei).'---'.json_encode($res);
                CommonService::addLog('同步备注信息', $data, $order['order_num'],'warehouse-addnot');
            }*/
            return $rest;
        }else{
            return false;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 验证备注长度并返回对应处理结果
     * @param string $note_content 备注内容
     * @retrun /multitype:array
     * @author dou 2022/3/7 14:43
     * |---------------------------------------------------------------------------------
    */
    public static function verificationNoteLong ( $note_content ){
        $long = mb_strlen($note_content);
        if($long > 180){
            $note_contents = mb_substr($note_content,0,20,'utf-8');
            $return['code'] = 2;
            $return['content'] = $note_contents;
        }else{
            $return['code'] = 1;
            $return['content'] = $note_content;
        }
        return $return;
    }

    /**
     * 获取备注
     * @param string/array $sys_num 系统单号/数id
     * @param int $group 权限
     * @param int $Login_id 登录人id
     * @param int $key 输出键
     * @return array 返回备注信息
     */
	public static function orderRemarks ( $sys_num , $key = '' ,$group = '' , $Login_id = ''){
		$db = new Note();
		if (empty($sys_num)){
            return false;
        }else{
		    $where['is_delet'] = 1;
	        if(is_array($sys_num)){
		        $where['orders_id_searchin'] = $sys_num;
		        $orderby['note_time'] = 'ASC';
	        }else{
                if(is_int($sys_num)){
                    $where['id'] = $sys_num;
                }else{
                    $where['orders_id'] = $sys_num;
                }
		        $orderby['note_time'] = 'DESC';
	        }
//	        if($group == '2'){
//		        $where['public_state'] = 2;
//		        $grouOR['note_group_noteq']  = 2;
//		        $grouOR['note_adid']  = $Login_id;
//		        $where['group_searchor'] = $grouOR;
//	        }else{
//
//	        }
	        if($group!='') {
                $bmmc_pids = BmmcService::searchPids($group);
                if (in_array('2', $bmmc_pids)) {
                    $where['public_state'] = 2;
                    $grouOR['note_group_noteq']  = 2;
                    $grouOR['note_adid']  = $Login_id;
                    $where['group_searchor'] = $grouOR;
                }
                if (in_array([7,8,9], $bmmc_pids)) {
                    $where['note_adid']  = $Login_id;
                }
            }
	        $data = CommonService::getMysqlData($db,$where,['id','note_name','note_content','note_time','public_state','note_type','orders_id','note_adid','note_mumtype'],$orderby);
            if($data) {
                foreach ($data as $k => $v) {
                    if ($v['public_state'] == 2) {
                        $data[$k]['public_state'] = true;
                    } elseif ($v['public_state'] == 1) {
                        $data[$k]['public_state'] = false;
                    }
                }
                if ($key) {
                    $data = CommonService::jointArrayKey($data, $key, 2);
                }
            }
       		return $data;
        }
	}
	/**|---------------------------------------------------------------------------------
	 * @name 获取指定条件用户信息
	 * @param string $key 请求键
     * @param string $value 请求值
     * @param array $select 获取信息
	 * @retrun multitype:array
	 * @author dou 2021/8/9 19:54
	 * |---------------------------------------------------------------------------------
	*/
    public static function getUser ( $key , $value , $select = [] , $type = 'get'){
        $db = new User();
        if($key == 'id'){
            $type = 'first';
        }
        if(count($select) == 1 && $type == 'first'){
            $type = 'value';
        }
        if(!$select){
            $select = ['id','shr_name','shr_phone','shr_sheng','shr_shi','shr_xian','shr_adress'];
        }
        $list = CommonService::getMysqlData($db, [$key=>$value],$select,[],$type);
        return $list;
    }

    /**|---------------------------------------------------------------------------------
     * @name 添加用户车型数据
     * @param string $sys_num 系统单号
     * @param string $car_make 车辆品牌
     * @param string $car_line 车辆系列
     * @param string $car_model 车辆型号
     * @param string $car_id 车辆id
     * @param string $car_infor 车型明心信息
     * @retrun /multitype:array
     * @author dou 2021/11/10 19:18
     * |---------------------------------------------------------------------------------
     */
    public static function addUserCar ( $sys_num , $car_make , $car_line , $car_model , $car_id = 0 , $car_infor = '' ){
        $new_customer_id = OrderService::getOrderBy('sys_num', $sys_num,['new_customer_id','customer_id']);
        $customer_id = [];
        $customer_id[] = $new_customer_id['new_customer_id'];
        $customer_id[] = $new_customer_id['customer_id'];
        $customer_id = array_unique($customer_id);
        $data = [];
        $data['car_id'] = $car_id;
        if($car_make!=''){
            $data['car_make'] = $car_make;
            $car_infor .= $car_make;
        }if($car_line!=''){
            $data['car_line'] = $car_line;
            $car_infor .= ' '.$car_line;
        }if($car_model!=''){
            $data['car_model'] = $car_model;
            $car_infor .= ' '.$car_model;
        }
        $data['car_infor'] = $car_infor;
        $letMe = User::whereIn("id",$customer_id)->update($data);
        return $letMe;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取用户车型信息
     * @param string $sys_num 系统单号
     * @retrun /multitype:array
     * @author dou 2021/11/10 19:57
     * |---------------------------------------------------------------------------------
    */
    public static function getUserCar ( $sys_num , $type = false){
        $new_customer_id = OrderService::getOrderBy('sys_num', $sys_num,['new_customer_id','customer_id']);
        $customer_id = [];
        $customer_id[] = $new_customer_id['new_customer_id'];
        $customer_id[] = $new_customer_id['customer_id'];
        $customer_id = array_unique($customer_id);
        $letMe = User::whereIn("id",$customer_id)->whereRaw("(car_make != '' or car_infor != '')")->select('car_make','car_line','car_model','car_id','car_infor')->first();
        if($letMe && $type){
            $data = $letMe['car_make'];
            $data .= self::joinUserCar($letMe['car_line']);
            $data .= self::joinUserCar($letMe['car_model']);
            if($data == ''){
                $data = $letMe['car_infor'];
            }
            $letMe = $data;
        }
        return $letMe;
    }
    public static function joinUserCar ( $data ){
        if($data != ''){
            $data = ' '.$data;
        }
        return $data;
    }
    /**|------------------------------------------------------------------
     * @name 计算使用时间
     * @param string $create_time 开始时间
     * @param string $end_time 结束时间
     * @return \Illuminate\Http\JsonResponse
     * @author he <2019-05-27 19:25>
     * |-------------------------------------------------------------------
     */
    public static function computeTime($create_time , $end_time = '' ){
        $date1=date("Y-m-d",strtotime($create_time));
        if($end_time == '') {
            $date2 = date("Y-m-d");
        }else{
            $date2=date("Y-m-d",strtotime($end_time));
        }
        if(strtotime($date1)>strtotime($date2)){
            return '时间异常请手动计算';
        }
        list($Y1,$m1,$d1)=explode('-',$date1);
        list($Y2,$m2,$d2)=explode('-',$date2);
        $Y=$Y2-$Y1;
        $m=$m2-$m1;
        $d=$d2-$d1;
        if($d<0){
            $d+=(int)date('t',strtotime("-1 month $date2"));
            $m--;
        }
        if($m<0){
            $m+=12;
            $Y--;
        }
        $month=$Y*12+$m;
        return $month.'月'.$d.'天';
    }
    /**|---------------------------------------------------------------------------------
     * @name 获取物理地址对应经纬度
     * @param string $city 所属城市
     * @param string $address 详细地址
     * @retrun multitype:array
     * @author dou 2021/8/16 0:33
     * |---------------------------------------------------------------------------------
    */
    public static function jingwei($city,$address){
        try{
            $url = "http://restapi.amap.com/v3/geocode/geo?key=bf7919b601432722e4353ba6358e9c10&address='".$address."'&city='".$city."'&output='json'";
            $result = CommonService::requestGet($url);//对比和post请求区别进行对应调整
            $arr = json_decode($result,true);
            if($arr['status'] == '1' && $arr['geocodes']){
                return $arr['geocodes'][0]['location'];
            }else{
                return '';
            }
        }catch(\Exception $e){
            return $e->getMessage();
        }

    }

    /**|---------------------------------------------------------------------------------
     * @name 计算距离
     * @param $start 开始坐标
     * @param $end  结束坐标
     * @return \Illuminate\Http\JsonResponse
     * @author he <2019>
     * |---------------------------------------------------------------------------------
     */
    public static function juli($start , $end , $type = 1){
        try{
            if($type == '1') {
                $url = "http://restapi.amap.com/v3/direction/driving?key=bf7919b601432722e4353ba6358e9c10&origin=" . $start . "&destination=" . $end . "&type=1&output=json";
                //$result = file_get_contents($url);
                $result = CommonService::requestGet($url);
                $arr = json_decode($result, true);
                if ($arr['status'] == '1') {
                    return round($arr['route']['paths'][0]['distance'] / 1000, 2);
                } else {
                    return '';
                }
            }else{
                $url = "http://restapi.amap.com/v3/distance?key=bf7919b601432722e4353ba6358e9c10&origins=".$start."&destination=".$end."&type=1&output=json";
                $result = CommonService::requestGet($url);
                $arr = json_decode($result,true);
                if($arr['status'] == '1'){
                    //return round($arr['route']['paths']['0']['distance'] / 1000,2);
                    return $arr['results'];
                }else{
                    return '';
                }
            }
        }catch(\Exception $e){
            return $e->getMessage();
        }

    }

    /**
     * 过滤特殊字符
     * @param string $str 需过滤字符串
     * @return string 返回过滤后的字符串
     */
    public static function restrict($str){
        $is_str=array(" ","　","\t","\n","\r","	");
        $is_str_er=array("","","","","","");
        return str_replace($is_str,$is_str_er,$str);
    }

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

     /**|---------------------------------------------------------------------------------
      * @name 生成唯一单号
      * @retrun  /multitype:string
      * @author dou 2021/8/24 19:54
      * |---------------------------------------------------------------------------------
     */
    public static function creactNumber ( ){
        return date('Ymd').substr(implode(NULL,array_map('ord',str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }

    /**|---------------------------------------------------------------------------------
     * @name 验证单号
     * @param int $type 1验证2验证并生成
     * @param int $is_type sys_num:系统单号 order_num:订单单号
     * @param string  $number 单号
     * @param int $num 拆分序列
     * @param bool $is_split 是否为拆单
     * @retrun /multitype:array
     * @author dou 2021/11/21 13:44
     * |---------------------------------------------------------------------------------
    */
    public static function validationNum ( $type , $is_type , $number , $num = 0 ,$params = [] , $is_split = true ){
        if($is_split){
            $pos = strpos($number, 'C-');
            if($pos === false || $pos !== 0) {
                $numbers = 'C-' . $number;
            }else{
                $numbers = $number;
            }
        }else{
            $numbers = $number;
        }
        $data = explode('-', $number);
        if(count($data)>1){
            $nums = end($data);
            if(is_int($nums) && $nums<100){
                $num = $nums + 1;
                $data = array_slice($data,'-1');
                $numbers = implode('-', $data);
            }
        }
        if($is_split && $num < 1){
            $num = 1;
        }
        if($num>0){
            $numbers .= '-'.$num;
        }
        if($params){
            $param = $params;
            $param[$is_type] = $numbers;
            $res = OrderService::getOrderMsgLocations($param,['id'],'first');
        }else{
            $res = OrderService::getOrderBy($is_type, $numbers,['id']);
        }
        if($res && $type == 2){
            $num++;
            return self::validationNum($type , $is_type , $number , $num , $params , $is_split);
        }else{
            return $numbers;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 添加结算单备注
     * @param string ju_ordernum 订单单号
     * @retrun /multitype:array
     * @author dou 2021/9/3 11:03
     * |---------------------------------------------------------------------------------
     */
    public static function insertApplyNote ( $apply_note , $settlement_ids , $crector , $group_type , $public = 1 , $note_model){
        $post['apply_note']=$apply_note;
        $post['settlement_ids']=$settlement_ids;
        $post['crector']=$crector;
        $post['group_type']=$group_type;
        $post['public']=$public;
        $post['note_model']=$note_model;
        $add_note=ApplyNote::insert($post);
        return $add_note;
    }

    /**|---------------------------------------------------------------------------------
     * @name 重置数组键从0开始
     * @param srray $list 需重置数据
     * @retrun /multitype:array
     * @author dou 2021/9/10 10:54
     * |---------------------------------------------------------------------------------
    */
    public static function resetListKey ( $list ){
        $data = [];
        foreach($list as $k => $v){
            $data[] = $v;
        }
        return $data;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取仓库
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/9/10 15:52
     * |---------------------------------------------------------------------------------
     */
    public static function getWarehouse ( ){
        $db = DB::table('warehouse');
        $datas = self::getMysqlData($db, ['staus'=>1],['shck_ckmc','id'],['id'=>'asc']);
        $data = [];
        if($datas){
            foreach($datas as $k => $v){
                $data[$k]['type'] = $v['id'];
                $data[$k]['name'] = $v['shck_ckmc'];
            }
        }
//        $data = array(array('type'=>1,'name'=>'天津仓'),array('type'=>2,'name'=>'涿州仓'));
        return $data;
    }

    /**|---------------------------------------------------------------------------------
     * @name 创建不重读系统单号
     * @param int $type 1:天猫  2:京东  3:京东车膜服务
     * @param string $sys 系统单号
     * @param string $Incre_key 变更参数
     * @retrun /multitype:string
     * @author dou 2021/9/27 19:46
     * |---------------------------------------------------------------------------------
     */
    public static function creactSysNum ( $type = 3 , $sys = false , $Incre_key = false ){
        if($sys && $Incre_key){
            $sys = $sys.rand(10,99).$Incre_key;
            $res = OrderService::getOrderBy('sys_num', $sys,['id']);
            if($res){
                $sys = self::creactSysNum($type,$sys,$Incre_key);
            }
            return $sys;
        }else{
            $sys = "L".$type.date("Ymdhis").rand(100,999);
            $res = OrderService::getOrderBy('sys_num', $sys,['id']);
            if($res){
                $sys = self::creactSysNum($type);
            }
            return $sys;
        }

    }

    /**|---------------------------------------------------------------------------------
     * @name 开启msql事务
     * @author dou 2021/11/19 17:05
     * |---------------------------------------------------------------------------------
    */
    public static function startmysql ( ){
        DB::connection()->enableQueryLog();#开启执行日志
    }

    /**|---------------------------------------------------------------------------------
     * @name 输出msql事务
     * @author dou 2021/11/19 17:05
     * |---------------------------------------------------------------------------------
     */
    public static function showmysql ( ){
        $query = DB::getQueryLog()[0];//sql数组
        $bindings = $query['bindings'];//sql参数
        $sql = $query['query'];//sql语句
        //正则替换
        foreach ($bindings as $replace) {
            $value = is_numeric($replace) ? $replace : "'" . $replace . "'";
            $sql = preg_replace('/\?/', $value, $sql, 1);
        }
        return $sql;
    }

    /**|---------------------------------------------------------------------------------
     * @name 数据类型转化 ->string
     * @param array $data 执行参数
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/12/7 10:59
     * |---------------------------------------------------------------------------------
    */
    public static function intToStr($data){
        foreach ($data as $k=>$v){
            if(is_array($v)){
                if($v==false){
                    $data[$k]=$v;
                }else{
                    $data[$k] = self::intToStr($v);
                }
            }else{
                $data[$k] = (string)$v;
            }
        }
        return $data;
    }

    /**|---------------------------------------------------------------------------------
     * @name 数据类型转化 ->int
     * @param array $data 执行参数
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/12/7 10:59
     * |---------------------------------------------------------------------------------
     */
    public static function strToint($data){
        foreach ($data as $k=>$v){
            if(is_array($v)){
                $data[$k] = self::strToint($v);
            }else{
                $data[$k] = (int)$v;
            }
        }
        return $data;
    }
    /**|---------------------------------------------------------------------------------
     * @name 拆分指定平台用户信息
     * @param string $data 需要拆分信息
     * @param int $pt_id 对那个执行平台id
     * @retrun /multitype:array
     * @author dou 2022/1/17 16:46
     * |---------------------------------------------------------------------------------
    */
    public static function getDataUser ( $data , $pt_id ){
        $type = self::getUserModelType(2,$pt_id);
        $return['shr_name'] = '';
        $return['shr_phone'] = '';
        $return['shr_dress'] = '';
        $return['not'] = '';
        if($type){
            $model = 'userModel'.$type;
            $model = (string)$model;
            return self::$model($data,$return);
        }else{
            return ['Data' => '', 'ErrorMessage' => '对应平台无操作权限', 'ErrorCode' => 2000];
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取用户对应平台拆分组/平台展示是否可拆分用户信息
     * @param int $pt_id 平台数据id
     * @param int $type 检索类型 1可拆分平台数据 2 数据对应model编号
     * @retrun /multitype:array
     * @author dou 2022/1/18 8:58
     * |---------------------------------------------------------------------------------
    */
    public static function getUserModelType ( $type , $pt_id = '' ){
        $pt_id_arr = PlatformService::getPtIdByPtType();
        $data[1] = $pt_id_arr;//[453];//线下分销
        $data[2] = [23,68];//临时测试
        if($type == 1){
            foreach($data as $k => $v){
                $data[$k] = implode(',', $v);
            }
            $data = implode(',', $data);
            $data = explode(',', $data);
            return $data;
        }else{
            foreach($data as $k => $v){
                if(in_array($pt_id, $v)){
                    return $k;
                }
            }
            return '';
        }
    }

    /*----------------------------------------------平台用户model开始---------------------------------------------------*/
    /**|---------------------------------------------------------------------------------
     * @name 线下分销model
     * @param string $data 需拆分数据
     * @retrun /multitype:array
     * @author dou 2022/1/18 8:51
     * |---------------------------------------------------------------------------------
    */
    public static function userModel1 ( $data , $return ){
        $data = explode("\n", $data);
        if(count($data)>1){
            foreach($data as $k => $v){
                if(strpos($v,'买家姓名：') !== false){
                    $name = explode("买家姓名：", $v);
                    $return['shr_name'] = self::restrict($name[1]);
                }
                if(strpos($v,'收货地址：') !== false){
                    $dress = explode("收货地址：", $v);
                    $return['shr_dress'] = self::restrict($dress[1]);
                }
                if(strpos($v,'联系方式：') !== false){
                    $phone = explode("联系方式：", $v);
                    $return['shr_phone'] = self::restrict($phone[1]);
                }
                if(strpos($v,'买家邮编：') !== false){
                    $return['not'] = $v;
                }
            }
            return ['Data' => $return, 'ErrorMessage' => '操作成功', 'ErrorCode' => 1];
        }else{
            return ['Data' => '', 'ErrorMessage' => '对应平台无操作权限', 'ErrorCode' => 1000];
        }
    }
    /*----------------------------------------------平台用户model结束---------------------------------------------------*/


    /**
     * 获取短信发送模块
     * @param bool $type
     * @return array|\string[][]
     * @author du
     * @date 2022/2/10
     */
    public static function getSmsModelType( $type = true)
    {
        $data = [['type'=>'AftersaleOrder','name'=>'售后'],['type'=>'SerInfor','name'=>'催单'],['type'=>'Refund','name'=>'退单'],['type'=>'OrderList','name'=>'派工单']];
        if($type){
            $data = array_column($data, 'name','type');
        }
        return $data;
    }

    /**
     * @param $input
     * @return array|string|string[]
     * @author du
     * @date 2022/2/11
     */
    public static function sendSmsModle($input){
        $OrdersInfo = OrderService::getOrderBy('order_num', $input['order_num'],['category','order_time','new_customer_id','order_num','ser_id']);
        if(!$OrdersInfo){
            return ['Data' => '', 'ErrorMessage' => '订单不存在', 'ErrorCode' => 9200];
        }
        $msg = SmsTemplate::where('type',$input['type'])->where('send_user_type',$input['send_user_type'])->where('category',$OrdersInfo['category'])->value('content');

        if(!$msg){
            return ['Data' => '', 'ErrorMessage' => '模板不存在', 'ErrorCode' => 9200];
        }
//print_r($OrdersInfo);
        $userInfo = UserService::getUserBy('id', $OrdersInfo['new_customer_id'],['shr_name','shr_phone','shr_sheng','shr_shi','shr_xian','shr_adress','shr_code']);
        //print_r($userInfo);
        /*$orderListInfo = OrderListService::getOrderListBy('order_num',$input['order_num']);
        print_r($orderListInfo);
        $goods = DB::table('order_msg')->where('id',$orderListInfo['order_goods_id'])->value('goods_name');
        print_r($goods);
        $orderAfterInfo = OrderAfter::where('order_num', $input['order_num'])->value('after_num');*/
        //print_r($orderAfterInfo);
        //admininfo
        $storePhone = AdminInfor::where('admin_id',$OrdersInfo['ser_id'])->value('phone');
        //print_r($storePhone);
        $address = $userInfo['shr_sheng'].$userInfo['shr_shi'].$userInfo['shr_xian'].$userInfo['shr_adress'];
        $msg = str_replace("|Dress|",$address,$msg);
        $msg = str_replace("|Phone|",$userInfo['shr_phone'],$msg);
        $msg = str_replace("|Name|",$userInfo['shr_name'],$msg);
        //$msg = str_replace("|SerialNum|",$orderListInfo['serial_number'],$msg);
        $msg = str_replace("|OrderNum|",$OrdersInfo['order_num'],$msg);
       // $msg = str_replace("|AfterNum|",$orderAfterInfo,$msg);
        //$msg = str_replace("|GoodsName|",$goods,$msg);
        $msg = str_replace("|CheckCode|",$userInfo['shr_code'],$msg);
        $msg = str_replace("|OrderTime|",explode(' ',$OrdersInfo['order_time'])[0],$msg);
        $msg = str_replace("|storePhone|",$storePhone,$msg);
        $data['msg'] = $msg;
        if($input['send_user_type']==1){
            $phone = $userInfo['shr_phone'];
        }else{
            $phone = $storePhone;
        }
        $data['phone'] = $phone;

        return ['Data' => $data, 'ErrorMessage' => '操作成功', 'ErrorCode' => 1];

    }

    /**
     * 一键发送短信（通用）
     * @param $input
     * @param $session
     * @return array|string|string[]
     * @author du
     * @date 2022/2/11
     */
    public static function sendMsgCommonModel($input,$session){
        if ($input['send_type'] == 1) {
            $checkKey = CommonService::checkKey(['order_num','type','send_user_type'],$input);
            if($checkKey['code']!=1){
                return ['Data' => '', 'ErrorMessage' => '参数'.$checkKey['data'].'未填写,或值为空', 'ErrorCode' => 9200];
            }
            $msg = CommonService::sendSmsModle($input);
            return $msg;

        } else {
            $checkKey = CommonService::checkKey(['msg', 'phone'],$input);
            if($checkKey['code']!=1){
                return ['Data' => '', 'ErrorMessage' => '参数'.$checkKey['data'].'未填写,或值为空', 'ErrorCode' => 9200];
            }
            //$db = new SmsRecord;
            // $res = SmsService::getInfoBy($db, 'customer_phone', $input['phone'],['created_at']);
            $res = SmsRecord::where('customer_phone',$input['phone'])->orderBy('created_at','Desc')->value('created_at');
            $oldTime = strtotime($res);
            $nowTime = time();
            if(($nowTime-$oldTime)<15){
                return ['Data' => '', 'ErrorMessage' => '15秒内不可重复发送', 'ErrorCode' => 9200];
            }
            //发送短信
            $ret = CommonService::senSms($input['phone'], $input['msg'], 'DianPingPaw');

            if($ret>=1){
//                SmsService::createSmsRecord($input['msg'], $input['phone'], $session['admin_acc'],1);
                return ['Data' => '', 'ErrorMessage' => '发送成功', 'ErrorCode' => 1];
            }else{
                return ['Data' => '', 'ErrorMessage' => '发送失败', 'ErrorCode' => 9200];
            }
        }
    }

    //校验地址
    public static function check_dress ( $sheng,$shi,$xian ){
        if($sheng == '北京' || $sheng == '北京市'){
            $sheng="北京";
            $shi="北京市";
        }elseif($sheng == '天津' || $sheng == '天津市'){
            $sheng="天津";
            $shi="天津市";
        }elseif($sheng == '上海' || $sheng == '上海市'){
            $sheng="上海";
            $shi="上海市";
        }elseif($sheng == '重庆' || $sheng == '重庆市'){
            $sheng="重庆";
            $shi="重庆市";
        }elseif($sheng == '河北' || $sheng == '河北省'){
            $sheng="河北";
        }elseif($sheng == '山西' || $sheng == '山西省'){
            $sheng="山西";
        }elseif($sheng == '辽宁' || $sheng == '辽宁省'){
            $sheng="辽宁";
        }elseif($sheng == '吉林' || $sheng == '吉林省'){
            $sheng="吉林";
        }elseif($sheng == '黑龙江' || $sheng == '黑龙江省'){
            $sheng="黑龙江";
        }elseif($sheng == '江苏' || $sheng == '江苏省'){
            $sheng="江苏";
        }elseif($sheng == '浙江' || $sheng == '浙江省'){
            $sheng="浙江";
        }elseif($sheng == '安徽' || $sheng == '安徽省'){
            $sheng="安徽";
        }elseif($sheng == '福建' || $sheng == '福建省'){
            $sheng="福建";
        }elseif($sheng == '江西' || $sheng == '江西省'){
            $sheng="江西";
        }elseif($sheng == '山东' || $sheng == '山东省'){
            $sheng="山东";
        }elseif($sheng == '河南' || $sheng == '河南省'){
            $sheng="河南";
        }elseif($sheng == '湖北' || $sheng == '湖北省'){
            $sheng="湖北";
        }elseif($sheng == '湖南' || $sheng == '湖南省'){
            $sheng="湖南";
        }elseif($sheng == '广东' || $sheng == '广东省'){
            $sheng="广东";
        }elseif($sheng == '海南' || $sheng == '海南省'){
            $sheng="海南";
        }elseif($sheng == '四川' || $sheng == '四川省'){
            $sheng="四川";
        }elseif($sheng == '贵州' || $sheng == '贵州省'){
            $sheng="贵州";
        }elseif($sheng == '云南' || $sheng == '云南省'){
            $sheng="云南";
        }elseif($sheng == '陕西' || $sheng == '陕西省'){
            $sheng="陕西";
        }elseif($sheng == '甘肃' || $sheng == '甘肃省'){
            $sheng="甘肃";
        }elseif($sheng == '青海' || $sheng == '青海省'){
            $sheng="青海";
        }elseif($sheng == '台湾' || $sheng == '台湾省'){
            $sheng="台湾";
        }elseif($sheng == '内蒙古' || $sheng == '内蒙古自治区'){
            $sheng="内蒙古";
        }elseif($sheng == '广西' || $sheng == '广西壮族自治区'){
            $sheng="广西";
        }elseif($sheng == '西藏' || $sheng == '西藏自治区'){
            $sheng="西藏";
        }elseif($sheng == '宁夏' || $sheng == '宁夏回族自治区'){
            $sheng="宁夏";
        }elseif($sheng == '新疆' || $sheng == '新疆维吾尔自治区'){
            $sheng="新疆";
        }elseif($sheng == '香港' || $sheng == '香港特别行政区'){
            $sheng="香港";
        }elseif($sheng == '澳门' || $sheng == '澳门特别行政区'){
            $sheng="澳门";
        }
        if(mb_strlen($xian,'utf-8')>10 || $xian=='' || $xian=='市、县级市'){
            $xian = $shi;
        }
        $data[0] = $sheng;
        $data[1] = $shi;
        $data[2] = $xian;
        return $data;
    }
    /**|---------------------------------------------------------------------------------
     * @name 列表页
     * @param string ju_ordernum 订单单号
     * @retrun /multitype:array
     * @author dou 2022-11-17 017 上午 9:56:17
     * |---------------------------------------------------------------------------------
     */
    public static function getSyncStores ( $ser_id , $category ){
        if(in_array($category, [1,2])) {
            $store = SyncStores::where("ser_id", $ser_id)->where("type", 2)->value('type');
        }elseif(in_array($category, [134])){
            $store = SyncStores::where("ser_id", $ser_id)->where("type", 3)->value('type');
        }
        return $store;
    }
    /*----------------------------------------------------同步库存erp系统-----------------------------------------------*/
    /**|---------------------------------------------------------------------------------
     * @name 同步库房回收
     * @param array $orderInfo 订单信息
     * @param array $goodsInfo 商品信息
     * @param string $type 请求类型 是否生产
     * @retrun /multitype:array
     * @author dou 2022-08-31 031 上午 10:22:19
     * |---------------------------------------------------------------------------------
    */
    public static function sysErpRetrieveInfor ( $orderInfo , $goodsInfo , $type = false ){
        $url = self::getErpUrl($type) . '/addRecycling';
        $orderData = $orderInfo;
        $orderData['time'] = time();
        $goodsData = [];
        foreach ($goodsInfo as $goods) {
            $goodsData[] = [
                'general_version' => $goods['goods_id'], //商品编号
                'goods_num' => $goods['goods_num'] //回收数量
            ];
        }
        $orderData['goods'] = $goodsData;
        $content = $orderData['time'] . self::getErpPrivateKey($type);
        $orderData['signature'] = md5($content);
        $res = CommonService::requestPost($url, json_encode($orderData), array('Content-Type: application/json'));
        return $res;
    }

    /**|---------------------------------------------------------------------------------
     * @name 库房接口privateKey
     * @param string $type 请求类型 是否生产
     * @retrun /multitype:string
     * @author dou 2022-08-31 031 上午 10:44:52
     * |---------------------------------------------------------------------------------
    */
    public static function getErpPrivateKey ( $type ){
        if($type) {
            return '97e11cbcc29cbd8a538395abce85d569';
        }else{
            return '97e11cbcc29cbd8a538395abce85d569';
        }

    }

    /**|---------------------------------------------------------------------------------
     * @name 库房接口链接
     * @param string $type 请求类型 是否生产
     * @retrun /multitype:string
     * @author dou 2022-08-31 031 上午 10:49:02
     * |---------------------------------------------------------------------------------
    */
    public static function getErpUrl ( $type = false ){
        if($type) {
            return 'http://jx.bluearp.com/m/index.php/PartyIrderInterfaceThree';
        }else{
            return 'http://jxtest.bluezp.com/m/index.php/PartyIrderInterfaceThree';
        }
    }
    /*----------------------------------------------------同步库存erp系统-----------------------------------------------*/
    //移动端操作日志 /*$type:操作类型  $order_number:操作单号   $content:操作内容   $model:操作模块*/
    public static function inserting_log($type,$order_number,$content,$model,$session,$ip){
        $model_name=$model;
        $data['czrz_name'] = $session['install_name'];//登录者
        $data['czrz_ip'] = $ip;//操作ip
        $data['czrz_czsj'] = date("Y-m-d H:i:s");//创建时间
        $data['test_data'] = $model_name;//操作模块名称
        $data['czrz_czlx'] = $type;//创建类型
        $data['czrz_czxq'] = $content;//操作内容
        $data['czrz_number']= $order_number;//操作单号
        $res = Czrz::insert($data); //添加操作日志
        if($res){
            return 1;
        }else{
            return 2;
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 推送微信通知
     * @param string ju_ordernum 订单单号
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2024/9/22 17:09
     * |---------------------------------------------------------------------------------
    */
    public static function push_order ( $input ){
        $ser_id=$input['ser_id'];

        $good=$input['goods_name'];
        $serial_number=$input['serial_number'];
        if(isset($input['install_type']) && $input['install_type']==2){
            $master = DB::table("ser_master")
                ->where('ser_id',$ser_id)
                ->where('type',2)
                ->where('is_delet',1)
                ->select('wechat_number')
                ->get();
        }else {
            $master = DB::table("ser_master")
                ->where('ser_id',$ser_id)
                ->where('type',1)
                ->where('is_delet',1)
                ->select('wechat_number')
                ->get();
        }
        if($master){
            $master = CommonService::dataToArray($master);
            $access_token= RedisService::redisGet('access_token_saas');
            if($access_token){
                $obj['access_token']=$access_token;
            }else {
                $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxf457f42f874c3545&secret=62c5530f13e8b88204818c8b98d3a5b6';//生产环境
                $arrContextOptions=array(
                    "ssl"=>array(
                        "verify_peer"=>false,
                        "verify_peer_name"=>false,
                    ),
                );
                $output = file_get_contents($url, false, stream_context_create($arrContextOptions));//运行curl
                $obj = json_decode($output, true);
                if($obj['access_token']){
                    RedisService::redisSet('access_token_saas', $obj['access_token'],'6480');
                }
            }
            //dump($obj);
            if($obj['access_token']){
                $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$obj['access_token'];
                $poss['template_id']="e4p_3KYl6xU25pxonkkSzfCklrg9K1QV5-bkdSu8JiM";
                if(isset($input['install_type']) && $input['install_type']==2){
                    $poss['url'] = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf457f42f874c3545&redirect_uri=http://jdh.bluearp.com/mobileWeb&response_type=code&scope=snsapi_base&state=InstallOrder&connect_redirect=1#wechat_redirect";
                }else {
                    $poss['url'] = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf457f42f874c3545&redirect_uri=http://jdh.bluearp.com/mobileWeb&response_type=code&scope=snsapi_base&state=OrderTaking&connect_redirect=1#wechat_redirect";
                }
                $data['character_string10']['value']=$input['order_num'];
                $data['thing5']['value']=$input['goods_name'];
                $data['time13']['value']=date("Y-m-d H:i:s");
                //$data['thing19']['value']=$input['dress'];
                //$data['const11']['value']='新订单';
                $poss['data']=$data;
                foreach( $master as $k => $v )
                {
                    $poss['touser']=$v['wechat_number'];
                    $res = CommonService::requestPost($url, json_encode($poss));
                    $insert['wps_number']=$serial_number;
                    $insert['wps_ordernum']=$input['order_num'];
                    $insert['wps_serid']=$ser_id;
                    $insert['wps_goodsname']=$good;
                    $insert['wps_openid']=$v['wechat_number'];
                    $insert['wps_weixindata']=$res;
                    $insert['wps_creactime']=date("Y-m-d H:i:s");
                    DB::table("weixin_push")->insert($insert);
                }
                return true;
            }else{
                $data['wps_number']=$serial_number;
                $data['wps_ordernum']=$input['order_num'];
                $data['wps_serid']=$ser_id;
                $data['wps_goodsname']=$good;
                $data['wps_weixindata']='获取授权失败：'.json_encode($obj);
                $data['wps_creactime']=date("Y-m-d H:i:s");
                DB::table("weixin_push")->insert($data);
                return false;
            }
        }else{
            $data['wps_number']=$serial_number;
            $data['wps_ordernum']=$input['order_num'];
            $data['wps_serid']=$ser_id;
            $data['wps_goodsname']=$good;
            $data['wps_weixindata']='无绑定微信';
            $data['wps_creactime']=date("Y-m-d H:i:s");
            DB::table("weixin_push")->insert($data);
            return true;
        }
    }

    //发送取消订单通知
    public static function push_order_rejected ( $input ){
        $ser_id=$input['ser_id'];

        $good=$input['goods_name'];
        $serial_number=$input['serial_number'];
        $master = DB::table("ser_master")
            ->where('ser_id',$ser_id)
            ->where('type',1)
            ->where('is_delet',1)
            ->select('wechat_number')
            ->get();
        if($master){
            $master = CommonService::dataToArray($master);
            $access_token= RedisService::redisGet('access_token_saas');
            if($access_token && $_GET['type']=='1'){
                $obj['access_token']=$access_token;
            }else {
                $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxf457f42f874c3545&secret=62c5530f13e8b88204818c8b98d3a5b6';//生产环境
                $arrContextOptions=array(
                    "ssl"=>array(
                        "verify_peer"=>false,
                        "verify_peer_name"=>false,
                    ),
                );
                $output = file_get_contents($url, false, stream_context_create($arrContextOptions));//运行curl
                $obj = json_decode($output, true);
                if($obj['access_token']){
                    RedisService::redisSet('access_token_saas', $obj['access_token'],'6480');
                }
            }
            //dump($obj);
            if($obj['access_token']){
                $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$obj['access_token'];
                $poss['template_id']="dI9VEYuMBzkKBBUXy7-8ygArrnnnGk-NoFyCGsRyehg";
                $data['character_string1']['value']=$input['order_num'];
                $data['const2']['value']=$input['goods_name'];
                $data['time3']['value']=date("Y-m-d H:i:s");
                //$data['const11']['value']='新订单';
                $poss['data']=$data;
                foreach( $master as $k => $v )
                {
                    $poss['touser']=$v['wechat_number'];
                    $res=CommonService::requestPost($url, json_encode($poss));
                    $data['wps_number']=$serial_number;
                    $data['wps_ordernum']=$input['order_num'];
                    $data['wps_serid']=$ser_id;
                    $data['wps_goodsname']=$good;
                    $data['wps_openid']=$v['wechat_number'];
                    $data['wps_weixindata']=$res;
                    $data['wps_creactime']=date("Y-m-d H:i:s");
                    DB::table("weixin_push")->insert($data);
                    return true;
                }
            }else{
                return false;
            }
        }else{
            $data['wps_number']=$serial_number;
            $data['wps_ordernum']=$input['order_num'];
            $data['wps_serid']=$ser_id;
            $data['wps_goodsname']=$good;
            $data['wps_weixindata']='无绑定微信';
            $data['wps_creactime']=date("Y-m-d H:i:s");
            DB::table("weixin_push")->insert($data);
            return true;
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 重置登录权限
     * @param string ju_ordernum 订单单号
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2024/9/27 14:37
     * |---------------------------------------------------------------------------------
    */
    public static function resetToken ( $session ){
        $result = Admin::where('id',$session['id'])->first();
        $company = Company::where("com_id",$result['company_id'])->first();
        $com_parent_id = $company['com_parent_id'];
        $result['com_parent_id'] = $com_parent_id.",".$result['company_id'];
        $result['com_brand'] = $company['com_brand'];
        $all_company = Company::whereRaw("FIND_IN_SET(".$result['company_id'].",com_parent_id) and com_type=2")->select('com_id')->get();
        $all_company = CommonService::dataToArray($all_company);
        if($all_company){
            $all_company = array_column($all_company, 'com_id');
            $all_company[] = $result['company_id'];
        }else{
            $all_company = [$result['company_id']];
        }
        $result['all_company'] = $all_company;

        $all_companys = Company::whereRaw("FIND_IN_SET(".$result['company_id'].",com_parent_id) and com_type=1")->select('com_id')->get();
        $all_companys = CommonService::dataToArray($all_companys);
        if($all_companys){
            $all_companys = array_column($all_companys, 'com_id');
            $all_companys[] = $result['company_id'];
        }else{
            $all_companys = [$result['company_id']];
        }
        $result['all_companys'] = $all_companys;
        $result['com_type'] = $company['com_type'];
        if($company['com_type']==2){
            $result['search_id'] = Admin::where('company_id',$result['company_id'])->where("admin_groupnew",3)->value('id');
        }else{
            $result['search_id']=$result['id'];
        }
        $function = Functions::where('function_type',3)->select('function_id','function_model','function_action')->get()->toArray();
        $list = [];
        foreach ($function as $k =>$v){
            $list[] = $v['function_model'].':'.$v['function_action'];
        }
        $arr['at_time'] = date('Y-m-d H:i:s');
        $arr['at_adminid'] = $result['id'];
        $at_permissions['admindata'] = $result;

        $search_token = AdminToken::where('at_adminid',$result['id'])->orderBy('at_time','DESC')->first();
        /*********************获取所有按钮**************************/

        $function_id = Department::where('id',$result['admin_groupnew'])->value('function_id');
        $function_id = explode(',',$function_id);
        $at_permissions['function_id'] = $function_id;
        $at_permissions = json_encode($at_permissions);
        $arr['at_permissions'] = $at_permissions;
        $res = Permissions::whereIn('function_id',$function_id)->where('function_position','!=',3)->select('function_id','function_parent_id','function_name','function_model','function_action','function_position','sort_order')->orderBy('sort_order','DESC')->get()->toArray();
        $at_permiss = [];
        foreach ($res as $k=>$v){
            $at_permiss[$v['function_parent_id']][] = $v;
        }
        $arr['at_perm'] = json_encode($at_permiss);
        $arr['at_accredit'] = '';
        /********************************************************************/
        if ($search_token){
            AdminToken::where('at_token',$search_token['at_token'])->update($arr);
        }else{
            AdminToken::where('at_token',$search_token['at_token'])->insert($arr);
        }
    }
}
