<?php
class crmAction extends action
{
    function __construct(){
        parent::__construct();
		$this->mod = new crmMod();
    }

    function __destruct(){
    }

	/**手动更新 */
	function update()
	{
		ignore_user_abort(true);
		echo "正在执行中...<br />\r\n";
		flush();

		$command =  \mvc::$cfg['ROOT'] . 'cmd/php getCrm.php';
		$command =  'php ' . \mvc::$cfg['ROOT'] . 'cmd/getCrm.php';
		// 打开一个进程并执行外部命令
		$handle = popen($command, 'r');

		// 从命令的输出管道中读取数据
		while (!feof($handle)) {
			$output = fgets($handle);
			echo $output."<br />\r\n";
			flush();
		}
		// 关闭进程的管道
		pclose($handle);		
		echo "<br />\r\n更新完成\r\n";
	}

	function moneyList()
	{
		$where = '';
		if ($_POST['filters']) {
			$groups = json_decode(htmlspecialchars_decode($_POST['filters']), true);
			$where = $this->groups2sql($groups);
		}
		$data = $this->mod->list($where, $_POST['page'], $_POST['rows'], $_POST['sidx'], $_POST['sord']);
		echo json_encode($data, JSON_UNESCAPED_UNICODE);
	}

	function getMoneyBaseData()
	{
		$data = $this->mod->getMoneyBaseData();
		echo json_encode(['code' => 0, 'data' => $data], JSON_UNESCAPED_UNICODE);
	}

	/**设置需要过滤的mon_id */
	function filter_mon_id()
	{
		$input = file_get_contents('php://input');
		$params = json_decode($input, true);

		$mon_id = $params['mon_id'];
		$isfilter = $params['isfilter']=='1' ?: false;
		$db = $this->mod->logic->db;
		$q = new sqler();
		$q->table('money_crm._qg_filter_mon_id')->set('filter_mon_id', $mon_id);
		if($isfilter){
			$db->replaceInto($q);
		}else{
			$db->delete($q->where('filter_mon_id', $mon_id));
		}
		echo json_encode(['code' => 0, 'data' => []], JSON_UNESCAPED_UNICODE);
	}

	
	function newVouvherView()
	{	
		//最大结算周期
		$maxCheckoutCycle = (new sqler($this->mod->logic->db))->table('voucher_checkout')->max('vc_cycle');
		require \mvc::$cfg['SITE_PATH_TPL']. 'crm/newVouvherList.php';
	}

	/**查看日志- */
	function logRecord()
	{
		require \mvc::$cfg['SITE_PATH_TPL'] . 'crm/logRecord.php';
	}

	/**查看日志- */
	function logFile()
	{
		$filename = $_REQUEST['file'];
		$content = file_get_contents($filename);
		$content = str_replace("\n", "<br />", $content);
		echo '<a href="javascript:history.back()" style="color:#008"> 返回  </a><br /><br />';
		echo $content;
	}
	
