<?php
/**
  * @method 宜配车型库主库表基本操作
  * @author soul
  * @copyright 2016/3/31
  */
class CrmBase
{
	public $CRMDb = null;
	public function __construct($CRMDb = null)
	{	
		$this->CRMDb = $CRMDb==null ?  new LibDb (mvc::$cfg['DB']['YP_CRM']): $CRMDb;
	}
	
	/**
	  * @method 查询表信息
	  * @param  $table 表明 如：yp_product 或者 yp_product as a join yp_number as b on a.pid=b.pid
	  * @param  $fieldArr 需要查询的字段名称数组
	  * @param  $where 查询条件
	  * @param  $oneRow true|false
	  * @author soul
	  * @copyright 2016/3/30
	  * @return 
			成功 ["status"=>true, "data"=> $oneRow=false 二维数组 ; $oneRow=true 一维数组] 
			失败 ["status"=>false, "data"=> 错误信息]  
	  */
	public function get($table, $fieldArr, $where = '', $oneRow = false)
	{
		if(!empty($table) && is_array($fieldArr))
		{
			$sql = sprintf("select %s from %s where 1=1 %s", implode(',', $fieldArr), $table, $where);
			$res = $oneRow? $this->CRMDb->Row($sql): $this->CRMDb->Table($sql);
			if($res !== false)
			{
				return LibFc::ReturnData(true, $res);
			}
			else
			{
				return LibFc::ReturnData(false, 'SQL:'.$sql.'执行失败。');
			}
		}
		return LibFc::ReturnData(false, $table.'查询提供的参数不正确。');
	}



	/**
	  * @method 获取指定条件下的某字段唯一值
	  * @param  $table 表明 如：yp_product 或者 yp_product as a join yp_number as b on a.pid=b.pid
	  * @param  $field 字段名称
	  * @param  $where 查询条件
	  * @author soul
	  * @copyright 2016/3/30
	  * @return 
			成功 ["status"=>true, "data"=> [111,222,....]] 
			失败 ["status"=>false, "data"=> 错误信息]  
	  */
	public function getFieldUniVal($table, $field, $where = '')
	{
		if(!empty($table) && !empty($field))
		{
			$field1 = stripos($where, ' group by ') !== false || stripos($table, ' group by ') !== false? $field: ' distinct '.$field;
			$sql = sprintf("select %s from %s where 1=1 %s", $field1, $table, $where);
			$resFlag = $this->CRMDb->Query($sql);
			if($resFlag)
			{
				$arr = array();
				while($row = $this->CRMDb->Fetch())
				{
					$arr[$row[$field]] = $row[$field];
				}
				return LibFc::ReturnData(true, array_values($arr));
			}
			return LibFc::ReturnData(false, 'SQL:'.$sql.'执行失败。');
		}
		return LibFc::ReturnData(false, $table.'查询提供的参数不正确。');
	}



	/**
	  * @method 添加记录
	  * @param  $table 表明 如：yp_product 或者 yp_product as a join yp_number as b on a.pid=b.pid
	  * @param  $dataArr 基本信息字段=>值 数组
	  * @param  $clobfiledArr $dataArr中字段类型为LONG的字段
	  * @author soul
	  * @copyright 2016/3/30
	  * @return 
			成功 ["status"=>true, "data"=> ID] 
			失败 ["status"=>false, "data"=> 错误信息] 
	  */
	public function add($table, $dataArr, $clobfiledArr = [])
	{
		if(empty($table) || !is_array($dataArr) || empty($dataArr))
		{
			return LibFc::ReturnData(false, $table.'提供添加记录的参数不正确。');
		}

		$filedArr = array();
		$valArr = array();
		foreach($dataArr as $k=>$v)
		{
			$filedArr[] = LibFc::Escape($k);
			$valArr[] = sprintf("'%s'", LibFc::Escape($v, true));
		}
		$AddSql = sprintf("insert into %s (%s) values(%s)", LibFc::Escape($table), implode(',', $filedArr), implode(',', $valArr));
		$this->CRMDb->Begin();
		$resFlag = $this->CRMDb->Query($AddSql);
		if($resFlag)
		{
			$Id = $this->CRMDb->InsertID();
			$this->CRMDb->End();
			return LibFc::ReturnData(true, $Id);
		}
		
		return LibFc::ReturnData(false, $table.'添加记录SQL语句执行失败。');
	}

