<?php
class sysAction extends baseAction
{
	/**
	  * @method 清空缓存
	  * @author soul 2017/6/16
	  */
	function clearCache()
	{
		echo date('Y-m-d H:i:s').'清除接口缓存<br>';
		foreach(mvc::$cfg['AUTOLOAD'] as $v)
		{
			$dir = $v['path'].'cache';

			LibDir::ClearDir($dir);
		}

		echo date('Y-m-d H:i:s').'清除前端缓存<br>';
		//前端缓存
		$homeCache = mvc::$cfg['ROOT'].'home/cache';
		LibDir::ClearDir($homeCache);
		//重新生成JS缓存
		echo date('Y-m-d H:i:s').'重建JS缓存';
		$LibHttp = new LibHttp();
		$res = $LibHttp->fetch(mvc::$cfg['HOST']['b2c'].'cache/auto');
		echo $res, '<br>';
		echo 'end';
	}


	/**
	  * @method 职员列表
	  * @author soul 2017/6/16
	  */
	function userList()
	{
		LibRule::Check('ZY01');
		$Params = mvc::$URL_PARAMS;
		LibTpl::Set('Params', $Params);
		LibTpl::Set('title', '系统管理-跑街的');
		$B2cBase = new B2cBase();
		$where = !empty($Params['keyword'])?sprintf("and ub_username like '%%%s%%'",LibFc::Escape($Params['keyword'])):'';
        $where .= !empty($Params['name'])?sprintf("and au_name like '%%%s%%'",LibFc::Escape($Params['name'])):'';
        $res = $B2cBase->get('an_user left join us_user_base on au_uid=ub_uid',['count(*) count'],$where,true);
		$Total = $res['data']['count'];
		if($Total>0)
		{
			$NowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
			$PerPage = empty($_COOKIE['perPage'])? 20: (int) $_COOKIE['perPage'];
			$where .= sprintf(" order by au_status desc,ub_username asc limit %d,%d", ($NowPage-1)*$PerPage, $PerPage);
			$res = $B2cBase->get('an_user mc left join us_user_base mb on au_uid=ub_uid', ['mc.*,mb.ub_username'], $where);
			$uId = array_column($res['data'],'au_uid');
			if(!empty($uId))
			{
				//获取会员名称
				$LibYpApi = new LibYpApi();
				$PostData = array(
					'uids'=>implode(',',$uId)
				);
				$ResArr = $LibYpApi->Get('user/getUserByIds', [], $PostData);
				LibTpl::Set('userReal', array_column($ResArr['data'],'u_real_name','u_id'));
			}
			LibTpl::Set('userArr', $res['data']);
			$userIdArr = array_column($res['data'], 'au_uid');
			//获取权限
			if(!empty($userIdArr))
			{
				$res = $B2cBase->get('an_user_rule left join an_rule on aur_arule_id=arule_id', ['aur_au_uid','arule_name'], sprintf(" and aur_au_uid in (%s)",implode(',', $userIdArr)));
			}
			if(!empty($res['data']))
			{
				$rules = [];
				foreach ($res['data'] as $key => $value)
				{
					foreach ($userIdArr as $k => $v)
					{
						if($v == $value['aur_au_uid'] && !empty($value['arule_name']))
						{
							$rules[$v][] = $value['arule_name'];
						}
					}
				}
				LibTpl::Set('rulesArr', $rules);
			}
			//获取职位名称
			$res = $B2cBase->get('an_user_group_link left join an_user_group on ugl_ugid=ugp_id', ['ugl_uid','ugp_name'], sprintf(" and ugl_uid in (%s)",implode(',', $userIdArr)));
			if($res['data']){
				$group = [];
			
				foreach ($res['data'] as $k => $v)
				{
				
					$group[$v['ugl_uid']][] = $v['ugp_name'];
					
				}

				LibTpl::Set('groupArr', $group);
			}
		}
		$Page = LibPage::Show($Total, $PerPage);
		LibTpl::Set('Page', $Page);
		LibTpl::Put();
	}

