<?php
/**
  * @method 店铺
  * @author soul
  * @copyright 2016/3/31
  */
class B2cShop extends B2cBase
{
	/**
	  * @method 获取店铺ID
	  * @param  $uid 会员ID
	  * @author soul
	  * @copyright 2017/7/7
	  * @return 
			成功 ["status"=>true, "data"=> shopId] 
			失败 ["status"=>false, "data"=> 错误信息] 
	  */
	public function getShopId($uid)
	{
		$res = $this->get('sh_shop', ['shop_id'], sprintf(" AND shop_uid=%d", $uid), true);
		$shopId = empty($res['data'])? 0: $res['data']['shop_id'];
		return LibFc::ReturnData(true, $shopId);
	}

	/**
	 * @method    获取店铺信息
	 * @param     [int|arr]    $shopIds  [店铺id]
	 * @param     [arr]        $fileArr  [需要获取的参数]
	 * @param     [string]     $order    [排序条件]
	 * @author     xu
	 * @copyright 2018-04-16
	 * @return    ["status"=>true, "data"=>[['logo','SERVICE','LOGISTICS'...],[...]]  
	 */
	public function getShopMsg($shopIds , $fileArr = [] ,$order='')
	{
		// 参数
		if(empty($shopIds))
			return LibFc::ReturnData(false, 'getShopMsg店铺ID为空');
		$ids = is_array($shopIds) ? array_filter($shopIds,'LibFc::Int') : [LibFc::Int($shopIds)];
		if(empty($ids))
			return LibFc::ReturnData(false, 'getShopMsg店铺ID格式不正确');
		$fileArr = empty($fileArr) ? ['*'] :$fileArr;
		// 执行
		$where =  sprintf(' and shop_id in (%s)',implode(',', $ids)).$order;
		$res = $this->get('sh_shop left join us_user_base on ub_uid = shop_uid', $fileArr , $where);
		$res = array_column($res['data'], null ,'shop_id');
		// 顺序
		$data = array();
		foreach ($ids as $v) {
			$data[] = $res[$v];
		}
		// 返回
		return LibFc::ReturnData(true,$data);		
	}


	/**
	 * @method 获取目录的指定用户的权限代码
	 * @http get 
	 * @param  shopid              int [必填] 店铺ID
	 * @param  uid              int [必填] 用户ID
	 * @author zhengweihua 
	 * @copyright 2022-05-20
	 * @return  {"status":true,"data":[{"smr_code":"item_buy","smr_name":"配件购买"},{"smr_code":"item_page","smr_name":"配件详情页"},{"smr_code":"search_engine","smr_name":"发动机查询"}],"code":"","encry":0,"runtime":99}
	 	smr_code 会员权限代码
	    smr_name 会员权限说明
	 */
	public function getSuperUseRule($shopid, $uid)
	{
		$shopid = (int) $shopid;
		$uid = (int) $uid;
		$B2cBase = new B2cBase();
		$now = time();
		$where = sprintf(" and ssu_status =1 and shop_status=1 and shop_id=%d and ssu_btime <= %d and ssu_etime >=%d ", $shopid, $now, $now);
		$superRes = $B2cBase->get('sh_super join sh_shop on ssu_shop_id = shop_id',['ssu_id,ssu_module','ssu_pjl_show'], $where, true);
		if(empty($superRes['data'])) LibFc::ReturnJson(true, []);
		$superModuleArr = $superRes['data']['ssu_module']? explode(',',$superRes['data']['ssu_module']):[];

		$table = 'sh_member_rule_link join sh_member_rule on smr_code = smrl_smr_code';
		$res = $B2cBase->get($table, ['smr_code,smr_name,smrl_mel_id'], sprintf(" and smrl_shop_id=%d order by smr_seq asc", $shopid));
		//未配置,拥有所有权限
		if ($shopid == $uid || empty($res['data'])) 
		{
			$result = $B2cBase->get('sh_member_rule', ['smr_code,smr_name']," order by smr_seq asc");
			$res = $result['data'];
		}
		else
		{	//未注册登陆
			$meml_id = -1;
			$result = [];
			foreach ($res['data'] as $item) 
			{
				$result[$item['smrl_mel_id']][] = [
					'smr_code' => $item['smr_code'],
					'smr_name' => $item['smr_name']
				];
			}
			if(in_array('user',$superModuleArr) || $superRes['data']['ssu_pjl_show'])
			{
				if(!empty($uid)) 
				{
					$meml_id = 0;
					//存在店铺用户
					$table = 'sh_member_link join sh_member on meml_mem_id = mem_id';
					$memberRes = $B2cBase->get($table, ['mem_mel_id'], sprintf(" and meml_uid=%d and meml_shop_id=%d ", $uid, $shopid), true);
					if (!empty($memberRes['data'])) $meml_id = $memberRes['data']['mem_mel_id'];
				}
			}
			$res = $result[$meml_id] ? $result[$meml_id] : [];
		}
		if(!in_array('price',$superModuleArr)){
			$res = array_column($res,null,'smr_code');
			unset($res['item_price']);
			$res = array_values($res);
		}
		return LibFc::ReturnData(true,$res);
	}