	/**
	  * @method 根据条件修改记录
	  * @param  $table 表明 如：yp_product 或者 yp_product as a join yp_number as b on a.pid=b.pid
	  * @param  $dataArr 基本信息字段=>值 数组  如果需要使用表达式 例如  num=num+1 则提供['num'=>'#@num+'.$num]
	  * @param  $where 修改条件
	  * @param  $clobfiledArr $dataArr中字段类型为LONG的字段
	  * @author soul
	  * @copyright 2016/3/30
	  * @return 
			成功 ["status"=>true, "data"=> 影响行数] 
			失败 ["status"=>false, "data"=> 错误信息] 
	  */
	public function set($table, $dataArr, $where, $clobfiledArr = [])
	{
		if(empty($table) || !is_array($dataArr) || empty($dataArr))
		{
			return LibFc::ReturnData(false, $table.'修改记录提供的参数不正确。');
		}
		$valArr = array();
		foreach($dataArr as $k=>$v)
		{
			if(stripos($v, '#@') === 0)
			{
				$valArr[] = sprintf("%s=%s", LibFc::Escape($k), LibFc::Escape(trim(substr($v, 2))));
			}
			else
			{
				$valArr[] = sprintf("%s='%s'", LibFc::Escape($k), LibFc::Escape($v, true));
			}
		}
		$SetSql = sprintf("update %s set %s where 1=1 %s ", LibFc::Escape($table), implode(',', $valArr), $where);
		$this->CRMDb->Begin();
		$resFlag = $this->CRMDb->Query($SetSql);
		if($resFlag)
		{
			$rows = $this->CRMDb->RowCount();
			$this->CRMDb->End();
			return LibFc::ReturnData(true, $rows);
		}
		return LibFc::ReturnData(false, $table.'修改记录SQL语句执行失败。');
	}

	/**
	  * @method 根据条件删除记录
	  * @param  $table 表明 如：yp_product 或者 yp_product as a join yp_number as b on a.pid=b.pid
	  * @param  $where 修改条件
	  * @author soul
	  * @copyright 2016/3/30
	  * @return 
			成功 ["status"=>true, "data"=> 影响行数] 
			失败 ["status"=>false, "data"=> 错误信息] 
	  */
	public function del($table, $where)
	{
		if(empty($table) || empty($where))
		{
			return LibFc::ReturnData(false, $table.'删除记录提供的参数不正确。');
		}
		$DelSql = sprintf("delete from %s where 1=1 %s",  LibFc::Escape($table), $where );
		$this->CRMDb->Begin();
		$resFlag = $this->CRMDb->Query($DelSql);
		if($resFlag)
		{
			$rows = $this->CRMDb->RowCount();
			$this->CRMDb->End();
			return LibFc::ReturnData(true, $rows);
		}
		return LibFc::ReturnData(false,  $table.'删除记录SQL语句执行失败。');
	}