	function userSet()
	{
		$Params = mvc::$URL_PARAMS;
		$_POST['order'] = $Params['order'] == 'edit' || $_POST['order'] == 'edit'?'edit':'add';
		if($_POST['order']=='add') LibRule::Check('ZY02');
		else LibRule::Check('ZY03');
		LibTpl::Set('title', '系统管理-跑街的');
		LibTpl::Set('Params',$Params);
		LibTpl::Set('userId',$Params['userId']);
		LibTpl::Set('type',$_POST['order']);
		if(LibFc::Int($_POST['userId']))
		{
			LibTpl::Set('userId',$_POST['userId']);
			$B2cRules = new B2cRules();
			$userRules_pjd = $_POST['userRules_pjd']?explode(',',$_POST['userRules_pjd']):[];
			$userRules_model = $_POST['userRules_model']?explode(',',$_POST['userRules_model']):[];
			$_POST['userRules'] = implode(',',array_merge($userRules_pjd,$userRules_model));
			$B2cRules->saveRulesUser($_POST);
			//判断是否修改了自己的信息
			if($_POST['userId'] == $_SESSION['admin_userid'])
			{
				$rules = array_filter(explode(',', $_POST['userRules']),'LibFc::Escape');
				$_SESSION['admin_rule'] = $rules;
			}
		}
		LibTpl::Put();
	}

