<?php
class userAction extends baseAction
{
	function index()
	{
		LibTpl::Set('title', '个人中心-'.mvc::$cfg['TITLE']);
		LibTpl::Put();
	}

	function login()
	{
		if(!empty($_SESSION['_userid'])) header("Location: ".mvc::$cfg['SELF_URI']);
		LibTpl::Set('title', '会员登录-'.mvc::$cfg['TITLE']);
		LibTpl::Put();
	}

	/**
	  * @method 用户数据唯一性，用户名、邮箱、昵称、手机号码....
	  * @remark 当用户已登录并且$_POST['uid'] == -1 自动取 $_SESSION['_userid']
	  * @author soul 2017/5/10
	  */
	function checkUnique()
	{
		$Val = trim($_POST['val']);
		$Uid = isset($_SESSION['_userid']) && $_POST['uid'] == -1 ? $_SESSION['_userid'] : (int) $_POST['uid'];
		$Where = '';
		$Return = ['status'=>true, 'data'=>[], 'code'=>''];
		switch($_POST['filed'])
		{
			case 'regname': 
				$Where = sprintf(" and u_name='%s'", LibFc::Escape($Val));
			break;
			case 'regemail': 
				$Where = sprintf(" and u_email='%s'", LibFc::Escape($Val));
			break;
			case 'mobile': 
				$Where = sprintf(" and u_id !=%d and u_mobile_check='Y' and u_mobile='%s'", $Uid, LibFc::Escape($Val));
			break;
			case 'regmobile': 
				$Where = sprintf(" and u_mobile_check='Y' and u_mobile='%s'", LibFc::Escape($Val));
			break;
			case 'nickname': 
				$Where = sprintf(" and u_id !=%d and u_nickname='%s'", $Uid, LibFc::Escape($Val));
			break;
		}
		if($Where != '')
		{
			$LibYpApi = new LibYpApi();
			$dataArr = [
				'filed'=>['count(*) as count'],	
				'where'=>$Where,
				'oneRow'=>true
			];
			$Return = $LibYpApi->Get('user/getUser', [], $dataArr);
		}
		LibFc::ajaxJsonEncode($Return);
	}

	function loginByQQ()
	{
		$Params = MVC::$URL_PARAMS;
		$LibYpApi = new LibYpApi();
		if(!empty($Params['udata']))
		{
			$QQUserArr = json_decode(base64_decode($Params['udata']), true);
			if(!empty($QQUserArr['unionid']))
			{
				$PostData = [
					'type'=>'qq',
					'data'=>['unionid'=>$QQUserArr['unionid']],
					'ip'=>LibFc::GetClientIp(),
					'from'=>mvc::$cfg['FROM'],
					'lang'=>'cn'
				];
				$res = $LibYpApi->Get('user/login', [], $PostData, true);
				if($res['status'] && !empty($res['data']['u_id']) && $this->initLogin($res['data'], 0))
				{
					LibFc::Go(mvc::$cfg['SELF_URI']);
				}else{
					LibTpl::Error(is_array($res['data'])? '账号不存在或者权限不足！': $res['data'], mvc::$cfg['ADMIN_URI'].'user/login');
				}
			}
		}
		$res = $LibYpApi->get('qq/getQQUserUrl', ['app'=>'web_yp', 'backUrl'=>mvc::$cfg['SELF_URI'].'user/loginByQQ?by=qq', 'scope'=>'']);
		header("Location: ".$res['data']);
	}

	function loginByWx()
	{
		$Params = MVC::$URL_PARAMS;
		$LibYpApi = new LibYpApi();
		if(!empty($Params['udata']))
		{
			$WXUserArr = json_decode(base64_decode($Params['udata']), true);
			if(!empty($WXUserArr['unionid']))
			{
				$PostData = [
					'type'=>'weixin',
					'data'=>['unionid'=>$WXUserArr['unionid']],
					'ip'=>LibFc::GetClientIp(),
					'from'=>mvc::$cfg['FROM'],
					'lang'=>'cn'
				];
				$res = $LibYpApi->Get('user/login', [], $PostData, true);
				if($res['status'] && !empty($res['data']['u_id']) && $this->initLogin($res['data'], 0))
				{
					LibFc::Go(mvc::$cfg['SELF_URI']);
				}else{
					LibTpl::Error(is_array($res['data'])? '账号不存在或者权限不足！': $res['data'], mvc::$cfg['ADMIN_URI'].'user/login');
				}
			}
		}
		$res = $LibYpApi->get('wx/getWxUserUrl', ['app'=>'gzh_app', 'backUrl'=>mvc::$cfg['SELF_URI'].'user/loginByWx?by=weixin', 'scope'=>'snsapi_login']);
		header("Location: ".$res['data']);
	}