	/**
	 * @param  [type] $auUid
	 * @param  [type] $ctrIdArr
	 * @method 查不属于业务员的客户
	 * @author zhengweihua 
	 * @copyright 2024-01-30
	 */
	public function checkCtrUserRule($auUid,$ctrIdArr)
	{
		$arr = [];
		if ($_SESSION['_usergroup'] != 'kefu' && $_SESSION['_usergroup'] != 'all') {
			if ($_SESSION['_usergroup'] == 'shangji') {
				$res = $this->getNextUId();
				$auUidArr = $res['data'];
				$auUidArr[] = $auUid;
			}else{
				$auUidArr = [$auUid];
			}
			if($auUidArr)
			{
				//获取当前用户不可见的客户
				$res = $this->get('crm_customer_admin', ['distinct cca_ctr_id'], sprintf(" and cca_ctr_id in (%s) and cca_level_id in (1,2,5) and cca_au_uid not in (%s) and cca_end_time > %d", implode(',', $ctrIdArr), implode(',', $auUidArr), time()));
				$arr = $res['data'] ? array_column($res['data'], 'cca_ctr_id') : [];	
			}
			
		}
		return LibFc::ReturnData(true,$arr);
	}

	public function getNextUId()
	{
		$arr = [];
		$B2cBase = new B2cBase();
		$res = $B2cBase->get('an_user_group_link',['ugl_ugid'],sprintf(" AND ugl_uid = %d",$_SESSION['_userid']));
		if($res['data'])
		{
			//比当前用户职位高级的用户
			$sql = sprintf("SELECT distinct ugl_uid 
			FROM an_user_group_link join an_user_group on ugl_ugid= ugp_id 
			WHERE ugl_ugid IN (SELECT ugp_pid FROM an_user_group WHERE ugp_id IN (%s))",implode(',',$_SESSION['_maxUgpId']));

			$userGroupIds = array_column($res['data'],'ugl_ugid');
			$where = sprintf(" and au_status=1 and ugp_pid IN (%s) AND ugl_uid NOT IN (%s) ",implode(',',$userGroupIds),$sql);
			$table = 'an_user_group_link  
				join an_user_group on ugl_ugid= ugp_id
				join an_user on au_uid = ugl_uid ';
			$res1 =  $B2cBase->get($table,['distinct au_uid'],$where);
			if ($res1['data']) {
				$arr= array_column($res1['data'],'au_uid');
			}
		}
		return LibFc::ReturnData(true, $arr);	
	}

	public function getCustomerDetail($ctrId)
	{
		
		$arr = [];
		if($ctrId){
			$table = 'crm_customer 
			left join ypdb_write.yp_user on ctr_uid = u_id
			left join yp_paojieling.pl_shop on shop_id = ctr_pjl_shop_id';
			$res = $this->get($table, ['crm_customer.*,u_name,u_real_name,u_nickname,u_mobile,shop_vip_etime,shop_enter_time,shop_apply_time'], sprintf(" and ctr_id=%d", $ctrId), true);
			if(!empty($res['data']))
			{
				$arr = $res['data'];
				if(empty($arr['ctr_tel'])){
					$arr['ctr_tel'] = $arr['u_mobile'];
				}
				$arr['au_name'] = '';
				$arr['cca_level_id'] = 0;
				$arr['cca_end_time'] = 0;
				$arr['weixin_count'] = 0;
				$arr['call_count'] = 0;
				$arr['follow_count'] = 0;
				$arr['part'] = [];
				$arr['make'] = [];
				$arr['self'] = [];
				$arr['ctr_pct_ids'] = json_decode($arr['ctr_pct_ids'], true);
				$tids = [];
				if(!empty($arr['ctr_pct_ids']['pid']))
				{
					$tids[] = (int) $arr['ctr_pct_ids']['pid'];
					if(!empty($arr['ctr_pct_ids']['cid']))
					{
						$tids[] = (int) $arr['ctr_pct_ids']['cid'];
						if(!empty($arr['ctr_pct_ids']['tid'])) $tids[] = (int) $arr['ctr_pct_ids']['tid'];
					}
				}
				$arr['pct_ids'] = $tids;
				$arr['pcts'] = [];
				$CrmContract = new CrmContract();
				$res = $CrmContract->getAddrByIds(implode(',', $arr['pct_ids']));
				$pctArr = $res['data'];
				foreach($arr['pct_ids'] as $pt)
				{
					if(empty($pctArr[$pt])) break;
					$arr['pcts'][] = $pctArr[$pt];
				}

				//获取所有业务员姓名
				$B2cBase = new B2cBase();
				$res = $B2cBase->get('an_user', ['au_uid', 'au_name']);
				$auArr = array_column($res['data'], 'au_name', 'au_uid');

				$lwhere = sprintf(" and cca_ctr_id =%d and cca_end_time >%d", $arr['ctr_id'], time());
				$res = $this->get('crm_customer_admin', ['cca_au_uid, cca_level_id, cca_end_time'], $lwhere, true);
				if(!empty($res['data']))
				{
					$tv = $res['data'];
					$arr['au_name'] = $auArr[$tv['cca_au_uid']];
					$arr['cca_level_id'] = $tv['cca_level_id'];
					$arr['cca_end_time'] = $tv['cca_end_time'];
				}

				// 给出可分享的业务员列表
				$res = $B2cBase->get('an_user', ['au_uid', 'au_name'], sprintf(" and au_status=1 and au_yewu=1"));
				foreach($res['data'] as $item)
				{
					$arr['auArr'][] = ['cla_id'=>$item['au_uid'], 'cla_name'=>$item['au_name']];
				}
				$res = $this->get('crm_customer_share left join ypb2c.an_user on ccs_au_uid = au_uid', ['ccs_au_uid, au_name'], sprintf(" and ccs_ctr_id =%d", $ctrId));
				$arr['share_au'] = array_column($res['data'], 'ccs_au_uid');
				//用户标签
				$lwhere = sprintf(" and cul_ctr_id =%d ORDER BY cla_seq", $arr['ctr_id']);
				$res = $this->get('crm_customer_label JOIN crm_label ON cla_id = cul_cla_id', ['cla_type, cla_id,cla_name'], $lwhere);
				foreach($res['data'] as $tv)
				{
					$arr[$tv['cla_type']][] = ['cla_id'=>$tv['cla_id'], 'cla_name'=>$tv['cla_name']];
				}
				$YpwBase = new YpwBase();
				
				//关注零件
				$res = $YpwBase->get('yp_user_act_part', ['uap_part'], sprintf(" and uap_uid=%d order by uap_count desc limit 3", $arr['ctr_uid']));
				$arr['act_part'] = array_column($res['data'], 'uap_part');

				//关注品牌
				$res = $YpwBase->get('yp_user_act_brand', ['uab_brand'], sprintf(" and uab_uid=%d order by uab_count desc limit 3", $arr['ctr_uid']));
				$arr['act_make'] = array_column($res['data'], 'uab_brand');
				$arr['ctr_uname'] = $arr['ctr_uname']?:($arr['u_name']?:$arr['u_real_name']);

				//联系人修改历史
				$arr['contactChange'] = [];
				$res = $this->get('crm_contact_log',['*'],sprintf(" AND ccl_ctr_id=%d ORDER by ccl_etime DESC",$ctrId),true);
				if($res['data'])
				{
					$res['data']['name'] = $auArr[$res['data']['ccl_uid']];
					$arr['contactChange'] = $res['data'];
				}
				
				// 获取所有添加了微信的业务员
				$wxTable = 'wx_user wu1
					left join wx_user_address on wu1.wu_id = wua_wu_id
					left join wx_user wu2 on wua_mwu_id = wu2.wu_id
					left join an_user on wu2.wu_auid = au_uid AND au_status = 1';
				$res = $B2cBase->get($wxTable,['au_uid','au_name'],sprintf(" and wu1.wu_uid = %d", $arr['ctr_uid']));
				$arr['weixin_workers'] = array_values(array_unique(array_filter(array_column($res['data'], 'au_name'), function ($item) {
					return $item !== null && trim((string)$item) !== '';
				})));
			}
		}
		return LibFc::ReturnData(true,$arr);
	}

}