	/**
	 * 获取用户详情
	 * @author 廖
	 * @copyright 2018/2/27
	 */
	function getUserMsgForSys()
	{
		$username = LibFc::Escape($_POST['username']);
		$LibYpApi = new LibYpApi();
		$PostData = array(
			'word'=>$username,
			'per'=>20,
			'page'=>1
		);
		$ResArr = $LibYpApi->Get('user/searchUser', [], $PostData);
		// 传递数据
		LibTpl::Set('data', $ResArr['data']);
		LibTpl::Set('username', $username);
		$html = LibTpl::Fetch('sys/userSelect.php');
		LibFc::ajaxJsonEncode(['status'=>true,'data'=>$html]);
	}
	/**
	 * 依据用户ID获取用户详情
	 * @author 廖
	 * @copyright 2018/2/27
	 */
	function getUserDetailForSys()
	{
		if(!LibFc::Int($_POST['userId']))
		{
			LibFc::ajaxJsonEncode(['status'=>false,'data'=>'请输入正确的用户ID！']);
		}

		$LibYpApi = new LibYpApi();
		$PostData = array(
			'uids'=>$_POST['userId']
		);
		$ResArr = $LibYpApi->Get('user/getUserByIds', [], $PostData);
		// 传递数据
		LibTpl::Set('data', current($ResArr['data']));

		$B2cBase = new B2cBase();
		//检查是否已经开通
		$res = $B2cBase->get('an_user',['*'],'and au_uid='.$_POST['userId'],true);

		// $group = $B2cBase->get('an_user',['au_group'],' group by au_group');
		// $group = $group['data'];
		// if(!empty($group)) foreach ($group as $key => $value) if(empty($value['au_group'])) unset($group[$key]);
		$auArr = ['au_modelsys'=>1,'au_pjsys'=>1];
		if(!empty($res['data']))
		{
			$res['data']['au_modelsys_cfg'] = $res['data']['au_modelsys_cfg']?json_decode($res['data']['au_modelsys_cfg'],true):['brand_ids'=>[],'etk_ids'=>[]];
			$auArr = $res['data'];
			$res = $B2cBase->get('an_user_rule join an_rule on arule_id = aur_arule_id', ['aur_arule_id','arule_sys'],'and aur_au_uid='.$_POST['userId']);
			$selectRules = [];
			foreach ($res['data'] as $val) {
				$selectRules[$val['arule_sys']][] = $val['aur_arule_id'];
			}
			LibTpl::Set('selectRules',$selectRules);
			LibTpl::Set('hasopen',true);
		}
		LibTpl::Set('auArr',$auArr);
		$table = 'an_user_group_link LEFT JOIN an_user_group ON ugl_ugid=ugp_id';
		$res =  $B2cBase->get($table,['ugl_ugid'],sprintf(" and  ugl_uid = %d ORDER BY ugp_path",$_POST['userId']));
		$userGroupIds = [];
		foreach ($res['data'] as $key => $val) {
			$userGroupIds[] = $val['ugl_ugid'];
		}
		LibTpl::Set('userGroupIds',$userGroupIds?implode(',',$userGroupIds):'');
		$groupArr = [];
		$res = $B2cBase->get('an_user_group',['ugp_id', 'ugp_pid', 'ugp_name']);
		foreach($res['data'] as $v){
			$check = in_array($v['ugp_id'], $userGroupIds) ? true:false;
			// $name = '<input type="checkbox" name="UgId[]" id="UgId'.$v['ugp_id'].'" value="'.$v['ugp_id'].'"'.$Check.'><label for="UgId'.$v['ugp_id'].'"> '.$v['ugp_name'].'</label>';
			$groupArr[] =['id'=>$v['ugp_id'], 'pId'=>$v['ugp_pid'],'name'=>$v['ugp_name'], 'open'=>true,'checked'=>$check];
		}
		// 获取所有权限
		$res = $B2cBase->get('an_rule',['arule_id','arule_name','arule_parent','arule_sys'],'');
		$newAllRule = array();
		$pIdArr = array_unique(array_column($res['data'],'arule_parent'));
		foreach ($res['data'] as $k => $v)
		{
			if(in_array($v['arule_id'],$pIdArr))
			{
				$newAllRule[$v['arule_sys']][] = array(
					'id'=>$v['arule_id'],
					'pId'=>$v['arule_parent'],
					'name'=>$v['arule_id'].'-'.$v['arule_name'],
					'open'=>true,
					'nocheck'=>true
				);
			}
			else
			{
				$newAllRule[$v['arule_sys']][] = array(
					'id'=>$v['arule_id'],
					'pId'=>$v['arule_parent'],
					'name'=>$v['arule_id'].'-'.$v['arule_name'],
					'open'=>true
				);
			}
		}
		LibTpl::Set('groupArr',$groupArr);
		LibTpl::Set('rules', json_encode($newAllRule));
		//获取车型品牌
		$YPCAR67Db = new BaseDb(mvc::$cfg['DB']['YPCAR67']);
		// $YPCAR67Db = new B2cBase();
		$ypcres = $YPCAR67Db->get('yp_brand',['b_id,b_name'],"order by b_initial asc");
		LibTpl::Set('ypcbrand',$ypcres['data']);

		$epcres = $YPCAR67Db->get('realoem_basic.data_etks',['etk_id,etk_name'],"order by etk_order asc");
		LibTpl::Set('epcbrand',$epcres['data']);
		$html = LibTpl::Fetch('sys/getUserDetailForSys.php');
		LibFc::ajaxJsonEncode(['status'=>true,'data'=>$html]);
	}
	/**
	 * @method    申请列表
	 * @author 卢
	 * @copyright 2018-04-02
	 */
	public function applyCom()
	{
		LibRule::Check('SL03');
		$B2cBase=new B2cBase();
		$YpwAddr=new YpwAddr();
		$Params = mvc::$URL_PARAMS;
		$nowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
		$perPage=isset($_COOKIE['perPage'])&&$_COOKIE['perPage']>0? $_COOKIE['perPage'] : 10;
		$where='';
		$where.=!empty($Params['comName'])?sprintf(" and ub_com_name='%s'",LibFc::Escape($Params['ub_com_name'])):'';
		$where.=!empty($Params['uName'])?sprintf(" and ub_username='%s'",LibFc::Escape($Params['uName'])):'';
		$where.=!empty($Params['code'])?sprintf(" and ub_com_code='%s'",LibFc::Escape($Params['code'])):'';
		$where.=(!empty($Params['status'])&&$Params['status']!='all')?sprintf(" and uca_status=%d",(int)$Params['status']):'';
		// print_r(explode(' - ', LibFc::Escape($Params['agreeTime'])));
		$where.=!empty($Params['agreeTime'])?sprintf(' and uca_chk_time>=%d and uca_chk_time<=%d',strtotime(explode(' - ', LibFc::Escape($Params['agreeTime']))[0]),strtotime(explode(' - ', LibFc::Escape($Params['agreeTime']))[1])):'';
		// echo $where;
		$where.=!empty($Params['applyTime'])?sprintf(' and uca_atime>=%d and uca_atime<=%d',strtotime(explode(' - ', LibFc::Escape($Params['applyTime']))[0]),strtotime(explode(' - ', LibFc::Escape($Params['applyTime']))[1])):'';
		$res=$B2cBase->get('us_user_base inner join us_com_apply on uca_uid=ub_uid',['count(1) total'],$where,true);
		// print_r($res);
		$total=$res['data']['total'];
		$where .= sprintf(" order by uca_atime desc limit %d,%d", ($nowPage-1)*$perPage, $perPage);
		$res=$B2cBase->get('us_user_base inner join us_com_apply on uca_uid=ub_uid',['ub_uid','ub_username','ub_com_name','ub_level','ub_com_img','ub_com_license','ub_com_code','ub_com_pct_ids','uca_atime','uca_chk_uname','uca_chk_remark','uca_chk_time','uca_status','ub_com_idcard'],$where);
		if(count($res['data']))
		{
			foreach ($res['data'] as $k=> $v)
			{
				$addrArr=$YpwAddr->getAddrByIds($v['ub_com_pct_ids']);
				$res['data'][$k]['addr']=implode('',$addrArr['data']);
				$res['data'][$k]['imgArr']=!empty($v['ub_com_img'])?explode(',', $v['ub_com_img']):'';
				$res['data'][$k]['imgCardArr']=!empty($v['ub_com_idcard'])?explode(',', $v['ub_com_idcard']):'';
			}
			LibTpl::Set('data',$res['data']);
			// print_r($res);
			$Page = LibPage::Show($total, $perPage);
		}
		LibTpl::Set('Params',$Params);
		LibTpl::Set('Page', $Page);
		LibTpl::Set('title','企业会员申请列表-跑街的后台');
		LibTpl::Put();
	}
	/**
	 * @method   改变审核状态
	 * @author 卢
	 * @copyright 2018-04-02
	 */
	public function changeApply()
	{
		$res=['status'=>false,'data'=>'参数错误'];
		if(isset($_POST['status'])&&$_POST['uid'])
		{
			$B2cUser=new B2cUser();
			$dataArr['uca_chk_uid']=mvc::$cfg['LOGUSER']['uid'];
			$dataArr['uca_chk_uname']=mvc::$cfg['LOGUSER']['urname'];
			$dataArr['uca_chk_time']=time();
			switch ($_POST['status'])
			{
				case '2':
					$dataArr['uca_status']=2;
					break;
				case '0':
					$dataArr['uca_status']=0;
					break;
				case '1':
					$dataArr['uca_status']=1;
					$dataArr['uca_chk_remark']=$_POST['remark'];
					break;
				case '-1':
					$dataArr['uca_status']=-1;
					$dataArr['uca_chk_remark']=$_POST['remark'];
					break;
			}
			$res=$B2cUser->setApplyStatus($dataArr,$_POST['uid'],$_POST['status']);
		}
		LibFc::ajaxJsonEncode($res);
	}
	/**
	 * @method    会员申请详情
	 * @author 卢
	 * @copyright 2018-04-09
	 */
	public function applyDetail()
	{
		$Params = mvc::$URL_PARAMS;
		if(LibFc::Int($Params['uId']))
		{
			$B2cBase=new B2cBase();
			$YpwAddr = new YpwAddr();
			$res=$B2cBase->get('us_user_base inner join us_com_apply on uca_uid=ub_uid',['ub_uid','ub_username','ub_com_name','ub_level','ub_com_img','ub_com_license','ub_com_code','ub_com_pct_ids','uca_atime','uca_chk_uname','uca_chk_remark','uca_chk_time','uca_status','ub_com_idcard'],sprintf(' and uca_uid=%d',$Params['uId']),true);
			if(!empty($res['data']))
			{
				$addrArr=$YpwAddr->getAddrByIds($res['data']['ub_com_pct_ids']);
				$res['data']['address']=!empty($addrArr['data'])?implode('',$addrArr['data']):'';
				$res['data']['imgArr']=!empty($res['data']['ub_com_img'])?explode(',', $res['data']['ub_com_img']):'';
				$res['data']['imgCardArr']=!empty($res['data']['ub_com_idcard'])?explode(',', $res['data']['ub_com_idcard']):'';
			}
			LibTpl::Set('data',$res['data']);
			LibTpl::Set('title','企业会员申请详情-跑街的后台');
			LibTpl::Put();
			exit();
		}
		LibFc::Go(mvc::$cfg['ADMIN_URI'].'sys/applyCom');
	}