	function ajaxLogin()
	{
		$dataArr = [
			'type'=>$_POST['type'],
			'data'=>['name'=>$_POST['username'],'password'=>$_POST['password']],
			'ip'=>LibFc::GetClientIp(),
			'from'=>mvc::$cfg['FROM'],
			'lang'=>'cn'
		];
		$LibYpApi = new LibYpApi();
		$res = $LibYpApi->Get('user/login', [], $dataArr);
		if($this->initLogin($res['data'], $_POST['remember']))
		{
			LibFc::ajaxJsonEncode(['status'=>true, 'data'=>$_SESSION['_userid']]);
		}
		else
		{
			LibFc::ajaxJsonEncode(['status'=>false, 'data'=>'账号不存在或者权限不足！']);
		}
	}

	/**
	  * @method 退出登录
	  * @author soul 2017/5/10
	  */
	function logout()
	{
		$this->clearLogin();
		header("Location: ".mvc::$cfg['SELF_URI'].'user/login');
	}

	/**
	  * @method 用户列表
	  * @author liao 2019/2/27
	  */
	function lists()
	{
		LibTpl::Set('title', '用户列表');
		LibTpl::Set('za_type', $_SESSION['_za_type']);
		LibTpl::Set('za_uid', $_SESSION['_userid']);
		LibTpl::Put();
	}

	/**
	  * @method 自媒体列表
	  * @author liao 2019/3/5
	  */
	function ulists()
	{
		LibTpl::Set('title', '自媒体列表');
		LibTpl::Put();
	}

	/**
	  * @method ajax 获取用户数据
	  * @author liao 2019/2/27
	  */
	function getUserList()
	{
		$Params = MVC::$URL_PARAMS;
		$type = $Params['za_type'];
		if (!in_array($type, ['0','1']))
		{
			echo json_encode(['status'=>'false','data'=>'参数错误']);
		}
		$PjlBase = new PjlBase();
		$count = $PjlBase->get('zx_admin',['count(*) count'],sprintf('and za_type=%s order by za_status desc', $type), true);
		$count = $count['data']['count'];
		if ($count > 0)
		{
			$baseWhere = '';
        	if (!LibFc::checkRule('AD00',false))
        	{
        		$baseWhere = sprintf('and za_uid='.$_SESSION['_userid']);
        	}
			$page = (int) $Params['page'];
			$page = $page < 1 ? 1: $page;
			$limit = empty($Params['limit'])? 30: (int) $Params['limit'];
			$res = $PjlBase->get('zx_admin left join zx_company on za_zc_id=zc_id',['*'],sprintf('%s and za_type=%s order by za_status desc,za_atime desc limit %s, %s', $baseWhere, $type, ($page-1)*$limit, $limit));

			if (!empty($res['data']))
			{
				$userIdArr = array_column($res['data'], 'za_uid');
				$where = sprintf("and u_id in(%s)", implode(',', $userIdArr));
	            $LibYpApi = new LibYpApi();
				$dataArr = [
					'filed'=>['u_id','u_name'],	
					'where'=>$where,
					'oneRow'=>false
				];
				$userArr = $LibYpApi->Get('user/getUser', [], $dataArr);
				$userArr = array_column($userArr['data'], 'u_name','u_id');
				foreach ($res['data'] as $key => $value) {
					$res['data'][$key]['za_uname'] = $userArr[$value['za_uid']];
					if ($value['za_uid'] == $_SESSION['_userid'])
						$res['data'][$key]['is_self'] = true;

					//转换时间格式
					$res['data'][$key]['za_atime'] = $res['data'][$key]['za_atime'] ? date('Y-m-d H:i:s', $res['data'][$key]['za_atime']) : '';

				}
			}
		}
		$arr = [
			"code"=>0,
			"msg"=>"",
			"count"=>$count,
			"data"=>$res['data'],
			'self'=>$_SESSION['_userid']
		];
		echo json_encode($arr);
	}