	/**
	 * @param  array $room_id
	 * @method 初始化微信账号
	 * @author zhengweihua 
	 * @copyright 2025-09-27
	 */
	public function initWxAccount($room_id = [])
	{
		$where = '';
		if(!empty($room_id)){
			$where = sprintf(" AND wrr_room_id in ('%s')",implode("','", $room_id));
		}
		// 分批获取数据，避免一次性加载过多数据到内存
		$limit = 1000;
		$offset = 0;

		do {
			$res = $this->get('wx_robot_room',['*'],sprintf(" %s LIMIT %d,%d",$where,$offset,$limit));
			$offset += $limit;

			if($res['data']){
				$data = [];
				$existingIds = []; // 存储已存在的ID
				$updateData = [];  // 存储需要更新的数据
				// 收集所有要插入的ID
				$allIds = [];
				foreach ($res['data'] as $val) {
					$allIds[] = $val['wrr_room_id'];
					
					if($val['wrr_mems']){

						$memsArr = json_decode($val['wrr_mems'],true);

						foreach ($memsArr as $mval) {
							$allIds[] = $mval['id'];
						}
					}
				}

				 // 查询已存在的记录
				if (!empty($allIds)) {
					$existingRes = $this->get('wx_acount', ['wa_id'], 
						sprintf(" AND wa_id in ('%s')", implode("','", array_unique($allIds))));
					if (!empty($existingRes['data'])) {
						$existingIds = array_column($existingRes['data'], 'wa_id');
					}
				}
				foreach ($res['data'] as $val) 
				{
					// 只有当记录不存在时才添加
					if (!in_array($val['wrr_room_id'], $existingIds)) {
						$data[$val['wrr_room_id']] = [
							'wa_id'=>$val['wrr_room_id'],
							'wa_nickname'=>LibFc::filterEmoji($val['wrr_room_name'])
						];
					}else{
						$updateData[$val['wrr_room_id']] = [
							'wa_id'=>$val['wrr_room_id'],
							'wa_nickname'=>LibFc::filterEmoji($val['wrr_room_name'])
						];
					}
	
					if($val['wrr_mems']){
						$memsArr = json_decode($val['wrr_mems'],true);
						foreach ($memsArr as $mval) {
							// 只有当记录不存在时才添加
							if (!in_array($mval['id'], $existingIds)) {
								$data[$mval['id']] = [
									'wa_id'=> $mval['id'],
									'wa_nickname'=> LibFc::filterEmoji($mval['name'])
								];
							}else{
								$updateData[$mval['id']] = [
									'wa_id'=> $mval['id'],
									'wa_nickname'=> LibFc::filterEmoji($mval['name'])
								];
							}
						}
					}
				}
				
				if($data){
					$this->addAny('wx_acount',['wa_id','wa_nickname'],array_values($data));
				}
				// 执行更新操作
				foreach($updateData as $updateItem) {
					$this->set('wx_acount', ['wa_nickname' => $updateItem['wa_nickname']], sprintf(" AND wa_id='%s'", $updateItem['wa_id']));
				}
			}
		}while (!empty($res['data']));

		return LibFc::ReturnData(true, '初始化成功');
	}

}