	/**
	 * @method     系统权限树
	 * @author     xu
	 * @copyright  2018-04-24
	 */
	public function ruleTree()
	{
		LibRule::Check('ZY01');
		// 获取所有权限
		$B2cBase = new B2cBase();
		$res = $B2cBase->get('an_rule',['*'],"");
		$parent = array_column($res['data'], 'arule_parent');
		$json = array();
		foreach ($res['data'] as $k => $v) {
			$json[] = [
				'id' => $v['arule_id'],
				'pId' => $v['arule_parent'],
				'name' => $v['arule_id'].':'.$v['arule_name'],
				'open'=>true
			];
		}
		// 根节点
		$json[] = ['id'=>'0000','pId'=>'','name'=>'所有权限','open'=>true];
		$json = json_encode($json);
		LibTpl::Set('json',$json);
		// meta
		LibTpl::Set('title','权限管理-跑街的');
		LibTpl::Put();
	}

	/**
	 * @method     保存系统权限更改
	 * @author     xu
	 * @copyright  2018-04-24
	 */
	public function ajaxSaveRule()
	{
		LibRule::Check('ZY01');
		if(empty($_POST['nodes']))
			LibFc::ajaxJsonEncode(['status'=>false,'data'=>'参数错误！']);
		// 整理节点数据
		$B2cRules = new B2cRules();
		$B2cRules->updateRules($_SESSION['admin_userid'],$_POST['nodes']);
		// 返回
		LibFc::ajaxJsonEncode(['status'=>true,'data'=>'权限已经更新！']);
	}