	/**
	  * @method ajax 获取自媒体数据
	  * @author liao 2019/2/27
	  */
	function getZimeitiList()
	{
		// 必须有自媒体管理权限
		LibFc::checkRule('AD01'); 
		$Params = MVC::$URL_PARAMS;
		$PjlBase = new PjlBase();
		$count = $PjlBase->get('zx_company',['count(*) count'], '', true);
		$count = $count['data']['count'];
		if ($count > 0)
		{
			$page = (int) $Params['page'];
			$page = $page < 1 ? 1: $page;
			$limit = empty($Params['limit'])? 30: (int) $Params['limit'];
			$res = $PjlBase->get('zx_company',['*'],sprintf(' limit %s, %s', ($page-1)*$limit, $limit));

			if (!empty($res['data']))
			{
				foreach ($res['data'] as $key => $value) {
					//转换时间格式
					$res['data'][$key]['zc_atime'] = $res['data'][$key]['zc_atime'] ? date('Y-m-d H:i:s', $res['data'][$key]['zc_atime']) : '';

				}
			}
		}
		$arr = [
			"code"=>0,
			"msg"=>"",
			"count"=>$count,
			"data"=>$res['data'],
		];
		echo json_encode($arr);
	}

	/**
	  * @method 用户编辑模版
	  * @author liao 2019/2/27
	  */
	function editUserHtml()
	{
		$Params = mvc::$URL_PARAMS;
		LibTpl::Set('Params', $Params);
		$uid= (int) $Params['uid'];
		$PjlBase = new PjlBase();
		if ($uid > 0)
		{
			$res = $PjlBase->get('zx_admin',['*'], 'and za_uid='.$uid, true);

			//获取用户的名字
			if(!empty($res['data']))
			{
				$where = sprintf("and u_id =%s ", $uid);
	            $LibYpApi = new LibYpApi();
				$dataArr = [
					'filed'=>['u_id','u_name'],	
					'where'=>$where,
					'oneRow'=>true
				];
				$name = $LibYpApi->Get('user/getUser', [], $dataArr);
				$res['data']['u_name'] = $name['data']['u_name'];
			}
			LibTpl::Set('user',$res['data']);
		}

		// 获取自媒体的列表
		$res = $PjlBase->get('zx_company',['zc_id','za_com_name'],'order by zc_atime desc');
		LibTpl::Set('zimeiti',$res['data']);
		$res = LibTpl::Fetch('user/userform.php', '');
		echo $res;
	}

	/**
	  * @method 自媒体编辑模版
	  * @author liao 2019/3/5
	  */
	function editZimeitiHtml()
	{
		// 必须有自媒体管理权限
		LibFc::checkRule('AD01'); 
		$Params = mvc::$URL_PARAMS;
		LibTpl::Set('Params', $Params);
		$zim= (int) $Params['zim'];
		if ($zim > 0)
		{
			$PjlBase = new PjlBase();
			$res = $PjlBase->get('zx_company',['*'], 'and zc_id='.$zim, true);
			LibTpl::Set('user',$res['data']);
		}
		$res = LibTpl::Fetch('user/zimeitiform.php', '');
		echo $res;
	}

	/**
	  * @method 获取宜配用户
	  * @author liao 2019/2/27
	  */
	function getUserInfoByWord()
	{
		$Params = mvc::$URL_PARAMS;
        $returnData = ['status'=>'true','data'=>[]];
        $name = LibFc::Escape($Params['name']);
        if (!empty($name))
        {
            $where = sprintf("and (u_name like '%%%s%%' or u_mobile like '%s%%') limit 0,8", $name, $name);
            $LibYpApi = new LibYpApi();
			$dataArr = [
				'filed'=>['u_id',"concat_ws(' : ',u_name,u_mobile) as u_name"],	
				'where'=>$where,
				'oneRow'=>false
			];
			$res = $LibYpApi->Get('user/getUser', [], $dataArr);

			foreach ($res['data'] as $key => $value) 
            {
                $returnData['data'][] = ['id'=>$value['u_id'], 'name'=>$value['u_name']];
            }
        }
        LibFc::ajaxJsonEncode($returnData);
	}