	function newVouvherList()
	{
		$where = '';
		$filters = $_REQUEST['filters'];
		$dateBegin = $_REQUEST['dateBegin'];
		$dateEnd = $_REQUEST['dateEnd'];
		if (empty($filters)) {
			$input = file_get_contents('php://input');
			$params = json_decode($input, true);
			$filters = $params['filters'];
		}
		if ($filters) {
			$groups = json_decode(htmlspecialchars_decode($filters), true);
			$where = $this->groups2sql($groups, function ($field, $op, $data){
				if (in_array($field, ['subjectText', 'depText', 'staffText', 'clientText',])) {
					$rule = [
						'subjectText' => ['findField' => 'v_subject',  'targetID' => 200, 'targetField' => 'getObjectChilds(o_id)'],
						'depText' =>    ['findField' => 'v_object_1', 'targetID' => 1, 'targetField' => 'o_id'],
						'staffText' =>  ['findField' => 'v_object_2', 'targetID' => 2, 'targetField' => 'o_id'],
						'clientText' => ['findField' => 'v_object_4', 'targetID' => 4, 'targetField' => 'o_id'],
					];
					$rootNode = $this->mod->dbRead->Row("SELECT o_lft,o_rgt FROM `object` WHERE o_id=" . $rule[$field]['targetID']);
					$arr = $this->mod->dbRead->Table("SELECT " . $rule[$field]['targetField'] . " ids FROM `object` 
                                WHERE o_lft>=" . $rootNode['o_lft'] . " AND o_rgt<=" . $rootNode['o_rgt'] . " AND o_keyword like '%" . trim($data) . "%'");
					if ($arr) {
						$field = $rule[$field]['findField'];
						$op = 'in';
						$data = implode(',', array_column($arr, 'ids'));
					} else {
						$field = '1';
						$op = 'eq';
						$data = '0';
					}
				}
				return ['field' => $field, 'op' => $op, 'data' => $data];
			});
		}
		if ($_POST['sidx'] == 'cycleseq') $_POST['sidx'] = 'v_cycle,v_seq';
		$this->mod->isForm = !empty($_REQUEST['form']);
		if(empty($where) && !empty($dateBegin) && !empty($dateEnd)){
			$where = "v_date >='". $dateBegin."' AND v_date <='". $dateEnd."'";
		}
		if($where){
			//只支持日期查询
			preg_match_all('/\'([^\']+)\'/',$where,$m);
			if(isset($m[1])){
				$date1 = $m[1][0];
				$date2 = null;
				if(isset($m[1][1])) $date2 = $m[1][1];
				if( $date2 == null){
					$where = "mon_date >='" . strtotime($date1) . "' AND mon_date <='" . strtotime($date1.' 23:59:59') . "'";
				}else{
					$where = "mon_date >='" . strtotime($date1) . "' AND mon_date <='" . strtotime($date2 . ' 23:59:59') . "'";
				}
			}
		}
		$data = $this->mod->newVouvherList(true, $where, $_POST['page']);
		foreach ($data['rows'] as $k => $row) {
			$row['subjectText'] = $row['subjectText'];
			if (empty($_REQUEST['form'])) {
				$row['v_j'] = numformat($row['v_j']);
				$row['v_d'] = numformat($row['v_d']);
			}
			$data['rows'][$k] = $row;
		}
		$data['dateBegin'] = $dateBegin;
		$data['dateEnd'] = $dateEnd;
		echo json_encode($data, JSON_UNESCAPED_UNICODE);
	}

	
	function outPayView()
	{	
		//最大结算周期
		$maxCheckoutCycle = (new sqler($this->mod->logic->db))->table('voucher_checkout')->max('vc_cycle');
		require \mvc::$cfg['SITE_PATH_TPL']. 'crm/outPayList.php';
	}


	function outPayList()
	{
		$where = '';
		$filters = $_REQUEST['filters'];
		$dateBegin = $_REQUEST['dateBegin'];
		$dateEnd = $_REQUEST['dateEnd'];
		if (empty($filters)) {
			$input = file_get_contents('php://input');
			$params = json_decode($input, true);
			$filters = $params['filters'];
		}
		if ($filters) {
			$groups = json_decode(htmlspecialchars_decode($filters), true);
			$where = $this->groups2sql($groups, function ($field, $op, $data) {
				if (in_array($field, ['subjectText', 'depText', 'staffText', 'clientText',])) {
					$rule = [
						'subjectText' => ['findField' => 'v_subject',  'targetID' => 200, 'targetField' => 'getObjectChilds(o_id)'],
						'depText' =>    ['findField' => 'v_object_1', 'targetID' => 1, 'targetField' => 'o_id'],
						'staffText' =>  ['findField' => 'v_object_2', 'targetID' => 2, 'targetField' => 'o_id'],
						'clientText' => ['findField' => 'v_object_4', 'targetID' => 4, 'targetField' => 'o_id'],
					];
					$rootNode = $this->mod->dbRead->Row("SELECT o_lft,o_rgt FROM `object` WHERE o_id=" . $rule[$field]['targetID']);
					$arr = $this->mod->dbRead->Table("SELECT " . $rule[$field]['targetField'] . " ids FROM `object` 
                                WHERE o_lft>=" . $rootNode['o_lft'] . " AND o_rgt<=" . $rootNode['o_rgt'] . " AND o_keyword like '%" . trim($data) . "%'");
					if ($arr) {
						$field = $rule[$field]['findField'];
						$op = 'in';
						$data = implode(',', array_column($arr, 'ids'));
					} else {
						$field = '1';
						$op = 'eq';
						$data = '0';
					}
				}
				return ['field' => $field, 'op' => $op, 'data' => $data];
			});
		}
		if ($_POST['sidx'] == 'cycleseq') $_POST['sidx'] = 'v_cycle,v_seq';
		$this->mod->isForm = !empty($_REQUEST['form']);
		if (empty($where) && !empty($dateBegin) && !empty($dateEnd)) {
			$where = "pay_date >='" . $dateBegin . "' AND pay_date <='" . $dateEnd . "'";
		}
		if ($where) {
			//只支持日期查询
			preg_match_all('/\'([^\']+)\'/', $where, $m);
			if (isset($m[1])) {
				$date1 = $m[1][0];
				$date2 = null;
				if (isset($m[1][1])) $date2 = $m[1][1];
				if ($date2 == null) {
					$where = "pay_date >='" . $date1 . "' AND pay_date <='" . $date1 . "'";
				} else {
					$where = "pay_date >='" . $date1 . "' AND pay_date <='" . $date2 . "'";
				}
			}
		}
		//dd($where);
		$data = $this->mod->outPayList(true, $where, $_POST['page']);
		foreach ($data['rows'] as $k => $row) {
			$row['subjectText'] = $row['subjectText'];
			if (empty($_REQUEST['form'])) {
				$row['v_j'] = numformat($row['v_j']);
				$row['v_d'] = numformat($row['v_d']);
			}
			$data['rows'][$k] = $row;
		}
		$data['dateBegin'] = $dateBegin;
		$data['dateEnd'] = $dateEnd;
		echo json_encode($data, JSON_UNESCAPED_UNICODE);
	}

	/**生成凭证 */
	function createVoucher()
	{
		$input = file_get_contents('php://input');
		$params = json_decode($input, true);
		$data = $this->mod->createVoucher($params);
		echo json_encode(['code' => 0, 'data' => $data], JSON_UNESCAPED_UNICODE);
	}

	/**生成凭证 */
	function createVoucher2()
	{
		$input = file_get_contents('php://input');
		$params = json_decode($input, true);
		$data = $this->mod->createVoucher2($params, 'outPayList');
		echo json_encode(['code' => 0, 'data' => $data], JSON_UNESCAPED_UNICODE);
	}
}