	/**
	 * @method     店铺权限树
	 * @author     xu
	 * @copyright  2018-04-24
	 */
	public function shopRuleTree()
	{
		LibRule::Check('ZY01');
		// 获取所有权限
		$B2cBase = new B2cBase();
		$res = $B2cBase->get('sh_rule',['*'],"");
		$parent = array_column($res['data'], 'rule_parent');
		$json = array();
		foreach ($res['data'] as $k => $v) {
			$json[] = [
				'id' => $v['rule_id'],
				'pId' => $v['rule_parent'],
				'name' => $v['rule_id'].':'.$v['rule_name'],
				'open'=>true
			];
		}
		// 根节点
		$json[] = ['id'=>'0000','pId'=>'','name'=>'所有权限','open'=>true];
		$json = json_encode($json);
		LibTpl::Set('json',$json);
		// meta
		LibTpl::Set('title','店铺权限-跑街的');
		LibTpl::Put();
	}

	/**
	 * @method     保存店铺权限更改
	 * @author     xu
	 * @copyright  2018-04-24
	 */
	public function ajaxSaveShopRule()
	{
		LibRule::Check('ZY01');
		if(empty($_POST['nodes']))
			LibFc::ajaxJsonEncode(['status'=>false,'data'=>'参数错误！']);
		// 整理节点数据
		$B2cRules = new B2cRules();
		$B2cRules->updateShopRules($_SESSION['admin_userid'],$_POST['nodes']);
		// 返回
		LibFc::ajaxJsonEncode(['status'=>true,'data'=>'权限已经更新！']);
	}



