<?php
namespace App\Http\Controllers\Common;

use App\Models\Company;
use App\Models\GoodCode;
use App\Models\GoodsSeries;
use App\Models\NoteDetail;
use App\Models\PjGoods;
use App\Models\ServiceMode;
use App\Models\SetmoneyType;
use App\Services\ExceloutService;
use App\Services\GoodsService;
use App\Services\KhAccountService;
use App\Services\OrderService;
use App\Services\RefundService;
use App\Services\ServiceModeService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use App\Models\PhoneCoke;
use App\Models\User;
use App\Models\Note;
use App\Models\Orders;
use App\Services\CommonService;
use App\Services\PjBrandsService;
use App\Services\AdminsService;
use App\Services\PlatformService;
use App\Services\BmmcService;
use App\Services\LabtypeService;
use BlueCity\Core\Inc\ErrorInc;
use DB;
use App\Http\Controllers\BaseController;
use App\Services\CategoryService;
use App\Services\GoodsSeriesService;
use App\Services\InstallPersonService;
use App\Services\FunctionsService;
use Ramsey\Uuid\Uuid;
//通用方法控制器
class CommonController extends BaseController
{
    /**|---------------------------------------------------------------------------------
     * @name  手机验证码
     * @param phone   电话号码
     * @param send_type   发送类型 TYPE_LOGIN_PC：pc端登录验证
     * @param type   操作类型 1发送  2 验证
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2021/07/14>
     * |---------------------------------------------------------------------------------
     */
     public function phoneCode ( Request $request ){
	    $parameter = $request->only('phone','send_type','type','code');
	    $checkKey = CommonService::checkKey(['phone','type','send_type'],$parameter);
	    if($checkKey['code']!=1){
			return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM, []);
		}
		$phc_type = CommonService::aginCodeType($parameter['send_type']);
		if($phc_type == 'error'){
			return $this->error('操作类型错误', ErrorInc::FAILED_PARAM, []);
		}else{
			switch ( $parameter['type'] ){
				case 1:
					return self::sendPhoneCode($parameter,$phc_type);
				break;
				case 2:
					return self::verifyPhoneCode($parameter,$phc_type);
				break;
				default:
					return $this->error('操作类型错误', ErrorInc::FAILED_PARAM, []);
					break;
			}
		}
     }
     /**|---------------------------------------------------------------------------------
     * @name  发送验证码
     * @param array  $parameter  请求参数
     * @param string  $phc_type 验证码类型
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2021/07/15>
     * |---------------------------------------------------------------------------------
     */
     public function sendPhoneCode ( $parameter , $phc_type ){
		$res = PhoneCoke::whereRaw("phc_phone='".$parameter['phone']."' AND phc_expirationtime>'".date("Y-m-d H:i:s")."'")->first();
		if($res){
            return $this->error('验证码未过期', ErrorInc::REPEAT_SUBMIT, []);
        }else{
	     	$code = rand(111111,999999);
	     	$res=PhoneCoke::insert(['phc_phone'=>$parameter['phone'],'phc_coke'=>$code,'phc_creacttime'=>date("Y-m-d H:i:s"),'phc_type'=>$phc_type,'phc_expirationtime'=>date('Y-m-d H:i:s', time() + 600)]);
	     	if($res){
	            $content="您本次的验证码为".$code.",有效时间为十分钟,请勿告诉他人";//内容
	            //$sms=CommonService::senSms($parameter['phone'],$content,'SuDianPaw');
	            $sms=10001;
		        if($sms>0){
			        $data['code'] = $code;
			        $data['phone'] = $parameter['phone'];
			        return $this->success('发送成功', $data);
			    }else{
			        return $this->error('验证码生成失败', ErrorInc::TRANSFER_FAILED, []);
			    }
	     	}else{
		     	return $this->error('验证码生成失败', ErrorInc::MYSQL_FAILED, []);
	     	}
     	}
    }
    /**|---------------------------------------------------------------------------------
     * @name  验证验证码
     * @param array  $parameter  请求参数
     * @param string  $phc_type 验证码类型
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2021/07/15>
     * |---------------------------------------------------------------------------------
     */
    public function verifyPhoneCode ( $parameter , $phc_type ){
	    $checkKey = CommonService::checkKey(['code'],$parameter);
	    if($checkKey['code']!=1){
			return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM, []);
		}
    	$res = PhoneCoke::whereRaw("phc_phone='".$parameter['phone']."' and phc_creacttime>'".date('Y-m-d H:i:s', time() - 900)."' and phc_coke='".$parameter['code']."' and phc_type='".$phc_type."'")->value('phc_expirationtime');
    	if(!$res){
            return $this->error('验证码不存在', ErrorInc::REQUEST_FORBIDDEN, []);
        }else{
	        if($res < date("Y-m-d H:i:s")){
		        return $this->error('验证码已过期', ErrorInc::REQUEST_FORBIDDEN, []);
	        }else{
		        $data['code']=$parameter['code'];
		        $data['phone']=$parameter['phone'];
		        return $this->success('验证成功', $data);
	        }
     	}
    }
    /**|---------------------------------------------------------------------------------
     * @name  获取商品品牌
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2021/07/26>
     * |---------------------------------------------------------------------------------
     */
    public function getBrand ( Request $request )
    {
        $type = 1;
    	if($request->get('session_token')['admin_groupnew'] == 7){//管理员默认展示全部平台
    	    if($request->filled('brand_id')){
                $type = 2;
                if(is_array($request->input('brand_id'))){
                    $brandId = $request->input('brand_id');
                }else{
                    $brandId = explode(',',$request->input('brand_id'));
                }
            }else {
                $brand = PjBrandsService::getAll();
            }
    	}else{
		    $brandId = trim($request->get('session_token')['ad_brand'],',');
		    if($brandId == ''){
                $brandId = [];
            }else {
                $type = 2;
                $brandId = explode(',', $brandId);
            }
            if($request->filled('brand_id')){
                $type = 2;
                if(is_array($request->input('brand_id'))){
                    $brandIds = $request->input('brand_id');
                }else{
                    $brandIds = explode(',',$request->input('brand_id'));
                }
                if($brandId) {
                    $brandId = array_intersect($brandIds, $brandId);
                }else{
                    $brandId = $brandIds;
                }
            }
	    }
        if($type == 1){
            $brand = PjBrandsService::getAll();
        }else {
            $brand = PjBrandsService::getAll($brandId);
        }
        if($request->get('session_token')['admin_groupnew'] != 7) {//管理员默认展示全部平台
            $session = Request()->get('session_token');//用户信息
            $brand = CommonService::arrayFilterFieldValue($brand,[['company_id'=>$session['company_id']]]);
        }
	    if($brand){
	    	return $this->success('操作成功', $brand);
    	}else{
	    	return $this->error('无数据', ErrorInc::DATA_EMPTY, []);
    	}
    }
    /**|---------------------------------------------------------------------------------
     * @name 获取商品
     * @param string good_name 商品型号
     * @param int brand_id 品牌id
     * @param string cd_id 品类ID
     * @param int searchtype 查询类型  1列表以及非商品列表检索  2商品添加以及编辑检索
     * @retrun multitype:array
     * @author dou 2021/8/9 17:06
     * |---------------------------------------------------------------------------------
    */
    public function getGoods ( Request $request ){
        /*$db = new PjGoods();
        $list = CommonService::getMysqlData($db, ['pg_id_searchgt'=>1000],['pg_id','general_version']);
        $num = 0;
        foreach($list as $k => $v){
            if($v['general_version']!='') {
                $poss[$num]['pgc_pgid'] = $v['pg_id'];
                $poss[$num]['pgc_type'] = 1;
                $poss[$num]['pgc_code'] = $v['general_version'];
                $poss[$num]['new'] = $v['general_version'];
                $num++;
            }
        }
        DB::table('pj_goodcode')->insert($poss);*/
        /*---------------------------用于同步商品品牌id----------------------------------------*/
//        $brand = PjBrandsService::getAll(['1','2','3','4','5','6','7','8','9','12','13','14','15','16','17','18','19','20','21','22','23','24'],'brand_name');
//        dump($brand);
//        $list = DB::table('pj_goods')->select('pg_id','brand_name','pg_series','version','cd_id')->get()->toarray();
//        foreach($list as $k => $v){
//            dump($brand[$v['brand_name']]['id']);
//            $poss[$k]['gs_bid'] = $brand[$v['brand_name']]['id']??0;
//            DB::table('pj_goods')->where('pg_id',$v['pg_id'])->update($poss[$k]);
//        }
//        return $this->success('操作成功', 1);
        /*---------------------------用于同步商品品牌id----------------------------------------*/
        /*-------------------------------------同步商品名称----------------------------------------------*/
//        $list = DB::table('pj_goods')->whereRaw("cd_id = 1 or pg_goodsname is null or pg_goodsname = ''")->select('pg_id','brand_name','pg_series','version','cd_id')->get()->toarray();
//        foreach($list as $k => $v){
//            if ($v['pg_series'] != '') {
//                $pg_series = '-' . $v['pg_series'];
//            } else {
//                $pg_series = '';
//            }
//            $poss[$k]['pg_goodsname'] = $v['brand_name'] . $pg_series . '-' . $v['version'];
//            DB::table('pj_goods')->where('pg_id',$v['pg_id'])->update($poss[$k]);
//        }
        /*-------------------------------------同步商品名称----------------------------------------------*/
        $where = [];
        if($request->filled('brand_id')){
            $where['gs_bid'] = $request->input('brand_id');
        }else{
           /* $bmmc_pids=BmmcService::searchPids($request->get('session_token')['admin_groupnew']);
            if(in_array('104',$bmmc_pids) || in_array('112',$bmmc_pids) || in_array('8',$bmmc_pids)) {
                if ($request->filled('gs_bids')) {
                    $where['gs_bid_searchin'] = $request->input('gs_bids');
                }
            }*/
        }
      if($request->filled('good_name')){
            $goods_name = $request->input('good_name');
            $goods_name = explode(' ', $goods_name);
            foreach($goods_name as $k => $v){
                $next = 'data'.$k.'_next_level';
                $where[$next]['data_searchor']['pg_goodsname_like'] = $v;
                $where[$next]['data_searchor']['general_version_like'] = $v;
            }
        }
        if($request->filled('cd_id')){
            $where['cd_id_searchin'] = $request->input('cd_id');
        }
        if($request->filled('searchtype')){
            if($request->input('searchtype') == 2){
                if(!$request->filled('cd_id') || !$request->filled('brand_id')){
                    return $this->error('品类id和品牌id必传', ErrorInc::FAILED_PARAM);
                }else{
                    $where['pg_parentid'] = 0;
                }
            }
        }
        $session = $request->get('session_token');
        if ($session['admin_groupnew'] != 7){//管理员可以看全部
            $where['company_id_searchin'] = $session['com_parent_id'];
        }
        $list = GoodsService::getGoodsBy($where);
        if($list){
            return $this->success('操作成功', $list);
        }else{
            return $this->error('无数据', ErrorInc::DATA_EMPTY, []);
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name  获取平台
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2021/07/26>
     * |---------------------------------------------------------------------------------
     */
    public function getPt ( Request $request )
    {
        $pt = PlatformService::getAll();
       // return $this->success('操作成功1', $pt);
	    if($request->get('session_token')['admin_groupnew'] == 7 || $request->get('session_token')['admin_groupnew'] == 8 || $request->get('session_token')['admin_groupnew'] == 9){//管理员默认展示全部平台
	    }else{
            $ptId = trim($request->get('session_token')['admin_pt_id'],',');
            $pt = CommonService::arrayFilterFieldValue($pt,array(array('id'=>explode(',',$ptId))));
            $pt = CommonService::resetListKey($pt);
//            $pt = PlatformService::getAll(explode(',',$ptId));
    	}

        if($request->get('session_token')['admin_groupnew'] != 7){
            $pt = CommonService::arrayFilterFieldValue($pt,array(array('company_id'=>$request->get('session_token')['company_id'])));
            $pt = CommonService::resetListKey($pt);//2022-1-19 du add
        }
	    if($pt && $request->filled('three_pd')){
            $pt = CommonService::arrayFilterFieldValue($pt,array(array('three_pd'=>1)));
            $pt = CommonService::resetListKey($pt);//2022-1-19 du add
        }
        if($pt && $request->filled('pt_zt')){
          //  return $this->success('操作成功11', $pt);
                $pt = CommonService::arrayFilterFieldValue($pt,array(array('pt_zt'=>1)));
                $pt = CommonService::resetListKey($pt);//2022-1-19 du add
        }
        if($pt && $request->filled('cd_id')){
            $cd_id = $request->input('cd_id');
            if(is_array($cd_id)) {
                $pts = [];
                foreach ($pt as $k => $v) {
                    if (array_intersect(explode(',', $v['cd_ids']), $cd_id)) {
                        $pts[] = $v;
                    }
                }
                $pt = $pts;
            }else{
                return $this->error('品类格式错误', ErrorInc::INVALID_PARAM, []);
            }
        }
	    if($pt){
	        $usermodel = CommonService::getUserModelType(1);
            foreach ($pt as $k => $v) {
                if($v['cd_ids'] == ''){
                    $pt[$k]['cd_ids'] = [];
                }else {
                    $pt[$k]['cd_ids'] = explode(',', $v['cd_ids']);
                }
                if($v['gs_bids'] == ''){
                    $pt[$k]['gs_bids'] = [];
                }else {
                    $pt[$k]['gs_bids'] = explode(',', $v['gs_bids']);
                }
                if(in_array($v['id'], $usermodel)){
                    $pt[$k]['usermodeltype'] = 1;
                }else{
                    $pt[$k]['usermodeltype'] = 2;
                }
            }
	    	return $this->success('操作成功', $pt);
    	}else{
	    	return $this->error('无数据', ErrorInc::DATA_EMPTY, []);
    	}
    }
    /**|---------------------------------------------------------------------------------
     * @name  获取人员信息
     * @param Request $request
     * @param int type 查询类型 1系统操作人 2 服务门店
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2021/07/26>
     * |---------------------------------------------------------------------------------
     */
    public function getAdmins ( Request $request )
    {
	    $parameter = $request->all();
	    $checkKey = CommonService::checkKey(['type'],$parameter);
	    if($checkKey['code']!=1){
			return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM, []);
		}
        $session = $request->get('session_token');
        if ($session['admin_groupnew'] != 7 ){//管理员可以看全部
            if($parameter['type'] ==2 && $parameter['Pri_id'] !=86) {
                $com_parent_id = explode(',', $session['com_parent_id']);
                if($session['company_id']!=1){
                    $com_parent_id = array_filter($com_parent_id, function($value) {
                        return $value != 1; // 这里可以修改条件来移除不同的值
                    });
// 重置数组键名
                    $com_parent_id = array_values($com_parent_id);
                }
                $parameter['company_id_searchin'] = $com_parent_id;
            }else{
                $parameter['company_id'] = $session['company_id'];
            }
        }
        $Pri_id = $parameter['Pri_id'];
		$type = $parameter['type'];
		unset($parameter['type']);
		unset($parameter['token']);
		unset($parameter['Login_id']);
		unset($parameter['Pri_id']);
//		$parameter['enable'] = 1;
		switch ( $type )
		{
			case 1:
				$parameter['admin_groupnew_noteq'] = 2;
				$list = AdminsService::getAdmins($parameter,['id','admin_acc']);//,['ptid'=>'desc','admin_groupnew'=>'asc']
			break;
			case 2:
			    if($parameter['company_name_like']!='统一价格') {
                    $parameter['admin_groupnew'] = 2;
                    $list = AdminsService::getAdmins($parameter, ['id', 'company_name'], []);
                    if($Pri_id !=86) {
                        $lists[0]['id'] = '0';
                        $lists[0]['company_name'] = '统一价格';
                        $list = array_merge($list, $lists);
                    }
                }else{
                    if($Pri_id ==86) {
                        $list = [];
                    }else {
                        $list[0]['id'] = '0';
                        $list[0]['company_name'] = '统一价格';
                    }
                }
            default:
				break;
		}
	    if($list){
	    	return $this->success('操作成功', $list);
    	}else{
	    	return $this->error('无数据', ErrorInc::DATA_EMPTY, []);
    	}
    }
    /**|---------------------------------------------------------------------------------
     * @name 获取用户明细
     * @param int id 数据id
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/8/14 14:20
     * |---------------------------------------------------------------------------------
    */
    public function getAdminDetail ( Request $request ){
        if($request -> filled('id')) {
            $list = AdminsService::getAdminDetail($request->input('id'), $request->get('session_token')['admin_groupnew'],$request->get('session_token')['company_id']);
            if($list){
                return $this->success('操作成功', $list);
            }else{
                return $this->error('无数据', ErrorInc::DATA_EMPTY, []);
            }
        }else{
            return $this->error('缺少参数', ErrorInc::INVALID_PARAM);
        }
    }
    /**
     * 获取品类
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年7月27日下午3:57:49
     */
    public function getCategory( Request $request ){
    	$list = CategoryService::getAll();
    	if($list){
    		return $this->success('操作成功', $list);
    	}else{
    		return $this->error('无数据', ErrorInc::DATA_EMPTY, []);
    	}

    }

    /**
     * 获取系列
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年7月27日下午4:14:04
     */
    public function getGoodsSeries( Request $request ){
    	if(!$request->filled('gs_bid')||!$request->filled('cd_id')){
    		return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);exit;
    	}
    	$gs_bid = $request->input('gs_bid');
    	$cd_id = $request->input('cd_id');
    	$list = GoodsSeriesService::getall($gs_bid, $cd_id);
    	if($list){
    		return $this->success('操作成功', $list);
    	}else{
    		return $this->error('无数据', ErrorInc::DATA_EMPTY, []);
    	}
    }

    /**
     * 获取技师列表
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年7月27日下午4:26:59
     */
    public function getInstallPerson( Request $request ){
    	if(!$request->filled('serId')){
    		return $this->error('参数错误', ErrorInc::INVALID_PARAM, []);exit;
    	}
    	$serId = $request->input('serId');
    	$list = InstallPersonService::getall($serId);
    	if($list){
    		return $this->success('操作成功', $list);
    	}else{
    		return $this->error('无数据', ErrorInc::DATA_EMPTY, []);
    	}
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取部门列表
     * @param admin_group 操作人权限
     * @return \Illuminate\Http\JsonResponse
     * @author dou
     * |---------------------------------------------------------------------------------
     */
	public function getBmmc ( Request $request ){
	 	$list = BmmcService::getBmmc($request->get('session_token'),$request->input('Pri_id'));
	 	if($list['code']=='1'){
	        return $this->success($list['msg'], $list['data']);
        }else{
	        return $this->error($list['msg'] , $list['code'] , $list['data']);
        }
	}

	/**|---------------------------------------------------------------------------------
     * @name 获取标签列表
     * @param int sety_id 标签id
     * @param int type 当前请求标签类型
     * @param string sys_num 系统单号
     * @return \Illuminate\Http\JsonResponse
     * @author dou 2021/07/29
     * |---------------------------------------------------------------------------------
     */
    public function getLable ( Request $request ){
    	if(!$request->filled('type')){
    		return $this->error('参数错误', ErrorInc::INVALID_PARAM, []);exit;
    	}
    	$key = 'lt_parent_id';
        $group = $request->get('session_token')['admin_groupnew'];
    	if($request->filled('sety_id')){
    	    $sety_id = $request->input('sety_id');
        }else{
    	    switch ( $request->input('type') ){
    	        case 'orderAfterApply'://售后申请标签
                    if(!$request->filled('category')) {
                        $category = OrderService::getOrderBy('sys_num', $request->input('sys_num'), ['category']);
                    }else{
                        $category = $request->input('category');
                    }
                    if($category == 3){
                        $sety_id = 510;
                    }else {
                        $sety_id = 208;
                    }
    	            break;
                case 'recoveryOfReason'://回收原因标签
                    $sety_id = 690;
                    break;
                case 'orderAfterAudit'://售后审核标签
                    if(!$request->filled('category')) {
                        $category = OrderService::getOrderBy('sys_num', $request->input('sys_num'), ['category']);
                    }else{
                        $category = $request->input('category');
                    }
                    if($category == 3){
                        $sety_id = 511;
                    }else {
                        $sety_id = 209;
                    }
                    break;
                case 'refuseOrder'://拒单
                    $sety_id = 25;
                    break;
                case 'serInfor'://催单反馈
                    $sety_id = 79;
                    break;
                case 'undoOrder':
                    $status = OrderService::getOrderBy('sys_num', $request->input('sys_num') , ['order_status','category']);
                    if($status['category']>2){
                        $sety_id = 31;//安装前退单
                    }else {
//                        if ($status['order_status'] < 34) {
//                            $sety_id = 31;//安装前退单
//                        } else {
                            $sety_id = 39;//安装后退单
//                        }
                    }
                    break;
                case 'ticketAdd'://申请罚单
                    $sety_id = 231;
                    break;
                case 'evenlution'://评价
                    $sety_id = 60;
                    break;
                case 'evenlutionFilm'://车膜
                    $sety_id = [458,459];
                    break;
                case 'appeal'://评价申诉
                    $sety_id = 242;
                    break;
                case 'ticketRepeal'://罚单申诉
                    $sety_id = 232;
                    break;
                case 'priceType'://金额标签
                    $sety_id = ['1','2','4'];
                    $key = 'sety_type';
                    $group = '';
                    break;
    	        default:
                    $sety_id = '';
    	            break;
    	    }
        }
        if(!$sety_id){
            return $this->error('参数错误', ErrorInc::INVALID_PARAM, []);exit;
        }
        $group = '';
    	$list = LabtypeService::getLable($key,$sety_id,$group,1);
    	if($list){
            $list = $this -> conversionLable( $request->input('type') , $list );
    		return $this->success('操作成功', $list);
    	}else{
    		return $this->error('无数据', ErrorInc::DATA_EMPTY, []);
    	}
    }

    /**|---------------------------------------------------------------------------------
     * @name 转化标签数据
     * @param string $type 查询类型
     * @param array $list 标签数据
     * @retrun /multitype:array
     * @author dou 2021/12/8 11:11
     * |---------------------------------------------------------------------------------
    */
    public function conversionLable ( $type , $list ){
        $data = [];
        switch ( $type ){
            case 'evenlutionFilm':
                $list = CommonService::jointArrayKey($list, 'lt_parent_id',2);
                $data['technology'] = $list['458'];
                $data['service'] = $list['459'];
                break;
            default:
                $data = $list;
                break;
        }
        return $data;
    }

    /**|---------------------------------------------------------------------------------
     * @name 添加备注
     * @param string sys_num 系统单号
     * @param string car_make 车辆品牌
     * @param string car_line 车辆系列
     * @param string car_model 车辆型号
     * @param string car_id 车辆id
     * @param string content 备注信息
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/8/12 16:48
     * |---------------------------------------------------------------------------------
    */
    public function addRemarks ( Request $request ){
        if (!$request->filled('sys_num') || (!$request->filled('content') && !$request->filled('car_model'))) {
            return $this->error('参数错误', ErrorInc::INVALID_PARAM, []);
            exit;
        }
        $sys_num = $request->input('sys_num');
        $letMe = false;
        $icon = false;
        /*-------------------------------------------添加用户车辆信息开始------------------------------------------------*/
        if($request->filled('car_id') || $request->filled('car_model') || $request->filled('car_infor')){
            $car_infor = $request->input('car_infor')??'';
            $letMe = CommonService::addUserCar($sys_num, $request->input('car_make'), $request->input('car_line'), $request->input('car_model'), $request->input('car_id'),$car_infor);
            Orders::where('sys_num',$request->input('sys_num'))->where('order_status','<',10)->update(['order_status'=>10]);
        }
        /*-------------------------------------------添加用户车辆信息结束------------------------------------------------*/

        /*--------------------------------------------添加备注信息开始----------------------------------------------------*/
        if ($request->filled('content')) {
            $content = $request->input('content');
            $avtion = FunctionsService::getFunctionsBy('function_id', $request->input('Pri_id'), ['function_name']);
            $icon = CommonService::accMe($request->input('sys_num'), $avtion, $content, '', 1, $request->get('session_token')['admin_groupnew'], $request->get('session_token')['admin_acc'], $request->get('session_token')['id']);
        }
        /*--------------------------------------------添加备注信息结束----------------------------------------------------*/

        if ($letMe || ($icon)) {
            return $this->success('操作成功');exit;
        } else {
            return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取备注
     * @param string sys_num 系统单号
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/8/12 18:24
     * |---------------------------------------------------------------------------------
    */
    public function getRemarks ( Request $request ){
        if (!$request->filled('sys_num')) {
            return $this->error('缺少参数', ErrorInc::INVALID_PARAM);
            exit;
        }
        $group = $request->get('session_token')['admin_groupnew'];
        $list = CommonService::orderRemarks($request->input('sys_num'),'',$group,$request->input('Login_id'));
        $bmmc_pids=BmmcService::searchPids($group);
        if(in_array('79',$bmmc_pids) || $group == 7){
            $remove = true;
        }else{
            $remove = false;
        }
        foreach($list as $k => $v){
            if($list[$k]['note_type'] == '订单管理'){
                $list[$k]['type'] = 1;
            }elseif(strpos($list[$k]['note_type'],'催单') !== false){
                $list[$k]['type'] = 2;
            }elseif(strpos($list[$k]['note_type'],'售后') !== false){
                $list[$k]['type'] = 3;
            }else{
                $list[$k]['type'] = 0;
            }
            $list[$k]['remove'] = $remove;
            if(!in_array($request->get('session_token')['admin_groupnew'], [7,79,84])){
                if($request->get("session_token")['id']!=$v['note_adid']){
                    $list[$k]['remove'] = false;
                }else {
                    $note_time = $v['note_time'];
                    $note_time = strtotime($note_time);
                    $now = time();
                    $guonian = ($now - $note_time) / 60;
                    if ($guonian > 15) {
                        $list[$k]['remove'] = false;
                    }
                }
            }
        }
        $data['carinfo'] = CommonService::getUserCar($request->input('sys_num'),true);
        if($list){
            $data['list'] = $list;
            return $this->success('操作成功',$data);exit;
        }else{
            return $this->error('无数据', ErrorInc::DATA_EMPTY,$data);
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取备注详情
     * @param int note_id 备注id
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2022/3/7 17:36
     * |---------------------------------------------------------------------------------
    */
    public function getRemarksDetail ( Request $request ){
        if ($request->filled('note_id')){
            $db = new NoteDetail();
            $data = CommonService::getMysqlData($db, ['ntd_nid'=>$request->input('note_id')],['ntd_content'],[],'value');
            return $this->success('操作成功',$data);
        }else{
            return $this->error('缺少参数', ErrorInc::INVALID_PARAM);exit;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 编辑备注
     * @param int note_id 备注id
     * @param int type 1:公开状态  2：移除
     * @param string sys_num 系统单号
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/8/12 19:19
     * |---------------------------------------------------------------------------------
    */
    public function editRemarks ( Request $request ){
        if ($request->filled('note_id') && $request->filled('type')) {
            $type = $request->input('type');
            $id = (int)$request->input('note_id');
            $not = Note::where('id', $id)->select('public_state','note_time','orders_id','note_adid')->first();
            if(!$not){
                return $this->error('数据不存在', ErrorInc::FAILED_PARAM);exit;
            }
            if($type == 1) {
                $public_state = $not['public_state'];
                if ($public_state == 1) {
                    $public_state = '公开备注';
                    $upRes = Note::where('id', $id)->update(['public_state' => 2]);
                } elseif ($public_state == 2) {
                    $public_state = '私有备注';
                    $upRes = Note::where('id', $id)->update(['public_state' => 1]);
                }
            }elseif ($type == 2){
                if(!in_array($request->get('session_token')['admin_groupnew'], [7,79,84])){
                    if($request->get("session_token")['id']!=$not['note_adid']){
                        return $this->error('请联系添加人或者管理员删除', ErrorInc::REQUEST_FORBIDDEN);exit;
                    }
                    $note_time = $not['note_time'];
                    $note_time = strtotime($note_time);
                    $now = time();
                    $guonian = ($now - $note_time) / 60;
                    if($guonian > 15){
                        return $this->error('已超出允许时间请联系负责人', ErrorInc::REQUEST_FORBIDDEN);exit;
                    }
                }
                $public_state = '移除备注';
                $upRes = Note::where('id', $id)->update(['is_delet' => 2]);
            }else{
                return $this->error('参数错误', ErrorInc::FAILED_PARAM);exit;
            }
            if ($upRes) {
                if($type == 1){
                    $this->insertingLog($public_state ,$not['orders_id'], $public_state.":".$id,"处理备注",$request->ip(),$request->get('session_token')['admin_acc']);
                }else{
                    $this->insertingLog($public_state ,$not['orders_id'], $public_state.":".$id,"处理备注",$request->ip(),$request->get('session_token')['admin_acc']);
                }
                return $this->success('操作成功');exit;
            } else {
                return $this->error('操作失败', ErrorInc::DATA_EMPTY);
            }
        } else {
            return $this->error('缺少参数', ErrorInc::INVALID_PARAM);exit;
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name  订单追踪
     * @param  tracking_state
     * @return \Illuminate\Http\JsonResponse
     *|---------------------------------------------------------------------------------
     */
    public function setTrack(Request $request)
    {
        if ($request->filled('sys_num') && $request->filled('type')) {
            if(in_array($request->input('type'), [1,2])) {
                if ($request->input('type') == 1) {
                    $state = OrderService::getOrderBy('sys_num', $request->input('sys_num'), ['tracking_state']);
                    return $this->success('操作成功', $state);
                    exit;
                } elseif ($request->input('type') == 2) {
                    $state = OrderService::getOrderBy('sys_num', $request->input('sys_num'), ['tracking_state']);
                    if ($state == 1) {
                        $track = 2;
                    } elseif ($state == 2) {
                        $track = 1;
                    }
                    $result = Orders::where('sys_num', $request->input('sys_num'))->update(['tracking_state' => $track]);
                    if ($result) {
                        $avtion = FunctionsService::getFunctionsBy('function_id', $request->input('Pri_id'), ['function_name']);
                        $this->insertingLog('订单追踪' ,$request->input('sys_num'), "订单追踪:".$request->input('sys_num')."(".$track.")",$avtion,$request->ip(),$request->get('session_token')['admin_acc']);
                        return $this->success('操作成功');
                        exit;
                    } else {
                        return $this->error('操作失败', ErrorInc::DATA_EMPTY);
                    }
                }
            }else{
                return $this->error('缺少参数', ErrorInc::FAILED_PARAM);exit;
            }
        }else{
            return $this->error('缺少参数', ErrorInc::INVALID_PARAM);exit;
        }

    }

    /**|---------------------------------------------------------------------------------
     * @name 获取系统推荐服务商
     * @param is_type 1:搜索匹配的服务中心; 4:名称匹配服务商
     * @param sys_num 系统单号（is_type=1）
     * @param sheng   省（is_type=1）
     * @param shi     是（is_type=1）
     * @param xian    县（is_type=1）
     * @param address 详细地址（is_type=1）
     * @param order_type 订单类型 1：普通；10：夜间；20：加急（is_type=1）
     * @param luotuo  是否为骆驼品牌 1：否 2：是（is_type=1）
     * @param
     * @param company_name 服务中心名称（is_type=4）
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/8/14 15:43
     * |---------------------------------------------------------------------------------
     */
    public function getService ( Request $request ){
        $input = $request->all();
        $session = $request->get('session_token');
        if($session['admin_groupnew']==2){
            return $this->error('无数据', ErrorInc::TRANSFER_FAILED);
        }
        $res = OrderService::getService($input,$session);
        return $this->error($res['ErrorMessage'], $res['ErrorCode'], $res['Data']);
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取车型信息列表
     * @param string keyword 查询参数
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/8/28 10:32
     * |---------------------------------------------------------------------------------
    */
    function getCarInfor(Request $request)
    {
        if(!$request->filled('keyword')){
            return  $this->error('请输入查询参数', ErrorInc::FAILED_PARAM);
        }
        $keywrord = $request->input('keyword');
        if($request->filled('limit')){
            $limit = $request->input('limit');
        }else{
            $limit = 10000;
        }
        if($request->filled('type') && $request->input('type') == '1'){
            $api = '/champion/car/simple-info/by-keyword';
        }else{
            $api = '/champion/search/by-keyword';
        }
        //$url = 'http://data.bluedata.org.cn/api';
        $url = 'http://data.bluedata.org.cn/manager';
        $poss['appId'] = "dispatch4m3s9e3df65s0";
        $poss['keyword'] = $keywrord;//关键词
        $poss['limit'] = $limit;// 条数
        $uuid = Uuid::uuid1();
        $poss['uuid'] = $uuid->toString();
        $poss['timeTamp'] = time();
        $poss = json_encode($poss,JSON_UNESCAPED_UNICODE);
        $header[] = "signature:".md5($poss."P8ztEh1WEkWxrC0YtFnZoFUXi5ewkF9qXuUNHA8kISDDCA07ME8oR5RweBj0");
        $header[] = 'Content-Type:application/json';
        $ret = CommonService::requestPost($url.$api,$poss,$header);
        $ret = json_decode($ret,true);
        if(!empty($ret['data'])){
            foreach ($ret['data']  as $k=>$v) {
                $res[$k]['oc_brand'] = $v['carMasterBrandName'];
                $res[$k]['oc_series'] = $v['carBrandName'];
                $res[$k]['oc_model'] = $v['carSeriesName'];
                if($request->filled('type') && $request->input('type') == '1'){
                    $res[$k]['oc_models'] = '';
                }else{
                    $res[$k]['oc_models'] = $v['carDpm'].' '.$v['carNewName'];
                }
                $res[$k]['oc_year'] = $v['carYear'];
                if($request->filled('type') && $request->input('type') == '1'){
                    $res[$k]['oc_detail'] = $res[$k]['oc_brand'] . ' ' . $res[$k]['oc_series'] . ' ' . $res[$k]['oc_model'] . ' ' . $res[$k]['oc_year'];
                }else {
                    $res[$k]['oc_detail'] = $res[$k]['oc_brand'] . ' ' . $res[$k]['oc_series'] . ' ' . $res[$k]['oc_model'] . ' ' . $res[$k]['oc_models'] . ' ' . $res[$k]['oc_year'];
                }
                $res[$k]['code'] = $v['code'];
                $res[$k]['oc_carid'] = $v['id'];
            }
            return $this->success('操作成功',$res);
        }

        return  $this->error('操作失败', ErrorInc::TRANSFER_FAILED);
    }

    /**
     * @name 获取导出
     * @param $pri_id　栏目ID
     * @param $sqls
     * @param $session
     * @return \Illuminate\Http\JsonResponse|mixed
     * @author du
     * @date 2021/8/26
     */
    public function getExcelOut($pri_id,$sqls,$session,$limit = 500){
        $exceout = new ExceloutService();
        if(!$sqls){
            return $this->error('暂无数据或请检查SQL日志是否打开', ErrorInc::MYSQL_FAILED);
        }
        $list = $exceout->getSqls($sqls)['list'];
        if($list){
            $sql = $exceout->getSqls($sqls)['sqls'];
            $avtion = FunctionsService::getFunctionsBy('function_id', $pri_id, ['function_name','function_model']);
            //dump($avtion);
            $con_name = $avtion['function_name'];//控制器名称
            $action = $avtion['function_model'];//控制器
            $field_data = $exceout->gainFields($session['id'],$action);
            if (empty($field_data)) {
                return $this->error('您暂时无导出权限', ErrorInc::MYSQL_FAILED);
            }
            return $exceout->createPlan($list,$sql,$limit,$action,$con_name,$session['id'],$session['admin_acc'],$session['company_id']);
        }else{
            return $this->error('暂无数据', ErrorInc::MYSQL_FAILED);
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取仓库
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/9/10 15:52
     * |---------------------------------------------------------------------------------
    */
    public function getWarehouse ( Request $request ){
        $data = CommonService::getWarehouse();
        return $this->success('操作成功',$data);
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取订单状态
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/9/13 19:44
     * |---------------------------------------------------------------------------------
     */
    public function getOrderType ( Request $request ){
        $list = OrderService::showOrderType($request->get('session_token')['admin_groupnew']);
        return $this->success('操作成功',$list);exit;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取当前版本号
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/9/16 10:13
     * |---------------------------------------------------------------------------------
    */
    public function getVersion ( Request $request ){
        $version_num = Db::table('version')->orderBy('id','DESC')->value('version_num');
        if($version_num){
            return $this->success('操作成功',$version_num);exit;
        }else{
            return $this->error('操作失败', ErrorInc::DATA_EMPTY);exit;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取当前系统年月
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/10/8 18:26
     * |---------------------------------------------------------------------------------
    */
    public function getSystemTime ( Request $request ){
        $data = [];
        $data['year'] = date("Y");
        $data['month'] = date("m");
        $data['day'] = date("d");
        $data['hours'] = date("H");
        $data['minutes'] = date("i");
        $data['seconds'] = date("s");
        $data['time'] = date("Y-m-d H:i:s");
        return $this->success('操作成功',$data);exit;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取表格模板
     * @param string modeltype 模板类型
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/10/9 10:15
     * |---------------------------------------------------------------------------------
    */
    public function getExcelModel ( Request $request ){
        if(!$request->filled('modeltype')){
            return $this->error('请填写模板类型', ErrorInc::INVALID_PARAM);
            exit;
        }else{
            $modeltype = array(
                "giftmodel",
                "fengfanmodel",
                "Evaluationmodel",
                'Importmodel',
                'F6Model',
                'F6OrderModel',
                'OrdersTaskModel',
                'noteModel',
                'recycleJdModle',
                'PtPhistory'
            );
            if(!in_array($request->input('modeltype'), $modeltype)){
                return $this->error('模板类型错误', ErrorInc::FAILED_PARAM);
                exit;
            }else{
                $modelUrl = array(
                    "giftmodel"=>array(
                        "name"=>"礼物模板",
                        "url"=>"excel/model/giftmodel.xlsx"
                    ),"fengfanmodel"=>array(
                        "name"=>"风帆模板",
                        "url"=>"excel/model/fengfanmodel.xlsx"
                    ),"Evaluationmodel"=>array(
                        "name"=>"评价模板",
                        "url"=>"excel/model/Evaluationmodel.xlsx"
                    ),"Importmodel"=>array(
                        "name"=>"订单模板",
                        "url"=>"excel/model/Importmodel.xlsx"
                    ),"F6Model"=>array(
                        "name"=>"F6模板",
                        "url"=>"excel/model/F6Model.xlsx"
                    ),"F6OrderModel"=>array(
                        "name"=>"F6订单模板",
                        "url"=>"excel/model/F6OrderModel.xlsx"
                    ),"OrdersTaskModel"=>array(
                        "name"=>"任务订单模板",
                        "url"=>"excel/model/OrdersTaskModel.xlsx"
                    ),"noteModel"=>array(
                        "name"=>"备注模板",//2022-3-4 新增
                        "url"=>"excel/model/noteModel.xlsx"
                    ),"recycleJdModle"=>array(
                        "name"=>"京仓回收模板",//2022-3-10 新增
                        "url"=>"excel/model/recycleJdModle.xlsx"
                    ),"PtPhistory"=>array(
                        "name"=>"平台核销模板",//2022-3-10 新增
                        "url"=>"excel/model/PtPhistory.xlsx"
                    )
                );
                return $this->success('操作成功',$modelUrl[$request->input('modeltype')]);exit;
            }
        }
    }

    /**
     * @name 获取撤销补助价格列表
     * @return mixed
     * @author du
     * @date 2021/10/13
     */
    public function getSubsidyPrice(){
        $sety_price = SetmoneyType::where('sety_id',4)->value('sety_price');
        $sety_price = explode(',', $sety_price);
        return $this->success('获取成功',$sety_price);
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取退款申请类型
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/11/2 16:22
     * |---------------------------------------------------------------------------------
    */
    public function getRefundApplyType ( Request $request ){
        if($request->filled('type')){
            if($request->input('type') == 2) {
                $applyType = RefundService::getRefundApplyType(false,false,2);
            }else{
                $applyType = RefundService::getRefundApplyType();
            }
        }else {
            $applyType = RefundService::getRefundApplyType(false, true);
        }
        return $this->success('操作成功',$applyType);
    }

    /**
     * name 获取订单状态名
     * @return mixed
     * @author du
     * @date 2021/11/19
     */
    public function getOrderStatusName(){
        $data = OrderService::getOrderStatusName(false);
        return $this->success('获取成功',$data);
    }

    /**
     * name 获取服务方式
     * @return array|\Illuminate\Http\JsonResponse|mixed
     * @author du
     * @date 2021/12/6
     */
    public function getServeicMode( Request $request ){
        $data = ServiceModeService::getall();
        /*if($request ->filled('cd_id')){
            $sm_id = CategoryService::getall($request ->input('cd_id'));
            if($sm_id){
                $sm_id = array_column($sm_id, 'sm_ids');
                $sm_id = implode(',', $sm_id);
                $sm_id = explode(',', $sm_id);
                $sm_id = array_unique($sm_id);
            }
            $data = ServiceModeService::getall($sm_id);
        }else {
            $data = ServiceModeService::getall();
        }*/
        return $this->success('获取成功',$data);
    }



    /**
     * @name 搜索账户名
     * @param id 服务商id
     * @param accountname 服务商账户名
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author du
     * @date 2021/12/16
     */
    public function getAccountname (Request $request)
    {
        $input = $request->all();
        $list = DB::table('admin_infor as ai')
            ->leftjoin('admin as a','a.id','=','ai.admin_id')
            ->where(function($query) use($input) {
                if (!empty($input['accountname'] )) {
                    $query->where('ai.accountname','like','%'.$input['accountname'].'%');
                }
            })
            ->where(function($query) use($input) {
                if (!empty($input['id'] )) {
                    $query->where('ai.admin_id',$input['id']);
                }
            })
            ->select('ai.id','ai.accountname','a.mouth_pay')
            ->orderBy('ai.id','ASC')->limit('10')->get()->toArray();
        return response()->json(['Data'=>$list,'ErrorCode'=>1,'ErrorMessage'=>'成功']);exit;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取商品库存
     * @param string pg_id 商品id
     * @param string cd_id 商品品类id
     * @param string ware_id 库房id
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2022/1/27 17:16
     * |---------------------------------------------------------------------------------
    */
    public function getWarehouseNum ( Request $request ){
        if($request ->filled('pg_id') && $request ->filled('cd_id')){
            $input = $request->all();
            if($input['cd_id']<3){
                $data = '服务单';
            }else {
                $goods_number = GoodCode::where('pgc_pgid', $input['pg_id'])->value('pgc_code');
//                $goods_number = 'MQL-LX-CHQ';
                if($goods_number) {
                    $zhipei['time'] = date('Y-m-d H:i:s');
                    $zhipei['signature'] = md5($zhipei['time'] . '97e11cbcc29cbd8a538395abce85d569');
                    $zhipei['goods_number'] = $goods_number;
                    $zhipei['ware_id'] = $input['ware_id'] ?? 4;
                    $res = CommonService::requestPost('http://jx.bluearp.com/m/index.php/PartyIrderInterfaceThree/GetInventory', json_encode($zhipei), array('Content-Type: application/json'));
                    $res = json_decode($res, true);
                    $Data = $res;
                    if($Data['code'] == '200'){
                        if(in_array($Data['error_type'], [2,3])){
                            PjGoods::where('pg_id',$input['pg_id'])->where('pg_id','!=','5912')->where('pg_parentid','!=','5912')->update(['is_delect'=>2]);
                            return $this->error('商品已被删除或下架', ErrorInc::DATA_EMPTY);
                        }
                        if(in_array($Data['error_type'], [4])){
                            return $this->success('操作成功', $Data['goods_num']);
                        }
                        if(in_array($Data['error_type'], [1])){
                            return $this->success('操作成功', $Data['goods_num']);
                        }
                    }else{
                        return $this->success('操作成功', '查询库存失败');
//                        return $this->error('同步智配失败:'.$Data['data'], ErrorInc::TRANSFER_FAILED);
                    }
                }else{
                    return $this->error('数据异常请联系管理员', ErrorInc::DATA_EMPTY);
                }
            }
            return $this->success('操作成功', $data);
        }else{
            return $this->error('参数错误', ErrorInc::FAILED_PARAM);
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取开户行号信息
     * @retrun /multitype:array
     * @author dou 2022/6/8 15:47
     * |---------------------------------------------------------------------------------
    */
    public function getKhAccount ( Request $request ){
        $list = KhAccountService::getKhAccount();
        return $this->success('操作成功', $list);
    }

    /**
     * @name 获取公司名
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2022/9/15
     * @Time: 17:47
     */
    public function getCompanyList(Request $request){
        $session = $request->get('session_token');
        $data = new Company();
        if ($session['admin_groupnew'] != 7){//管理员可以看全部
            $data = $data->whereRaw("FIND_IN_SET(".$session['company_id'].",com_parent_id) or com_id = '".$session['company_id']."'");
//            if ($session['admin_groupnew'] != 8) {//管理员可以看全部
//                $data = $data->where('com_id', $session['company_id']);
//            }else{
//                $data = $data->where('com_id', '>',1);
//            }
        }
        $data = $data->select('com_id','com_name')->get()->toarray();
        return $this->success('获取成功', $data);

    }

}