	/**
	  * @method 新增或者编辑用户
	  * @author liao 2019/2/27
	  */
	function editUser()
	{
		$Params = $_POST['field'];
		$type = (int)$Params['za_type'];
		$is_self = false;
		if ($type == '0')
		{
			if (!LibFc::checkRule('AD01',false))
			{
				if ($Params['za_uid'] == $_SESSION['_userid'])
				{
					$is_self = true;
				}else
				{
					LibFc::checkRule('AD01');
				}
			}
		}
		else if ($type == '1')
		{

			if (!LibFc::checkRule('AD02',false))
			{
				if ($Params['za_uid'] == $_SESSION['_userid'])
				{
					$is_self = true;
				}else
				{
					LibFc::checkRule('AD02');
				}
			}
		}

		if ($is_self)
		{
			unset($Params['za_status']);
			unset($Params['za_type']);
			unset($Params['za_com_name']);
			unset($Params['za_remark']);
			unset($Params['za_rule_ids']);
			unset($Params['za_zc_id']);
		}

		$PjlZx = new PjlZx();
		$res = $PjlZx->editZxUser($Params);
		LibFc::ajaxJsonEncode($res);
	}

	function editZimeiti()
	{
		LibFc::checkRule('AD01');
		$Params = $_POST;
		unset($Params['file']);
		$PjlZx = new PjlZx();
		$res = $PjlZx->editZimeiti($Params);
		LibFc::ajaxJsonEncode($res);
	}

	/**
	  * @method 删除用户
	  * @author liao 2019/2/27
	  */
	function delUser()
	{
		$Params = mvc::$URL_PARAMS;
		$Params['type'] = (int)$Params['type'];
		if ($Params['type'] == '0')
			LibFc::checkRule('AD01');
		else if ($Params['type'] == '1')
			LibFc::checkRule('AD02');
		else
			LibFc::ajaxJsonEncode(['status'=>false,'data'=>'参数不正确']);

		$ids = $Params['ids'];
		$ids = array_filter(explode(',', $ids), 'LibFc::Int');
		if (empty($ids))
			LibFc::ajaxJsonEncode(['status'=>false,'data'=>'参数不正确']);

		$PjlBase = new PjlBase();
		$res = $PjlBase->del('zx_admin', sprintf("and za_uid in (%s) and za_type=%s", implode(',', $ids), $Params['type']));
		LibFc::ajaxJsonEncode($res);
	}

	/**
	  * @method 修改权限弹窗
	  * @author liao 2019/2/27
	  */
	function userRuleHtml()
	{
		LibFc::checkRule('RU00');
		$Params = mvc::$URL_PARAMS;
		$type = $Params['type'];
		if ($type != '1')
		{
			echo '参数错误';
			exit;
		}
		$uid = (int) $Params['uid'];
		if ($uid > 0)
		{
			$PjlBase = new PjlBase();
			$res = $PjlBase->get('zx_admin',['za_rule_ids','za_type'],'and za_uid='.$uid, true);

			if ($res['data']['za_type'] != '1')
			{
				echo '参数错误';
				exit;
			}

			$rule = explode(',', $res['data']['za_rule_ids']);
			$user = [
				'rule'=>$rule,
				'za_uid'=>$uid,
			];
			LibTpl::Set('user',$user);
			//获取所有的权限 
			$res = $PjlBase->get('zx_rule',['rule_id','rule_name'], $where);

			LibTpl::Set('ruleArr',$res['data']);
		}
		$res = LibTpl::Fetch('user/userRule.php', '');
		echo $res;
	}

	/**
	  * @method 修改用户权限
	  * @author liao 2019/2/27
	  */
	function editUserRlue()
	{
		LibFc::checkRule('RU00');
		$Params = $_POST;
		$uid = (int) $Params['za_uid'];
		if ($uid > 0)
		{
			$PjlBase = new PjlBase();

			$res = $PjlBase->get('zx_admin',['count(*) count'],' and za_type=1 and za_uid='.$uid, true);
			if ($res['data']['count'] < 1)
			{
				LibFc::ajaxJsonEncode(['status'=>false,'data'=>'该用户不是管理员，无法分配权限']);
			}

			if (empty($Params['rule']))
			{
				$rule = '';
			}else
			{
				$rule = array_keys($Params['rule']);
				$rule = array_filter($rule);
				$rule = implode(',', $rule);
			}
			$res = $PjlBase->set('zx_admin',['za_rule_ids'=>LibFc::Escape($rule)],'and za_uid='.$uid);
			LibFc::ajaxJsonEncode(['status'=>true,'data'=>'修改成功']);
		}else
		{
			LibFc::ajaxJsonEncode(['status'=>false,'data'=>'参数错误']);
		}
	}

