<?php
// 地区管理模型
class AreaModel extends Model {
	private $areaArray = array();
	private $areas = array();
	public function save($info = array()) {
		$info or $info = $_POST['info'];
		$info['areaid'] = intval($info['areaid']);
		// 名称有效性
		$info['name'] = trim($info['name']);
		if (empty($info['name'])) {
			$this -> error = L('NAME_EMPTY');
			return false;
		}
		$info['sign'] = trim($info['sign']);
		if ($info['sign']) {
			$rs = $this -> where('sign=' . $info['sign']) -> find();
			if ($rs && (!$info['areaid'] || $info['areaid'] != $rs['areaid'])) {
				$this -> error = L('AREA_SIGN_IS_EXIST');
				return false;
			}
		}
		$info['strong'] = isset($info['strong'])?intval($info['strong']):0;
		if (!$info['areaid']) {
			$info['areaid'] = $this -> getId('areaid');
			$isAdd = true;
		} else $isAdd = false;
		$this -> create($info);
		return $isAdd?$this -> add():$this -> update();
	}
	// 删除
	public function del() {
		$selids = R('selids');
		if (!empty($selids)) {
			$where = strstr($selids, ',')?"areaid IN ($selids)":"areaid=$selids";
			if (!$this -> where($where) -> delete()) {
				$this -> error = L('OPERATE_FAIL');
				$rs = false;
			} else $rs = true;
		} else {
			$this -> error = L('NOPARAM');
			$rs = false;
		}
		return $rs;
	}
	/**
	 * 生成顺序正确的地区数组，并添加每个地区的层级和是否是父分类
	 *
	 * @param array $data
	 * @param int $areaid
	 * @param int $level 分类深度
	 * @access private
	 */
	private function format(&$data, $areaid = 0, $level = 0) {
		if (isset($data[$areaid])) {
			$total = count($data[$areaid]);
			foreach($data[$areaid] as $k => $v) {
				$v['level'] = $level;
				$v['subnum'] = isset($data[$k])?count($data[$k]):0;
				$this -> areaArray[$v['areaid']] = $v;
				$v['subnum'] && $this -> format($data, $k, $level + 1);
			}
		}
		return $this -> areaArray;
	}
	public function cache() {
		$tmp = $this -> order(array('orderid', 'areaid')) -> select();
		if (is_array($tmp)) {
			$data = array();
			// 将父类areaid相同的分类合并,产生二维数组$areaArray
			foreach($tmp as $v) {
				unset($v['orderid']);
				$data[$v['pid']][$v['areaid']] = $v;
			}
		}
		$data = $this -> format($data);
		is_array($data) && Cache :: write('area', $data);
	}
	public function area($area = '', $index = '') {
		$this -> areas or $this -> areas = Cache :: read('area');
		if ($area) {
			$rs = '';
			if (is_numeric($area)) {
				if (isset($this -> areas[$area])) $rs = $this -> areas[$area];
			} else {
				foreach($this -> areas as $tmp) {
					if ($area == $tmp['sign']) {
						$rs = $tmp;
						break;
					}
				}
			}
			if ($rs && $index && isset($rs[$index])) $rs = $rs[$index];
		} else $rs = $this -> areas;
		return $rs;
	}
	public function child($pid) {
		$pid = intval($pid);
		$this -> areas or $this -> areas = $this -> area();
		$rs = array();
		foreach($this -> areas as $tmp) {
			if ($tmp['pid'] == $pid) {
				$rs[] = $tmp;
			}
		}
		return $rs;
	}
}