	/**
	 * @method     字典管理
	 * @author     xu
	 * @copyright  2018-05-05
	 */
	public function dist()
	{
        LibRule::Check('AP00');

		$Params = mvc::$URL_PARAMS;

		$where = '';

		// 关键字筛选
		if(!empty($Params['keyword']))
			$where .=  sprintf(" and di_word like '%%%s%%'", LibFc::Escape($Params['keyword']));

		// 状态筛选
		if(empty($Params['status']))
		{
			$where .= 'and di_status=1';
		}
		elseif($Params['status']!='a')
		{
			$status = ($Params['status']=='w')?1:-1;
			$where .= ' and di_status='.$status;
		}

		// 分页
		$page= !empty($Params['page']) ? (int) $Params['page'] : 1;
		$perPage = !empty($_COOKIE['perPage']) ? (int) $_COOKIE['perPage'] : 253;
		$limit = ' limit '.(($page-1)*$perPage).','.$perPage;

		// 调用接口
		$LibYpApi = new LibYpApi();
		$dataArr = [
			'filedArr'=>['di_id','di_status','di_word'],
			'where'=>$where,
			'order'=>' order by di_seq asc, di_word asc',
			'limit'=> $limit
		];
		$res = $LibYpApi->Get('dist/getWords', [], $dataArr);
		$dist = $res['data']['data'];
		LibTpl::Set('data',$dist);

		// 页码
		$count = $res['data']['count'];
		$Page = LibPage::Show($count, $perPage);
		LibTpl::Set('Page', $Page);
		LibTpl::Set('Params',$Params);

		// meta
		LibTpl::Set('title','词典管理-跑街的');
		LibTpl::Put();
	}


	/**
	 * @method     更改状态
	 * @author     xu
	 * @copyright  2018-05-05
	 */
	public function changeDistStat()
	{
		// 参数
		if(empty($_POST['ids']) || empty($ids = array_filter(explode(',',$_POST['ids']))) || empty($status=$_POST['status']))
			LibFc::ajaxJsonEncode(['status'=>false, 'data'=>'修改字典参数错误！']);
		// 更改状态
		$status = $status=='yes'?'status1':'status-1';
		$LibYpApi = new LibYpApi();
		$temp = [
			'action' => $status,
			'dataArr' => $ids,
			'setBy'=> 'id',
		];
		$LibYpApi->Get('dist/setWords', [], $temp);
		LibFc::ajaxJsonEncode(['status'=>true, 'data'=>true]);
	}

	/**
	 * @method     删除
	 * @author     xu
	 * @copyright  2018-05-05
	 */
	public function delDist()
	{
		// 参数
		if(empty($_POST['ids']) || empty($ids = array_filter(explode(',',$_POST['ids']))))
			LibFc::ajaxJsonEncode(['status'=>false, 'data'=>'删除字典参数错误！']);
		// 执行
		$LibYpApi = new LibYpApi();
		$temp = [
			'action' => 'del',
			'dataArr' => $ids,
			'setBy'=> 'id',
		];
		$LibYpApi->Get('dist/setWords', [], $temp);
		LibFc::ajaxJsonEncode(['status'=>true, 'data'=>true]);
	}


	/**
	 * @method     新增
	 * @author     xu
	 * @copyright  2018-05-05
	 */
	public function addDist()
	{
		// 参数
		$fengefu = ['；',';'];
		if(empty($_POST['str']) || empty($str = array_filter(explode(';',str_replace($fengefu, ';', $_POST['str'])))))
			LibFc::ajaxJsonEncode(['status'=>false, 'data'=>'新增字典参数错误！']);
		// 执行
		$LibYpApi = new LibYpApi();
		$temp = ['wordArr' => $str];
		$LibYpApi->Get('dist/addWords', [], $temp);
		LibFc::ajaxJsonEncode(['status'=>true, 'data'=>true]);
	}