	function reloadPicture()
	{
		$PjlBase = new PjlBase();
		$OthFileCenter = new OthFileCenter();
		$res = $PjlBase->get('zx_article', ['art_id','art_imgs'],'');
		$baseDir = 'E:/Catch/yp_paojieling/201813/picture/';
		foreach ($res['data'] as $key => $value) {
			if (empty($value['art_imgs'])) continue;

			if (strpos($value['art_imgs'], 'http') === false) continue;

			$name = explode('mmbiz.qpic.cn/', $value['art_imgs'])[1];
			$name = substr($name, strpos($name, '/')+1);
			$jpeg = explode('=', $name)[1];
			$name = substr($name, 0,strpos($name, '/'));
			$file = $baseDir.$name.'.'.$jpeg;

			if (!file_exists($file)) continue;
			$dataArr = [
				'cate'=>'zxl',
				'file'=>[
					'name'=>$name.'.'.$jpeg,
					'tmp_name'=>$file,
				],
			];
			$res = $OthFileCenter->upload($dataArr, 'pjl');
			if ($res['status'])
			{
				$PjlBase->set('zx_article',['art_imgs'=>$res['data']['sfile']], 'and art_id='.$value['art_id']);
			}
			
		}
		echo 'ok';
		exit();
	}

	function reArticlePictrue()
	{
		$PjlBase = new PjlBase();
		$OthFileCenter = new OthFileCenter();
		$res = $PjlBase->get('zx_article', ['art_id','art_txt'],'');
		$source = array_column($res['data'], 'art_txt', 'art_id');
		$data = [];
		$baseDir = 'C:/Webserver/www/crawler/ypweixingzh/image_source.php';
		foreach ($res['data'] as $key => $value) {
			if (empty($value['art_txt'])) continue;
			if (strpos($value['art_txt'],'data-src') === false) continue;
			$arr = explode('data-src="', $value['art_txt']);
			if (empty($arr)) continue;
			unset($arr[0]);
			$temp = [];
			foreach ($arr as $k => $v) {
				$str = trim(substr($v, 0, strpos($v, '"')));
				if (empty($str)) continue;
				$temp[] = substr($v, 0, strpos($v, '"'));
			}
			$data[$value['art_id']] = $temp;

		}
		LibFc::ArraySave($data, $baseDir);
		$arr = require 'C:/Webserver/www/crawler/ypweixingzh/ote.php';

		// LibFc::ArraySave([], 'C:/Webserver/www/crawler/ypweixingzh/final.php');
		$tempArr = @include 'C:/Webserver/www/crawler/ypweixingzh/final.php';

		foreach ($arr as $key => $value) {
			foreach ($value as $k => $v) {
				if (!empty($tempArr[$key][$k])) continue;
				if (strpos($v, 'video/') !== false) continue;

				$name = explode('E:/Catch/yp_paojieling/201813/rpic/', $v)[1];
				$dataArr = [
					'cate'=>'zx',
					'file'=>[
						'name'=>$name,
						'tmp_name'=>$v,
					],
				];
				$res = $OthFileCenter->upload($dataArr, 'pjl');
				if ($res['status'])
				{
					if (empty($res['data']['sfile']))
					{
						print_r($res);die();
					}
					$tempArr[$key][$k] = $res['data']['sfile'];
				}
			}
		}
		LibFc::ArraySave($tempArr, 'C:/Webserver/www/crawler/ypweixingzh/final.php');

		//替换

		foreach ($tempArr as $key => $value) {
			foreach ($value as $k => $v) {
				$str = 'data-src="'.$data[$key][$k].'"';
				$source[$key] = str_replace($str, 'src="http://file.yiparts.com/center/read.php?site=pjl&c=zx&f='.$v.'&i=f1"', $source[$key]);
				
			}
			$PjlBase->set('zx_article',['art_txt'=>$source[$key]],'and art_id='.$key);
		}
		echo 'ok';
		exit();
	}


	//通过用户ID获取TOKEN
	function getToken()
	{
		$LibYpApi = new LibYpApi();
		$ResArr = $LibYpApi->Get('user/getToken', ['uid'=>md5('yp'.$_SESSION['_userid']), 'uname'=>$_SESSION['_username']]);
		LibFc::ajaxJsonEncode($ResArr);
	}
}