<?php

/**
 *--------------------------------------
 * 档案
 *--------------------------------------
 * @project		: uwa
 * @author		: cblee
 * @created		: 2012-10-6
 * @copyright	: (c)2012 AsThis
 *--------------------------------------
 */

class ArchiveModl extends Modl
{
	public function get_archiveList($where = '', $order = '`a_rank` DESC, `a_edit_time` DESC', $limit = 10, $archiveModelId = 0)
	{
		/* 获取附加表需列表字段 */
		if(0 < $archiveModelId)
		{
			$addonFields = '';
			$_AMI = M('ArchiveModel')->get_modelInfo($archiveModelId);
			if(empty($_AMI))
			{
				return null;
			}
			foreach($_AMI['am_field'] as $field => $params)
			{
				if(1 == $params['f_is_list'])
				{
					$addonFields .= ',`'.$field.'`';
				}
			}
			$_AL = M('Archive')->field('__ARCHIVE__.`archive_id`,`member_id`,`m_username`,`a_title`,`a_short_title`,`a_thumb`,`a_keywords`,`a_description`,`a_add_time`,`a_edit_time`,`a_add_ip`,`a_edit_ip`,`a_cost_points`,`a_view_count`,`a_support_count`,`a_rank`,`a_status`,`a_review_switch`,`a_is_html`,`af_alias`,__ARCHIVE__.`archive_channel_id`,`a_url`,`ac_name`,`ac_keywords`,`ac_description`,`ac_url`'.$addonFields)
				->join('__ARCHIVE_CHANNEL__ AS ac ON ac.archive_channel_id = __ARCHIVE__.archive_channel_id')
				->join('__'.strtoupper($_AMI['am_addon_table']).'__ AS addon ON addon.archive_id = __ARCHIVE__.archive_id')
				->where($where)->order($order)->limit($limit)->select();
		}
		else
		{
			$_AL = M('Archive')->field('__ARCHIVE__.`archive_id`,`member_id`,`m_username`,`a_title`,`a_short_title`,`a_thumb`,`a_keywords`,`a_description`,`a_add_time`,`a_edit_time`,`a_add_ip`,`a_edit_ip`,`a_cost_points`,`a_view_count`,`a_support_count`,`a_rank`,`a_status`,`a_review_switch`,`a_is_html`,`af_alias`,__ARCHIVE__.`archive_channel_id`,`a_url`,`ac_name`,`ac_keywords`,`ac_description`,`ac_url`')
				->join('__ARCHIVE_CHANNEL__ AS ac ON ac.archive_channel_id = __ARCHIVE__.archive_channel_id')
				->where($where)->order($order)->limit($limit)->select();
		}

		if(!empty($_AL))
		{
			foreach($_AL as $k => $v)
			{
				/* url 更新 */
				if(empty($v['a_url']))
				{
					$_r = $this->update_url($v['archive_id']);
					$_AL[$k]['a_url'] = $_r['data'];
				}

				/* 默认缩略图 */
				if(empty($v['a_thumb']))
				{
					$_AL[$k]['a_thumb'] = APP_ROOT.'/u/site/no_thumb.png';
				}
			}
		}
		return  $_AL;
	}

	public function get_archiveInfo($archiveId)
	{
		$_AI = $this->where('__ARCHIVE__.archive_id = \''.$archiveId.'\'')
			->join('__ARCHIVE_CHANNEL__ AS ac ON ac.archive_channel_id = __ARCHIVE__.archive_channel_id')
			->join('__ARCHIVE_MODEL__ AS am ON am.archive_model_id = ac.archive_model_id')
			->find();
		if(empty($_AI))
		{
			return null;
		}

		/* url 更新 */
		if(empty($_AI['a_url']))
		{
			$_r = $this->update_url($_AI['archive_id']);
			$_AI['a_url'] = $_r['data'];
		}

		/* 默认缩略图 */
		if(empty($_AI['a_thumb']))
		{
			$_AI['a_thumb'] = APP_ROOT.'/u/site/no_thumb.png';
		}

		/* 处理档案属性 */
		$_AI['af_alias'] = explode(',', $_AI['af_alias']);

		/* 获取模型附加字段 */
		$at = get_instance('ATag', 'field');
		$at->tags = array();
		$at->parse_content($_AI['am_fieldset']);
		$_AI['am_field'] = $at->tags;

		/* 获取附加表信息 */
		$addon = M(parse_name($_AI['am_addon_table'], 1))->where('archive_id = \''.$_AI['archive_id'].'\'')->find();
		$_AI = array_merge($_AI, $addon);

		/* 获取上下页 */
		$_t_where = array();
		$_t_where['a_status'] = array('EQ', 1);
		$_t_where['archive_channel_id'] = array('EQ', $_AI['archive_channel_id']);
		$_t_where['archive_id'] = array('LT', $_AI['archive_id']); /* prev */
		$_AI['a_prev'] = $this->field('`a_title`,`a_url`')->order('`archive_id` DESC')->where($_t_where)->find();
		$_t_where['archive_id'] = array('GT', $_AI['archive_id']); /* next */
		$_AI['a_next'] = $this->field('`a_title`,`a_url`')->order('`archive_id` ASC')->where($_t_where)->find();

		return $_AI;
	}