	public function yzmcw()
    {

        LibRule::Check('OT01');
        $Params = mvc::$URL_PARAMS;

        if($Params['export'] == 1){
            $this->exportYzmcw();
            exit();
        }
        $page = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page'] : 1;
        $pageSize = empty($_COOKIE['perPage']) ? 20: (int) $_COOKIE['perPage'];
        $db = new YpwBase();
        $table = 'ocr_imgcode_error';
        $where = sprintf(" and oie_status = %d",$Params['status']);
        if(!empty($Params['sitetype'])){
            $where .= sprintf(" and oie_sitetype='%s'",$Params['sitetype']);
        }
        if(!empty($Params['oie_atime'])){
            $t = explode(' ~ ', $Params['oie_atime']);
            $where .= sprintf(" and oie_atime >= %d and oie_atime < %d",strtotime($t[0]),strtotime($t[1])+86400);
        }

        $sitetype = $db->get($table,['oie_sitetype'],sprintf(" group by oie_sitetype"));
        $count = $db->get($table,['count(*) as count'],$where,true);
        $count = $count['data']['count'];
        if($count > 0){
            $where .= sprintf(' order by oie_id limit %s,%s',($page-1)*$pageSize,$pageSize);
            $list = $db->get($table,['*'],$where);
            LibTpl::Set('list',$list['data']);
        }
        LibTpl::Set('sitetype',$sitetype['data']);
        LibTpl::Set('statusArr',[0 => '待处理', 1 => '已纠正', -1 => '忽略']);
        LibTpl::Set('Page', LibPage::Show($count, $pageSize));
        LibTpl::Set('Params',$Params);
        LibTpl::Put();
    }

    //保存验证🐎
    public function saveYzmcw()
    {
        LibRule::Check('OT01');
        $id = (int) $_POST['id'];
        $count = (int) $_POST['count'];
        $value = trim($_POST['value']);
        if(strlen($value) != $count){
            LibFc::ajaxJsonEncode(['status' => false,'data' => '参数错误']);
        }
        $db = new YpwBase();
        $result = $db->set('ocr_imgcode_error',['oie_realcode' => $value,'oie_status' => 1],sprintf(" and oie_id=%d",$id));
        LibFc::ajaxJsonEncode($result);
    }

    public function deleteYzmcw()
    {
        LibRule::Check('OT01');
        $id = (int) $_POST['id'];
        if($id <= 0) LibFc::ajaxJsonEncode(['status' => false,'data' => '参数错误']);
        $result = (new YpwBase)->set('ocr_imgcode_error',['oie_status' => '-1'],sprintf(" and oie_id = %d",$id));
        LibFc::ajaxJsonEncode($result);
    }

    public function exportYzmcw()
    {
        $Params = mvc::$URL_PARAMS;
        LibRule::Check('OT01');
        $where = sprintf(" and oie_sitetype = '%s' and oie_status=%d",$Params['sitetype'],$Params['status']);
        $db = new YpwBase;
        $result = $db->get('ocr_imgcode_error',['*'],$where);
        if(empty($result['data'])){
            echo '无文件';exit();
        }

        $path = './temp/';
        $result = $result['data'];
        if(!is_dir($path)){
            mkdir($path,0777);
        }
        foreach ($result as $k => $value)
        {
            if(!empty($value['oie_realcode'])){
                file_put_contents($path.$value['oie_realcode'].'_'.$this->num(15).'.jpg',base64_decode($value['oie_img']));
            }else{
				file_put_contents($path.date('md').'_'.$k.'.jpg',base64_decode($value['oie_img']));
			}
           // $db->set('ocr_imgcode_error',['oie_status' => 2 ],sprintf(" and oie_id=%d",$value['oie_id']));
        }
        $zip = new \ZipArchive();
        if($zip->open('./temp.zip', \ZipArchive::CREATE)=== TRUE)
        {
            $this->addFileToZip($path, $zip); //调用方法，对要打包的根目录进行操作，并将ZipArchive的对象传递给方法
            $zip->close(); //关闭处理的zip文件
        }
        $this->downFile('./temp.zip');
    }