	public function add_archive($data)
	{
		$result = array('data' => '', 'error' => '');

		$result['data'] = $this->insert($data);
		if(false === $result['data'])
		{
			$result['error'] = L('ADD_FAILED');
			return $result;
		}

		return $result;
	}

	public function add_archive_addon($data)
	{
		$result = array('data' => '', 'error' => '');

		$archiveChannelId = $data['archive_channel_id'];
		$_ACI = M('ArchiveChannel')->get_channelInfo($archiveChannelId);
		/* 处理附加表字段 */
		load('field#func');
		foreach($_ACI['am_field'] as $tag => $params)
		{
			$data[$tag] = get_fieldValue($tag, $params, $data);
		}
		if(false === M(parse_name($_ACI['am_addon_table'], 1))->insert($data))
		{
			$result['error'] = L('ADD_ADDON_DATA_FAILED');
			return $result;
		}

		return $result;
	}

	public function edit_archive($data)
	{
		$result = array('data' => '', 'error' => '');

		$_AI = $this->get_archiveInfo($data['archive_id']);
		if(empty($_AI))
		{
			$result['error'] = L('ITEM_NOT_EXSIT');
			return $result;
		}

		if(false === $this->update($data))
		{
			$result['error'] = L('UPDATE_FAILED');
			return $result;
		}

		return $result;
	}

	public function edit_archive_addon($data)
	{
		$result = array('data' => '', 'error' => '');

		/* 编辑附加表数据 */
		$archiveChannelId = $data['archive_channel_id'];
		$_ACI = M('ArchiveChannel')->get_channelInfo($archiveChannelId);
		/* 处理附加表字段 */
		load('field#func');
		foreach($_ACI['am_field'] as $tag => $params)
		{
			$data[$tag] = get_fieldValue($tag, $params, $data);
		}
		if(false === M(parse_name($_ACI['am_addon_table'], 1))->update($data))
		{
			$result['error'] = L('UPDATE_ADDON_DATA_FAILED');
			return $result;
		}

		return $result;
	}

	public function delete_archive($archiveId)
	{
		$result = array('data' => '', 'error' => '');

		$_AI = $this->get_archiveInfo($archiveId);
		if(empty($_AI))
		{
			$result['error'] = L('ITEM_NOT_EXSIT');
			return $result;
		}

		if(false === $this->delete($archiveId))
		{
			$result['error'] = L('DELETE_FAILED');
			return $result;
		}

		/* 删除附加表信息 */
		if(false === M(parse_name($_AI['am_addon_table'], 1))->delete($archiveId))
		{
			$result['error'] = L('DELETE_ADDON_DATA_FAILED');
			return $result;
		}

		/* 删除上传文件 */
		$_AUL = M('Upload')->where("`u_item_type` = '".$_AI['am_alias']."' and `u_item_id` = '".$archiveId."'")->select();
		if(!empty($_AUL))
		{
			foreach($_AUL as $au)
			{
				/* 删除文件 */
				@unlink(realpath($_SERVER['DOCUMENT_ROOT'].$a['u_src']));
			}
		}
		/* 删除上传表信息 */
		M('Upload')->where("`u_item_type` = '".$_AI['am_alias']."' and `u_item_id` = '".$archiveId."'")->delete();

		/* 删除html文件 */
		$_dir = '';
		if(0 == $_AI['a_html_path'])
		{
			$_dir = trim(str_replace('{uwa_path}', '', $_AI['ac_html_dir']), '/');
		}

		$pyc = get_instance('Pinyin');

		/* 判断文件名 */
		if(!empty($_AI['a_html_naming']))
		{
			$naming = $_AI['a_html_naming'];
		}
		else
		{
			$naming = $_AI['ac_html_naming_archive'];
		}
		$naming = str_replace(
			array(
				'{ac_py}',
				'{ac_id}',
				'{Y}',
				'{M}',
				'{D}',
				'{a_py}',
				'{a_id}'),
			array(
				$pyc->get_pinyin($_AI['ac_name'], 'utf-8'),
				$_AI['archive_channel_id'],
				date('Y', $_AI['a_add_time']),
				date('m', $_AI['a_add_time']),
				date('d', $_AI['a_add_time']),
				$pyc->get_pinyin($_AI['a_title'], 'utf-8'),
				$_AI['archive_id']),
			$naming
		);
		@unlink(realpath(APP_PATH.'/'.$_dir.'/'.trim($naming, '/').C('HTML.FILE_SUFFIX')));
		/* 删除分页文件 */
		foreach($_AI['am_field'] as $field => $params)
		{
			if(1 == $params['f_is_paging'])
			{
				$pagingField = $field;
				break;
			}
		}
		if(isset($pagingField) and false !== strpos($_AI[$pagingField], '#uwa_paging#'))
		{
			$rowsNum = count(explode('#uwa_paging#', $_AI[$pagingField]));
			for($_i = 1; $_i < $rowsNum + 1; $_i++)
			{
				@unlink(realpath(APP_PATH.'/'.$_dir.'/'.trim($naming, '/').'-'.$_i.C('HTML.FILE_SUFFIX')));
			}
		}
		return $result;
	}

	public function pass_archive($archiveId)
	{
		$result = array('data' => '', 'error' => '');

		$_AI = $this->get_archiveInfo($archiveId);
		if(empty($_AI))
		{
			$result['error'] = L('ITEM_NOT_EXSIT');
			return $result;
		}

		if(false === $this->where('archive_id = \''.$archiveId.'\'')->set_field('a_status', 1))
		{
			$result['error'] = L('PASS_FAILED');
			return $result;
		}

		return $result;
	}

	public function refund_archive($archiveId)
	{
		$result = array('data' => '', 'error' => '');

		$_AI = $this->get_archiveInfo($archiveId);
		if(empty($_AI))
		{
			$result['error'] = L('ITEM_NOT_EXSIT');
			return $result;
		}

		if(false === $this->where('archive_id = \''.$archiveId.'\'')->set_field('a_status', 2))
		{
			$result['error'] = L('REFUND_FAILED');
			return $result;
		}

		return $result;
	}

	public function add_flag($archiveId, $afALias)
	{
		$result = array('data' => '', 'error' => '');

		$_AI = $this->get_archiveInfo($archiveId);
		if(empty($_AI))
		{
			$result['error'] = L('ITEM_NOT_EXSIT');
			return $result;
		}

		/* 获取属性值 */
		$afAliasValue = M('ArchiveFlag')->get_flag_value($afALias);

		if(!$afAliasValue)
		{
			$result['error'] = L('PARAMS_ERROR');
			return $result;
		}

		/* 添加属性 */
		$_t_sql = "UPDATE __ARCHIVE__ SET `af_alias` = `af_alias` | {$afAliasValue} WHERE `archive_id` = '{$archiveId}';";
		if(!$this->execute($_t_sql))
		{
			$result['error'] = L('ADD_FLAG_FAILED');
			return $result;
		}

		return $result;
	}

	public function delete_flag($archiveId, $afALias)
	{
		$result = array('data' => '', 'error' => '');

		$_AI = $this->get_archiveInfo($archiveId);
		if(empty($_AI))
		{
			$result['error'] = L('ITEM_NOT_EXSIT');
			return $result;
		}

		/* 获取属性值 */
		$afAliasValue = M('ArchiveFlag')->get_flag_value($afALias);

		if(!$afAliasValue)
		{
			$result['error'] = L('PARAMS_ERROR');
			return $result;
		}

		/* 添加属性 */
		$_t_sql = "UPDATE __ARCHIVE__ SET `af_alias` = `af_alias` &~ {$afAliasValue} WHERE `archive_id` = '{$archiveId}';";
		if(!$this->execute($_t_sql))
		{
			$result['error'] = L('DELETE_FLAG_FAILED');
			return $result;
		}

		return $result;
	}

	public function update_url($archiveId)
	{
		$result = array('data' => '', 'error' => '');

		$_AI = $this->join('__ARCHIVE_CHANNEL__ AS ac ON ac.archive_channel_id = __ARCHIVE__.archive_channel_id')
			->where('__ARCHIVE__.archive_id = \''.$archiveId.'\'')->find();
		if(empty($_AI))
		{
			$result['error'] = L('ITEM_NOT_EXSIT');
			return $result;
		}

		$_o = M('Option')->get_option('core');

		if($_o['html_switch'] and $_AI['ac_is_html'] and $_AI['a_is_html'] and 0 == $_AI['a_cost_points'])
		{
			$_dir = __APP__;
			if(0 == $_AI['a_html_path'])
			{
				$_dir .= '/'.trim(str_replace('{uwa_path}', '', $_AI['ac_html_dir']), '/');
			}
			$pyc = get_instance('Pinyin');

			/* 判断文件名 */
			if(!empty($_AI['a_html_naming']))
			{
				$naming = $_AI['a_html_naming'];
			}
			else
			{
				$naming = $_AI['ac_html_naming_archive'];
			}
			$naming = str_replace(
				array(
					'{ac_py}',
					'{ac_id}',
					'{Y}',
					'{M}',
					'{D}',
					'{a_py}',
					'{a_id}'),
				array(
					$pyc->get_pinyin($_AI['ac_name'], 'utf-8'),
					$_AI['archive_channel_id'],
					date('Y', $_AI['a_add_time']),
					date('m', $_AI['a_add_time']),
					date('d', $_AI['a_add_time']),
					$pyc->get_pinyin($_AI['a_title'], 'utf-8'),
					$_AI['archive_id']),
				$naming
			);
			$url = $_dir.'/'.trim($naming, '/').C('HTML.FILE_SUFFIX');
		}
		else
		{
			$url = Url::U('home@archive/show_archive?archive_id='.$archiveId);
		}
		$this->where('archive_id = \''.$archiveId.'\'')->set_field('a_url', $url);

		$result['data'] = $url;
		return $result;
	}

}


?>