    private function deldir($path)
    {
        if(is_dir($path))
        {
            $p = scandir($path);

            foreach($p as $val)
            {
                if($val !="." && $val !="..")
                {
                    if(is_dir($path.$val)){
                        $this->deldir($path.$val.'/');
                    }else{
                        unlink($path.$val);
                    }
                }
            }
        }
    }

    private function downFile($fileName)
    {
        if(file_exists($fileName))
        {
            $fp = fopen($fileName,"r");
            $fileSize = filesize($fileName);
            Header("Content-type: application/octet-stream");
            Header("Accept-Ranges: bytes");
            Header("Accept-Length:".$fileSize);
            Header("Content-Disposition: attachment; filename=".$fileName);
            $buffer = 1024; //设置一次读取的字节数，每读取一次，就输出数据（即返回给浏览器）
            $fileCount = 0; //读取的总字节数
            //向浏览器返回数据
            while(!feof($fp) && $fileCount  < $fileSize)
            {
                //读取打开的文件
                $fileCon = fread($fp,$buffer);
                $fileCount += $buffer;
                echo $fileCon;
            }
            //关闭打开的文件
            fclose($fp);
            //下载完成后删除文件
            if($fileCount >= $fileSize)
            {
                unlink($fileName);
                //删除文件
                $this->deldir('./temp/');
            }
        }
    }

    private function addFileToZip($path,$zip)
    {
        $handler = opendir($path); //打开当前文件夹由$path指定。
        while(($filename = readdir($handler)) !== false)
        {
            if($filename != "." && $filename != "..")
            {//文件夹文件名字为'.'和‘..'，不要对他们进行操作
                if(is_dir($path."/".$filename)){// 如果读取的某个对象是文件夹，则递归
                    $this->addFileToZip($path."/".$filename, $zip);
                }else{ //将文件加入zip对象
                    $zip->addFile($path."/".$filename);
                }
            }
        }
        @closedir($path);
    }

    private function num( $length = 8 )
    {
        $chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
            'i', 'j', 'k', 'l','m', 'n', 'o', 'p', 'q', 'r', 's',
            't', 'u', 'v', 'w', 'x', 'y','z', 'A', 'B', 'C', 'D',
            'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L','M', 'N', 'O',
            'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y','Z',
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
        $keys = array_rand($chars, $length);
        $password = '';
        for($i = 0; $i < $length; $i++)
        {
            $password .= $chars[$keys[$i]];
        }
        return $password;
    }


	function apiServer()
	{
		LibRule::Check('AP00');
		LibTpl::Set('title', '接口服务控制');
		LibTpl::Put();
	}
	

	//接口服务控制?api=pjlapi&act=start
	public function apiServerChange()
	{
		LibRule::Check('AP00');
		//避免修改异常，每次都使用内容替换形式
		$allcfg = [
			'pjlapi'=>[
				'path'=>'/home/wwwroot/paojieling/api/',//项目入口
				'start'=>'index_start.php',	//正常的运行代码
				'stop'=>'index_stop.php',	//停止的运行代码
				'run'=>'index.php',	//入口文件
			],
			'ypapi'=>[
				'path'=>'/home/wwwroot/api.paojd.cn/home/',
				'start'=>'index_start.php',	
				'stop'=>'index_stop.php',	
				'run'=>'index.php',
			],
		];
		$api = $_POST['api'];
		$act = $_POST['act'];
		if($allcfg[$api] && in_array($act, ['start', 'stop'])){
			$cfg = $allcfg[$api];
			if(file_exists($cfg['path'].$cfg[$act]) && copy($cfg['path'].$cfg[$act], $cfg['path'].$cfg['run'])){
				LibFc::ajaxJsonEncode(['status'=>false, 'data'=>'主服务器171'.$cfg['path'].$cfg['run'].'入口文件变更成功']);
			}else{
				LibFc::ajaxJsonEncode(['status'=>false, 'data'=>'主服务器171复制'.$cfg['path'].$cfg[$act].'文件到'.$cfg['path'].$cfg['run'].'失败']);
			}
		}
		LibFc::ajaxJsonEncode(['status'=>false, 'data'=>'参数不足，操作失败']);
	}
}