<?php
class shopAction extends baseAction
{
	public function __construct()
	{
		parent::__construct();
		$modelSelectArr = mvc::$cfg['MODEL_OPTS'];
		LibTpl::Set('modelSelectArr', $modelSelectArr);
		LibTpl::Set('tokenTypeArr',mvc::$cfg['ROBOT_CONFIG']['tokentype']);
	}

	/**
	 * @method 店铺管理主页
	 * @author xu
	 * @copyright 2017.01.04
	 */
	function index()
	{
	    $Param = mvc::$URL_PARAMS;
		LibRule::Check('SL01');
		LibTpl::Set('Params',$Param);
		LibTpl::Set('title','店铺管理-跑街的');
		LibTpl::Put();
	}

	function clearShopPro()
	{
		/*$B2cBase = new B2cBase();
		$shopId = 0;
		$res = $B2cBase->get('bc_product', ['pro_id'], sprintf("and pro_shop_id=%d", $shopId));
		$proIdArr= array_column($res['data'], 'pro_id');
		$B2cProduct = new B2cProduct();
		$B2cProduct->delProduct($shopId, $proIdArr);*/
	}

	/**
	 * @店铺列表页
	 * @author xu
	 * @copyright 2017.12.19
	 */
	function lists()
	{
		LibRule::Check('SL01');
		$Params = mvc::$URL_PARAMS;
		$where = '';

		// 参数
		if(!empty($Params['status']))
		{
			switch ($Params['status']) {
				case 'forbidden':
					$where .= " and shop_status =-1";
					break;
				case 'stop':
					$where .= " and shop_status = 0";
					break;
				case 'using':
					$where .= " and shop_status = 1";
					break;
				case 'open':
					$where .= " and shop_status = -2";
					break;
			}
		}
		foreach(array_filter($Params) as $k=>$v)
		{
			switch($k)
			{
				case 'shopname': // 店铺名
					$where .= sprintf(" and (shop_name like '%%%s%%' or shop_com_name like '%%%s%%')", LibFc::Escape($v),LibFc::Escape($v));
				break;
				case 'username': // 店铺管理员名称
					//$where .= sprintf(" and (ub_username like '%%%s%%')", LibFc::Escape($v));
					//根据用户名搜索
					$LibYpApi = new LibYpApi();
					$post = [
						'filed'=>['u_id'],
						'where'=>sprintf(" and (u_name like '%s%%' or u_nickname like '%s%%' or (u_mobile='%s' and u_mobile_check = 'Y'))", LibFc::Escape($v), LibFc::Escape($v), LibFc::Escape($v)),
						'oneRow'=>false
					];
					$userArr = $LibYpApi->Get('user/getUser',[], $post);
					$userArr = array_column($userArr['data'], 'u_id');
					if(!empty($userArr))
						$where .= sprintf(" and shop_id in(%s)", implode(',', $userArr));
					else
						$where .= " and shop_id < 0";
				break;
			}
		}
		if(!empty($Params['shop_id'])){
		    $where .= sprintf(" and shop_id=%d",$Params['shop_id']);
        }
        $table = 'sh_shop left join us_user_base on shop_uid=ub_uid ';
		if(is_numeric($Params['mulu']) || is_numeric($Params['gongzhonghao']))
        {
            $B2cShop = new B2cShop();
            // 都是未开通
            if($Params['mulu'] == 0 && $Params['gongzhonghao'] == 0)
            {
                $superId = $B2cShop->get('sh_super',['ssu_shop_id'],sprintf(' and ssu_shop_id != %d',0));
                $shopAppId = $B2cShop->get('sh_shop_app',['aps_shop_id'],sprintf(' and aps_shop_id != %d',0));
                //合并数组
                $shopId = array_merge(array_column($superId['data'],'ssu_shop_id'),array_column($shopAppId['data'],'aps_shop_id'));
                $where = sprintf(' and shop_id not in (%s)',implode(',',array_keys(array_flip($shopId))));
            }

            //都是已开通
            if($Params['mulu'] == 1 && $Params['gongzhonghao'] == 1)
            {
                $superId = $B2cShop->get('sh_super',['ssu_shop_id'],sprintf(' and ssu_shop_id != %d',0));
                $shopAppId = $B2cShop->get('sh_shop_app',['aps_shop_id'],sprintf(' and aps_shop_id != %d',0));
                //取交集
                $shopId = array_intersect(array_column($superId['data'],'ssu_shop_id'),array_column($shopAppId['data'],'aps_shop_id'));
                $where = sprintf(' and shop_id in (%s)',implode(',',array_keys(array_flip($shopId))));
            }

            if($Params['mulu'] == 0 && $Params['gongzhonghao'] == 1)
            {
                $shopAppId = $B2cShop->get('sh_shop_app',['aps_shop_id'],sprintf(' and aps_shop_id != %d',0));
				$superId = $B2cShop->get('sh_super',['ssu_shop_id'],sprintf(' and ssu_shop_id in (%s)',implode(',',array_column($shopAppId['data'],'aps_shop_id'))));
				$shopId = array_diff(array_column($shopAppId['data'],'aps_shop_id'),array_column($superId['data'],'ssu_shop_id'));
                // $where = sprintf(' and shop_id in (%s)',implode(',',array_keys(array_flip(array_column($shopAppId['data'],'aps_shop_id')))));
				$where = sprintf(' and shop_id in (%s)',implode(',',array_keys(array_flip($shopId))));
            }

            if($Params['mulu'] == 1 && $Params['gongzhonghao'] == 0)
            {
                $superId = $B2cShop->get('sh_super',['ssu_shop_id'],sprintf(' and ssu_shop_id != %d',0));
				$shopAppId = $B2cShop->get('sh_shop_app',['aps_shop_id'],sprintf(' and aps_shop_id in (%s)',implode(',',array_column($superId['data'],'ssu_shop_id'))));
				$shopId = array_diff(array_column($superId['data'],'ssu_shop_id'),array_column($shopAppId['data'],'aps_shop_id'));
				$where = sprintf(' and shop_id in (%s)',implode(',',array_keys(array_flip($shopId))));
                // $where = sprintf(' and shop_id in (%s)',implode(',',array_keys(array_flip(array_column($superId['data'],'ssu_shop_id')))));
            }
        }
		$B2cBase = new B2cBase();
		//新增机器人查询条件
		if(is_numeric($Params['robot']))
		{	
			$wrres = $B2cBase->get('wx_robot',['wr_uid']);
			if($wrres['data'])
			{
				$wrUidArr = array_column($wrres['data'],'wr_uid');
				switch ($Params['robot']) 
				{
					case 1:
						$where .= sprintf(" and shop_uid in (%s)", implode(',', $wrUidArr));
						break;
					case 0:
						$where .= sprintf(" and shop_uid not in (%s)", implode(',', $wrUidArr));
						break;
				}
			}
		}
		// 分页
		$perPage=isset($_COOKIE['perPage']) ? $_COOKIE['perPage'] : 20;
		$page=isset($Params['page']) ? $Params['page'] : 1;

		// 条件下总数
		$res = $B2cBase->get($table,['count(*) sum'],$where);
		$count = current($res['data']);
		$Page = LibPage::Show($count['sum'], $perPage);
		LibTpl::Set('Page', $Page);
		$where .= sprintf(" order by shop_status desc,shop_id asc limit %d,%d",($page-1)*$perPage, $perPage);
		$res = $B2cBase->get($table, ['shop_id,shop_uid'], $where);
		$shopIds = array_column($res['data'], 'shop_id');
		$uids = array_column($res['data'],'shop_uid');
		if(!empty($shopIds))
		{
			// 店铺详情
			$temp = ['*'];
			$B2cShop = new B2cShop();
			$res = $B2cShop->getShopMsg($shopIds,$temp);

			LibTpl::Set('allShopMsg', $res['data']);

			// 商品数量
			$res = $B2cShop->getShopProNums($shopIds);
			LibTpl::Set('shopProNums',$res['data']);

			// 上架数量
			$res = $B2cShop->getShopProNums($shopIds,1);
			LibTpl::Set('shopProNumsSelling',$res['data']);

			//查看公众号店铺
			$res = $B2cShop->get('sh_shop_app',['aps_shop_id'],sprintf('and aps_shop_id in (%s)',implode(',', $shopIds)));
			LibTpl::Set('gzhArr', array_column($res['data'], 'aps_shop_id'));

			$res = $B2cShop->get('sh_super',['ssu_shop_id', 'ssu_id'],sprintf('and ssu_shop_id in (%s)',implode(',', $shopIds)));
			LibTpl::Set('superArr', array_column($res['data'], 'ssu_id', 'ssu_shop_id'));

			//有无合同
			$res = $B2cShop->get('sh_shop_file',['count(*) count','shf_shop_id'],sprintf('and shf_shop_id in (%s) and shf_iscon = 1 group by shf_shop_id',implode(',', $shopIds)));
			LibTpl::Set('heTongArr',array_column($res['data'], 'count', 'shf_shop_id'));
		}
		if(!empty($uids))
		{	
			$res = $B2cBase->get('wx_robot',['wr_uid'],sprintf(' and wr_uid in (%s)',implode(',', $uids)));
			LibTpl::Set('robotArr', array_column($res['data'], 'wr_uid'));
		}
		// 店铺状况枚举
		LibTpl::Set('shopStatusDes', ['-1'=>'禁用','-2'=>'开通中','1'=>'正常','0'=>'停用']);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('title','店铺列表-跑街的');
		LibTpl::Put();
	}



	/**
	 * @method 店铺详情
	 * @author xu
	 * @copyright 2017.12.19
	 */
	function detail()
	{
		LibRule::Check('SL03');
		$B2cBase = new B2cBase();

		// 编辑店铺信息
		if($_SERVER['REQUEST_METHOD'] == 'POST')
		{
			$B2cShop = new B2cShop();
			$data = $_POST['data'];
			// 店铺ID校验
			if(empty($data['shop_id']) || !LibFc::Int($shopId = $data['shop_id']))
    			LibTpl::Error('参数错误，请稍后重试！');
			// 信用代码校验
			if(!empty($data['shop_com_code']) && !LibFc::RegularValida($data['shop_com_code'],'societyCode'))
			    LibTpl::Error('信用代码格式错误！');
            // 店铺禁用说明
            if(($data['shop_status']==-1) && empty($data['shop_status_notice']))
                LibTpl::Error('请填写店铺禁用说明！');
			// 拼接入库
			$item = [
				'shop_status' =>	(in_array($data['shop_status'],['-1','0','1','-2'])) ? $data['shop_status']:'-1',//店铺状态
				'shop_status_notice' =>	$data['shop_status_notice'],//状态改变说明
				'shop_idcard' => $_POST['idcardOne'].','.$_POST['idcardTwo'],//法人身份证图片正反面
				'shop_main_idcard' => $_POST['mainCardOne'].','.$_POST['mainCardTwo'],//负责人身份证正反面
				'shop_license' => $_POST['license'],//营业执照
				'shop_logo'=> $_POST['logo'],//店铺logo
				'shop_pct_ids' => implode(',', array_filter([$data['province'],$data['city'],$data['region'],$data['street']],'LibFc::Int')),//省市区
				'shop_name' => $data['shop_name'],//店铺名称
				'shop_zbnum' => (int) $data['shop_zbnum'],
				'shop_smainnum' => (int) $data['shop_smainnum'],
				'shop_srefnum' => (int) $data['shop_srefnum'],
				'shop_sorder' => $data['shop_sorder'],
				'shop_profile' => $data['shop_profile'],//经营范围
				'shop_address' => $data['shop_address'],//店铺地址
				'shop_cor_name' => $data['shop_cor_name'],//法人姓名
				'shop_cor_tel' => $data['shop_cor_tel'],//法人电话
				'shop_main_name' => $data['shop_main_name'],//商城负责人姓名
				'shop_main_tel' => $data['shop_main_tel'],//商城负责人电话
				'shop_yw_tels' => $data['shop_yw_tels'],
				'shop_com_name' => $data['shop_com_name'],//企业名称
				'shop_com_code' => $data['shop_com_code'],//企业信用代码
				'shop_mod_search'=> $data['shop_mod_search'], // 车型关键字搜索类型 
				'shop_report_industry' => strtotime($data['shop_report_industry']),//行业报表
				'shop_corder'=> $data['shop_corder'],
			];

			$fujian = [];
			if (!empty($_POST['name']))
			{
				foreach ($_POST['name'] as $key => $value)
				{
					$id = (int) $key;
					if ($id > 0)
					{
						$fujian[$id]['shf_name'] = $value;
						$fujian[$id]['shf_iscon'] = $_POST['check'][$id] ? 1 : 0;
						$fujian[$id]['shf_seq'] = $_POST['sort'][$id] > 0 ? $_POST['sort'][$id] : 99;
					}
				}
			}
			if (!empty($fujian))
			{
				$B2cShop->saveShopFujian($fujian,$shopId);
			}
			// 有权限就接收参数
			if(LibRule::Check('SL07',false)) $item['shop_commission'] = $data['shop_commission'];
			if(LibRule::Check('SL08',false)) $item['shop_money_bail'] = $data['shop_money_bail'];
			// 入库
			$B2cBase->set('sh_shop',$item,sprintf(" and shop_id=%d ",$shopId));

			//配件展示配置
			$itemCofArr = [
				'shop_show_b2c' => (int) $data['shop_show_b2c'],
				'shop_show_app' => (int) $data['shop_show_app'],
				'shop_show_super' => (int) $data['shop_show_super'],
				'shop_show_pjl' => (int) $data['shop_show_pjl']
			];
			$B2cShop->changeShopItemToShow($shopId, $itemCofArr);

			//保存全车件品牌
			// $brandArr = array_filter(explode(',',$_POST['ssb_brand_id']));
			// $B2cShop->setShopBrand($shopId,$brandArr);

			//调用日志
			$B2cLog = new B2cLog();
			$item = [
				'log_shop_id'=>(int)$data['shop_id'],
				'log_category'=>'21',
				'log_txt'=>'修改店铺信息',
				'log_dataid'=>(int)$data['shop_id']
			];
			$B2cLog->addFastLog($item);
		}

		// 店铺基本信息
		$B2cShop = new B2cShop();
		$Params = mvc::$URL_PARAMS;
		$res = $B2cShop->getShopMsg($Params['id']);
		$shopMsg = current($res['data']);
		$shopMsg['shop_idcard'] = explode(',', $shopMsg['shop_idcard']);// 法人身份证
		$shopMsg['shop_main_idcard'] = explode(',', $shopMsg['shop_main_idcard']);// 商城负责人身份证
		$sqShop = $B2cShop->get("sh_dshop_link inner join sh_dshop on dsl_dshop_id=dshop_id",['dsl_btime','dsl_etime','dshop_id','dshop_name'],sprintf(" and dsl_from_shop_id=%d",$shopMsg['shop_id']));
		if(!empty($sqShop['data'])){
			foreach ($sqShop['data'] as &$item) {
				$item['status_name'] = date('Y-m-d',$item['dsl_btime']) .'-'.date('Y-m-d',$item['dsl_etime']);
				if($item['dsl_etime'] > time()){
					$item['status_name'] .= '(离过期还有'.sprintf("%d天)",floor(($item['dsl_etime']-time()) / 86400));
					$item['is_timeout'] = 0;
				}else{
					$item['status_name'] .= '(已过期'.sprintf("%d天)",floor((time()-$item['dsl_etime']) / 86400));
					$item['is_timeout'] = 1;
				}
			}
		}
		$sqShop = $sqShop['data'] ?: [];
		LibTpl::Set('sqShop',$sqShop);
		LibTpl::Set('data', $shopMsg);

		// 已购买服务信息
		$purchaseArr = [];
		// 商城目录
		$res = $B2cShop->get('sh_shop_app',['aps_shop_id','aps_btime','aps_etime'],sprintf('and aps_shop_id = (%s)',$Params['id']));
		if(!empty($res['data'])){
			$purchaseArr['gzh'] = $res['data'][0];
		}
		// 目录
		$res = $B2cShop->get('sh_super',['ssu_id','ssu_btime','ssu_etime'],sprintf('and ssu_shop_id = (%s)',$Params['id']));
		if(!empty($res['data'])){
			$purchaseArr['super'] = $res['data'][0];
		}
		// 机器人
		$res = $B2cBase->get('wx_robot',['wr_uid','wr_btime','wr_etime'],sprintf('and wr_uid = (%s) order by wr_etime desc limit 1',$Params['id']));
		if(!empty($res['data'])){
			$purchaseArr['robot'] = $res['data'][0];
		}
		// TOKEN
		if(LibRule::Check('AP01',false)){
			$B2cWxRobot = new B2cWxRobot();
			$res = $B2cWxRobot->get('wx_robot_token',['wrt_uid','wrt_endtime'],sprintf('and wrt_uid = (%s) order by wrt_endtime desc limit 1', $Params['id']));
			if(!empty($res['data'])){
				$purchaseArr['token'] = $res['data'][0];
			}
		}
		if(LibRule::Check('AP02',false)){
			// 接口管理
			$MainBase = new MainBase();
			$res = $MainBase->get('api_user',['au_uid','au_btime','au_etime'],sprintf('and au_uid = (%s) order by au_etime desc limit 1', $Params['id']));
			if(!empty($res['data'])){
				$purchaseArr['api'] = $res['data'][0];
			}
			// 资源包管理
			$res = $MainBase->get('api_zyb',['az_uid','az_btime','az_etime'],sprintf('and az_uid = (%s) order by az_etime desc limit 1', $Params['id']));
			if(!empty($res['data'])){
				$purchaseArr['zyb'] = $res['data'][0];
			}
		}
		// 商家入驻
		if(LibRule::Check('JS01',false)){
			$PjlBase= new PjlBase();
			$res = $PjlBase->get('pl_shop',['shop_pu_id','shop_enter_time','shop_vip_etime'],sprintf('and shop_pu_id = %d order by shop_vip_etime desc limit 1', $Params['id']));
			$purchaseArr['pjlShop'] = $res['data'][0];
		}
		// PC会员
		if(LibRule::Check('PC01',false)){
			$PjlBase= new PjlBase();
			$res = $PjlBase->get('pl_user_vip',['uvip_uid','uvip_btime','uvip_etime'],sprintf('and uvip_uid = %d and uvip_paymoney <> 0 order by uvip_etime desc limit 1', $Params['id']));
			$purchaseArr['pjlVip'] = $res['data'][0];
		}
		LibTpl::Set('purchaseArr', $purchaseArr);
		// 地址信息
		$YpwAddr = new YpwAddr();
		$shopMsg['shop_pct_ids'] = implode(',', array_filter(explode(',', $shopMsg['shop_pct_ids'])));
		$address = $YpwAddr->getAddrByIds($shopMsg['shop_pct_ids']);
		LibTpl::Set('address', implode('',$address['data']));

		//行业报表信息
		$res = $B2cBase->get('sh_shop',['shop_report_industry'],sprintf('and shop_id=%d',$Params['id']));
		LibTpl::Set('industryReport', $res['data'][0]);
		//店铺附件信息
		$res = $B2cShop->get('sh_shop_file',['*'],sprintf('and shf_shop_id=%d order by shf_seq asc,shf_id asc',$Params['id']));
		LibTpl::Set('fujianArr', $res['data']);
		$sorder = [
			'code'=>'自编号',
			'part_code'=>'零件+自编号',
			'part_proname'=>'零件+配件名称',
			'sort_code'=>'店铺分类+自编号',
			'sort_proname'=>'店铺分类+配件名称',
			'sort_part_code'=>'店铺分类+零件+自编号',
			'sort_part_proname'=>'店铺分类+零件+配件名称',
		];
		LibTpl::Set('sorder', $sorder);
		//车型关键字搜索类型
		$modsearchList = [
			'mod3'=>'车型明细', 
			'mod2'=>'车代'
		];
		LibTpl::Set('modsearchList', $modsearchList);
		// meta
		LibTpl::Set('title','店铺详情-跑街的');
		LibTpl::Put();
	}

	
	function loginSadmin()
	{
		$Param = mvc::$URL_PARAMS;
		LibRule::Check('SL10');
		$B2cBase = new B2cBase();
		$res = $B2cBase->get("sh_shop", ['shop_id'], sprintf(" and shop_id=%d", $Param['shop_id']),true);
		if(!empty($res['data']))
		{
			$YpwBase = new YpwBase();
			$res = $YpwBase->get('yp_user', ['u_name', 'u_password'], sprintf(" and u_id=%d", $res['data']['shop_id']), true);
			if(!empty($res['data']))
			{
				$LibEncry = new LibEncry();
				$userArr = $res['data'];
				$html = '<form method="post" action="'.mvc::$cfg['HOST']['sadmin'].'user/login" target="_blank" id="tempForm">
				<input type="hidden" name="name" value="'.$userArr['u_name'].'"/>
				<input type="hidden" name="encode" value="1"/>
				<input type="hidden" name="type" value="password"/>
				<input type="hidden" name="password" value="'.$LibEncry->encode($userArr['u_password']).'"/>
				<input type="hidden" name="search" value="n"/>
				</form>';
				LibFc::ReturnJson(true, $html);
			}
		}
		LibFc::ReturnJson(false, '账号不存在');
	}

	/**
	 * @method 禁用店铺
	 * @author xu
	 * @copyright 2017.12.19
	 */
	function stopShopUse()
	{
		LibRule::Check('SL03');
		$where .=sprintf(" and shop_id = %d",(int) $_POST['id']);
		$B2cBase = new B2cBase();

		$reason = LibFc::Escape($_POST['reason']);
		// print_r($reason);DIE;

		$DataArr = array('shop_status'=>-1,'shop_status_notice'=>$reason,'shop_status_ltime'=>time());

		$res = $B2cBase->set("sh_shop",$DataArr,$where);
		$array = array('status'=>true,'data'=>'success','code'=>0);
		LibFc::ajaxJsonEncode($array);
	}

	/**
	 * @method 取消禁用
	 * @author xu
	 * @copyright 2017.12.19
	 */
	function stopShopUseTwo()
	{
		LibRule::Check('SL03');
		$where .=sprintf(" and shop_id = %d",(int) $_POST['id']);
		$B2cBase = new B2cBase();

		$reason = LibFc::Escape($_POST['reason']);
		// print_r($reason);DIE;

		$DataArr = array('shop_status'=>1,'shop_status_notice'=>$reason,'shop_status_ltime'=>time());

		$res = $B2cBase->set("sh_shop",$DataArr,$where);
		$array = array('status'=>true,'data'=>'success','code'=>0);
		LibFc::ajaxJsonEncode($array);
	}


	/**
	 * @method 开通店铺
	 * @author xu
	 * @copyright 2017.12.23
	 */
	function openShop()
	{
		// 权限检测
		LibRule::Check('SL02');

		$B2cBase = new B2cBase();

		if(!empty($_GET['username']))
		{
			// 获取所有用户信息
			$username = LibFc::Escape($_GET['username']);
			$LibYpApi = new LibYpApi();
			$res = $LibYpApi->Get('user/searchUser', [], ['word'=>$username,'per'=>100,'page'=>1]);
			if(!empty($res['data']))
			{
				// 键值更新为uid
				$api = array_column($res['data'],NULL,'u_id');
				// 去除已开通店铺用户
				$res = $B2cBase->get('sh_shop',['shop_uid'],sprintf('and shop_uid in (%s)',implode(',', array_column($res['data'],'u_id'))));
				$shopUid = array_column($res['data'], 'shop_uid');
				$api = array_filter($api, function($v)use($shopUid){ if(!in_array($v['u_id'],$shopUid)) return true;else return false;} );
				// 去除子账户
				if(!empty($apiUid = array_column($api, 'u_id')))
				{
					$res = $B2cBase->get('sh_worker',['wor_uid'],sprintf(" and wor_uid in (%s) ",implode(',', $apiUid)));
					$shWorkerUid = array_column($res['data'], 'wor_uid');
					$api = array_filter($api, function($v)use($shWorkerUid){ if(!in_array($v['u_id'],$shWorkerUid)) return true;else return false;} );
				}
			}
			$res = array_merge(array_column($api, 'ui_province'),array_column($api, 'ui_city'));
			if(!empty($res))
			{
				// 获取所有的省市区
				$YpwBase = new YpwBase();
				$res = $YpwBase-> get('yp_province_city',['pc_id','pc_name'], sprintf(' and pc_id in (%s) ',implode(',', $res)));
				$province_city = array_column($res['data'],'pc_name','pc_id');
			}
			// 被搜索的字段
			$search = array('u_name','u_nickname','u_email','u_real_name');
			// 关键词描红
			foreach ($api as $k => $v) {
				foreach ($v as $kk => $vv) {
					if(in_array($kk, $search))
					{
						if(!empty($vv)) $api[$k][$kk] = LibFc::keywordRed($vv, $username);
							else
						$api[$k][$kk] = '无';
					}
					if(($kk == 'u_logo')&& empty($vv)) $api[$k][$kk] = mvc::$cfg['ADMIN_STATIC_URL'].'images/no_img.gif';
					if(($kk=='ui_province')||($kk=='ui_city'))
						$api[$k][$kk] = $province_city[$vv];
				}
			}

			// 性别枚举
			LibTpl::Set('uiSex', ['1'=>'男','2'=>'女','0'=>'未知']);
			// 传递数据
			LibTpl::Set('data', $api);
			LibTpl::Set('username', $username);
		}

		LibTpl::Set('title','开通店铺-跑街的');
		LibTpl::Put();
	}

	/**
	 * 开通填写店铺相关信息
	 * @author xu
	 * @copyright 2017.12.25
	 */
	function prepare()
	{
		LibRule::Check('SL03');
		// 参数
		if(empty($_GET['userid']) || !LibFc::Int($userId = $_GET['userid']))
			LibTpl::Error('用户ID错误！',mvc::$cfg['ADMIN_URI'].'shop/openShop');

		// 子账户校验
		$B2cBase = new B2cBase();
		$res = $B2cBase->get('sh_worker',['wor_uid'],sprintf(" and wor_uid=%d ",$userId),true);
		if(!empty($res['data'])) LibTpl::Error('不能为店铺子账户开通店铺！',mvc::$cfg['ADMIN_URI'].'shop/openShop');

		// 用户详情
		$LibYpApi = new LibYpApi();
		$res = $LibYpApi->Get('user/getUserByIds', [], ['uids'=>$userId]);
		$detail = array_map(function($v){if(empty($v)){return '未知';}else{return $v;}},current($res['data']));
		$detail['u_logo'] = $res['data']['u_logo'];
		LibTpl::Set('data', $detail);
		if(empty($detail)) LibTpl::Error('用户不存在！',mvc::$cfg['ADMIN_URI'].'shop/openShop');
		// 地址
		$pctIds = array_filter([$detail['ui_province'],$detail['ui_city']],function($v){if($v=='未知'){return false;}else{return true;}});
		$address = array();
		if(!empty($pctIds))
		{
			$YpwAddr = new YpwAddr();
			$address = $YpwAddr->getAddrByIds(implode(',', $pctIds));
			$address = $address['data'];
		}
		// 开通店铺
		if($_SERVER['REQUEST_METHOD'] == 'POST')
		{
			$B2cShop = new B2cShop();
			$B2cShop->createNewShop($_POST['data'],$userId);
			LibTpl::success('成功开通店铺',mvc::$cfg['ADMIN_URI'].'shop/openShop');
		}
		LibTpl::Set('userAddress', implode('',$address));
		LibTpl::Set('title','开通店铺-跑街的');
		LibTpl::Put();
	}


	/**
	 * 获取用户的所在区域
	 * @author xu
	 * @copyright 2017.12.25
	 */
	function initAddr()
	{
		$YpwBase = new YpwBase();
		$table='us_address';
		// 省份选择器
		$AllProvince = $YpwBase-> get('yp_province_city',['pc_id','pc_name'], sprintf(' and pc_pid = 0'));
		LibTpl::Set('AllProvince',$AllProvince['data']);
		// 市选择器
		if(isset($_POST['province']) && LibFc::Int($province = $_POST['province']))
		{
			LibTpl::Set('province',$province);
			$AllCity = $YpwBase-> get('yp_province_city',['pc_id','pc_name'], sprintf(' and pc_pid ='.$province));
			LibTpl::Set('AllCity',$AllCity['data']);
		}
		// 区选择器
		if(isset($_POST['city']) && LibFc::Int($city = $_POST['city']))
		{
			LibTpl::Set('city',$city);
			$AllRegion = $YpwBase-> get('yp_province_city',['pc_id','pc_name'], sprintf(' and pc_pid ='.$city));
			LibTpl::Set('AllRegion',$AllRegion['data']);
		}
		// 街道选择器
		if(isset($_POST['region']) && LibFc::Int($region = $_POST['region']))
		{
			LibTpl::Set('region',$region);
			$AllStreet = $YpwBase-> get('yp_province_city',['pc_id','pc_name'], sprintf(' and pc_pid ='.$region));
			LibTpl::Set('AllStreet',$AllStreet['data']);
		}
		if(isset($_POST['street']) && LibFc::Int($street = $_POST['street'])) LibTpl::Set('street',$street);
		$html = LibTpl::Fetch('shop/initAddr.php');
		LibFc::ajaxJsonEncode(['status'=>true,'data'=>$html]);
	}



	/**
	 * 选择地址
	 * @author xu
	 * @copyright 2017.12.25
	 */
	function selectAddr()
	{
		// 校验地址ID
		if(!LibFc::Int($_POST['id'])) LibFc::ajaxJsonEncode(['status'=>true,'data'=>""]);
		$YpwBase = new YpwBase();
		// 获取下一级地名列表
		$table='us_address';
		$res = $YpwBase-> get('yp_province_city',['pc_id','pc_name'], sprintf(' and pc_pid = '.$_POST['id']));
		$res = $res['data'];
		if(empty($res)) LibFc::ajaxJsonEncode(['status'=>true,'data'=>""]);
		LibTpl::Set('res',$res);
		// 传递类型用户更改下一级的name属性以及标志当前节点所属省市区层级
		$type = LibFc::Escape($_POST['type']);
		if($type=='city') $nextype = 'region';
		if($type=='region') $nextype = 'street';
		if($type=='street') $nextype = 'end';
		LibTpl::Set('nextype',$nextype);
		LibTpl::Set('type',$type);
		// 返回渲染好的html
		$html = LibTpl::Fetch('shop/selectAddr.php');
		LibFc::ajaxJsonEncode(['status'=>true,'data'=>$html]);
	}
	/**
	 * 店铺日志
	 * @author 廖
	 * @copyright 2018-1-18
	 */
	public function shopLog()
	{
		LibRule::Check('SL05');
		LibTpl::Put();
	}
	/**
	 * 店铺日志-左边筛选条件
	 * @author 廖
	 * @copyright 2018-1-18
	 */
	public function logLeft()
	{
		LibRule::Check('SL05');
		$B2cShop = new B2cShop();
		$shopData=$B2cShop->Get('sh_shop',array('shop_id','shop_name'));
		// print_r($shopData['data']);
		LibTpl::Set('shopArr',$shopData['data']);
		$logStatus = ['0'=>'普通','1'=>'配件','2'=>'配件价格','10'=>'订单','11'=>'订单价格','21'=>'店铺'];
		LibTpl::Set('logStatus',$logStatus);
		LibTpl::Put();
	}
	/**
	 * 店铺日志-右边日志列表
	 * @author 廖
	 * @copyright 2018-1-18
	 */
	public function logLists()
	{
		LibRule::Check('SL05');
		$Params = mvc::$URL_PARAMS;
		LibTpl::Set('Params',$Params);
		$NowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
		$PerPage = empty($_COOKIE['perPage'])? 40: (int) $_COOKIE['perPage'];
		$oderby = '';
		if(isset($Params['log']))
		{
			if($Params['log'] == '0')
			{
				$oderby .= ' order by shop_uid asc';
			}
			if($Params['log'] == '1')
			{
				$oderby .= ' order by shop_uid desc';
			}
		}
		if(isset($Params['logType']))
		{
			if($oderby == '') $oderby .= ' order by ';
			else $oderby .= ' ,';

			if($Params['logType'] == '0')
			{
				$oderby .= 'log_dataid asc';
			}
			if($Params['logType'] == '1')
			{
				$oderby .= 'log_dataid desc';
			}
		}
		if(isset($Params['logTime']))
		{
			if($oderby == '') $oderby .= ' order by ';
			else $oderby .= ' ,';

			if($Params['logTime'] == '0')
			{
				$oderby .= 'log_atime asc';
			}
			if($Params['logTime'] == '1')
			{
				$oderby .= 'log_atime desc';
			}
		}
		else if($Params['logSeq'] !='8' && $Params['logSeq'] !='9')
		{
			if($oderby == '') $oderby .= ' order by log_atime desc';
			else $oderby .= ' ,log_atime desc';
		}
		$status = isset($Params['logStatus']) && $Params['logStatus'] != 'all'?sprintf(" and log_category=%s",LibFc::Escape($Params['logStatus'])):'';
		$statusId = LibFc::Int($Params['statusId'])?sprintf(" and log_dataid=%d",$Params['statusId']):'';
		$shopId = LibFc::Int($Params['shopId'])?sprintf(" and log_shop_id=%d",$Params['shopId']):'';
		$shopName = isset($Params['shopName']) &&  $Params['shopName']!= '' ?" and shop_name like '%".LibFc::Escape($Params['shopName'])."%'":'';
		$userId = LibFc::Int($Params['userId'])?sprintf(" and log_uid=%d",$Params['userId']):'';
		$userName = isset($Params['userName']) &&  $Params['userName']!= '' ?" and log_uname like '%".LibFc::Escape($Params['userName'])."%'":'';
		$startTime = isset($Params['startTime']) &&  $Params['startTime']!= '' ?sprintf(" and log_atime >=%s",strtotime(LibFc::Escape($Params['startTime']))):'';
		$endTime = isset($Params['endTime']) &&  $Params['endTime']!= '' ?sprintf(" and log_atime <=%s",strtotime(LibFc::Escape($Params['endTime']))):'';
		$logStatus = ['0'=>'普通','1'=>'配件','2'=>'配件价格','10'=>'订单','11'=>'订单价格','21'=>'店铺'];
		LibTpl::Set('logStatus',$logStatus);
		if(isset($Params['logSeq']))
		{
			if($oderby == '') $oderby .= ' order by ';
			else $oderby .= ' ,';
			switch ($Params['logSeq'])
			{
				case '0':
					$oderby .= 'log_id desc';
					break;
				case '1':
					$oderby .= 'log_id asc';
					break;
				case '2':
					$oderby .= 'log_shop_id asc';
					break;
				case '3':
					$oderby .= 'log_shop_id desc';
					break;
				case '4':
					$oderby .= 'log_uid asc';
					break;
				case '5':
					$oderby .= 'log_uid desc';
					break;
				case '6':
					$oderby .= 'log_dataid asc';
					break;
				case '7':
					$oderby .= 'log_dataid desc';
					break;
				case '8':
					$oderby .= 'log_atime asc';
					break;
				case '9':
					$oderby .= 'log_atime desc';
					break;
			}

		}
		$selectId ='';
		if(!empty($_POST['logId']))
		{
			$selectIdArr = array_filter($_POST['logId'],'LibFc::Int');
			if(!empty($selectIdArr))
			{
				$selectId = sprintf('and log_id in (%s)',implode(',', $selectIdArr));
			}
		}
		$where = $selectId.$status.$statusId.$shopId.$shopName.$userId.$userName.$startTime.$endTime;
		$B2cBase = new B2cBase();
		$Total = $B2cBase->get('sh_log left join sh_shop on log_shop_id=shop_id',['count(*) count'],$where,true);
		$where .= $oderby;
		if($Total['data']['count']>0)
		{
        	$res = $B2cBase->get('sh_log a left join sh_shop b on log_shop_id=shop_id', ['*'], $where.sprintf(" limit %d,%d",($NowPage-1)*$PerPage, $PerPage));
			LibTpl::Set('logArr',$res['data']);
        	$userIdArr = array_filter(array_unique(array_column($res['data'],'log_uid')),'LibFc::Int');
        	if(!empty($userIdArr))
        	{
	        	$res = $B2cBase->get('us_user_base',['ub_uid','ub_username'],sprintf('and ub_uid in (%s)',implode(',', $userIdArr)));
	        	LibTpl::Set('nameArr',array_column($res['data'],'ub_username','ub_uid'));
        	}
		}
		$Page = LibPage::Show($Total['data']['count'], $PerPage);
		LibTpl::Set('Page',$Page);
		LibTpl::Put();
	}
	/**
	 * 店铺日志-session保存所选
	 * @author 廖
	 * @copyright 2018-1-18
	 */
	function ajaxLogCheck()
	{
		LibRule::Check('SL05');
    	$logChkIds = trim($_POST['chkIds'],',');
		$notCheck = trim($_POST['notChkIds'],',');
		if(isset($_SESSION['logChkIds']))
		{
			$_SESSION['logChkIds'] = array_filter(array_unique(array_merge(explode(',',$logChkIds),$_SESSION['logChkIds'])));
			foreach ($_SESSION['logChkIds'] as $k => $v)
			{
				if(in_array($v, explode(',', $notCheck)))
				{
					unset($_SESSION['logChkIds'][$k]);
				}
			}
		}else
		{
			if(!empty($logChkIds)) $_SESSION['logChkIds'] = explode(',', $logChkIds);
		}
		$logChkIds = trim(implode(',', $_SESSION['logChkIds']),',');
		$data = array('status'=>true,'data'=>array('check'=>$_SESSION['logChkIds']));
		LibFc::ajaxJsonEncode($data);
	}
	/*
	ajax更新选中日志的session
	*/
	function updateCheck()
	{
		LibRule::Check('SL05');
		if(!is_array($_POST['logId']))
		{
			$logDelCheId = trim($_POST['logId'],',');
			$logDelCheId = [$logDelCheId];
		}
		else
		{
			$logDelCheId = $_POST['logId'];
		}
		if(isset($_SESSION['logChkIds']))
		{
			foreach ($_SESSION['logChkIds'] as $k => $v)
			{
				if(in_array($v, $logDelCheId))
				{
					unset($_SESSION['logChkIds'][$k]);
				}
			}
		}
		LibFc::ajaxJsonEncode(array('status'=>true,'data'=>true));
	}
	public function ajaxDelLog()
	{
		LibRule::Check('SL06');
		$data = array('status'=>false,'data'=>'删除失败');
		if(!empty($_POST['logId']))
		{
			if(is_array($_POST['logId']) )
			{
				$delIdArr = array_filter($_POST['logId'],'LibFc::Int');
			}
			else
			{
				$delIdArr = array_filter(explode(',',$_POST['logId']));
			}
			if(!empty($delIdArr))
			{
				$B2cBase = new B2cBase();
				$res = $B2cBase->del('sh_log',sprintf('and log_id in (%s)',implode(',', $delIdArr)));
				if($res['status'])
				{
					$data = array('status'=>true,'data'=>$delIdArr);
				}
				else
				{
					$data = array('status'=>false,'data'=>'删除失败');
				}
			}
		}
		LibFc::ajaxJsonEncode($data);
	}



	/**
	  * @method 店铺提现账号管理
	  * @author soul 2018/3/3
	  */
	function account()
	{
		LibRule::Check('SL03');
		$Params = mvc::$URL_PARAMS;
		$shopArr = [];
		$B2cBase = new B2cBase();
		if(!empty($Params['shopId']))
		{
			$res = $B2cBase->get('sh_shop', ['shop_id', 'shop_name'], sprintf(" and shop_id=%d", (int) $Params['shopId']), true);
			$shopArr = $res['data'];
			LibTpl::Set('shopArr', $shopArr);
		}
		if(empty($shopArr)) exit('店铺不存在');

		if(!empty($_POST['shopId']) && $shopArr['shop_id'] == $_POST['shopId'])
		{
			$accbArr = isset($_POST['accb'])? $_POST['accb']: [];
			$B2cShop = new B2cShop();
			$B2cShop->setMoneyAccountBind($shopArr['shop_id'], $accbArr);
			LibTpl::Success('保存成功');
		}

		//店铺提现人信息
		$res = $B2cBase->get('sh_account_bind', ['*'], sprintf(" and acb_shop_id=%d", $shopArr['shop_id']));
		$accountBind = $res['data'];
		LibTpl::Set('accountBind', $accountBind);

		//店铺提现微信账号
		$res = $B2cBase->get('sh_account', ['*'], sprintf(" and acc_shop_id=%d", $shopArr['shop_id']));
		$accArr = [];
		foreach($res['data'] as $v)
		{
			$v['acc_weixin_info'] = json_decode(base64_decode($v['acc_weixin_info']), true);
			$accArr[$v['acc_acb_id']][] = $v;
		}
		// print_r($accArr);
		LibTpl::Set('accArr', $accArr);
		LibTpl::Set('title','店铺提现账号管理-跑街的后台');
		LibTpl::Put();
	}
	/**
	 * @method    提现列表
	 * @author 卢
	 * @copyright 2018-03-13
	 */
	function tiXianList()
	{
		LibRule::Check('SL09');
		$B2cBase = new B2cBase();
		$Params = mvc::$URL_PARAMS;
		LibTpl::Set('Params', $Params);
		$nowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
		$perPage=isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;
		$TimeArr = [
			'0'=>'--请选择状态--',
			'-1'=>'已关闭',
			'-2'=>'处理中',
			'1'=>'转账完成',
		];
		LibTpl::Set('TimeArr', $TimeArr);
		//取记录
		$shopData=$B2cBase->get('sh_shop',array('shop_id','shop_name'));
		foreach ($shopData['data'] as $v)
		{
			if($v['shop_id']==$Params['shopId'])
			{
				LibTpl::Set('shopName',$v['shop_name']);
				break;
			}
		}
		LibTpl::Set('shopArr',$shopData['data']);
		$shopData=array_column($shopData['data'], null,'shop_id');
		$where='';
		if(!empty($Params['shopId']))
		{
			$where.=sprintf(' and mow_shop_id=%d',(int)$Params['shopId']);
		}
		//状态筛选
		switch ($Params['status']) {
			case '-1':
				$where.=' and mow_status=-1';
				break;
			case '-2':
				$where.=' and mow_status=0';
				break;
			case '1':
				$where.=' and mow_status=1';
		}
		//日期筛选
		if(!empty($Params['time'])&&strpos($Params['time'], ' - '))
		{
			$timeArr=explode(' - ', $Params['time']);
			$startTime=strtotime(trim($timeArr[0]));
			$endTime=strtotime(trim($timeArr[1]));
			$where.=sprintf(' and mow_atime>=%d',$startTime);
			$where.=sprintf(' and mow_atime<=%d',$endTime);
		}
		$res=$B2cBase->get('sh_money_withdrawals',['count(1) total'],$where,true);
		$total=$res['data']['total'];
		$where .=sprintf(" order by mow_atime desc limit %d,%d",($nowPage-1)*$perPage, $perPage);
		$limit=sprintf(' and rn>=%d',$start);
		$res=$B2cBase->get('sh_money_withdrawals',['mow_id','mow_shop_id','mow_status','mow_by_uname','mow_total_money','mow_real_money','mow_comm_money','mow_atime','mow_ok_time','mow_shop_commission','mow_acc_data','mow_close_time','mow_remark'], $where);
		if(count($res['data']))
		{
			//取操作人和收款人信息
			foreach ($res['data'] as $k=> $v)
			{

				$accArr=json_decode($v['mow_acc_data'],true);
				$res['data'][$k]['accName']=$accArr['acb_name'];
				$res['data'][$k]['shopName']=$shopData[$v['mow_shop_id']]['shop_name'];
				$res['data'][$k]['accArr']=$accArr;
				if($accArr['acc_type']==0)
					$res['data'][$k]['weixin']=json_decode(base64_decode($accArr['acc_weixin_info']),true);
			}
		}
		// print_r($res['data']);
		LibTpl::Set('list',$res['data']);
		$Page = LibPage::Show($total, $perPage);
		LibTpl::Set('Page', $Page);
		LibTpl::Set('title','提现记录-跑街的后台');
		LibTpl::Put();
	}
	/**
	 * @method    提现详情
	 * @author 卢
	 * @copyright 2018-03-13
	 */
	function tiXianDes()
	{
		LibRule::Check('SL09');
		$B2cBase = new B2cBase();
		$B2cMoney=new B2cMoney();
		$Params = mvc::$URL_PARAMS;
		if(LibFc::Int($Params['mowId']))
		{
			$res=$B2cBase->get('sh_money_withdrawals',['mow_id','mow_status','mow_shop_id','mow_by_uname','mow_total_money','mow_real_money','mow_comm_money','mow_atime','mow_ok_time','mow_shop_commission','mow_acc_data'],sprintf(' and mow_id=%d',(int)$Params['mowId']),true);
			if(count($res['data']))
			{
				$shopArr=$B2cBase->get('sh_shop',['shop_name'],sprintf(' and shop_id=%d',$res['data']['mow_shop_id']),true);
				$res['data']['shopName']=$shopArr['data']['shop_name'];
				$res['data']['jsonArr']=json_decode($res['data']['mow_acc_data'],true);
				if($res['data']['jsonArr']['acc_type']==0)
					$res['data']['jsonArrWetChat']=json_decode(base64_decode($res['data']['jsonArr']['acc_weixin_info']),true);
				// print_r($res);
				LibTpl::Set('desArr',$res['data']);
			}
			else
			{
				LibFc::ajaxJsonEncode(['status'=>false,'data'=>'记录不存在！']);
			}
		}
		else
		{
			LibFc::ajaxJsonEncode(['status'=>false,'data'=>'记录不存在！']);
		}
		$data=LibTpl::Fetch();
		LibFc::ajaxJsonEncode(['status'=>true,'data'=>$data]);
	}
	/**
	 * @method    资金冻结记录
	 * @author 卢
	 * @copyright 2018-03-13
	 */
	function moneyUnav()
	{
		LibRule::Check('SL09');
		$B2cBase = new B2cBase();
		$B2cMoney=new B2cMoney();
		$Params = mvc::$URL_PARAMS;
		LibTpl::Set('Params', $Params);
		$nowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
		$perPage=isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 10;
		$TimeArr = [
			'0'=>'--请选择状态--',
			'-1'=>'已关闭',
			'-2'=>'处理中',
			'1'=>'转账完成',
		];
		LibTpl::Set('TimeArr', $TimeArr);
		//自动填充店铺
		$shopData=$B2cBase->get('sh_shop',array('shop_id','shop_name'));
		foreach ($shopData['data'] as $v)
		{
			if($v['shop_id']==$Params['shopId'])
			{
				LibTpl::Set('shopName',$v['shop_name']);
				break;
			}
		}
		LibTpl::Set('shopArr',$shopData['data']);
		$shopData=array_column($shopData['data'], null,'shop_id');
		$where='';
		if(!empty($Params['shopId']))
		{
			$where.=sprintf(' and mou_shop_id=%d',(int)$Params['shopId']);
		}
		//状态筛选
		switch ($Params['status']) {
			case '-1':
				$where.=' and mou_status=-1';
				break;
			case '-2':
				$where.=' and mou_status=0';
				break;
			case '1':
				$where.=' and mou_status=1';
		}
		//日期筛选
		if(!empty($Params['time'])&&strpos($Params['time'], ' - '))
		{
			$timeArr=explode(' - ', $Params['time']);
			$startTime=strtotime(trim($timeArr[0]));
			$endTime=strtotime(trim($timeArr[1]));
			$where.=sprintf(' and mou_atime>=%d',$startTime);
			$where.=sprintf(' and mou_atime<=%d',$endTime);
		}
		//计算总数
		$res=$B2cBase->get('sh_money_unav',['count(1) total'],$where,true);
		$total=$res['data']['total'];
		$where .=sprintf(" order by mou_atime desc limit %d,%d", ($nowPage-1)*$perPage, $perPage);
		$res=$B2cBase->get('sh_money_unav',['mou_id','mou_status','mou_shop_id','mou_title','mou_money','mou_atime','mou_ok_time','mou_close_time'],$where);
		foreach ($res['data'] as $k=> $v)
		{
			$res['data'][$k]['shopName']=$shopData[$v['mou_shop_id']]['shop_name'];
		}
		// print_r($res);
		LibTpl::Set('list',$res['data']);
		$Page = LibPage::Show($total, $perPage);
		LibTpl::Set('Page', $Page);
		LibTpl::Set('title','冻结记录详情-跑街的后台');
		LibTpl::Put();
	}
	/**
	 * @method    开店申请列表
	 * @author 卢
	 * @copyright 2018-04-10
	 */
	function openShopApply()
	{
		LibRule::Check('SL02');
		$B2cShop = new B2cShop();
		$Params = mvc::$URL_PARAMS;
		$nowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
		$perPage=isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 10;
		$where=' and shop_apply_tatus is not null';
		//计算总数
		$res=$B2cShop->get('sh_shop',['count(1) total'],$where,true);
		$total=$res['data']['total'];
		$where .=sprintf(" order by shop_apply_atime desc limit %d,%d", ($nowPage-1)*$perPage, $perPage);
		$res=$B2cShop->get('sh_shop',['shop_id','shop_uid','shop_status','shop_name','shop_logo','shop_pct_ids','shop_address','shop_license','shop_idcard','shop_com_code','shop_apply_tatus','shop_apply_atime','shop_apply_res','shop_apply_etime','shop_com_name','shop_main_idcard'],$where);
		if(!empty($res['data']))
		{
			$YpwAddr = new YpwAddr();
			foreach ($res['data'] as $k => $v)
			{
				// $res['data'][$k]['shop_apply_tatus']=(int)$v['shop_apply_tatus'];
				// var_dump($v['shop_apply_tatus']);
				$address = $YpwAddr->getAddrByIds($v['shop_pct_ids']);
				$res['data'][$k]['shop_address']=implode('',$address['data']).$v['shop_address'];
				$res['data'][$k]['imgCardArr']=explode(',', $v['shop_idcard']);
				$res['data'][$k]['imgMainCardArr']=explode(',',$v['shop_main_idcard']);
			}
		}
		// print_r($res['data']);
		$Page = LibPage::Show($total, $perPage);
		LibTpl::Set('Page', $Page);
		LibTpl::Set('data',$res['data']);
		LibTpl::Set('title','开店申请-跑街的后台');
		LibTpl::Put();
	}
	/**
	 * @method    开店审核
	 * @author 卢
	 * @copyright 2018-04-10
	 */
	function changeApply()
	{
		LibRule::Check('SL02');
		$res=['status'=>false,'data'=>'参数错误'];
		if(isset($_POST['status'])&&LibFc::Int($_POST['shop']))
		{
			$B2cShop=new B2cShop();
			$dataArr['shop_apply_etime']=time();
			switch ($_POST['status'])
			{
				case '2':
					$dataArr['shop_apply_tatus']=2;
					break;
				case '0':
					$dataArr['shop_apply_tatus']=0;
					break;
				case '1':
					$dataArr['shop_apply_tatus']=1;
					$dataArr['shop_apply_res']=$_POST['remark'];
					break;
				case '-1':
					$dataArr['shop_apply_tatus']=-1;
					$dataArr['shop_apply_res']=$_POST['remark'];
					break;
			}
			$res=$B2cShop->get('sh_shop',['shop_apply_tatus'],sprintf(' and shop_id=%d',$_POST['shop']),true);
			if($res['data']['shop_apply_tatus']==$_POST['status'])
				LibFc::ajaxJsonEncode(['status'=>true,'data'=>true]);

			$res=$B2cShop->setApplyStatus($dataArr,$_POST['shop'],$_POST['status']);
		}
		LibFc::ajaxJsonEncode($res);
	}
	/**
	 * @method    开店申请详情
	 * @author 卢
	 * @copyright 2018-04-10
	 */
	function applyShopDetail()
	{
		LibRule::Check('SL02');
		$Params = mvc::$URL_PARAMS;
		if(LibFc::Int($Params['shopId']))
		{
			$B2cBase=new B2cBase();
			$YpwAddr = new YpwAddr();
			$res=$B2cBase->get('sh_shop',['shop_id','shop_uid','shop_status','shop_name','shop_logo','shop_pct_ids','shop_address','shop_license','shop_idcard','shop_com_code','shop_apply_tatus','shop_apply_res','shop_com_name','shop_main_idcard','shop_main_tel','shop_cor_tel','shop_cor_name','shop_main_name','shop_apply_atime','shop_apply_etime'],sprintf(' and shop_id=%d',$Params['shopId']),true);
			if(!empty($res['data']))
			{
				$addrArr=$YpwAddr->getAddrByIds($res['data']['shop_pct_ids']);
				$res['data']['address']=!empty($addrArr['data'])?implode('',$addrArr['data']):'';
				$res['data']['shop_idcard']=explode(',',$res['data']['shop_idcard']);
				$res['data']['shop_main_idcard']=explode(',',$res['data']['shop_main_idcard']);
			}
			// print_r($res);
			LibTpl::Set('data',$res['data']);
			LibTpl::Set('title','开店申请详情-跑街的后台');
			LibTpl::Put();
			exit();
		}
		LibFc::Go(mvc::$cfg['ADMIN_URI'].'shop/openShopApply');
	}
	/**
	 * @method    售后设置申请
	 * @author 卢
	 * @copyright 2018-04-19
	 */
	function customApply()
	{
		LibRule::Check('SL02');
		$B2cBase=new B2cBase();
		$Params = mvc::$URL_PARAMS;
		$nowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
		$perPage=isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 10;
		$where=' and shop_service is not null';
		if(!empty($Params['shopName']))
		{
			$where.=sprintf(" and shop_name='%s'",LibFc::Escape($Params['shopName']));
		}
		if(isset($Params['status']))
		{
			if($Params['status']!=='all')
			{
				$where.=sprintf(' and shop_service_status=%d',(int)$Params['status']);
			}
		}
		$res=$B2cBase->get('sh_shop',['count(1) total'],$where,true);
		$total=$res['data']['total'];
		$where .=sprintf(" order by shop_id asc limit %d,%d",($nowPage-1)*$perPage, $perPage);
		$res=$B2cBase->get('sh_shop',['shop_id','shop_uid','shop_status','shop_name','shop_service','shop_money_bail','shop_service_status'],$where);
		if(!empty($res['data']))
		{
			foreach ($res['data'] as $k => $v)
			{
				$res['data'][$k]['val']=json_decode($v['shop_service'],true);
			}
		}
		LibTpl::Set('Params',$Params);
		$Page = LibPage::Show($total, $perPage);
		LibTpl::Set('Page', $Page);
		LibTpl::Set('data',$res['data']);
		LibTpl::Set('title','售后设置申请-跑街的后台');
		LibTpl::Put();
	}
	/**
	 * @method    修改退回申请审核状态
	 * @author 卢
	 * @copyright 2018-04-19
	 */
	function changeCustom()
	{
		LibRule::Check('SL02');
		$res=['status'=>false,'data'=>'参数错误'];
		if(!empty($_POST['sStatus']))
		{
			$shopId=current(array_keys($_POST['sStatus']));
			$status=$_POST['sStatus'][$shopId];
			$B2cBase=new B2cBase();
			$res=$B2cBase->set('sh_shop',['shop_service_status'=>(int)$status],sprintf(' and shop_id=%d',$shopId));
		}
		LibFc::ajaxJsonEncode($res);
	}

	/**
	 * @method    店铺公众号编辑
	 * @author     廖
	 * @copyright 2018-07-11
	 */
	public function gzhEdit()
	{
		LibRule::Check('SL03');
		$Params = mvc::$URL_PARAMS;
		if (LibFc::Int($Params['shopid']))
		{
			$B2cShop = new B2cShop();
			$res =  $B2cShop->get('sh_shop_app',['count(*) count'],sprintf('and aps_shop_id = %s',$Params['shopid']),true);
			LibTpl::Set('shopId',$Params['shopid']);
			if ($res['data']['count'] > 0)
			{
				$_POST['aps_model'] = base64_decode($_POST['aps_model']);
				//保存信息
				if($_SERVER['REQUEST_METHOD'] == "POST" && LibFc::Int($_POST['aps_shop_id']))
				{
					//接口处理
					$res = $B2cShop->saveGzhBaseInfo($_POST,$_POST['aps_shop_id']);
					if ($res['status'])
					{
						LibTpl::Set('msg','保存成功!');
						//文件中心删除图片
						if (!empty($_POST['aps_banner']['imgs']))
						{
							$delImg = [];
							$OthFileCenter = new OthFileCenter();
							foreach ($_POST['aps_banner']['imgs'] as $key => $value)
							{
								if ($value != $_POST['oldimgs'][$key] && $_POST['oldimgs'][$key] != '')
								{
									//这是要删除的图片
									$delLogoArr = ['cate'=>'adorn', 'files'=>$_POST['oldimgs'][$key]];
									$OthFileCenter->del($delLogoArr);
								}
							}
						}
					}
				}
			}
			else
            {
                if ($_SERVER['REQUEST_METHOD'] == "POST" && LibFc::Int($_POST['aps_shop_id']))
                {
                    //接口处理
                    $res = $B2cShop->saveGzhBaseInfo($_POST, $_POST['aps_shop_id'], 'add');
                    if ($res['status'])
                    {
                        LibTpl::Set('msg', '保存成功!');
                    }
                }
			}
            $res =  $B2cShop->get('sh_shop_app as ssp join sh_shop as ss on ss.shop_id=ssp.aps_shop_id',['ssp.*,ss.shop_uid'],sprintf('and ssp.aps_shop_id = %s',$Params['shopid']),true);
            $res['data']['aps_banner'] = json_decode($res['data']['aps_banner'],true);
            $res['data']['aps_contact'] = json_decode($res['data']['aps_contact'],true);
			$hasRobot = false;
			$robotRes =	$B2cShop->get('wx_robot',['wr_id,wr_btime,wr_etime'],sprintf(" and wr_uid=%d and wr_totype='gzh' and wr_type!='wxgr'",$res['data']['shop_uid']),true);
			if($robotRes['data'])
			{
				$hasRobot = true;
				if (!empty($_POST['aps_btime'])) $upData['wr_btime'] = strtotime(LibFc::Escape($_POST['aps_btime']));
				if (!empty($_POST['aps_etime'])) $upData['wr_etime'] = strtotime(LibFc::Escape($_POST['aps_etime']));
				if ( $upData['wr_btime'] && $robotRes['data']['wr_btime'] != $upData['wr_btime'] || $upData['wr_etime'] && $robotRes['data']['wr_etime'] != $upData['wr_etime'])
				{
					$B2cShop->set('wx_robot', $upData, sprintf(" and wr_id=%d", $robotRes['data']['wr_id']));
				}
			}
		
			// $PjlBase = new PjlBase();
			// $salesRes = $PjlBase->get('bu_user',['usr_name']," AND usr_status=1 AND usr_name!='' order by usr_seq,convert(usr_name using gbk)");
			//业务员
			$salesRes = $B2cShop->getYeWuList();
			LibTpl::Set('salesArr', $salesRes['data']);
			LibTpl::Set('wr_id', $robotRes['data']['wr_id']);
			LibTpl::Set('hasRobot', $hasRobot);
            LibTpl::Set('data', $res['data']);
		}
		LibTpl::Set('title','公众号设置-跑街的后台');
		LibTpl::Put();
	}

	/**
	 * @method    gzhBase 公众号信息
	 * @author     廖
	 * @copyright 2018-07-10
	 * @return   {'status':true,'data':xxx...}
	 */
	function ajxCheckGzhNameUnique()
	{
		if (!empty($_POST['name']) && LibFc::Int($_POST['id']))
		{
			$B2cBase = new B2cBase();
			$res = $B2cBase->get('sh_shop_app',['count(*) count'],sprintf(" and aps_shop_name = '%s' and aps_shop_id != %s",LibFc::Escape($_POST['name']),$_POST['id']),true);
			LibFc::ajaxJsonEncode($res);
		}
	}

	/**
	 * @method    根据关键字搜索分类
	 * @return    [json]            [{'status':true,'data':xxx}]
	 * @author     廖
	 * @copyright 2018-07-17
	 */
	public function ajaxGetPartByword()
	{
		LibRule::Check('SL03');
		$Params = mvc::$URL_PARAMS;
		$word = LibFc::Escape($Params['word']);
		$resArr = [];
		if($word != '')
		{
			$B2cBase = new B2cBase();
			$res = $B2cBase->get('bc_part', ['distinct part_id part_id'], sprintf(" and (part_keyword like '%%%s%%' or part_name like '%%%s%%' or part_initial like '%%%s%%')", $word, $word , strtoupper($word)));
			if(!empty($res['data']))
			{
				$whereArr = [];
				$temPartidArr = [];
				foreach($res['data'] as $v)
				{
					$temPartidArr[] = $v['part_id'];
					$whereArr[] = sprintf(" pt_path like '%%,%s,%%' or pt_path like '%%,%s'", $v['part_id'], $v['part_id']);
				}
				$whereArr[] = sprintf(" pt_part_id in (%s)", implode(',', $temPartidArr));
				$res = $B2cBase->get('bc_part_tree join bc_part on part_id=pt_part_id', ["concat(pt_path,',',pt_part_id) as path"], sprintf(" and (%s)  and part_is_end = 1 order by pt_seq", implode(' or ', $whereArr)));
				foreach($res['data'] as $v)
				{
					$resArr[] = $v['path'];
				}
			}
		}
		LibFc::ajaxJsonEncode(['status'=>true, 'data'=>array_unique($resArr)]);
	}


	/**
	 * @method   ajax获取ueditor图片空间弹窗
	 * @author 卢
	 * @copyright 2017-08-23
	 */
	public function getUeditorPic()
	{
		LibRule::Check('SL03');
		$Params = mvc::$URL_PARAMS;
		$shopId = $Params['shopId'];
		if (LibFc::Int($shopId))
		{
			$data=LibTpl::Fetch('/shop/getUeditorPic.php');
			LibFc::ajaxJsonEncode(['status'=>true,'data'=>$data]);
		} else
		{
			LibFc::ajaxJsonEncode(['status'=>false,'data'=>'参数不正确!']);
		}
	}

	/**
	 * @method    修改上传的图片的父目录
	 * @author 卢
	 * @copyright 2017-09-08
	 */
	public function updateUploadPic()
	{
		//必须开通店铺
		LibRule::Check('SL03');
		$Params = mvc::$URL_PARAMS;
		$B2cBase = new B2cBase();
		$spiId=(int)$Params['spi_id'];
		$spiPicaId=(int)$Params['spi_pica_id'];
		if($spiId)
		{
			$target=['spi_pica_id'=>$spiPicaId];
			$res=$B2cBase->set('sh_pic',$target,sprintf('and spi_id=%d',$spiId));
			LibFc::ajaxJsonEncode($res);
		}
	}
	public function delFuJian()
	{
		LibRule::Check('SL03');
		$Params = mvc::$URL_PARAMS;
		$fjid = (int) $Params['fjid'];
		$shopid = (int) $Params['shopid'];
		if ($fjid > 0 && $shopid > 0)
		{
			$B2cBase = new B2cBase();
			$res = $B2cBase->get('sh_shop_file',['count(*) count'],sprintf('and shf_id=%d and shf_shop_id=%d',$fjid,$shopid),true);
			if ($res['data']['count'] < 1)
				LibFc::ajaxJsonEncode(['status'=>false,'data'=>'附件信息错误!']);
			$res = $B2cBase->del('sh_shop_file',sprintf('and shf_id=%d and shf_shop_id=%d',$fjid,$shopid),true);
			LibFc::ajaxJsonEncode($res);
		}
		LibFc::ajaxJsonEncode(['status'=>false,'data'=>'参数不正确!']);
	}
	/**
	 * @method    审核提现
	 * @author 卢
	 * @copyright 2018-11-02
	 */
	function checkTiXian()
	{
		$Params = mvc::$URL_PARAMS;
		$B2cBase = new B2cBase();
		$mowId=$Params['mowid'];
		if(LibFc::Int($mowId))
		{
			$res=$B2cBase->get('sh_money_withdrawals',['mow_id','mow_status','mow_shop_id','mow_by_uname','mow_total_money','mow_real_money','mow_comm_money','mow_atime','mow_ok_time','mow_shop_commission','mow_acc_data','mow_remark'],sprintf(' and mow_id=%d',$mowId),true);
			if(count($res['data']))
			{
				$shopArr=$B2cBase->get('sh_shop',['shop_name'],sprintf(' and shop_id=%d',$res['data']['mow_shop_id']),true);
				$res['data']['shopName']=$shopArr['data']['shop_name'];
				$res['data']['jsonArr']=json_decode($res['data']['mow_acc_data'],true);
				if($res['data']['jsonArr']['acc_type']==0)
					$res['data']['jsonArrWetChat']=json_decode(base64_decode($res['data']['jsonArr']['acc_weixin_info']),true);
				LibTpl::Set('desArr',$res['data']);
				LibTpl::Set('title','审核提现记录-跑街的后台');
				LibTpl::Put();
			}
			else
			{
				LibTpl::Error('记录不存在！');
			}
			exit();
		}
		elseif(!empty($_POST))
		{
			if(empty($_POST['mow_id']))
			{
				LibTpl::Error('提现记录不存在');
			}
			if(!empty($_POST['mow_status']))
			{
				if(empty($_POST['mow_ramark']))
				{
					LibTpl::Error('备注不能为空');
				}
				$B2cMoney=new B2cMoney();
				$dataArr=[
					'mow_ok_time'=>(!empty($_POST['mow_ok_time'])?strtotime($_POST['mow_ok_time']):time()),
					'mow_remark'=>LibFc::Escape($_POST['mow_ramark']),
				];
				$res=$B2cMoney->setShopMoneyWithdrawals($_POST['mow_id'], $_POST['mow_status'], $dataArr);
			}
			LibFc::Go(mvc::$cfg['ADMIN_URI'].'shop/checkTiXian?mowid='.$_POST['mow_id']);
		}else{
			LibTpl::Error('记录不存在！');
		}
	}

	//品牌目录列表
    public function superList()
    {
		LibRule::Check('SU01');
        $Params = mvc::$URL_PARAMS;
        $nowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
        $perPage = isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;
        $where  ='';
		foreach($Params as $k=>$v)
		{
			$v = trim($v);
			if($v == '') continue;
			switch($k)
			{
				case 'keyword':
					$where .= sprintf(" and ssu_name like '%%%s%%'", LibFc::Escape($v));
					break;
				case 'ssu_style':
					if($v != -1) $where .= sprintf(" and ssu_style ='%s'", LibFc::Escape($v));
				break;
                case 'ssu_status':
                    switch ($v){
                        case 1:
                            $where .= sprintf(" and ssu_status = 0 ");
                            break;
                        case 2:
                            $where .= sprintf(" and ssu_etime < %d and ssu_status = 1",time());
                            break;
                        case 3:
                            $where .= sprintf(" and ssu_etime > %d and ssu_status = 1",time());
                            break;
                    }
                    break;
                case 'ssu_zhiming_btime':
                    if($v == 1){
                        $where .= sprintf(" and ssu_zhiming_btime > 0");
                    }elseif ($v == 2){
                        $where .= sprintf(" and ssu_zhiming_btime <= 0");
                    }
                    break;
				case 'ssu_prostyle':
					if($v == 1){
						$where .= sprintf(" and ssu_prostyle = '全车件'");
					}elseif($v == 0){
						$where .= sprintf(" and ssu_prostyle = ''");
					}
					break;
				case 'ssu_super_gzh':
					if($v !=-1) $where .= sprintf(" and ssu_super_gzh =%d", (int)$v);
					break;
				case 'ssu_pjl_show':
					if($v != -1) $where .= sprintf(" and ssu_pjl_show =%d", (int)$v);
					break;
			}
		}
		$B2cBase = new B2cBase();
		$res = $B2cBase->get('sh_super', ["count(*) as count"], $where, true);
		$count = $res["data"]['count'];
        $Page = LibPage::Show($count, $perPage);
		if($count > 0)
		{
			$where .= sprintf(" order by ssu_status desc, (ssu_etime>%d) desc,ssu_etime asc limit %d,%d",time(), ($nowPage-1)*$perPage, $perPage);
			$res = $B2cBase->get('sh_super left join sh_shop on ssu_shop_id=shop_id left join us_user_base on shop_uid=ub_uid', ['sh_super.*','ub_username','shop_com_name'], $where);
			$list = $res['data'];
			if(!empty($list))
			{
				$shopIdArr = array_column($list, 'ssu_shop_id');
				if(!empty($shopIdArr))
				{
					$res = $B2cBase->get('bc_product', ["pro_shop_id, count(*) as pro_count"], sprintf(" and pro_show_super =1 and pro_status >=0 and pro_shop_id in (%s) group by pro_shop_id", implode(',', $shopIdArr)));
					$tjArr = array_column($res['data'], 'pro_count', 'pro_shop_id');
				}

				$facIdArr = array_column($list, 'ssu_fac_id');
				/*if(!empty($facIdArr))
				{
					$TcdcnItem = new TcdcnItem();
					$res = $TcdcnItem->get('data_product', ["pro_bra_id, count(*) as pro_count"], sprintf(" and pro_bra_id in (%s) group by pro_bra_id", implode(',', $facIdArr)));
					$ftjArr = array_column($res['data'], 'pro_count', 'pro_bra_id');
				}*/
				foreach($list as $k=>$v)
				{
					if(!empty($v['ssu_logo'])) $v['ssu_logo'] = mvc::$cfg['FILE_CENTER']['b2c']['url_get'].'&c=shopLogo&f='.$v['ssu_logo'].mvc::$cfg['FILE_CENTER']['b2c']['get_uri'];
					if($v['ssu_shop_id'] > 0)
					{
						$v['pro_count'] = $tjArr[$v['ssu_shop_id']];
						$filepath = 'ewm/super_'.$v['ssu_shop_id'].'.png';
						$ewmFile = mvc::$cfg['ROOT'].'home/'.$filepath;
						if(!file_exists($ewmFile))
						{
							$url = mvc::$cfg['HOST']['super'].$v['ssu_shop_id'].'/index.php';
							$OthQrcode = new OthQrcode();
							$OthQrcode->png($url, $ewmFile, 1, 6, 2, $v['ssu_logo']);
						}
						$v['ewm'] = mvc::$cfg['HOST']['b2c'].$filepath;
					}
					else
					{
						$v['pro_count'] = $ftjArr[$v['ssu_fac_id']];
					}
					$list[$k] = $v;
				}
			}
        }
		$pjlShowArr = [1=>'开通',0=>'未开通'];
		$superGzhArr = ['未开通','基础版目录','定制版目录','机器人目录'];
		LibTpl::Set('pjlShowArr',$pjlShowArr);
		LibTpl::Set('superGzhArr',$superGzhArr);
        LibTpl::Set('list', $list);
        LibTpl::Set('title', '品牌目录');
        LibTpl::Set("Params", $Params);
        LibTpl::Set('Page', $Page);
        LibTpl::Put();
    }


	//配置品牌目录
	function superSet()
	{
		LibRule::Check('SU02');
		$Params = mvc::$URL_PARAMS;
		$B2cBase = new B2cBase();
		if(!empty($_POST['sup']) && !empty($_POST['sup']['ssu_name']))
		{
			$dataArr = $_POST['sup'];
			$dataArr['ssu_btime'] = strtotime($dataArr['ssu_btime']);
			$dataArr['ssu_etime'] = strtotime($dataArr['ssu_etime']);
			$dataArr['ssu_zhiming_btime'] = empty($dataArr['ssu_zhiming_btime'])? 0: strtotime($dataArr['ssu_zhiming_btime']);
			$dataArr['ssu_zhiming_etime'] = empty($dataArr['ssu_zhiming_etime'])? 0: strtotime($dataArr['ssu_zhiming_etime']);
			$dataArr['ssu_model'] = base64_decode($dataArr['ssu_model']);
			$dataArr['ssu_conf'] = !empty($_POST['conf'])? json_encode($_POST['conf']): '{}';
			$dataArr['ssu_module'] = !empty($dataArr['ssu_module']) ? implode(',',$dataArr['ssu_module']):'';
			$dataArr['ssu_banner'] = !empty($dataArr['ssu_banner']) ? implode(',',array_filter($dataArr['ssu_banner'])):'';
			$B2cShop = new B2cShop();
			$_POST['part'] =$_POST['part']? explode(',',$_POST['part']):[];
			// 2023/06/09 未开通知名品牌，过期的强制为-1
			if(!$dataArr['ssu_zhiming'] && $dataArr['ssu_zhiming_etime'] && $dataArr['ssu_zhiming_etime']<time())
			{
				$dataArr['ssu_tuijian_seq'] = -1;
			}
			$res = $B2cShop->setShopSuper($_POST['ssu_id'], $dataArr, empty($_POST['part'])? []: $_POST['part']);
			// 更新机器人时间
			if(!empty($res['data']))
			{	
				$robotRes = $B2cBase->get('wx_robot join sh_shop on shop_uid = wr_uid',['wr_id,wr_btime,wr_etime'],sprintf(" and shop_id=%d and wr_totype='super' and wr_type!='wxgr'",(int)$dataArr['ssu_shop_id']),true);
		
				if($robotRes['data'])
				{
					if($robotRes['data']['wr_btime']!=$dataArr['ssu_btime']||$robotRes['data']['wr_etime']!=$dataArr['ssu_etime'])
					{
						$upData = [
							'wr_btime'=>(int)$dataArr['ssu_btime'],
							'wr_etime'=>(int)$dataArr['ssu_etime']
						];
						$B2cBase->set('wx_robot',$upData,sprintf(" and wr_id=%d",(int)$robotRes['data']['wr_id']));
					}
				}
			}
			LibFc::Go(mvc::$cfg['ADMIN_URI'].'shop/superSet?ssu_id='.$res['data']);
		}
		$superArr = [];
		$hasRobot = false;
		if(!empty($Params['ssu_id']))
		{
			$res = $B2cBase->get('sh_super', ['*'], sprintf(" and ssu_id=%d", $Params['ssu_id']), true);
			$superArr = $res['data'];
			if(!empty($superArr))
			{
				$superArr['betime'] = empty($superArr['ssu_btime'])? date('Y-m-d H:i:s').' ~ '. date('Y-m-d H:i:s', strtotime('+1year')): date('Y-m-d H:i:s', $superArr['ssu_btime']).' ~ '. date('Y-m-d  H:i:s', $superArr['ssu_etime']);
			}
		}
		else if(!empty($Params['shop_id']))
		{
			$superArr['ssu_shop_id'] = $Params['shop_id'];
		}

		if(!empty($superArr['ssu_shop_id']))
		{
			$res = $B2cBase->get('sh_shop', ['*'], sprintf(" and shop_id=%d", $superArr['ssu_shop_id']), true);
			LibTpl::Set('shopArr', $res['data']);
			$robotRes = $B2cBase->get('wx_robot',['wr_id'],sprintf(" and wr_uid=%d and wr_totype='super'",$res['data']['shop_uid']),true);
			if($robotRes['data'])
			{
				$hasRobot = true;
				LibTpl::Set('wr_id', $robotRes['data']['wr_id']);
			}

			//开通的类别
			$res = $B2cBase->get('sh_super_part', ['*'], sprintf(" and sup_shop_id=%d", $superArr['ssu_shop_id']));
			$superArr['parts'] = array_column($res['data'], 'sup_part_id');
		}
		$superArr['ssu_style'] = empty($superArr['ssu_style'])? 'B2C': $superArr['ssu_style'];
		$superArr['ssu_conf'] = !empty($superArr['ssu_conf']) ? json_decode($superArr['ssu_conf'], true): [];
		$superArr['ssu_banner'] = !empty($superArr['ssu_banner']) ? explode(',',$superArr['ssu_banner']):[];
        $superArr['ssu_banner'] = array_pad((Array) $superArr['ssu_banner'],5,'');
		//TODO 可以直接联表
        $superPartArr = [];
        if($superArr['parts']){
            $res = $B2cBase->get('bc_part JOIN bc_part_tree ON pt_part_id = part_id and pt_ismain=1 left join bc_part_small on pas_part_id=part_id', ['group_concat(pas_name) as pas_name','pt_path','part_name as name','part_id as value'], sprintf(' and part_id in (%s) group by part_id ORDER BY pt_seq,part_initial',implode(',',$superArr['parts'])));
            if(!empty($res['data'])){
                $pt_paths = array_column($res['data'],'pt_path');
                $pt_path = [];
                foreach ($pt_paths as $v){
                    $temp = explode(',',$v);
                    foreach ($temp as $id){
                        if($id > 0 && !in_array($id,$pt_path)){
                            array_push($pt_path,$id);
                        }
                    }
                }
                $pt = $B2cBase->get('bc_part',['part_name','part_id'],sprintf(" and part_id in (%s)",implode(',',$pt_path)));
                if(!empty($pt['data'])){
                    $pt = array_column($pt['data'],'part_name','part_id');
                }else{
                    $pt = [];
                }
            }
            foreach ($res['data'] as &$value)
            {
                if(!empty($value['pas_name'])){
                    $value['name'] = $value['name'].'('.$value['pas_name'].')';
                }
                if(!empty($value['pt_path']) && !empty($pt)){
                    $a = explode(',',$value['pt_path']);
                    foreach ($a as $id)
                    {
                        if($id > 0){
                            if(isset($pt[$id])){
                                $value['name'] = $pt[$id].'》'.$value['name'];
                            }
                        }
                    }
                }
                unset($value['pt_path']);
                unset($value['pas_name']);
            }

            $superPartArr = $res['data'];

        }
		if(empty($superArr['ssu_btime'])) $superArr['ssu_btime'] = time();
		if(empty($superArr['ssu_etime'])) $superArr['ssu_etime'] = strtotime('+1year');
		$superArr['moduleArr'] = $superArr['ssu_module']?explode(',',$superArr['ssu_module']):[];
		$moduleArr = [
			'user'=>'会员系统',
			'price'=>'价格系统'
		];
		//业务员
		// $PjlBase = new PjlBase();
		// $salesRes = $PjlBase->get('bu_user',['usr_name']," AND usr_status=1 AND usr_name!='' order by usr_seq,convert(usr_name using gbk)");
		$salesRes = $B2cBase->getYeWuList();
		LibTpl::Set('salesArr', $salesRes['data']);
		$superGzhArr = ['未开通','基础版公众号','定制版公众号','机器人目录'];
		LibTpl::Set('superGzhArr', $superGzhArr);
		LibTpl::Set('hasRobot', $hasRobot);
		LibTpl::Set('moduleArr',$moduleArr);
		LibTpl::Set('superPartArr', $superPartArr);
		LibTpl::Set('superArr', $superArr);
		LibTpl::Set('title', '配置品牌目录');
		LibTpl::Put();
	}

	/**
	 * @method    目录组合
	 * @author hongzhang
	 * @copyright 2025-07-15
	 */
	function superPack()
	{
		LibRule::Check('SU01'); //权限需确认
        $Params = mvc::$URL_PARAMS;
        $nowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
        $perPage = isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;
        $where  ='';
		foreach($Params as $k=>$v)
		{
			$v = trim($v);
			if($v == '') continue;
			switch($k)
			{
				// 组合名称模糊查询
				case 'keyword':
					$where .= sprintf(" and ssp_name like '%%%s%%'", LibFc::Escape($v));
					break;
			}
		}
		$B2cBase = new B2cBase();
		$res = $B2cBase->get('sh_super_pack', ["count(*) as count"], $where,true);
		$count = $res['data']['count'];
        $Page = LibPage::Show($count, $perPage);
		
		if($count > 0)
		{	
			$where .= sprintf("order by ssp_seq asc, ssp_name asc limit %d,%d",($nowPage-1)*$perPage,$perPage);
			$res = $B2cBase->get('sh_super_pack', ["*"], $where);
			$list = $res['data'];
			if(!empty($list))
			{
				$sspIds = array_column($list, 'ssp_id');
				// 查询每个组合包含的目录详细信息，包含ID信息、名称、排序、过期时间
				$table = 'sh_super_pack_link 
					left join sh_super on sspl_ssu_id = ssu_id';
				$res = $B2cBase->get($table, 
					['sspl_ssp_id','ssu_id','ssu_name','sspl_seq','ssu_etime'], 
					sprintf(" and sspl_ssp_id in (%s) order by sspl_seq asc, CONVERT(ssu_name USING gbk) COLLATE gbk_chinese_ci asc", implode(',', $sspIds))
				);
				
				// 按组合ID分组处理目录数据
				$superDataArr = [];
				foreach($res['data'] as $row) {
					$sspId = $row['sspl_ssp_id'];
					if(!isset($superDataArr[$sspId])) {
						$superDataArr[$sspId] = [];
					}
					// 保存完整的目录信息，便于后续操作扩展
					$superDataArr[$sspId][] = [
						'ssu_id' => $row['ssu_id'],
						'ssu_name' => $row['ssu_name'],
						'ssu_seq' => $row['ssu_seq'],
						'ssu_etime' => $row['ssu_etime'],
					];
				}
					
				// 将目录名称和详细数据添加到列表数据中
				foreach($list as $k => $v)
				{
					$list[$k]['super_data'] = isset($superDataArr[$v['ssp_id']]) ? $superDataArr[$v['ssp_id']] : [];
				}
			}
        }
		
        LibTpl::Set('list', $list);
        LibTpl::Set('title', '目录组合');
        LibTpl::Set("Params", $Params);
        LibTpl::Set('Page', $Page);
        LibTpl::Put();
    }

	/**
	 * @method    添加or编辑目录组合
	 * @author hongzhang
	 * @copyright 2025-07-15
	 */
	public function superPackSet()
	{
		LibRule::Check('SU02'); //权限需确认
		$Params = mvc::$URL_PARAMS;
		$B2cBase = new B2cBase();

		//以下为superPackSet页面提交数据的处理
		if(!empty($_POST['supPack']) && !empty($_POST['supPack']['ssp_name'])){
			//数据处理
			$dataArr = $_POST['supPack'];
			$dataArr['ifEditChildrenList'] = (int) $_POST['ifEditChildrenList'];
			$dataArr['ssp_begin_time'] = strtotime($dataArr['ssp_begin_time']);
			$dataArr['ssp_end_time'] = strtotime($dataArr['ssp_end_time']);
			$B2cShop = new B2cShop();
			$res = $B2cShop->setShopSuperPack($_POST['ssp_id'], $dataArr);
			// Ajax请求，返回JSON响应
			if ($res['status']) {
				LibFc::ajaxJsonEncode(['status' => true, 'msg' => '操作成功','ssp_id' => $res['data']]);
			} else {
				LibFc::ajaxJsonEncode(['status' => false, 'msg' => $res['msg'] ?? '操作失败']);
			}
			exit;
		}

		$isEdit = isset($Params['ssp_id']) && !empty($Params['ssp_id']);//是否是编辑
		$superRow = [];
		$superList = [];
		$title = '添加目录组合';//标题默认添加

		//请求所有的目录数据，用于下拉框(启用状态，未过期)
		$superListWhere = ' and ssu_status=1 and ssu_pjl_show=1 and ssu_etime > '.time();
		$superListWhere .= ' order by CONVERT(ssu_name USING gbk) COLLATE gbk_chinese_ci asc';
		$res = $B2cBase->get('sh_super', ['ssu_id', 'ssu_name','ssu_etime','ssu_seq'], $superListWhere);
		$superList = $res['data'];

		if($isEdit)
		{
			$title = '编辑目录组合';
			$B2cShop = new B2cShop();
			$res = $B2cShop->ShopSuperPackDetail($Params['ssp_id']);
			$superRow =  $res['data'];
		}
		//查询包含的目录
		LibTpl::Set('superList', $superList);
		LibTpl::Set('superRow', $superRow);
		LibTpl::Set('title', $title);
		LibTpl::Set("Params", $Params);
		LibTpl::Put();
	}

	/**
	 * @method    删除目录组合
	 * @author hongzhang
	 * @copyright 2025-07-15
	 */
	public function superPackDel()
	{
		LibRule::Check('SU02');
		$Params = mvc::$URL_PARAMS;
		$B2cBase = new B2cBase();
		$res = $B2cBase->del('sh_super_pack', sprintf("and ssp_id =%d", $Params['ssp_id']));
		$B2cBase->del('sh_super_pack_link', sprintf("and sspl_ssp_id =%d", $Params['ssp_id']));
		LibFc::ajaxJsonEncode($res);
	}

	public function getPartList()
    {
        $param = mvc::$URL_PARAMS;
        $B2cBase = new B2cBase();
        $where = ' and part_is_end = 1';
        if(isset($param['keyword']) && !empty($param['keyword'])) {
            $where .= sprintf(" and (part_name like '%%%s%%' 
			or part_keyword like '%%%s%%' 
			or part_id in (SELECT pas_part_id FROM bc_part_small WHERE pas_name LIKE '%%%s%%'))",LibFc::Escape($param['keyword']),LibFc::Escape($param['keyword']),LibFc::Escape($param['keyword']));
            $where .= ' group by part_id';
			//其他的排后面
            $where .= sprintf(' ORDER BY CASE WHEN pt_parent_part_id = 4161 THEN 1 ELSE 0 END, pt_seq,pt_parent_part_id,part_name');
            $res = $B2cBase->get('bc_part left join bc_part_tree on pt_part_id = part_id and pt_ismain=1 left join bc_part_small on pas_part_id=part_id', ['group_concat(pas_name) as pas_name','pt_path','part_name as name','part_id as value'], $where);
            if(!empty($res['data'])){
                $pt_paths = array_column($res['data'],'pt_path');
                $pt_path = [];
                foreach ($pt_paths as $v){
                    $temp = explode(',',$v);
                    foreach ($temp as $id){
                        if($id > 0 && !in_array($id,$pt_path)){
                            array_push($pt_path,$id);
                        }
                    }
                }
                $pt = $B2cBase->get('bc_part',['part_name','part_id'],sprintf(" and part_id in (%s)",implode(',',$pt_path)));
                if(!empty($pt['data'])){
                    $pt = array_column($pt['data'],'part_name','part_id');
                }else{
                    $pt = [];
                }
            }
            foreach ($res['data'] as &$value){
                if(!empty($value['pas_name'])){
                    $value['name'] = $value['name'].'('.$value['pas_name'].')';
                }
                if(!empty($value['pt_path']) && !empty($pt)){
                    $a = explode(',',$value['pt_path']);
                    foreach ($a as $id)
                    {
                        if($id > 0){
                            if(isset($pt[$id])){
                                $value['name'] = $pt[$id].'》'.$value['name'];
                            }
                        }
                    }
                }
                unset($value['pt_path']);
                unset($value['pas_name']);
            }
        }else{
            $res = [];
            $res['status'] = true;
            $res['data'] = [];
        }
        $res['code'] = 0;
        LibFc::ajaxJsonEncode($res);
    }

	 //删除品牌目录
    public function superDel()
    {
		LibRule::Check('SU02');
        $Params = mvc::$URL_PARAMS;
		$B2cBase = new B2cBase();
        $PjlBase = new PjlBase();
		$res = $B2cBase->del('sh_super', sprintf("and ssu_id =%d", $Params['ssu_id']));
        //$PjlBase->del('pl_user_super', sprintf("and usb_ssu_id =%d", $Params['ssu_id']));
        LibFc::ajaxJsonEncode($res);
    }

	 //店铺下的所有产品设置为目录产品
	function resetSuperData()
	{
		LibRule::Check('SU02');
		$Params = mvc::$URL_PARAMS;
		$B2cBase = new B2cBase();
		$res = $B2cBase->set('bc_product', ['pro_show_super'=>1], sprintf(" and pro_shop_id=%d", $Params['shop_id']));
        LibFc::ajaxJsonEncode($res);
	}


	//同步商城的数据到跑街令产品表
	function resetB2cProToPjlPro()
	{
		$Params = mvc::$URL_PARAMS;
		$B2cBase = new B2cBase();
		$table = 'bc_product
			join bc_product_info on pri_pro_id = pro_id
			left join bc_probrand on pro_prb_id = prb_id
			join bc_number on pro_id = num_pro_id  and num_self =1';
		$res = $B2cBase->get($table, ['pro_id, pro_shop_id, num_display, num_format, pro_name,  pro_sale_price, prb_name'], sprintf(" and pro_shop_id=%d order by num_format", $Params['shop_id']));
		$PjlBase = new PjlBase();
		foreach($res['data'] as $v)
		{
			$PjlBase->del('pl_product', sprintf(" and pro_shop_id=%d and pro_id_b2c=%d", $Params['shop_id'], $v['pro_id']));
			$addArr = [
				'pro_shop_id'=>$v['pro_shop_id'],
				'pro_status'=>1,
				'pro_display'=>$v['num_display'],
				'pro_format'=>$v['num_format'],
				'pro_name'=>$v['pro_name'],
				'pro_ischeck'=>1,
				'pro_price'=>$v['pro_sale_price'],
				'pro_quality'=>'品牌',
				'pro_quality_des'=>$v['prb_name'],
				'pro_id_b2c'=>$v['pro_id']
			];
			$PjlBase->add('pl_product', $addArr);
		}
		echo 'ok';
	}

    /**
     *  公众号列表页
     */
	public function shopAppList()
    {
        LibRule::Check('SL03');
        $Params = mvc::$URL_PARAMS;
        $nowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
        $perPage = isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;
        $where  ='';
        foreach($Params as $k=>$v)
        {
            $v = trim($v);
            if($v == '') continue;
            switch($k)
            {
                case 'keyword':
                    $where .= sprintf(" and aps_shop_name like '%%%s%%'", LibFc::Escape($v));
                    break;
                case 'status':
                    //筛选过期
                    if($v == 2)
                    {
                        $where .= sprintf(" and aps_etime < %d ", time());
                    }
                    elseif($v == 1)
                    {
                        $where .= sprintf(" and aps_status = %d and aps_etime > %d ", $v,time());
                    }elseif(is_numeric($v)){
                        $where .= sprintf(" and aps_status = %d ", $v);
                    }
                    break;
            }
        }
        $B2cBase = new B2cBase();

		$res = $B2cBase->get('sh_shop_app', ["count(*) as count"], $where, true);
        $Page = LibPage::Show($res["data"]["count"], $perPage);
        $list = [];

        if($res['data']['count'] > 0){
            $where .= sprintf(" order by aps_status desc, aps_etime asc limit %d,%d", ($nowPage-1)*$perPage, $perPage);
            $res = $B2cBase->get('sh_shop_app inner join sh_shop on aps_shop_id=shop_id left join us_user_base on shop_uid=ub_uid', ["sh_shop_app.*",'shop_com_name','ub_username'], $where);
            $list = $res['data'];
        }

        LibTpl::Set('list', $list);
        LibTpl::Set('title', '公众号列表');
        LibTpl::Set("Params", $Params);
        LibTpl::Set('Page', $Page);
        LibTpl::Put();
    }

	//产品从某个店铺同步到另外一个店铺
	public function copyShopPro()
	{
		exit;
		$toShopId = 696927;
		$B2cProduct = new B2cProduct();
		$B2cProduct->copyShopPro($toShopId);
		echo 'ok';
	}

	/**
	  * @method 重新初始化底盘件、发动机件模式车型的末级车型
	  * @param  $shopId  int [选填] 店铺ID 如果不填，刷整个产品库
	  * @author soul
	  * @copyright 2021/7/13
	  * @return 
	  */
	public function initModelByOthModType()
	{
		$B2cProduct = new B2cProduct();
		$B2cProduct->initModelByOthModType();
		echo 'ok';
	}

	
	//从tcd复制产品
	public function copyItemFromTcd()
	{
		exit('请人工启用');
		$toShopId = 732634;
		$supId = 6;
		$TcdBase = new BaseDb(mvc::$cfg['DB']['TCD']);
		$LibYpApi = new LibYpApi();
		$B2cProduct = new B2cProduct();
		
		$res = $B2cProduct->get('bc_product', ['pro_dfrom_id'], sprintf(" and pro_shop_id = %d and pro_dfrom='tcd'", $toShopId));
		$hasArtIdArr = array_column($res['data'], 'pro_dfrom_id');

		$table = 'tof_articles
		join tof_suppliers on sup_id = art_sup_id
		join tof_generic_articles on art_ga_id = ga_id';
		$ares = $TcdBase->get($table, ['ART_ID, SUP_BRAND, ART_ARTICLE_NR,GA_DES_CN'], sprintf(" and art_sup_id = %d", $supId));
		$artArr = [];
		$uniNumArr = [];
		$addItemArr = [];
		foreach($ares['data'] as $v)
		{
			if(in_array($v['ART_ID'], $hasArtIdArr)) continue;
			$dres = $LibYpApi->get('number/itemDes', ['type'=>'tcd', 'proId'=>$v['ART_ID']]);
			$v = array_merge($v, $dres['data']);
			
			$newPro = [
				'part_name'=>$v['GA_DES_CN'],
				'shop_sort'=>$v['GA_DES_CN'],
				'pro_name'=>$v['pro_name'],
				'prb_name'=>$v['SUP_BRAND'],
				'pri_code'=>$v['ART_ARTICLE_NR'],
				'pro_param'=>'',
				'number'=>'',
				'pro_dfrom'=>'tcd',
				'pro_dfrom_id'=>$v['ART_ID'],
			];
			
			foreach($v['para'] as $pv)
			{
				$newPro['pro_param'] .= sprintf("%s:%s %s;", $pv['name'], $pv['val'], $pv['unit']);
			}
			
			$dres = $LibYpApi->get('number/itemNumber', ['type'=>'tcd', 'proId'=>$v['ART_ID'], 'numtype'=>'all']);
			foreach($dres['data'] as $pv)
			{
				$newPro['number'] .= sprintf("%s:%s;", $pv['oe']? 'OE': $pv['factory'], $pv['display']);
			}

			$cres = $B2cProduct->checkImportB2cItem($toShopId, [$newPro]);
			$ires = $B2cProduct->importB2cItem($toShopId, $cres['data']['items']);
			$proId = $ires['data'][0];

			//车型
			/*$mres = $LibYpApi->get('tcd/getArtYpcModelIds', ['proId'=>$v['ART_ID']]);
			if(!empty($mres['data']))
				$B2cProduct->setProductModel($proId, $mres['data'], 'tcd');*/
			$artArr[$v['ART_ID']] = $v;
		}
		echo 'ok';
	}

	//根据条件删除产品
	public function delAnyProduct()
	{
		exit('请人工启用');
		$toShopId = 732634;
		$proIdArr = [];

		$B2cProduct = new B2cProduct();
		$res = $B2cProduct->get('bc_product', ['pro_id'], sprintf(" and pro_shop_id = %d and pro_dfrom='tcd'", $toShopId));
		$proIdArr = array_column($res['data'], 'pro_id');
		$B2cProduct->delProduct($toShopId, $proIdArr);
		echo 'ok';
	}

	//目录统计
	function superTjIndex()
	{
		LibRule::Check('SU01');
		LibTpl::Set('title','目录统计');
		LibTpl::Put();
	}


	//目录统计
	function superTj()
	{
		LibRule::Check('SU01');
		$Params = mvc::$URL_PARAMS;
		$fastTime = [
			'本月'=>date('Y-m-01').' ~ '.date('Y-m-d'),	
			'上个月'=>date('Y-m-01', strtotime('-1 month', strtotime(date('Y-m')))).' ~ '.date('Y-m-d', strtotime(date('Y-m-01'))-1),
			'本年'=>date('Y-01-01').' ~ '.date('Y-m-d')
		];
		LibTpl::Set('fastTime', $fastTime);

		$OthBase= new OthBase();
		$table = 'tj_super_date join ypb2c.sh_super on ssu_shop_id=sub_shop_id and ssu_style="B2C"';
		$where ='';
		$Params['betime'] = empty($Params['betime'])? $fastTime['本月']: $Params['betime'];
		foreach($Params as $k=>$v)
        {
            $v = trim($v);
            if($v == '') continue;
            switch($k)
            {
				case 'betime':
					$t = explode(' ~ ', $v);
					$where .= sprintf(" and sub_date >= %d and sub_date < %d", date("Ymd", strtotime($t[0])), date("Ymd", strtotime($t[1])+86400));
				break;
            }
        }
		$where .= " GROUP BY sub_shop_id ORDER BY SUM(sub_pv) DESC";
		$res = $OthBase->get($table, ["ssu_name, sub_shop_id, sum(sub_client) sub_client, sum(sub_pv) sub_pv, sum(sub_ip) sub_ip, sum(sub_itemlist) sub_itemlist, sum(sub_item) sub_item"], $where);
		$tjArr = $res['data'];
		$B2cBase = new B2cBase();
		$res = $B2cBase->get('bc_product join sh_super on ssu_shop_id = pro_shop_id', ["ssu_shop_id, count(*) count"], ' group by ssu_shop_id');
		LibTpl::Set('shopArr', array_column($res['data'], null, 'ssu_shop_id'));
		LibTpl::Set('tjArr',$tjArr);
		LibTpl::Set('Params',$Params);
		LibTpl::Set('title','目录统计');
		LibTpl::Put();
	}


	//目录统计明细
	function superTjDes()
	{
		LibRule::Check('SU01');
		$Params = mvc::$URL_PARAMS;
		$perPage=isset($_COOKIE['perPage']) ? $_COOKIE['perPage'] : 20;
		$page=isset($Params['page']) ? $Params['page'] : 1;
		$where = sprintf(" and sub_shop_id=%d", $Params['shop_id']);
		$OthBase = new OthBase();
		$res = $OthBase->get('tj_super_date', ['count(*) as count'], $where, true);
		$total = $res['data']['count']; 
		$where .= sprintf(" order by sub_date desc limit %d,%d",($page-1)*$perPage, $perPage);
		$res = $OthBase->get('tj_super_date', ['*'], $where);
		$tjArr = $res['data'];

		$Page = LibPage::Show($total, $perPage);
		LibTpl::Set('Page', $Page);
		LibTpl::Set('tjArr', $tjArr);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('title', '目录统计明细');
		LibTpl::Put();
	}

	/**
	 * @method 机器人管理
	 * @author zhengweihua 
	 * @copyright 2022-05-30
	 */
	public function robot()
	{
		LibRule::Check('SL01');
		$Params = mvc::$URL_PARAMS;
		$perPage = isset($_COOKIE['perPage']) ? $_COOKIE['perPage'] : 20;
		$page = isset($Params['page']) ? $Params['page'] : 1;
		$where = '';
		$robotArr = [];
		$PjlBase = new PjlBase();
		foreach($Params as $k=>$v)
		{
			$v = trim($v);
			if ($v == '') continue;
			switch ($k) 
			{
				case 'wr_type':
					$where .= sprintf(" and wr_type ='%s'", LibFc::Escape($v));
					break;
				case 'wr_totype':
					$where .= sprintf(" and wr_totype ='%s'", LibFc::Escape($v));
					break;
				case 'wr_status':
					$v = (int)$v;
					if($v==1){
						$where .= sprintf(" and wr_status = %d and wr_etime>%d",$v,time());	
					}elseif ($v==-1) {
						$where .= sprintf(" and (wr_status = %d or wr_etime<%d)",$v,time());	
					}
					
					break;
				case 'keyword':
					$swhere ='';
					$res = $PjlBase->get('pl_shop',['shop_id'],sprintf(" AND shop_name like '%%%s%%'",$v));
					if($res['data']) $swhere  = sprintf(" or wr_uid in (%s)",implode(',',array_column($res['data'],'shop_id')));
					$where .= sprintf(" and (wr_remark like '%%%s%%' or wr_wxname like '%%%s%%' or wr_name like '%%%s%%' %s) ",LibFc::Escape($v),LibFc::Escape($v),LibFc::Escape($v),$swhere);
					break;
				case 'wr_uid':
					$where .= sprintf(" and wr_uid = %d ",(int)$v);
					break;
				case 'wx_number':
					$where .= sprintf(" and wr_id in (select wrw_wr_id from wx_robot_wx where 1=1 and wrw_wx='%s')",LibFc::Escape($v));
					break;
				case 'wrg_status':
					//群状态
					$sql = "select distinct wrr_wr_id from wx_robot_room";
					if($v==1){
						$where .= sprintf(" AND wr_type='wxgr' AND wr_id in (%s)",$sql);
					}elseif ($v=-1) {
						$where .= sprintf(" AND wr_type='wxgr' AND wr_id not in (%s)",$sql);
					}
					break;
				case 'wx_bind':
					//微信绑定
					$sql = "select distinct wrw_wr_id from wx_robot_wx";
					if($v==1){
						$where .= sprintf(" AND wr_type='wxgr' AND wr_id in (%s)",$sql);
					}elseif ($v=-1) {
						$where .= sprintf(" AND wr_type='wxgr' AND wr_id not in (%s)",$sql);
					}
					break;
				case 'wrt_loginurl':
					if($v==1){
						$where .=" AND wrt_loginurl !=''";
					}elseif ($v==-1) {
						$where .=" AND wrt_loginurl =''";
					}
					break;
				case 'wrt_token_type':
					$where .= sprintf(" AND wrt_token_type ='%s'",$v);
					break;
				case 'wr_wrt_id':
					$where .= sprintf(" AND wr_wrt_id =%d",$v);
					break;
			}
		}
		$B2cBase = new B2cBase();
		$table = 'wx_robot 
		left join wx_robot_token on wrt_id = wr_wrt_id
		left join sh_shop on shop_uid = wr_uid 
		left join us_user_base on ub_uid = wr_uid';
		$res = $B2cBase->get($table, ['count(*) as count'], $where, true);
		$total = $res['data']['count'];
		if($total>0){
			$where .= sprintf(" order by wr_id desc limit %d,%d",($page-1)*$perPage, $perPage);
			$res = $B2cBase->get($table, ['wx_robot.*,wrt_id,wrt_uid,wrt_token_type,wrt_wxnickname,wrt_server,wrt_type,wrt_endtime,wrt_loginstatus,wrt_wxinfo,shop_com_name,ub_username'], $where);
			$robotArr = $res['data'];
			foreach ($robotArr as $key => $val) 
			{
				if($val['wr_type']=='wxgr') $wrIdArr[] = $val['wr_id'];
				if($val['wr_totype']=='pjlshop'){
					$pjlshopId[] = $val['wr_uid'];
				}
				$robotArr[$key]['wrt_wxinfo'] = json_decode($val['wrt_wxinfo'],true);
			}
			if($wrIdArr){
				$roomres = $B2cBase->get('wx_robot_room',['count(wrr_id) as counts,wrr_wr_id'],sprintf(" AND wrr_wr_id in (%s) group by wrr_wr_id",implode(',',$wrIdArr)));
				LibTpl::Set('roomCounts',$roomres['data']?array_column($roomres['data'],'counts','wrr_wr_id'):[]);
			}
			if($pjlshopId){
				
				$res = $PjlBase->get('pl_shop',['shop_id,shop_name'],sprintf(" AND shop_id in (%s)",implode(',',$pjlshopId)));
				LibTpl::Set('pjlShopName',array_column($res['data'],'shop_name','shop_id'));
			}

		} 
		$B2cWxRobot = new B2cWxRobot();
		$wrtList = $B2cWxRobot->getAllTokenList();
		LibTpl::Set('wrtList',$wrtList['data']);

		$salesRes = $B2cBase->getYeWuList();
		LibTpl::Set('salesArr', array_column($salesRes['data'],null,'au_uid'));
		
		$typeArr = ['wxgzh'=>'微信公众号','wxgr'=>'微信群聊','wxkf'=>'企微客服'];
		$toTypeArr = ['super'=>'公众号目录','gzh'=>'商城版目录','pjlshop'=>'入驻商家','yiparts'=>'宜配','vin'=>'车架号','crm'=>'CRM','customize'=>'定制'];
		$Page = LibPage::Show($total, $perPage);
		LibTpl::Set('Page', $Page);
		LibTpl::Set('typeArr', $typeArr);
		LibTpl::Set('toTypeArr', $toTypeArr);
		LibTpl::Set('robotArr', $robotArr);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('title', '机器人');
		LibTpl::Put();
	}
	/**
	 * @method 配置机器人
	 * @author zhengweihua 
	 * @copyright 2022-05-30
	*/
	public function robotSet()
	{
		LibRule::Check('SL01');
		$Params = mvc::$URL_PARAMS;
		$B2cBase = new B2cBase();
		$B2cWxRobot = new B2cWxRobot();
		if($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['rob']))
		{
			$dataArr = $_POST['rob'];
			if(!empty($dataArr['wr_autotxt']) && is_array($dataArr['wr_autotxt']))
			{	
				$dataArr['wr_autotxt'] = array_map(function($item){
					$partern = array('/<p>(([\s\S])*?)<\/p>/','/<div>(([\s\S])*?)<\/div>/','/(([\s\S])*?)<br>/');
					$str =  strip_tags(preg_replace($partern,"$1\r\n",$item),'<a>');
					return preg_replace('/<a .*?href="(.*?)".*?>/is',"<a href='$1'>",rtrim($str));
				},$dataArr['wr_autotxt']);
			}
			$dataArr['wr_autotxt'] = $dataArr['wr_autotxt']? json_encode($dataArr['wr_autotxt'],JSON_UNESCAPED_UNICODE): '{}';
			if(empty($dataArr['user_name']))
			{
				return LibFc::ReturnJson(false, '请输入用户名');
			}
			else 
			{
				$username = LibFc::Escape($dataArr['user_name']);
				$LibYpApi = new LibYpApi();
				$getData = ['account' => $username];
				$resArr = $LibYpApi->Get('user/getUserByAccount', $getData);
				if (empty($resArr['data'])) LibFc::ReturnJson(false, '用户不存在');
				$dataArr['wr_uid'] = $resArr['data'][0]['u_id'];
			}
			
			//类型为公众号和公众号目录时间保持一致
			if($dataArr['wr_type']=='wxgzh' && in_array($dataArr['wr_totype'],['super','gzh','pjlshop']))
			{	
				$wr_btime= strtotime($dataArr['wr_btime']);
				$wr_etime= strtotime($dataArr['wr_etime']);
				$where = sprintf(" and shop_uid = %d",(int)$dataArr['wr_uid']);
				if($dataArr['wr_totype'] == 'super')
				{
					$table = "sh_super join sh_shop on shop_id = ssu_shop_id";
					$fieldArr = ['ssu_btime as wr_btime','ssu_etime as wr_etime'];
					$shopResult = $B2cBase->get($table,$fieldArr,$where,true);
					$dataArr['wr_btime'] = $shopResult['data']['wr_btime'];
					$dataArr['wr_etime'] = $shopResult['data']['wr_etime'];
				}	
				if($dataArr['wr_totype'] == 'gzh')
				{
					$table = "sh_shop_app join sh_shop on shop_id = aps_shop_id";
					$fieldArr = ['aps_btime as wr_btime','aps_etime as wr_etime'];
					$shopResult = $B2cBase->get($table,$fieldArr,$where,true);
					$dataArr['wr_btime'] = $shopResult['data']['wr_btime'];
					$dataArr['wr_etime'] = $shopResult['data']['wr_etime'];
				}	
				if($dataArr['wr_totype'] == 'pjlshop')
				{
					$where = sprintf(" and shop_id = %d", (int)$dataArr['wr_uid']);
					$PjlBase= new PjlBase();
					$fieldArr = ['shop_enter_time as wr_btime, shop_vip_etime as wr_etime'];
					$shopResult = $PjlBase->get('pl_shop', $fieldArr, $where, true);	
					$dataArr['wr_btime'] = $shopResult['data']['wr_btime'];
					$dataArr['wr_etime'] = $shopResult['data']['wr_etime'];
				}

				if(!$dataArr['wr_btime']||!$dataArr['wr_etime']){
					$dataArr['wr_btime'] = $wr_btime;
					$dataArr['wr_etime'] = $wr_etime;
				}
			}
			else
			{
				$dataArr['wr_btime'] = strtotime($dataArr['wr_btime']);
				$dataArr['wr_etime'] = strtotime($dataArr['wr_etime']);
			}
			$dataArr['wr_selfmod'] = $dataArr['wr_selfmod']??[];
			//根据wr_selfmod判断是否需要同步更新对应的wx_robot_room表
			$existRoompart = in_array('roompart',$dataArr['wr_selfmod']);
			$existRoompbrand = in_array('roompbrand',$dataArr['wr_selfmod']);
			$existRoomsort = in_array('roomsort',$dataArr['wr_selfmod']);

			$editTable = 'wx_robot_room';
			$editWhere = sprintf(" and wrr_wr_id = %d", $_POST['wr_id']);
			$clearArr =[];
			if(!$existRoompart) $clearArr['wrr_part_ids'] = '';
			if(!$existRoompbrand) $clearArr['wrr_prb_ids'] = '';
			if(!$existRoomsort) $clearArr['wrr_sort_ids'] = '';
			if(!empty($clearArr)){
				$B2cBase->set($editTable,$clearArr,$editWhere);
			}
			$res = $B2cWxRobot->setWxRobot($_POST['wr_id'], $dataArr);
			
			return LibFc::ajaxJsonEncode($res);
		}
		$robotArr = [
			'wr_vin_fileds'=>['mod3_engine','mod3_kw','mod3_cc','mod3_transmission','mod3_drive','mod3_year'],
			'wr_othcof'=>['numzb','nummain','url_vin','itempara_one'],
			'wr_selfmod'=>[]
		];
		$robotArr['wr_uid'] =!empty($Params['wr_uid'])? $Params['wr_uid']:0;
		$validTimeArr = [];
		if($robotArr['wr_uid'])
		{
			$where = sprintf(" and shop_uid = %d", (int)$robotArr['wr_uid']);
			//目录的有效时间
			$table = "sh_super join sh_shop on shop_id = ssu_shop_id";
			$fieldArr = ['ssu_btime as wr_btime,ssu_etime as wr_etime'];
			$shopResult = $B2cBase->get($table, $fieldArr, $where, true);	
			if($shopResult['data']){
				$validTimeArr['super'] = ['wr_btime'=> date('Y-m-d H:i:s',$shopResult['data']['wr_btime']) ,'wr_etime'=>date('Y-m-d H:i:s',$shopResult['data']['wr_etime'])];
			}  
			//公众号的有效时间
			$table = "sh_shop_app join sh_shop on shop_id = aps_shop_id";
			$fieldArr = ['aps_btime as wr_btime, aps_etime as wr_etime'];
			$shopResult = $B2cBase->get($table, $fieldArr, $where, true);	
			if($shopResult['data']){
				$validTimeArr['gzh'] = ['wr_btime'=> date('Y-m-d H:i:s',$shopResult['data']['wr_btime']) ,'wr_etime'=>date('Y-m-d H:i:s',$shopResult['data']['wr_etime'])];
			}
			//入驻商家的有效时间 
			$where = sprintf(" and shop_id = %d", (int)$robotArr['wr_uid']);
			$PjlBase= new PjlBase();
			$fieldArr = ['shop_enter_time as wr_btime, shop_vip_etime as wr_etime'];
			$shopResult = $PjlBase->get('pl_shop', $fieldArr, $where, true);	
			if($shopResult['data'])
			{
				$validTimeArr['pjlshop'] = ['wr_btime'=> date('Y-m-d H:i:s',$shopResult['data']['wr_btime']) ,'wr_etime'=>date('Y-m-d H:i:s',$shopResult['data']['wr_etime'])];
			}
		}
		LibTpl::Set('validTimeArr',$validTimeArr);	


		

		if(!empty($Params['wr_id']))
		{
			$res = $B2cBase->get('wx_robot left join wx_robot_token on wrt_id=wr_wrt_id', ['*',"MD5(CONCAT('Y@', wrt_id, '@P', DATE_FORMAT(NOW(), '%Y-%m-%d'))) as md5key"], sprintf(" and wr_id=%d", $Params['wr_id']), true);
			$robotArr = $res['data'];
			if (!empty($robotArr)) 
			{
				$robotArr['wr_autotxt'] = json_decode($robotArr['wr_autotxt'], true);
				if($robotArr['wr_autotxt']){
					$robotArr['wr_autotxt'] = array_map(function($item){
						return str_replace("\r\n","<br>",$item);
					},$robotArr['wr_autotxt']);
				}
				$robotArr['wr_vin_fileds'] = !empty($robotArr['wr_vin_fileds'])? explode(',',$robotArr['wr_vin_fileds']):[];
				$robotArr['wr_othcof'] = !empty($robotArr['wr_othcof']) ? explode(',',$robotArr['wr_othcof']):[];
				$robotArr['wr_selfmod'] = !empty($robotArr['wr_selfmod']) ?explode(',',$robotArr['wr_selfmod']):[];
				//取关联的微信号
				if(in_array($robotArr['wr_type'],['wxgr','wxkf']))
				{
					$wrwRes = $B2cBase->get('wx_robot_wx', ['wrw_wx'], sprintf(" and wrw_wr_id=%d", $Params['wr_id']));
					if($wrwRes['data'])
					{	
						$wrw_wx = array_column($wrwRes['data'],'wrw_wx');
						$robotArr['usedWxCount'] = count($wrw_wx);
						$robotArr['wrw_wx'] = implode(',',$wrw_wx);
					}
					$wrwRoomRes = $B2cBase->get('wx_robot_room',['count(*) as count'],sprintf(" and wrr_wr_id=%d",$Params['wr_id']),true);
					$robotArr['usedRoomCount'] = $wrwRoomRes['data']['count']?:0;
				}

				$robotArr['wr_btime']  = date('Y-m-d H:i:s',$robotArr['wr_btime']);
				$robotArr['wr_etime']  = date('Y-m-d H:i:s',$robotArr['wr_etime']);

				$brandres = $B2cBase->get('wx_robot_brand',['*'],sprintf(" AND wrb_wr_id=%d",$Params['wr_id']));
				$robotArr['brand_ids'] = $brandres['data']?array_column($brandres['data'],'wrb_brand_id'):[];
			}	
		}
		else
		{
			
			$robotArr['wr_totype'] =!empty($Params['wr_totype'])? $Params['wr_totype']:'super';
			$robotArr['wr_type'] = in_array($robotArr['wr_totype'],['super', 'gzh'])?'wxgzh':'wxgr';
			
			if($validTimeArr[$robotArr['wr_totype']])
			{
				if(empty($robotArr['wr_btime'])) $robotArr['wr_btime'] = $validTimeArr[$robotArr['wr_totype']]['wr_btime'];
				if(empty($robotArr['wr_etime'])) $robotArr['wr_etime'] = $validTimeArr[$robotArr['wr_totype']]['wr_etime'];
			}
		}
		if(!empty($robotArr['wr_uid']))
		{
			$LibYpApi = new LibYpApi();
			$getData = ['uid' => $robotArr['wr_uid']];
			$res  = $LibYpApi->Get('user/getUserById',$getData);
			$robotArr['user_name'] = $res['data']['u_name'];
		}
		if(empty($Params['wr_totype']))
		{
			if(empty($robotArr['wr_btime'])) $robotArr['wr_btime'] = date('Y-m-d H:i:s');
			if(empty($robotArr['wr_etime'])) $robotArr['wr_etime'] = date('Y-m-d H:i:s',strtotime('+1 year'));
		}

		$wrtList = $B2cWxRobot->getWxRobotTokenListV2($robotArr['wr_id']);

		if($Params['type']=='copy' && $robotArr['wr_id']){
			unset($robotArr['wr_id']);
		}

		$typeArr = ['wxgzh'=>'微信公众号','wxgr'=>'微信群聊','wxkf'=>'企微客服'];
		$toTypeArr = ['super'=>'公众号目录', 'gzh'=>'商城版目录','pjlshop'=>'入驻商家','yiparts'=>'宜配','vin'=>'车架号','crm'=>'CRM','customize'=>'定制'];
		//业务员
		// $PjlBase = new PjlBase();
		// $salesRes = $PjlBase->get('bu_user',['usr_name']," AND usr_status=1 AND usr_name!='' order by usr_seq,convert(usr_name using gbk)");
		$salesRes = $B2cBase->getYeWuList();
		LibTpl::Set('salesArr', $salesRes['data']);

		$tres = $B2cBase->get('wx_robot_label', ['*'], ' order by wrl_seq');
		$allLabelArr = [];
		foreach($tres['data'] as $v)
		{
			$allLabelArr[$v['wrl_type']][$v['wrl_code']] = $v;
		}
		//格式化wrt_wxinfo
		$robotArr['wrt_wxinfo'] = $robotArr['wrt_wxinfo']?json_decode($robotArr['wrt_wxinfo'], true):[];
		//请求总接口
		if($robotArr['wrt_id']){
			$LibYpApi = new LibYpApi();
			$LibYpApi->Get('index/chkRobotStatus',['wrt_id'=>$robotArr['wrt_id']]);
		}
		LibTpl::Set('othCnfArr', $allLabelArr['othcfg']);
		LibTpl::Set('wrtList',$wrtList['data']);
		LibTpl::Set('selfModArr', $allLabelArr['selfmod']);
		LibTpl::Set('vinFieldsArr', $allLabelArr['vinfileds']);
		LibTpl::Set('robotArr', $robotArr);
		LibTpl::Set('typeArr', $typeArr);
		LibTpl::Set('toTypeArr', $toTypeArr);
		LibTpl::Set('title', '配置机器人');
		LibTpl::Put();
	}
	/**
	* @method 删除机器人
	* @author zhengweihua 
	* @copyright 2022-05-30
	*/
	public function robotDel()
	{
		LibRule::Check('SL01');
		$Params = mvc::$URL_PARAMS;
		$B2cWxRobot = new B2cWxRobot();
		$res = $B2cWxRobot->delWxRobot($Params['wr_id']);
		return LibFc::ajaxJsonEncode($res);
	}

	/**
	 * @method 店铺配件同步列表
	 * @author zhengweihua 
	 * @copyright 2022-08-10
	 */
	public function shopSync()
	{
		LibRule::Check('SL03');
		$Params = mvc::$URL_PARAMS;
		$syncList = [];
		$perPage = isset($_COOKIE['perPage']) ? $_COOKIE['perPage'] : 20;
		$page = isset($Params['page']) ? $Params['page'] : 1;
		$B2cBase =	new B2cBase();
		$table = 'sh_shop_synch 
		left join sh_shop as sf on sf.shop_id = sss_shop_id_from 
		left join sh_shop as st on st.shop_id = sss_shop_id_to';
		$where = '';

		if(!empty($Params['keyword']))
		{
			$where .= sprintf(" and (sf.shop_name like '%%%s%%' or st.shop_name like '%%%s%%' or sss_shop_id_from = %d or sss_shop_id_to = %d) ",LibFc::Escape($Params['keyword']),LibFc::Escape($Params['keyword']),LibFc::Escape($Params['keyword']),LibFc::Escape($Params['keyword']));
		}
		
		$countres = $B2cBase->get($table,['count(*) as count'],$where,true);

		if($countres['data']['count']>0){
			$where .= sprintf(" order by sss_etime desc limit %d,%d",($page-1)*$perPage, $perPage);
			$res = $B2cBase->get($table, ['sh_shop_synch.*,sf.shop_name as shop_name_from,st.shop_name as shop_name_to'], $where);
			$syncList = $res['data'];
		}
		$Page = LibPage::Show($countres['data']['count'], $perPage);
		LibTpl::Set('Page', $Page);
		LibTpl::Set('Params',$Params);
		LibTpl::Set('syncList', $syncList);
		LibTpl::Set('title', '店铺配件同步');
		LibTpl::Put();
	}

	/**
	 * @method 店铺同步设置
	 * @author zhengweihua 
	 * @copyright 2022-08-10
	 */
	public function shopSyncSet()
	{	
		LibRule::Check('KW04');
		$Params = mvc::$URL_PARAMS;
		$B2cBase = new B2cBase();
		if($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['sync'])){

			$syncData = $_POST['sync'];

			$sss_shop_id_from = $syncData['sss_shop_id_from']; 
			$sss_shop_id_to = $syncData['sss_shop_id_to']; 
			if(empty($sss_shop_id_from) || empty($sss_shop_id_to))  LibFc::ajaxJsonEncode(['status'=>false,'data'=>'请填写店铺ID!']);
			
			$where = sprintf(" and shop_id = '%s'",(int)$sss_shop_id_from);
			$fromres = $B2cBase->get('sh_shop',['shop_id'],$where,true);
			if(empty($fromres['data'])) LibFc::ajaxJsonEncode(['status'=>false,'data'=>'源店铺不存在!']);
			
			$where = sprintf(" and shop_id = '%s'",(int)$sss_shop_id_to);
			$tores = $B2cBase->get('sh_shop',['shop_id'],$where,true);
			if(empty($tores['data'])) LibFc::ajaxJsonEncode(['status'=>false,'data'=>'目标店铺不存在!']);
			
			$where = sprintf(' and sss_shop_id_from = %d and sss_shop_id_to = %d', (int)$sss_shop_id_from, (int)$sss_shop_id_to);
			$res = $B2cBase->get('sh_shop_synch', ['*'], $where, true);
	
			$data = [
				'sss_act' => json_encode($syncData['sss_act']),
				'sss_etime' => time()
			];
			if (!empty($res['data'])) {
				
				$setres = $B2cBase->set('sh_shop_synch', $data, $where);
			}else{
				$data['sss_shop_id_from'] = $sss_shop_id_from;
				$data['sss_shop_id_to'] = $sss_shop_id_to;
				$setres = $B2cBase->add('sh_shop_synch', $data);
			}
			return LibFc::ajaxJsonEncode($setres);
		}
		$where = sprintf(' and sss_shop_id_from = %d and sss_shop_id_to = %d', (int)$Params['sss_shop_id_from'], (int)$Params['sss_shop_id_to']);

		$table = 'sh_shop_synch 
		left join sh_shop as sf on sf.shop_id = sss_shop_id_from 
		left join sh_shop as st on st.shop_id = sss_shop_id_to';
		$res = $B2cBase->get($table, ['sh_shop_synch.*,sf.shop_name as shop_name_from,st.shop_name as shop_name_to'], $where, true);
		if($res['data']){
			$res['data']['sss_act'] = json_decode($res['data']['sss_act'],true);
		}

		LibTpl::Set('syncArr', $res['data']);	
		LibTpl::Set('title', '设置店铺同步');
		LibTpl::Put();
	}

	/**
	 * @method 删除店铺同步设置
	 * @author zhengweihua 
	 * @copyright 2022-08-10
	 */
	public function delShopSync()
	{
		$Params = mvc::$URL_PARAMS;	
		$B2cBase = new B2cBase();
		$where = sprintf(' and sss_shop_id_from = %d and sss_shop_id_to = %d', (int)$Params['sss_shop_id_from'], (int)$Params['sss_shop_id_to']);
		$res = $B2cBase->get('sh_shop_synch', ['*'], $where, true);
		if(empty($res['data']))  LibFc::ajaxJsonEncode(['status'=>false,'data'=>'参数不正确!']);

		$res = $B2cBase->del('sh_shop_synch',$where);
		LibFc::ajaxJsonEncode($res);
	}

	/**
	 * @method 接口管理
	 * @author zhengweihua 
	 * @copyright 2022-08-26
	 */
	public function  apiManager()
	{
		LibRule::Check('AP02');
		$Params = mvc::$URL_PARAMS;
		$perPage = isset($_COOKIE['perPage']) ? $_COOKIE['perPage'] : 20;
		$page = isset($Params['page']) ? $Params['page'] : 1;
		$where = '';
		$dataArr = [];
		foreach($Params as $k=>$v)
		{
			$v = trim($v);
			if ($v == '') continue;
			switch ($k) 
			{
				case 'au_status':
					$where .= sprintf(" and au_status = %d ", (int)$v);
					break;
				case 'keyword':
	
					$owhere = sprintf(" au_comname like '%%%s%%' or au_remark like '%%%s%%' ",LibFc::Escape($v),LibFc::Escape($v));

					$LibYpApi = new LibYpApi();
					$post = [
						'filed'=>['u_id'],
						'where'=>sprintf(" and (u_name like '%s%%' or u_nickname like '%s%%')", LibFc::Escape($v), LibFc::Escape($v)),
						'oneRow'=>false
					];
					$userArr = $LibYpApi->Get('user/getUser',[], $post);
					$userArr = array_column($userArr['data'], 'u_id');
					if(!empty($userArr))
						$owhere .= sprintf(" or au_uid in (%s)", implode(',', $userArr));

					$where .= sprintf(" and (%s)",$owhere);
					break;
				// 添加店铺页面单独跳转的逻辑
				case 'au_id':
					$where .= sprintf(" and au_uid = %d ", (int)$v);
					break;
			}
		}
		$MainBase = new MainBase();
		$table = 'api_user';
		$res = $MainBase->get($table, ['count(*) as count'], $where, true);
		$total = $res['data']['count'];
		if($total>0){
			$where .= sprintf(" order by au_btime desc limit %d,%d",($page-1)*$perPage, $perPage);
			$res = $MainBase->get($table, ['*'], $where);
			$dataArr = $res['data'];
		} 
		if($dataArr){
			$LibYpApi = new LibYpApi();
			$uids =  implode(',', array_column($dataArr, 'au_uid'));
			$getData = ['uids' => $uids];
			$userres  = $LibYpApi->Get('user/getUserByIds', [], $getData);
			$userArr  = array_column($userres['data'], null, 'u_id');
			foreach ($dataArr as $key => $item) {
				//统计资源包剩余情况
				$where  = sprintf(" and az_uid = %d and az_status = 1 and az_btime<=%d and az_etime>=%d group by az_style", (int)$item['au_uid'],time(),time());
				$field = ["SUM(az_count_has) as count,az_style"];
				$res = $MainBase->get('api_zyb', $field, $where);
				$item['tjArr'] = $res['data']? array_column($res['data'],null,'az_style'):[];
				$item['user_name'] = $userArr[$item['au_uid']] ? $userArr[$item['au_uid']]['u_name'] : '';
				$dataArr[$key] = $item;
			}
		}
		$Page = LibPage::Show($total, $perPage);
		LibTpl::Set('Page', $Page);
		LibTpl::Set('dataArr', $dataArr);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('title', 'API管理');
		LibTpl::Put();
	}

	/**
	 * @method 添加接口
	 * @author zhengweihua 
	 * @copyright 2022-08-26
	 */
	public function apiSet()
	{
		LibRule::Check('AP01');
		$Params = mvc::$URL_PARAMS;
		//保存
		if($_SERVER['REQUEST_METHOD'] == 'POST')
		{
			if(empty($_POST['api'])) return LibFc::ReturnJson(false, '参数错误');
			$apiData = $_POST['api'];
			if(empty($apiData['user_name'])) return LibFc::ReturnJson(false, '请输入用户名');
			$username = LibFc::Escape($apiData['user_name']);
			$LibYpApi = new LibYpApi();
			$getData = ['account' => $username];
			$resArr = $LibYpApi->Get('user/getUserByAccount', $getData);
			if (empty($resArr['data'])) LibFc::ReturnJson(false, '用户不存在');
			$apiData['au_uid'] = $resArr['data'][0]['u_id'];
			$apiData['au_btime'] = strtotime($apiData['au_btime']);
			$apiData['au_etime'] = strtotime($apiData['au_etime']);
			$MainApiUser = new MainApiUser();
			$res = 	$MainApiUser->apiUserSet($apiData);
			return LibFc::ajaxJsonEncode($res);
		}
		//GET
		$MainBase =	new MainBase();
		if(!empty($Params['au_uid']))
		{
			$table = 'api_user left join api_doc on au_ado_id = ado_id';
			$res = $MainBase->get($table, ['*'], sprintf(" and au_uid=%d", $Params['au_uid']), true);
			$dataArr = $res['data'];
			if (!empty($dataArr)) 
			{
				$aidRes = $MainBase->get('api_user_act', ['*'], sprintf(" and aua_uid=%d", $Params['au_uid']));
				if($aidRes['data'])
					$dataArr['uact'] = array_column($aidRes['data'],'aua_aa_id');			
			}	
		}
		if(!empty($dataArr['au_uid']))
		{
			$LibYpApi = new LibYpApi();
			$getData = ['uid' => $dataArr['au_uid']];
			$res  = $LibYpApi->Get('user/getUserById',$getData);
			$dataArr['user_name'] = $res['data']['u_name'];
		}
		if(!isset($dataArr['uact'])) $dataArr['uact'] = [];
		if(empty($dataArr['au_btime'])) $dataArr['au_btime'] = time();
		if(empty($dataArr['au_etime'])) $dataArr['au_etime'] =strtotime('+1 year');
		$actArr = [];
		$actres = $MainBase->get("api_act",['aa_id,aa_name']," order by aa_seq asc");
		if($actres['data']) $actArr = array_column($actres['data'],'aa_name','aa_id');
		//获取所有文档列表
		$docArr = [];
		$docres = $MainBase->get("api_doc",['ado_id,ado_name'],"");
		if($docres['data']) $docArr = array_column($docres['data'],'ado_name','ado_id');
		//获取所有资源包列表
		LibRule::Check('AP02');//先检查是否有权限
		$zybArr = [];
		if(!empty($Params['au_uid'])){
			//编辑api时 才获取资源包列表
			$zybres = $MainBase->get("api_zyb",['*']," and az_uid = ".$Params['au_uid']." order by az_atime desc");
			if($zybres['data']) $zybArr = $zybres['data'];
		}
		
		$zybStyleArr = ['vin'=>'VIN解码', 'common'=>'普通接口', 'matchmod'=>'号码匹配车型'];
		LibTpl::Set('actArr', $actArr);
		LibTpl::Set('docArr', $docArr);
		LibTpl::Set('zybArr', $zybArr);
		LibTpl::Set('zybStyleArr', $zybStyleArr);
		LibTpl::Set('dataArr', $dataArr);
		LibTpl::Set('title', 'API管理');
		LibTpl::Put();	
	}

	/**
	 * @method 删除接口管理
	 * @author zhengweihua 
	 * @copyright 2022-08-26
	 */
	public function apiDel()
	{
		LibRule::Check('AP01');
		$Params = mvc::$URL_PARAMS;
		
		$MainApiUser = new MainApiUser();
		$res = 	$MainApiUser->delApiSet($Params['au_uid']?:0);
		return LibFc::ajaxJsonEncode($res);
	}

	/**
	 * @method 资源包管理
	 * @author zhengweihua 
	 * @copyright 2022-08-27
	 */
	public function zybManager()
	{
		LibRule::Check('AP02');
		$Params = mvc::$URL_PARAMS;
		$perPage = isset($_COOKIE['perPage']) ? $_COOKIE['perPage'] : 20;
		$page = isset($Params['page']) ? $Params['page'] : 1;
		$where = '';
		$dataArr = [];
		foreach($Params as $k=>$v)
		{
			$v = trim($v);
			if ($v == '') continue;
			switch ($k) 
			{
				case 'az_style':
					$where  .= sprintf(" and az_style = '%s'",LibFc::Escape($v));
					break;
				case 'az_status':
					$where .= sprintf(" and az_status = %d ", (int)$v);
					break;
				case 'keyword':
					$owhere = sprintf(" az_remark like '%%%s%%' ",LibFc::Escape($v));

					$LibYpApi = new LibYpApi();
					$post = [
						'filed'=>['u_id'],
						'where'=>sprintf(" and (u_name like '%s%%' or u_nickname like '%s%%')", LibFc::Escape($v), LibFc::Escape($v)),
						'oneRow'=>false
					];
					$userArr = $LibYpApi->Get('user/getUser',[], $post);
					$userArr = array_column($userArr['data'], 'u_id');
					
					$B2cBase = new B2cBase();
					$shopres = $B2cBase->get('sh_shop',['shop_id'],sprintf(" and (shop_name like '%%%s%%' or shop_com_name like '%%%s%%')", LibFc::Escape($v),LibFc::Escape($v)));
					if($shopres['data']){
						$arr = array_column($shopres['data'],'shop_id');
						$userArr = array_merge($userArr,$arr);
					}
					if(!empty($userArr))
						$owhere .= sprintf(" or az_uid in (%s)", implode(',', array_unique($userArr)));
					$where .= sprintf(" AND (%s)",$owhere); 
					break;
				// 添加店铺页单独跳转的逻辑
				case 'az_uid':
					$where .= sprintf(" and az_uid = %d ", (int)$v);
					break;
			}
		}
		$MainBase = new MainBase();
		$table = 'api_zyb';
		$res = $MainBase->get($table, ['count(*) as count'], $where, true);
		$total = $res['data']['count'];
		if($total>0){
			$where .= sprintf(" order by az_atime desc limit %d,%d",($page-1)*$perPage, $perPage);
			$res = $MainBase->get($table, ['*'], $where);
			$dataArr = $res['data'];
		} 
		if($dataArr){
			$LibYpApi = new LibYpApi();
			$uids =  implode(',', array_column($dataArr, 'az_uid'));
			$getData = ['uids' => $uids];
			$userres  = $LibYpApi->Get('user/getUserByIds', [], $getData);
			$userArr  = array_column($userres['data'], null, 'u_id');
			// $userArr  = [];
			//店铺名称
			$B2cBase = new B2cBase();
			$shopres = $B2cBase->get('sh_shop',['shop_id','shop_name'],sprintf(" AND shop_id IN (%s)",$uids));
			$shopArr  = array_column($shopres['data'], null, 'shop_id');
			foreach ($dataArr as $key => $item) {
				$item['user_name'] = $userArr[$item['az_uid']] ? $userArr[$item['az_uid']]['u_name'] : '';
				$item['shop_name'] = $shopArr[$item['az_uid']] ? $shopArr[$item['az_uid']]['shop_name'] : '';
				$dataArr[$key] = $item;
			}
		}
		$styleArr = ['vin'=>'VIN解码', 'common'=>'普通接口', 'matchmod'=>'号码匹配车型'];
		$statusArr = [-2=>'退款', -1=>'过期',0=>'待付款', 1=>'正常'];
		LibTpl::Set('styleArr', $styleArr);
		LibTpl::Set('statusArr', $statusArr);
		$Page = LibPage::Show($total, $perPage);
		LibTpl::Set('Page', $Page);
		LibTpl::Set('dataArr', $dataArr);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('title', '资源包管理');
		LibTpl::Put();
	}

	/**
	 * @method 添加资源包
	 * @author zhengweihua 
	 * @copyright 2022-08-27
	 */
	public function zybSet()
	{
		LibRule::Check('AP01');
		$Params = mvc::$URL_PARAMS;
		//保存
		if($_SERVER['REQUEST_METHOD'] == 'POST')
		{
			if(empty($_POST['zyb'])) return LibFc::ReturnJson(false, '参数错误');
			$zybData = $_POST['zyb'];
			if(empty($zybData['user_name'])) return LibFc::ReturnJson(false, '请输入用户名');
			$username = LibFc::Escape($zybData['user_name']);
			$LibYpApi = new LibYpApi();
			$getData = ['account' => $username];
			$resArr = $LibYpApi->Get('user/getUserByAccount', $getData);
			if (empty($resArr['data'])) LibFc::ReturnJson(false, '用户不存在');
			$addArr = [
				'az_uid'=> $resArr['data'][0]['u_id'],
				'az_status'=>$zybData['az_status'],
				'az_style'=>$zybData['az_style'],
				'az_count_has'=>$zybData['az_count_has'],
				'az_count'=>$zybData['az_count'],
				'az_money'=>$zybData['az_money']?:0,
				'az_remark'=>$zybData['az_remark'],
				'az_btime'=>strtotime($zybData['az_btime']),
				'az_etime'=>strtotime($zybData['az_etime']),
				'az_by_uid'=>$_SESSION['admin_userid'],
				'az_type'=>$zybData['az_type'],
			];
			$MainBase = new MainBase();
			if($zybData['az_id']){
				$res = 	$MainBase->set('api_zyb',$addArr,sprintf(" and az_id= %d",LibFc::Int($zybData['az_id'])));
			}else{
				$addArr['az_atime']=time();
				$res = 	$MainBase->add('api_zyb',$addArr);
			}
			return LibFc::ajaxJsonEncode($res);
		}
		//GET
		$dataArr = [];
		$MainBase =	new MainBase();
		if(!empty($Params['az_id']))
		{
			$res = $MainBase->get('api_zyb', ['*'], sprintf(" and az_id=%d", $Params['az_id']), true);
			$dataArr = $res['data'];

		}
		if(!empty($dataArr['az_uid']))
		{
			$LibYpApi = new LibYpApi();
			$getData = ['uid' => $dataArr['az_uid']];
			$res  = $LibYpApi->Get('user/getUserById',$getData);
			$dataArr['user_name'] = $res['data']['u_name'];
		}
		if(empty($dataArr['az_btime'])) $dataArr['az_btime'] = time();
		if(empty($dataArr['az_etime'])) $dataArr['az_etime'] =strtotime('+1 year');
		LibTpl::Set('dataArr', $dataArr);
		LibTpl::Set('title', 'API管理');
		LibTpl::Put();			
	}

	/**
	 * @method 删除资源包
	 * @author zhengweihua 
	 * @copyright 2022-08-27
	 */
	public function zybDel()
	{	
		LibRule::Check('AP01');
		$Params = mvc::$URL_PARAMS;
		$MainBase = new MainBase();
		$az_id = LibFc::Int($Params['az_id']);
		if (empty($az_id)) LibFc::ReturnJson(false, '参数错误');
		$where = sprintf(" and az_id=%d", $az_id);
		$res = $MainBase->get('api_zyb', ['*'], $where, true);
		if (empty($res['data'])) LibFc::ReturnJson(false, '记录不存在');
		$res = $MainBase->del('api_zyb', $where);
		return LibFc::ajaxJsonEncode($res);
	}
	/**
	 * @method 获取机器人的登陆二维码[暂时]
	 * @author zhengweihua 
	 * @copyright 2022-10-12
	 */
	public function getRobotEwm()
	{
		$Params = mvc::$URL_PARAMS;
		$wr_id = LibFc::Int($Params['wr_id']);
		$forwardEwm = $Params['forwardEwm'];
		if($wr_id){
			$B2cBase = new B2cBase();
			$table = 'wx_robot 
			left join wx_robot_token on wrt_id = wr_wrt_id';
			$res  =	 $B2cBase->get($table,['wrt_chknew','wrt_loginurl','wr_id','wr_uid','wrt_wxnickname','wrt_token_type'],sprintf(" and wr_id = %d",$wr_id),true);
			
			if(empty($res['data']['wrt_loginurl'])){

                if ($res['data']['wr_uid']) {
                    $res = $B2cBase->get('wx_robot_token', ['wrt_loginurl', 'wrt_wxnickname'], sprintf(" and wrt_uid = %d", $res['data']['wr_uid']), true);
                }
                if (empty($res['data']['wrt_loginurl'])) {
                    return LibFc::ReturnJson(false, '无需登陆');
                }
			}
			$data['wrt_chknew'] = $res['data']['wrt_chknew'];	
			$data['wrt_wxnickname'] = $res['data']['wrt_wxnickname'];
			$data['loginurl']=$res['data']['wrt_loginurl'];
			if($forwardEwm && $forwardEwm == $res['data']['wrt_loginurl']){
				return LibFc::ReturnJson(true,$data);
			}
			if(in_array($res['data']['wrt_token_type'],mvc::$cfg['ROBOT_CONFIG']['nobase64'])){
				$ewmurl = $res['data']['wrt_loginurl'];
			}else{
				$OthQrcode = new OthQrcode();
				$ewmurl = $OthQrcode->png($res['data']['wrt_loginurl']);
			}
			
			$data['ewmurl'] = $ewmurl; 
			return LibFc::ReturnJson(true,$data);
		}
		return LibFc::ReturnJson(false,'参数错误');
	}

	/**
	 * @method 获取机器人验证
	 * @author zhengweihua 
	 * @copyright 2024-01-08
	 */
	public function getRobotVerify()
	{
		$Params = mvc::$URL_PARAMS;
        $wr_id = LibFc::Int($Params['wr_id']);

        if ($wr_id) {
            $B2cBase = new B2cBase();
            $table = 'wx_robot 
			left join wx_robot_token on wrt_id = wr_wrt_id';
            $res  =  $B2cBase->get($table, ['wrt_loginurl', 'wr_id', 'wrt_wxnickname'], sprintf(" and wr_id = %d and wrt_verify=1 and wrt_verifycode=''", $wr_id), true);
            if($res['data']){
                return LibFc::ReturnJson(true,1);
            }
            return LibFc::ReturnJson(true,0); 
        }
	}

	/**
	 * @method 保存机器人验证码
	 * @author zhengweihua 
	 * @copyright 2024-01-08
	 */
	public function setVerifycode()
	{
		if($_SERVER['REQUEST_METHOD']=='POST'&&$_POST)
		{
			if(!empty($_POST['wr_id'])&&!empty($_POST['verifycode'])){
				$wr_id = LibFc::Int($_POST['wr_id']);
				$verifycode = $_POST['verifycode'];
				$B2cWxRobot = new B2cWxRobot();
				$res = $B2cWxRobot->setVerifyCode($wr_id,$verifycode);
				LibFc::ajaxJsonEncode($res);
			}
		}
	}

	/**
	 * @method 机器人token列表
	 * @author zhengweihua 
	 * @copyright 2024-02-28
	 */
	public function robotToken()
	{
		LibRule::Check('AP01');
		$Params = mvc::$URL_PARAMS;
		$where = '';
		$order = 'order by (wrt_endtime > NOW()) DESC, wrt_endtime ASC';
		$perPage = isset($_COOKIE['perPage']) ? $_COOKIE['perPage'] : 20;
		$page = isset($Params['page']) ? $Params['page'] : 1;
		foreach ($Params as $key => $val) {
			if(!$val) continue;
			$val =  LibFc::Escape($val);
			switch ($key) {
				case 'keyword':
					$where .=sprintf(" AND (wrt_wxnum like '%%%s%%' or wrt_comname like '%%%s%%'  
					or wrt_wxnickname like '%%%s%%' or wrt_token ='%s' or wrt_remark like '%%%s%%')",$val,$val,$val,$val,$val);
					break;
				case 'wrt_server':
					$where .=sprintf(" AND wrt_server like '%%%s%%'",$val);
					break;
				case 'wrt_loginurl':
					if($val==1){
						$where .=" AND wrt_loginurl !=''";
					}elseif ($val==-1) {
						$where .=" AND wrt_loginurl =''";
					}
					break;
				case 'wrt_token_type':
					$where .= sprintf(" AND wrt_token_type ='%s'",$val);
					break;
				case 'wrt_type':
					$where .= sprintf(" AND wrt_type ='%s'",$val);
					break;
				// 商铺详情页进入时的特殊筛选
				case 'wrt_uid':
					$where .= sprintf(" AND wrt_uid ='%s'",$val);
					break;
				case 'wrt_loginstatus':
					$where .= sprintf(" AND wrt_loginstatus =%d",$val);
					break;
			}
		}

		$B2cWxRobot = new B2cWxRobot();
		$res = $B2cWxRobot->get('wx_robot_token', ['count(*) as counts'], $where,true);
		$list = [];
		$total = $res['data']['counts'];
		if ($total> 0) {
			$res = $B2cWxRobot->get('wx_robot_token',['*'],sprintf("%s %s limit %d,%d",$where,$order,($page-1)*$perPage,$perPage));
			$list = $res['data'];
		}
		LibTpl::Set('statusArr',[0=>'所有','-1'=>'离线','1'=>'在线']);
		LibTpl::Set('Params',$Params);
		LibTpl::Set('Page',LibPage::Show($total,$perPage,true));
		LibTpl::Set('list',$list);
		LibTpl::Set('typeArr',['wx'=>'微信','wxwork'=>'企业微信','wxkf'=>'企微客服']);
		LibTpl::Set('title', 'TOKEN管理');
		LibTpl::Put();
	}

	
	public function robotTokenSet()
	{
		LibRule::Check('AP01');
		$Params = mvc::$URL_PARAMS;
		if($_SERVER['REQUEST_METHOD']=='POST' && $_POST['rob']){
			$B2cWxRobot = new B2cWxRobot();
			$data = $_POST['rob'];
			$wrt_id = (int)$_POST['wrt_id'];
			$user_name = LibFc::Escape($_POST['user_name']);
			if($user_name){
				$LibYpApi = new LibYpApi();
				$post = [
					'filed'=>['u_id'],
					'where'=>sprintf(" and (u_name like '%s%%' or u_nickname like '%s%%')", $user_name, $user_name),
					'oneRow'=>false
				];
				$userArr = $LibYpApi->Get('user/getUser',[], $post);
				$data['wrt_uid'] = $userArr['data'][0]['u_id'];
				if(!$data['wrt_uid']) LibFc::ajaxJsonEncode(['status'=>false,'data'=>'用户名不存在，请重新输入!']);
			}

			$B2cWxRobot = new B2cWxRobot();
			$res = $B2cWxRobot->get('wx_robot_token',['wrt_id'],sprintf(" AND wrt_token='%s' AND wrt_id!=%d",$data['wrt_token'],$wrt_id),true);
			if($res['data']){
				LibFc::ajaxJsonEncode(['status'=>false,'data'=>'TOKEN已存在，请重新输入!']);
			}
			if(empty($data['wrt_kfcfg'])){
				$data['wrt_kfcfg'] = '{"kf_token": "", "kf_secret": "", "kf_encodingaeskey": ""}';
			}
			$isExist =false;
			if($wrt_id){
				$ares = $B2cWxRobot->get('wx_robot_token',['wrt_id'],sprintf(" AND wrt_id=%d",$wrt_id),true);
				if($ares['data']){
					$isExist = true;
					$data['wrt_sleeptime'] = $data['wrt_sleeptime']?:'#@NULL';
					$B2cWxRobot->set('wx_robot_token',$data,sprintf(" AND wrt_id=%d",$wrt_id));
					$res  = ['status'=>true,'data'=>$wrt_id];
				}
			}
			if(!$isExist){
				if(!$data['wrt_sleeptime']){
					unset($data['wrt_sleeptime']);
				}
				$res = 	$B2cWxRobot->add('wx_robot_token',$data);
			}
			LibFc::ajaxJsonEncode($res);
		}

		$tokenArr = ['wrt_type'=>'wx','wrt_kfcfg'=>'{"kf_token": "", "kf_secret": "", "kf_encodingaeskey": ""}'];
		$wcof = []; // 初始化wcof变量
		$qwkfArr = []; // 初始化qwkfArr变量
		$B2cWxRobot = new B2cWxRobot();
		if($Params['wrt_id']){
			$wrt_id =(int)$Params['wrt_id'];
			
			$res = $B2cWxRobot->get('wx_robot_token',['*'],sprintf(" AND wrt_id=%d",$wrt_id),true);
			
			if($res['data']){
				$tokenArr = $res['data'];
				if($tokenArr['wrt_uid']){
					$LibYpApi = new LibYpApi();
					$getData = ['uid' => $tokenArr['wrt_uid']];
					$res  = $LibYpApi->Get('user/getUserById',$getData);
					$tokenArr['user_name'] = $res['data']['u_name'];
				}
				if($tokenArr['wrt_loginurl']){
					if(in_array($tokenArr['wrt_token_type'],mvc::$cfg['ROBOT_CONFIG']['nobase64'])){
						
						$tokenArr['ewmurl'] = $tokenArr['wrt_loginurl'];
					}else{
						$OthQrcode = new OthQrcode();
						$tokenArr['ewmurl'] = $OthQrcode->png($tokenArr['wrt_loginurl']);	
					}
					
				}
				//获取企业微信客服相关信息
				if($tokenArr['wrt_type']==='wxkf' && $tokenArr['wrt_wxid']){
					$wxkf_config = json_decode($tokenArr['wrt_kfcfg'], true);
					$wcof = [
						'corpid'=>$tokenArr['wrt_wxid'],
						'kf_secret'=>$wxkf_config['kf_secret'],
					];
					$qwkfListRes = $this->weworkApi('kf/account/list',[],$wcof);
					if($qwkfListRes['errcode'] == 0 && count($qwkfListRes['account_list'])){
						$qwkfArr = $qwkfListRes['account_list'];
					}
				}
			}
		}else{
			$res = $B2cWxRobot->get('wx_robot_token',['max(wrt_id) as maxId'],'',true);
			$tokenArr['maxId'] = $res['data']['maxId'];
		}

		
		
		$provinceArr = mvc::$cfg['ROBOT_CONFIG']['proxy'][$tokenArr['wrt_token_type']]?:[];
		LibTpl::Set('provinceArr',$provinceArr);
		LibTpl::Set('provinceJson',mvc::$cfg['ROBOT_CONFIG']['proxy']);
		LibTpl::Set('tokenArr',$tokenArr);
		LibTpl::Set('qwkfArr',$qwkfArr);
		LibTpl::Set('wcof',$wcof);
		LibTpl::Set('typeArr',['wx'=>'微信','wxwork'=>'企业微信','wxkf'=>'微信客服']);
		LibTpl::Set('title', 'TOKEN管理');
		LibTpl::Put();
	}


	/**
	 * @method 删除token
	 * @author zhengweihua 
	 * @copyright 2024-02-28
	 */
	public function delToken()
	{
		LibRule::Check('AP01');
		if($_SERVER['REQUEST_METHOD']=='POST' && $_POST['wrt_id']){
			$wrt_id = (int)$_POST['wrt_id'];
			$B2cWxRobot = new B2cWxRobot();
			$res = $B2cWxRobot->del('wx_robot_token',sprintf(" AND wrt_id=%d",$wrt_id));
			LibFc::ajaxJsonEncode($res);
		}
	}

	/**
	 * @method 获取token信息
	 * @author zhengweihua 
	 * @copyright 2024-06-11
	 */
	public function getTokenInfo()
	{
		$params = mvc::$URL_PARAMS;
		if($params['wrt_id'])
		{
			$wrt_id = (int)$params['wrt_id'];
			$B2cWxRobot = new B2cWxRobot();
			$res = $B2cWxRobot->get('wx_robot_token',['*'],sprintf(" AND wrt_id=%d",$wrt_id),true);
			if($res['data'])
			{
				$res['data']['days'] = ceil((strtotime($res['data']['wrt_endtime'])-time())/3600/24);
				$res['data']['wrt_token_type_name'] = mvc::$cfg['ROBOT_CONFIG']['tokentype'][$res['data']['wrt_token_type']]?:'';
				$res['data']['wrt_wxinfo'] = $res['data']['wrt_wxinfo']?json_decode($res['data']['wrt_wxinfo'], true):'';
			}
			return LibFc::ajaxJsonEncode($res);
		}
	}


	public function restartRobot()
	{
		$Params= mvc::$URL_PARAMS;
		if(!$Params['wr_id']) return LibFc::ReturnJson(false,'参数错误');
		$wr_id = (int)$Params['wr_id'];
		$B2cBase = new B2cBase();
		$res  =	 $B2cBase->get('wx_robot',['*'],sprintf(" and wr_id = %d",$wr_id),true);
		if($res['data']['wr_wrt_id'])
		{
			$tokenres = $B2cBase->get('wx_robot_token', ['*'], sprintf(" and wrt_id = %d", $res['data']['wr_wrt_id']), true);
			$wrt_id = $tokenres['data']['wrt_id'];
			$token_type= $tokenres['data']['wrt_token_type'];
		}
		if($wrt_id)
		{
			$LibYpApi = new LibYpApi();
			$res = $LibYpApi->Get('index/restartRobot',['wrt_id'=>$wrt_id]);
			$return = json_decode($res['data'],true);
			if(is_array($return)){
				LibFc::ReturnJson($return['status'],$return['data']);
			}else{
				LibFc::ajaxJsonEncode($res);
			}
		}
		LibFc::ReturnJson(true);
		
	}

	/**
	 * @method 检测是否能重启
	 * @author zhengweihua 
	 * @copyright 2024-07-17
	 */
	public function checkRestart()
	{
		$Params= mvc::$URL_PARAMS;
		$wr_id = (int)$Params['wr_id'];
		if ($wr_id) {
            $B2cBase = new B2cBase();
            $table = 'wx_robot 
			left join wx_robot_token on wrt_id = wr_wrt_id';
            $res  =  $B2cBase->get($table, ['*'], sprintf(" and wr_type='wxgr' and wr_id = %d", $wr_id), true);
            if($res['data']){
                if(time()-$res['data']['wrt_restart_last']>120){
                    return LibFc::ReturnJson(true,1);
                }
            }
            return LibFc::ReturnJson(true,0); 
        }  
	}


	public function checkRebots()
	{
		$Params= mvc::$URL_PARAMS;
		$wr_id = (int)$Params['wr_id'];
		//二维码
		$forwardEwm = $Params['forwardEwm'];
		$data = [];
		if($wr_id){
			$B2cBase = new B2cBase();
			$res  =	 $B2cBase->get('wx_robot',['*'],sprintf(" and wr_id = %d",$wr_id),true);
			
			if($res['data']['wr_wrt_id'])
			{
				$tokenres = $B2cBase->get('wx_robot_token', ['*'], sprintf(" and wrt_id = %d", $res['data']['wr_wrt_id']), true);
			}

			if($tokenres['data'])
			{
				$data = $tokenres['data'];
				//检测验证码,0不需要，1需要
				$data['verify'] = 0;
				if ($tokenres['data']['wrt_verify'] == 1 && $tokenres['data']['wrt_verifycode'] == '') {
					$data['verify'] = 1;
				}
				//检测登录二维码
				$data['showewm']=0;
				if(!empty($tokenres['data']['wrt_loginurl'])){
					$data['showewm'] = 1;
					$data['wrt_wxnickname'] = $tokenres['data']['wrt_wxnickname'];
					$data['loginurl'] = $tokenres['data']['wrt_loginurl'];
					if ($forwardEwm && $forwardEwm == $tokenres['data']['wrt_loginurl']) {
					} else {
						if(in_array($tokenres['data']['wrt_token_type'],mvc::$cfg['ROBOT_CONFIG']['nobase64'])){
							$data['ewmurl'] = $data['loginurl'];
						}else{
							$OthQrcode = new OthQrcode();
							$ewmurl = $OthQrcode->png($data['loginurl']);
							$data['ewmurl'] = $ewmurl;
						}
						
					}
				}
				
				$data['chknew'] = 0;
				if($tokenres['data']['wrt_chknew']){
					$data['chknew'] = 1;
					$data['chknewurl'] = $data['wrt_chknew'];
				}

				//检测显示重启按钮
				$data['showrestart']=0;
				if(time()-$tokenres['data']['wrt_restart_last']>120){
					$data['showrestart']=1;
				}
			}
			
			return LibFc::ReturnJson(true,$data);
		}
	}


	/**
	 * @method 行业报表统计
	 * @author zhengweihua 
	 * @copyright 2025-09-15
	 */
	public function industryTj()
	{
		$Params= mvc::$URL_PARAMS;

		// $Params['betime'] = !empty($Params['betime'])?$Params['betime']:date('Y-01').' ~ '.date('Y-m');
		$_GET['group']  = !empty($_GET['group'])?$_GET['group']:['mod2_brand_id']; 
		$group = $_GET['group'];
		$BaseDb = new BaseDb(mvc::$cfg['DB']['API_TJ']);
		$pctArr = [];
		$where  = '';
		//查最大和最小可查年份
		$limitYearRes = $BaseDb->get('at_report_industry_month',['min(ari_date) as minYear','max(ari_date) as maxYear'],$where,true);
		
		$minYear = substr($limitYearRes['data']['minYear'], 0, 4).'-'.substr($limitYearRes['data']['minYear'], 4, 2);
		$maxYear = substr($limitYearRes['data']['maxYear'], 0, 4).'-'.substr($limitYearRes['data']['maxYear'], 4, 2);
	
		LibTpl::Set('limitYear',['minYear'=> $minYear.'-01','maxYear'=>$maxYear.'-30']);
		if(!$Params['betime']){
			$Params['betime'] = date('Y').'01'>=$limitYearRes['data']['minYear']? date('Y-01'):$minYear;
			$Params['betime'] = $Params['betime'].' ~ '.(date('Ym')<=$limitYearRes['data']['maxYear']?date('Y-m'):$maxYear);
		}

		//获取分页参数
		$page = isset($Params['page']) ? max(1, (int)$Params['page']) : 1;
		$perPage = isset($_COOKIE['perPage']) ? (int)$_COOKIE['perPage'] : 20;
		$offset = ($page - 1) * $perPage;
		
		//转换一下
		$fromNameArr = ['PJL'=>'跑街令','YP'=>'宜配','SUPER'=>'目录'];
		$selectIdArr = [];
		foreach ($Params as $key => $val) {
			if(!$val) continue;	
			switch ($key) {
				case 'betime':
					$dateArr = explode('~',$val);
					$where1 = '';
					if(count($dateArr)==2){
						$where1 .= sprintf(" and ari_date >= '%s' ",date('Ym',strtotime(trim($dateArr[0]))));
						$where1 .= sprintf(" and ari_date <= '%s' ",date('Ym',strtotime(trim($dateArr[1]))));
				
						$where .= $where1;
					}
					break;
				case 'brand':
					$where .= sprintf(" and mod2_brand_id in (%s) ",implode(',',explode(',',$val)));
					//回显品牌
					$missingRes = $BaseDb->get('bc_brand', ['brand_id as value', 'brand_name as name'], 
							sprintf(" and brand_id in (%s)", implode(',',explode(',',$val))));
					$selectIdArr['brandIds'] =$missingRes['data'];
					break;
				case 'mod1_id':
					$where .= sprintf(" and mod2_mod1_id in (%s) ",implode(',',explode(',',$val)));
					//回显车系
					$missingRes = $BaseDb->get('bc_model1', ['mod1_id as value', 'mod1_name as name'], 
							sprintf(" and mod1_id in (%s)", implode(',',explode(',',$val))));
					$selectIdArr['mod1Ids'] =$missingRes['data'];
					break;
				case 'mod2_id':
					$where .= sprintf(" and ari_mod2_id in (%s) ",implode(',',explode(',',$val)));
	
					$missingRes = $BaseDb->get('bc_model2', ['mod2_id as value', 'mod2_name as name'], 
							sprintf(" and mod2_id in (%s)", implode(',',explode(',',$val))));
					$selectIdArr['mod2Ids'] =$missingRes['data'];
					$Params['mod1_id'] = 1;
					break;
				case 'province_id':
					$where .=  sprintf(" AND ari_province in (%s) ",implode(',',explode(',',$val)));
					$Ypw = new YpwBase();
					$missingRes = $Ypw->get('yp_province_city', ['pc_id as value', 'pc_name as name'], 
							sprintf(" and pc_id in (%s)", implode(',',explode(',',$val))));
					$selectIdArr['provinceIds'] =$missingRes['data'];
					break;
				case 'from':
	
					$fromArr = explode(',',$val);
					
					$escapedFromArr = array_map(function($item) {
						return "'" . LibFc::Escape($item) . "'";
					}, $fromArr);
					$fromStr = implode(',', $escapedFromArr);
					$where .= " and ari_from in ($fromStr) ";
					
					foreach ($fromArr as $val) {
						
						$selectIdArr['from'][] = ['value'=>$val,'name'=>$fromNameArr[$val]];
					}
				
					break;
			}
		}

		// 获取所有时间范围内的月份
		$startDate = date('Ym', strtotime(trim($dateArr[0])));
		$endDate = date('Ym', strtotime(trim($dateArr[1])));
		$months = [];
		$current = $startDate;
		while ($current <= $endDate) {
			$months[] = $current;
			$current = date('Ym', strtotime('+1 month', strtotime($current . '01')));
		}

		// 构建分组字段（不包含ari_date）
		$groupFields = array_unique($group);
		
		$useItemTable = $this->shouldUseItemTable($group, $Params);
		if($useItemTable)
		{	
			//单维度查询
			$table = 'at_report_industry_item';
			$where = $where1.sprintf(" AND ari_type='%s' %s",$useItemTable['type'],$useItemTable['condition']);
			$table1 = "(
				SELECT ari_keyid
				FROM $table
				WHERE 1=1 $where
				group by ari_keyid,ari_keyid2
			) as tmp";

			$countRes = $BaseDb->get($table1, ['count(*) as count'], '', true);
			$total = $countRes['data']['count'];

			$totalRes = $BaseDb->get($table,['SUM(ari_count) as totalCounts'], $where1 .sprintf(" AND ari_type='%s'",$useItemTable['type']) ,true);	
			$totalCounts = $totalRes['data']['totalCounts'];

			// 查询数据
			$field = ['ari_keyid','ari_keyid2', 'SUM(ari_count) as total'];
			$res = $BaseDb->get($table, $field, sprintf(" %s GROUP BY ari_keyid,ari_keyid2 ORDER BY total DESC LIMIT %d,%d", $where, $offset, $perPage));

			$result = [];
			if ($res['data']) {
				switch($useItemTable['type']) {
				 	case 'brand_model2':
						$keykey = 'ari_keyid2';
						$ids = array_column($res['data'],'ari_keyid2');
						$where .= sprintf(" AND ari_keyid2 IN (%s) ", implode(',', $ids));
						$nameRes = $BaseDb->get('bc_model2 
						join bc_model1 on mod2_mod1_id =mod1_id
						join bc_brand on mod2_brand_id =brand_id', ['brand_id','brand_name','mod1_name','mod2_id', 'mod2_name','mod2_start_year','mod2_end_year'], 
							sprintf(' and mod2_id in (%s)', implode(',', $ids)));
						foreach ($nameRes['data'] as $key => $val) {
							$val['years'] =(!empty($val['mod2_start_year']) || !empty($val['mod2_end_year'])) ? 
							((!empty($val['mod2_start_year']) && $val['mod2_start_year'] > 0 ? $val['mod2_start_year'] : '') . 
							'-' . 
							(!empty($val['mod2_end_year']) && $val['mod2_end_year'] > 0 ? $val['mod2_end_year'] : '')) : 
							'';
							$nameMap[$val['mod2_id']] = $val;
						}
					break;
					
				case 'brand_model1': // mod2_mod1_id
					$ids = array_column($res['data'],'ari_keyid2');
					$keykey = 'ari_keyid2';
					$where .= sprintf(" AND ari_keyid2 IN (%s) ", implode(',', $ids));
					$nameRes = $BaseDb->get('bc_model1 join bc_brand on mod1_brand_id =brand_id', ['brand_id','brand_name','mod1_id', 'mod1_name'], 
						sprintf(' and mod1_id in (%s)', implode(',', $ids)));
					$nameMap = array_column($nameRes['data'], null, 'mod1_id');
					break;
					
				case 'brand': // mod2_brand_id
					$ids = array_column($res['data'],'ari_keyid');
					$keykey = 'ari_keyid';
					$where .= sprintf(" AND ari_keyid IN (%s) ", implode(',', $ids));
					$nameRes = $BaseDb->get('bc_brand', ['brand_id','brand_name'], 
						sprintf(' and brand_id in (%s)', implode(',', $ids)));
					$nameMap = array_column($nameRes['data'], null, 'brand_id');
					break;
					
				case 'province': // ari_province
					$ids = array_column($res['data'],'ari_keyid');
					$keykey = 'ari_keyid';
					$where .= sprintf(" AND ari_keyid IN (%s) ", implode(',', $ids));
					$nameRes = $BaseDb->get('yp_province_city', ['pc_id as province_id','pc_name as province_name'], 
						sprintf(' and pc_id in (%s)', implode(',', $ids)));
					$nameMap = array_column($nameRes['data'], null, 'province_id');
					$nameMap['0'] = ['province_id'=>'0','province_name'=>'其他'];
					break;
					
				case 'province_city': // ari_province + ari_city
					$ids = array_column($res['data'],'ari_keyid2');
					$keykey = 'ari_keyid2';
					$where .= sprintf(" AND ari_keyid2 IN (%s) ", implode(',', $ids));
					// 对于省市区组合，需要特殊处理
					$nameRes = $BaseDb->get('yp_province_city as province 
					left join yp_province_city as city on city.pc_pid = province.pc_id', 
					['province.pc_id as province_id', 'province.pc_name as province_name', 
					 'city.pc_id as city_id', 'city.pc_name as city_name'], 
						sprintf(' and city.pc_id in (%s)', implode(',', $ids)));
					foreach ($nameRes['data'] as $item) {
						$nameMap[$item['city_id']] = $item;
					}
					break;
					
				case 'brand_province': // mod2_brand_id + ari_province
					$ids = array_column($res['data'],'ari_keyid');
					$keykey = 'ari_keyid';
					$where .= sprintf(" AND ari_keyid IN (%s) ", implode(',', $ids));
					// 获取品牌和省份的组合信息
					$nameRes = $BaseDb->get('bc_brand', ['brand_id','brand_name'], 
					sprintf(' and brand_id in (%s)', implode(',', $ids)));
					$brandMap = array_column($nameRes['data'], null, 'brand_id');

					// 获取相关的省份信息
					$provinceIds = array_column($res['data'],'ari_keyid2');
					if (!empty($provinceIds)) {
						$provinceRes = $BaseDb->get('yp_province_city', ['pc_id','pc_name'], 
							sprintf(' and pc_id in (%s)', implode(',', array_filter($provinceIds))));
						$provinceMap = array_column($provinceRes['data'], null, 'pc_id');
						
						// 构建组合名称映射
						foreach ($res['data'] as $item) {
							$brandId = $item['ari_keyid'];
							$provinceId = $item['ari_keyid2'];
							if (isset($brandMap[$brandId]) && isset($provinceMap[$provinceId])) {
								$nameMap[$brandId] = [
									'brand_id' => $brandId,
									'brand_name' => $brandMap[$brandId]['brand_name'],
									'pc_id' => $provinceId,
									'pc_name' => $provinceMap[$provinceId]['pc_name']
								];
							}
						}
					}
					break;
				}
				$ids = array_column($res['data'], 'id');

				// 填充各月数据（从数据库查询月度详情）
				$monthDetailRes = $BaseDb->get($table, ['ari_date', 'ari_count as month_total','ari_keyid','ari_keyid2'], 
				sprintf(" %s  GROUP BY ari_date,ari_keyid,ari_keyid2 ORDER BY ari_date", $where, implode(',', $ids)));
				$monthData = [];
				foreach ($monthDetailRes['data'] as $key => $val) {
					$monthData[$val[$keykey]][$val['ari_date']] = intval($val['month_total']);
				}

				// 组装结果，使其与多维度查询结构一致
				foreach ($res['data'] as $index => $row) {
					$nameItem = $nameMap[$row[$keykey]] ?? [];

					$item = [
						'brand_id' => $nameItem['brand_id'] ?? '',
						'brand' => $nameItem['brand_name'] ?? '',
						'mod1_id' => $nameItem['mod1_id'] ?: '',
						'mod1' => $nameItem['mod1_name'] ?: '',
						'mod2_id' => $nameItem['mod2_id'] ?: '',
						'mod2' => $nameItem['mod2_name'] ?: '',
						'years' => $nameItem['years'] ?: '',
						'percent' => $totalCounts > 0 ? round(($row['total'] / $totalCounts) * 100, 2) : 0,
						'total' => $row['total'],
						'province' => $nameItem ?$nameItem['province_name']: '',
						'city'=>$nameItem['city_name']
					];
					
					// 填充各月数据（单维度查询没有月度详情，所以都为0）
					foreach ($months as $key => $val) {
						$item[$val] = isset($monthData[$row[$keykey]][$val]) ? $monthData[$row[$keykey]][$val] : '';
					}

					$result[] = $item;
				}
			}

		}
		else
		{

			$groupby = '';
			if (!empty($groupFields)) {
				$groupby = 'group by ' . implode(',', $groupFields);
			}
			
			// 不再预先连接所有表，而是根据实际需要动态连接
			$baseTable = 'at_report_industry_month as tj';
			$joinClause = '';

			// 根据group字段决定需要连接哪些表
			$needBrand = in_array('mod2_brand_id', $group);
			$needModel1 = in_array('mod2_mod1_id', $group);


			// 构建动态连接语句
			if ($needBrand||$needModel1||$Params['brand']) {
			
				$joinClause .= ' join bc_model2 as mod2 on mod2_id=ari_mod2_id';
			
			}

			// 组合表和连接条件
			$table = $baseTable . $joinClause;

			// 先获取去重后的分组总数（用于分页）
			$table1 = "(
				SELECT " . implode(',', $groupFields) . "
				FROM $table
				WHERE 1=1 $where
				$groupby
			) as tmp";

			$countRes = $BaseDb->get($table1,['count(*) as count'],'',true);
			$total = $countRes['data']['count'];

			// 计算总销量 -查询所有数据的总和 (20251010变更为这个时间段整表的总数)
			$totalRes = $BaseDb->get('at_report_industry_month',['SUM(ari_count) as totalCounts'],$where1,true);    
			$totalCounts = $totalRes['data']['totalCounts'];

			// 获取当前页的分组数据
	
			$field = $groupFields;
			$res = $BaseDb->get($table,$field,sprintf(" %s  %s order by SUM(ari_count) DESC LIMIT $offset, $perPage",$where,$groupby));

			if($res['data'])
			{
				// 收集需要查询的ID
				$brandIds = [];
				$model1Ids = [];
				$model2Ids = [];
				$provinceIds = [];
				$cityIds = [];
				
				foreach ($res['data'] as $row) {
					if (isset($row['mod2_brand_id'])) {
						$brandIds[] = $row['mod2_brand_id'];
					}
					if (isset($row['mod2_mod1_id'])) {
						$model1Ids[] = $row['mod2_mod1_id'];
					}
					if (isset($row['ari_mod2_id'])) {
						$model2Ids[] = $row['ari_mod2_id'];
					}
					if (isset($row['ari_province'])) {
						$provinceIds[] = $row['ari_province'];
					}
					if (isset($row['ari_city'])) {
						$cityIds[] = $row['ari_city'];
					}
				}
				
				// 批量查询相关数据
				$brandMap = [];
				$model1Map = [];
				$model2Map = [];
				$provinceMap = [];

				// 查询车型信息
				if (!empty($model2Ids)) {
					$model2Res = $BaseDb->get('bc_model2  
					join bc_model1 on mod2_mod1_id =mod1_id
					join bc_brand on brand_id =mod2_brand_id', ['brand_id','brand_name','mod1_id', 'mod1_name','mod2_id', 'mod2_name', 'mod2_start_year', 'mod2_end_year'], 
						sprintf(" and mod2_id in (%s)", implode(',', array_unique($model2Ids))));
					if (!empty($model2Res['data'])) {
						foreach ($model2Res['data'] as $model) {
							$model2Map[$model['mod2_id']] = $model;
						}
					}
				}// 查询车系信息
				else if (!empty($model1Ids)) {
					$model1Res = $BaseDb->get('bc_model1 join bc_brand on brand_id =mod1_brand_id', ['brand_id','brand_name','mod1_id', 'mod1_name'], 
						sprintf(" and mod1_id in (%s)", implode(',', array_unique($model1Ids))));
					if (!empty($model1Res['data'])) {
						$model1Map = array_column($model1Res['data'], null, 'mod1_id');
					}
				}// 查询品牌信息
				else if (!empty($brandIds)) {
					$brandRes = $BaseDb->get('bc_brand', ['brand_id', 'brand_name'], 
						sprintf(" and brand_id in (%s)", implode(',', array_unique($brandIds))));
					if (!empty($brandRes['data'])) {
						$brandMap = array_column($brandRes['data'], null, 'brand_id');
					}
				}
				
				// 查询省市信息
				$pcIds = array_merge($provinceIds, $cityIds);
				if (!empty($pcIds)) {
					$pctres = $BaseDb->get('yp_province_city', ['pc_id', 'pc_name'], 
						sprintf(" and pc_id in (%s)", implode(',', array_unique($pcIds))));
					if (!empty($pctres['data'])) {
						$provinceMap = array_column($pctres['data'], 'pc_name', 'pc_id');
					}
				}
				
				// 处理结果数据
				foreach ($res['data'] as $row) {
					// 构建详细查询条件
					$detailWhere = $where;
					if (isset($row['mod2_brand_id'])) {
						$detailWhere .= " AND mod2_brand_id = " . $row['mod2_brand_id'];
					}
					if (isset($row['mod2_mod1_id'])) {
						$detailWhere .= " AND mod2_mod1_id = " . $row['mod2_mod1_id'];
					}
					if (isset($row['ari_mod2_id'])) {
						$detailWhere .= " AND ari_mod2_id = " . $row['ari_mod2_id'];
					}
					if (isset($row['ari_province'])) {
						$detailWhere .= " AND ari_province = " . $row['ari_province'];
					}
					if (isset($row['ari_city'])) {
						$detailWhere .= " AND ari_city = " . $row['ari_city'];
					}
					if (isset($row['ari_from'])) {
						$detailWhere .= " AND ari_from = '" . $row['ari_from'] . "'";
					}

					// 获取该分组的月份统计数据
					$detailRes = $BaseDb->get($table, ['ari_date','SUM(ari_count) as totalcount'], 
						$detailWhere.' GROUP BY ari_date ORDER BY ari_date');
					
					// 获取车型年份信息
					$years = '';
					if (isset($row['ari_mod2_id']) && isset($model2Map[$row['ari_mod2_id']])) {
						$modelInfo = $model2Map[$row['ari_mod2_id']];
						$years = (!empty($modelInfo['mod2_start_year']) || !empty($modelInfo['mod2_end_year'])) ? 
							((!empty($modelInfo['mod2_start_year']) && $modelInfo['mod2_start_year'] > 0 ? $modelInfo['mod2_start_year'] : '') . 
							'-' . 
							(!empty($modelInfo['mod2_end_year']) && $modelInfo['mod2_end_year'] > 0 ? $modelInfo['mod2_end_year'] : '')) : 
							'';
					}
					if($model2Ids){
						$mapItem = $model2Map[$row['ari_mod2_id']];
					}elseif ($model1Ids) {
						$mapItem = $model1Map[$row['mod2_mod1_id']];
					}elseif ($brandIds) {
						$mapItem = $brandMap[$row['mod2_brand_id']];
					}
					// 构建结果
					$item = [
						'brand_id' => $mapItem['brand_id'] ?? '',
						'brand' => $mapItem['brand_name'] ?? '',
						'mod1_id' => $mapItem['mod1_id'] ?? '',
						'mod1' => $mapItem['mod1_name'] ?? '',
						'mod2_id' => $mapItem['mod2_id'] ?? '',
						'mod2' => $mapItem['mod2_name'] ?? '',
						'province' => isset($row['ari_province']) ? ($provinceMap[$row['ari_province']] ?? '') : '',
						'city' => isset($row['ari_city']) ? ($provinceMap[$row['ari_city']] ?? '') : '',
						'from' => $fromNameArr[$row['ari_from']] ?? '其它',
						'years'=> $years,
						'counts' => [],
						'total' => 0
					];

					$monthsDetail = [];
					if (!empty($detailRes['data'])) {
						$monthsDetail = array_column($detailRes['data'], 'totalcount', 'ari_date');
						// 计算总销量
						$item['total'] = array_sum(array_column($detailRes['data'], 'totalcount'));
					}

					// 填充各月数据
					foreach ($months as $month) {
						$item[$month] = $monthsDetail[$month] ?? 0;
					}
				
					$item['percent'] = $item['total'] > 0 ? round(($item['total'] / $totalCounts) * 100, 2) : 0;
					$result[] = $item;
				}
			}
		}
		
		// 品牌  车系  车代   省份  城市
		$groupTypeArr = ['mod2_brand_id'=>'品牌','mod2_mod1_id'=>'车系','ari_mod2_id'=>'车代','ari_province'=>'省份','ari_city'=>'城市','ari_from'=>'来源'];
		LibTpl::Set('groupTypeArr',$groupTypeArr);
		//看看哪些列要显示
		$selectedGroup = $_GET['group']??[];
		$showCols = [
			'brand' => in_array('mod2_brand_id', $selectedGroup)||in_array('mod2_mod1_id', $selectedGroup)||in_array('ari_mod2_id', $selectedGroup),
			'mod1' => in_array('mod2_mod1_id', $selectedGroup)||in_array('ari_mod2_id', $selectedGroup),
			'mod2' => in_array('ari_mod2_id', $selectedGroup),
			'province' => in_array('ari_province', $selectedGroup),
			'city' => in_array('ari_city', $selectedGroup),
			'percent' => true,
			'from'=>in_array('ari_from',$selectedGroup),
		];
		// 设置分页
		$Page = LibPage::Show($total, $perPage);
		LibTpl::Set('Page', $Page);
		LibTpl::Set('group',$selectedGroup);	
		LibTpl::Set('selectIdArr',$selectIdArr);
		LibTpl::Set('showCols', $showCols);
		LibTpl::Set('months',$months);
		LibTpl::Set('tjArr',$result?:[]);
		LibTpl::Set('Params',$Params);
		LibTpl::Set('title', '行业报表');
		LibTpl::Put();
	}

	/**
	 * 判断group 数组和查询参数 params 来决定是否使用单维度表
	 * 1 group 包含 mod2_brand_id、mod2_mod1_id、ari_mod2_id、ari_province，ari_city 中的任意组合
	 * 2,item 表中存在的维度是 brand ,brand_model1 ,brand_model2,brand_province,province,province_city 
	 * 3,只有当 group和查询参数 params的组合符合item表的维度和查询规则，才使用单维度表
	 * 4，$params查询参数包含 brand、province_id、from
	 */
	private function shouldUseItemTable($group, $params)
	{	
		// 允许的group字段
		$allowedGroups = ['mod2_brand_id', 'mod2_mod1_id', 'ari_mod2_id', 'ari_province', 'ari_city'];
    
		// 检查group中是否包含不允许的字段
		$invalidGroups = array_diff($group, $allowedGroups);
		if (!empty($invalidGroups)) {
			return false;
		}
		
		// 检查查询条件
		$hasBrandCondition = !empty($params['brand']);
		$hasProvinceCondition = !empty($params['province_id']);
		$hasCityCondition = !empty($params['city_id']);
		$hasFromCondition = !empty($params['from']);
		// 如果有来源条件，不使用单维度表优化
		if ($hasFromCondition) {
			return false;
		}
		
		// 根据注释优化维度判断逻辑：
		
		// 1. 当group包含ari_province和ari_city时才是province_city
		if (in_array('ari_province', $group) && in_array('ari_city', $group)) {
			$otherGroups = array_diff($group, ['ari_province', 'ari_city']);
			if (empty($otherGroups)) {
				if (!$hasBrandCondition && !$hasFromCondition) {
					$condition = '';
					if ($hasProvinceCondition) {
						$condition .= sprintf(" AND ari_keyid=%d", $params['province_id']);
					}
					if ($hasCityCondition) {
						$condition .= sprintf(" AND ari_keyid2=%d", $params['city_id']);
					}
					return ['type' => 'province_city', 'condition' => $condition];
				}
			}
			return false;
		}
		
		// 2. 当group包含mod2_brand_id和ari_province时才是brand_province
		if (in_array('mod2_brand_id', $group) && in_array('ari_province', $group)) {
			$otherGroups = array_diff($group, ['mod2_brand_id', 'ari_province']);
			if (empty($otherGroups)) {
				if (!$hasCityCondition ) {
					$condition = '';
					if ($hasBrandCondition) {
						$condition .= sprintf(" AND ari_keyid=%d", $params['brand']);
					}
					if ($hasProvinceCondition) {
						$condition .= sprintf(" AND ari_keyid2=%d", $params['province_id']);
					}
					return ['type' => 'brand_province', 'condition' => $condition];
				}
			}
			return false;
		}
		
		// 3. 当group包含mod2_brand_id、mod2_mod1_id、ari_mod2_id三个任意组合时，
		// 优先级分别是ari_mod2_id > mod2_mod1_id > mod2_brand_id
		$mainGroups = array_intersect($group, ['mod2_brand_id', 'mod2_mod1_id', 'ari_mod2_id']);
		if (!empty($mainGroups)  && count($mainGroups) > 1) {
			$otherGroups = array_diff($group, ['mod2_brand_id', 'mod2_mod1_id', 'ari_mod2_id']);
			if (empty($otherGroups)) {
				// 检查是否有冲突的查询条件
				if ($hasProvinceCondition || $hasCityCondition ) {
					return false;
				}
				
				// 按优先级判断类型
				if (in_array('ari_mod2_id', $group)) {
					return ['type' => 'brand_model2', 'condition' => $hasBrandCondition ? sprintf(" AND ari_keyid=%d", $params['brand']) : ''];
				}
				
				if (in_array('mod2_mod1_id', $group)) {
					return ['type' => 'brand_model1', 'condition' => $hasBrandCondition ? sprintf(" AND ari_keyid=%d", $params['brand']) : ''];
				}
				
				if (in_array('mod2_brand_id', $group)) {
					return ['type' => 'brand', 'condition' => $hasBrandCondition ? sprintf(" AND ari_keyid=%d", $params['brand']) : ''];
				}
			}
			return false;
		}
		
		// 4. 单个维度情况
		if (count($group) == 1) {
			$groupField = $group[0];
			
			switch ($groupField) {
				case 'ari_province':
					// province类型不能有品牌、城市、来源条件
					if (!$hasBrandCondition && !$hasCityCondition && !$hasFromCondition) {
						$condition = $hasProvinceCondition ? sprintf(" AND ari_keyid=%d", $params['province_id']) : '';
						return ['type' => 'province', 'condition' => $condition];
					}
					return false;
					
				case 'ari_city':
					if (!$hasBrandCondition && !$hasFromCondition) {
						$condition = $hasProvinceCondition ? sprintf(" AND ari_keyid=%d AND ari_keyid2!=0", $params['province_id']) : ' AND ari_keyid2!=0';
						return ['type' => 'province_city', 'condition' => $condition];
					}
					return false;
				case 'mod2_brand_id':
					// brand类型可以有省份条件，这时使用brand_province类型
					if (!$hasCityCondition) {
						$condition = '';
						if ($hasBrandCondition) {
							$condition .= sprintf(" AND ari_keyid=%d", $params['brand']);
						}
						if ($hasProvinceCondition) {
							$condition .= sprintf(" AND ari_keyid2=%d", $params['province_id']);
							// 当有省份条件时，使用brand_province类型
							return ['type' => 'brand_province', 'condition' => $condition];
						}
						return ['type' => 'brand', 'condition' => $condition];
					}
					return false;
					
				case 'mod2_mod1_id':
					// brand_model1类型不能有省市条件
					if (!$hasProvinceCondition && !$hasCityCondition) {
						$condition = $hasBrandCondition ? sprintf(" AND ari_keyid=%d", $params['brand']) : '';
						return ['type' => 'brand_model1', 'condition' => $condition];
					}
					return false;
					
				case 'ari_mod2_id':
						// brand_model2类型不能有省市条件
						if (!$hasProvinceCondition && !$hasCityCondition) {
							$condition = $hasBrandCondition ? sprintf(" AND ari_keyid=%d", $params['brand']) : '';
							return ['type' => 'brand_model2', 'condition' => $condition];
						}
						return false;
			}
		}
		
		// 其他情况不使用优化
		return false;
	}

	/**
	 * @method 搜素相关字段
	 * @author zhengweihua 
	 * @copyright 2025-09-16
	 */
	public function getIndustrySearch()
	{
		$Params= mvc::$URL_PARAMS;
		if(empty($Params['type'])) LibFc::ReturnJson(false,'参数错误');

		$BaseDb = new BaseDb(mvc::$cfg['DB']['API_TJ']);

		$keyword = LibFc::Escape($Params['keyword']);

		$selectedIds = isset($Params['selected_ids']) && !empty($Params['selected_ids']) ? explode(',', $Params['selected_ids']) : [];


		switch ($Params['type']) {
			case 'brand':
				$where = " order by brand_initial ASC";
				if($Params['keyword']){
					$where = sprintf(" and brand_name like '%%%s%%' order by brand_initial ASC",$keyword);
				}
				$res = $BaseDb->get('bc_brand',['brand_id as value','brand_name as name'],$where);	

				// 如果有 selected_ids，则补充缺失的品牌
				if (!empty($selectedIds)) {
					$existingIds = array_column($res['data'], 'value');
					$missingIds = array_diff($selectedIds, $existingIds);
	
					if (!empty($missingIds)) {
						$missingRes = $BaseDb->get('bc_brand', ['brand_id as value', 'brand_name as name'], 
							sprintf(" and brand_id in (%s)", implode(',', $missingIds)));
						$res['data'] = array_merge($missingRes['data'],$res['data']);
					}
				}
				break;
			case 'model1':
				$where = "";
				$order = " order by mod1_name ASC limit 20";
				if($Params['keyword']){
					$where .= sprintf(" and mod1_name like '%%%s%%' ",$keyword);
				}
				if($Params['brand_id']){
					$where .= sprintf(" and mod1_brand_id in (%s) ",implode(',',explode(',',$Params['brand_id'])));
				}
				
				$res = $BaseDb->get('bc_model1',['mod1_id as value','mod1_name as name'],sprintf(" %s %s",$where,$order));
				// 如果有 selected_ids，则补充缺失的品牌
				if (!empty($selectedIds)) {
					$existingIds = array_column($res['data'], 'value');
					$missingIds = array_diff($selectedIds, $existingIds);
	
					if (!empty($missingIds)) {
						$missingRes = $BaseDb->get('bc_model1', ['mod1_id as value','mod1_name as name'], 
							sprintf(" and mod1_id in (%s)", implode(',', $missingIds)));
						$res['data'] = array_merge($missingRes['data'],$res['data']);
					}
				}
				break;
			case 'model2':
				$where = "";
				$order = " order by mod2_name ASC limit 20";
				if($Params['keyword']){
					$where .= sprintf(" and mod2_name like '%%%s%%'",$keyword);
				}
				if($Params['mod1_id']){
					$where .= sprintf(" and mod2_mod1_id in (%s) ",implode(',',explode(',',$Params['mod1_id'])));
				}
				$res = $BaseDb->get('bc_model2',['mod2_id as value','mod2_name as name'],sprintf(" %s %s",$where,$order));	
				// 如果有 selected_ids，则补充缺失的品牌
				if (!empty($selectedIds)) {
					$existingIds = array_column($res['data'], 'value');
					$missingIds = array_diff($selectedIds, $existingIds);
	
					if (!empty($missingIds)) {
						$missingRes = $BaseDb->get('bc_model2', ['mod2_id as value','mod2_name as name'], 
							sprintf(" and mod2_id in (%s)", implode(',', $missingIds)));
						$res['data'] = array_merge($missingRes['data'],$res['data']);
					}
				}
				break;
			case 'province':
				$Ypw = new YpwBase();
				$where = '';
				$order = ' and pc_pid=0 order by pc_id,pc_seq';
				if($Params['keyword']){
					$where = sprintf(" and pc_name like '%%%s%%' ",$keyword);
				}
				$res = $Ypw->Get('yp_province_city', ['pc_id as value','pc_name as name'],sprintf(" %s %s",$where,$order));
				// 补充选中的省份
				if (!empty($selectedIds)) {
					$existingIds = array_column($res['data'], 'value');
					$missingIds = array_diff($selectedIds, $existingIds);
	
					if (!empty($missingIds)) {
						$missingRes = $Ypw->get('yp_province_city', ['pc_id as value', 'pc_name as name'], 
							sprintf(" and pc_id in (%s)", implode(',', $missingIds)));
						$res['data'] = array_merge( $missingRes['data'],$res['data']);
					}
				}
				break;
			case 'city':
				$Ypw = new YpwBase();
				$where = '';
				$order = ' and a.pc_pid=0 order by a.pc_seq,a.pc_name limit 20';
				if($Params['keyword']){
					$where = sprintf(" and b.pc_name like '%%%s%%'",$keyword);
				}
				
				$table  = 'yp_province_city as a 
				join yp_province_city as b on a.pc_id=b.pc_pid';
				$res = $Ypw->Get($table, ['b.pc_id as value','b.pc_name as name'], sprintf(" %s %s",$where,$order));
				 // 补充选中的城市
				if (!empty($selectedIds)) {
					$existingIds = array_column($res['data'], 'value');
					$missingIds = array_diff($selectedIds, $existingIds);
	
					if (!empty($missingIds)) {
						$missingRes = $Ypw->get('yp_province_city', ['pc_id as value', 'pc_name as name'], 
							sprintf(" and pc_id in (%s)", implode(',', $missingIds)));
						$res['data'] = array_merge($missingRes['data'],$res['data']);
					}
				}	
				break;
			case 'from':
				$res = ['status'=>true,'data'=>[['value'=>'PJL','name'=>'跑街令'],['value'=>'YP','name'=>'宜配'],['value'=>'SUPER','name'=>'目录']]];
				break;
		}

		LibFc::ajaxJsonEncode($res);
	}

	/**
	 * @method 企业微信客服api方法
	 * @author hongzhang
	 * @copyright 2025-10-20
	 */
	private function weworkApi($uri, $postArr = [], &$wcof){
		try{
			$baseUrl = 'https://qyapi.weixin.qq.com/cgi-bin/';
			$url = $baseUrl.$uri;
			if(stripos($uri, 'gettoken') === false){
				$apitoken = $this->getApiToken($wcof);
				$url .= stripos($url, '?') ? '&access_token='.$apitoken: '?access_token='.$apitoken;
			}
			$LibHttp = new LibHttp();
			if($postArr){
				$LibHttp->httpheader = ['Content-Type: application/json'];
				$postArr = json_encode($postArr, JSON_UNESCAPED_UNICODE);
			}
			$html = $LibHttp->fetch($url, $postArr);
			if(stripos($html, 'errcode') !== false){
				$htmlArr = json_decode($html, true);
				if($htmlArr['errcode'] == 0){
					return $htmlArr;
				}else if($htmlArr['errcode'] == 40014){
					//access_token无效重试一次
					$wcof['wrt_access_out'] = 0;
					$wcof['wrt_access'] = '';
					return $this->weworkApi($uri, $postArr, $wcof);
				}else{
					return $html;
				}
			}else{
				return $html;
			}
		}catch(Exception $e) {
			echo $e->getMessage();	
			exit;
		}
	}

	/**
	 * @method 获取客服token 含缓存
	 * @author hongzhang
	 * @copyright 2025-10-20
	 */
	private function getApiToken(&$wcof){
		$now = time();
		if($wcof['wrt_access_out'] > $now && $wcof['wrt_access']){
			$apitoken = $wcof['wrt_access'];
		}else{
			$arr = $this->weworkApi('gettoken?corpid='.$wcof['corpid'].'&corpsecret='.$wcof['kf_secret'],[],$wcof);
			$apitoken = $arr['access_token'];
			$set = [
				'wrt_access'=>$apitoken,
				'wrt_access_out'=>$now + $arr['expires_in'] - 600,
			];
			$wcof['wrt_access_out'] = $set['wrt_access_out'];
			$wcof['wrt_access'] = $set['wrt_access'];
			// $B2cBase->set('wx_robot_token', $set, sprintf(" and wrt_id=%d", $wcof['wrt_id']));
		}
		return $apitoken;
	}

	/**
	 * @method 添加企微客服
	 * @author hongzhang
	 * @copyright 2025-10-20
	 */
	public function addWeworkKf(){
		LibRule::Check('AP01');
		$Params = mvc::$URL_PARAMS;
		// 合并GET和POST参数
		$allParams = array_merge($Params, $_POST);
		$kf_name = $allParams['kf_name'] ?? '';
		$media_id = $allParams['media_id'] ?? '';
		
		if(empty($kf_name)){
			LibFc::ajaxJsonEncode(['errcode' => 40001, 'errmsg' => 'missing kf_name parameter']);
			return;
		}
		if(empty($media_id)){
			LibFc::ajaxJsonEncode(['errcode' => 40002, 'errmsg' => 'missing media_id parameter']);
			return;
		}
		
		// 获取企业微信配置信息
		$wrt_id = isset($Params['wrt_id']) ? (int)$Params['wrt_id'] : 0;
		if (empty($wrt_id)) {
			LibFc::ajaxJsonEncode(['errcode' => 40009, 'errmsg' => 'missing wrt_id parameter']);
			return;
		}
		$wcof = $this->getWcof($wrt_id);
		if (empty($wcof)) {
			LibFc::ajaxJsonEncode(['errcode' => 40010, 'errmsg' => 'robot token config not found']);
			return;
		}
		$res = $this->weworkApi('kf/account/add',[
			'name'=>$kf_name,
			'media_id'=>$media_id,
		],$wcof);
		if($res['errcode'] == 0){
			LibFc::ajaxJsonEncode(['errcode' => 0, 'errmsg' => 'success']);
			return;
		}else{
			LibFc::ajaxJsonEncode(['errcode' => $res['errcode'], 'errmsg' => $res['errmsg']]);
			return;
		}
	}

	/**
	 * @method 企业微信临时素材上传代理接口
	 * @author hongzhang
	 * @copyright 2025/10/21
	 */
	public function uploadWxMedia(){
		LibRule::Check('AP01');
		$Params = mvc::$URL_PARAMS;
		try {
			// 检查是否有文件上传
			if (!isset($_FILES['media']) || $_FILES['media']['error'] !== UPLOAD_ERR_OK) {
				LibFc::ajaxJsonEncode(['errcode' => 40004, 'errmsg' => 'empty media data']);
				return;
			}
			
			$file = $_FILES['media'];
			
			// 验证文件类型和大小
			$allowedTypes = ['image/png', 'image/jpg', 'image/jpeg'];
			if (!in_array($file['type'], $allowedTypes)) {
				LibFc::ajaxJsonEncode(['errcode' => 40005, 'errmsg' => 'unsupported media type']);
				return;
			}
			
			// 文件大小限制 2MB
			if ($file['size'] > 2 * 1024 * 1024) {
				LibFc::ajaxJsonEncode(['errcode' => 40006, 'errmsg' => 'media size out of limit']);
				return;
			}
			
			// 获取企业微信配置信息
			$wrt_id = isset($Params['wrt_id']) ? (int)$Params['wrt_id'] : 0;
			if (empty($wrt_id)) {
				LibFc::ajaxJsonEncode(['errcode' => 40009, 'errmsg' => 'missing wrt_id parameter']);
				return;
			}
			
			// 获取企业微信配置信息
			$wcof = $this->getWcof($wrt_id);
			if (empty($wcof)) {
				LibFc::ajaxJsonEncode(['errcode' => 40010, 'errmsg' => 'robot token config not found']);
				return;
			}
			
			// 获取access_token
			$accessToken = $this->getApiToken($wcof);
			if (empty($accessToken)) {
				LibFc::ajaxJsonEncode(['errcode' => 40001, 'errmsg' => 'failed to get access_token']);
				return;
			}
			
			// 构建企业微信上传请求
			$url = 'https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=' . $accessToken . '&type=image';
			
			// 使用原生cURL进行文件上传
			$curl = curl_init();
			curl_setopt($curl, CURLOPT_URL, $url);
			curl_setopt($curl, CURLOPT_POST, true);
			curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($curl, CURLOPT_TIMEOUT, 30);
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
			
			// 创建CURLFile对象用于multipart/form-data上传
			$cfile = new CURLFile($file['tmp_name'], $file['type'], $file['name']);
			$postData = ['media' => $cfile];
			curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
			
			// 记录调试信息
			error_log("WeChat Upload Debug - URL: $url, File: {$file['name']}, Size: {$file['size']}, Type: {$file['type']}");
			
			// 发送请求
			$response = curl_exec($curl);
			$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
			$curlError = curl_error($curl);
			curl_close($curl);
			
			// 记录响应调试信息
			error_log("WeChat Upload Debug - HTTP Code: $httpCode, Response: $response, cURL Error: $curlError");
			
			if (empty($response) || !empty($curlError)) {
				LibFc::ajaxJsonEncode(['errcode' => 40007, 'errmsg' => 'request failed: ' . ($curlError ?: 'empty response')]);
				return;
			}
			
			// 解析企业微信的响应
			$result = json_decode($response, true);
			if (json_last_error() !== JSON_ERROR_NONE) {
				LibFc::ajaxJsonEncode(['errcode' => 40008, 'errmsg' => 'invalid response format: ' . $response]);
				return;
			}
			
			// 直接返回企业微信的响应
			LibFc::ajaxJsonEncode($result);
			
		} catch (Exception $e) {
			error_log("WeChat Upload Exception: " . $e->getMessage());
			LibFc::ajaxJsonEncode(['errcode' => 40012, 'errmsg' => 'system error: ' . $e->getMessage()]);
		}
	}

	/**
	 * @method 编辑企微客服
	 * @author hongzhang
	 * @copyright 2025-10-21
	 */
	public function editWeworkKf(){
		LibRule::Check('AP01');
		$Params = mvc::$URL_PARAMS;
		// 合并GET和POST参数
		$allParams = array_merge($Params, $_POST);
		$kf_name = $allParams['kf_name'] ?? '';
		$media_id = $allParams['media_id'] ?? '';
		$open_kfid = $allParams['open_kfid'] ?? '';

		if(empty($open_kfid)){
			LibFc::ajaxJsonEncode(['errcode' => 40003, 'errmsg' => 'missing open_kfid parameter']);
			return;
		}
		// 获取企业微信配置信息
		$wrt_id = isset($Params['wrt_id']) ? (int)$Params['wrt_id'] : 0;
		if (empty($wrt_id)) {
			LibFc::ajaxJsonEncode(['errcode' => 40009, 'errmsg' => 'missing wrt_id parameter']);
			return;
		}
		$wcof = $this->getWcof($wrt_id);
		if (empty($wcof)) {
			LibFc::ajaxJsonEncode(['errcode' => 40010, 'errmsg' => 'robot token config not found']);
			return;
		}
		$postArr = ['open_kfid'=>$open_kfid];
		if(!empty($kf_name)){
			$postArr['name'] = $kf_name;
		}
		if(!empty($media_id)){
			$postArr['media_id'] = $media_id;
		}

		$res = $this->weworkApi('kf/account/update',$postArr,$wcof);
		if($res['errcode'] == 0){
			LibFc::ajaxJsonEncode(['errcode' => 0, 'errmsg' => 'success']);
			return;
		}else{
			LibFc::ajaxJsonEncode(['errcode' => $res['errcode'], 'errmsg' => $res['errmsg']]);
			return;
		}
	}

	/**
	 * @method 删除企微客服
	 * @author hongzhang
	 * @copyright 2025-10-21
	 */
	public function delWeworkKf(){
		LibRule::Check('AP01');
		$Params = mvc::$URL_PARAMS;
		$allParams = array_merge($Params, $_POST);
		$open_kfid = $allParams['open_kfid'] ?? '';
		if(empty($open_kfid)){
			LibFc::ajaxJsonEncode(['errcode' => 40003, 'errmsg' => 'missing open_kfid parameter']);
			return;
		}
		// 获取企业微信配置信息
		$wrt_id = isset($Params['wrt_id']) ? (int)$Params['wrt_id'] : 0;
		if (empty($wrt_id)) {
			LibFc::ajaxJsonEncode(['errcode' => 40009, 'errmsg' => 'missing wrt_id parameter']);
			return;
		}
		$wcof = $this->getWcof($wrt_id);
		if (empty($wcof)) {
			LibFc::ajaxJsonEncode(['errcode' => 40010, 'errmsg' => 'robot token config not found']);
			return;
		}
		$res = $this->weworkApi('kf/account/del',[
			'open_kfid'=>$open_kfid,
		],$wcof);
		if($res['errcode'] == 0){
			LibFc::ajaxJsonEncode(['errcode' => 0, 'errmsg' => 'success']);
			return;
		}else{
			LibFc::ajaxJsonEncode(['errcode' => $res['errcode'], 'errmsg' => $res['errmsg']]);
			return;
		}
	}

	/**
	 * @method 从数据库获取企业微信配置信息
	 * @author hongzhang
	 * @copyright 2025/10/21
	 */
	private function getWcof($wrt_id){
		$B2cWxRobot = new B2cWxRobot();
		$wcofRes = $B2cWxRobot->get('wx_robot_token', ['*'], sprintf(" AND wrt_id=%d", $wrt_id), true);
		if (!$wcofRes['data']) {
			return '';
		}
		$wxkf_config = json_decode($wcofRes['data']['wrt_kfcfg'], true);
		$wcof = [
			'corpid'=>$wcofRes['data']['wrt_wxid'],
			'kf_secret'=>$wxkf_config['kf_secret'],
		];
		return $wcof;
	}

	/**
	 * @method 获取客服账号链接
	 * @author hongzhang
	 * @copyright 2025/10/27
	 */
	public function getKfLink(){
		LibRule::Check('AP01');
		$Params = mvc::$URL_PARAMS;
		// 合并GET和POST参数
		$allParams = array_merge($Params, $_POST);
		$open_kfid = $allParams['open_kfid'] ?? '';
		if(empty($open_kfid)){
			LibFc::ajaxJsonEncode(['errcode' => 40003, 'errmsg' => 'missing open_kfid parameter']);
			return;
		}
		// 获取企业微信配置信息
		$wrt_id = isset($Params['wrt_id']) ? (int)$Params['wrt_id'] : 0;
		if (empty($wrt_id)) {
			LibFc::ajaxJsonEncode(['errcode' => 40009, 'errmsg' => 'missing wrt_id parameter']);
			return;
		}
		$wcof = $this->getWcof($wrt_id);
		if (empty($wcof)) {
			LibFc::ajaxJsonEncode(['errcode' => 40010, 'errmsg' => 'robot token config not found']);
			return;
		}
		$scene = substr(str_replace(['+', '/', '='], ['_', '-', ''], base64_encode(random_bytes(24))), 0, 16);
		$res = $this->weworkApi('kf/add_contact_way',[
			'open_kfid'=>$open_kfid,
			'scene'=>$scene,
		],$wcof);
		LibFc::ajaxJsonEncode($res);
	}

	/**
	 * @method 账号的通讯录列表统计
	 * @author hongzhang
	 * @copyright 2026/05/26
	 */
	public function wxTxlList(){
		$userTxlList = [];
		$B2cBase = new B2cBase();
		$res = $B2cBase->get('
		wx_user wu1
		left join (
			select wua_mwu_id,count(wua_id) as friends_done_count
			from wx_user_address
			where wua_ustatus = 2
			group by wua_mwu_id
		) wua1 on wu1.wu_id = wua1.wua_mwu_id
		left join (
			select 
				wua_mwu_id,
				count(wua_id) as friends_total_count,
				sum(case when wu_uid > 0 then 1 else 0 end) as friends_yp_count
			from wx_user_address
			left join wx_user on wua_wu_id = wu_id
			group by wua_mwu_id
		) wua2 on wu1.wu_id = wua2.wua_mwu_id
		left join (
			select
				tmh_from_wu_id,
				count(tmh_id) as ts_total_count,
				sum(case when tmh_reply_wum_id > 0 then 1 else 0 end) as ts_reply_count
			from yp_crm.ts_msg_history
			group by tmh_from_wu_id
		) ts on wu1.wu_id = ts.tmh_from_wu_id
		left join wx_robot_token wrt on wu1.wu_wxid = wrt.wrt_wxid',
		[
			'wu1.wu_realname',
			'wu1.wu_wxid',
			'wu1.wu_weixin',
			'wu1.wu_nickname',
			'wu1.wu_headimg',
			'wu1.wu_mobile',
			'wu1.wu_address_utime2',
			'wrt.wrt_loginstatus',
			'ifnull(wua1.friends_done_count,0) as friends_done_count',
			'ifnull(wua2.friends_total_count,0) as friends_total_count',
			'ifnull(wua2.friends_yp_count,0) as friends_yp_count',
			'ifnull(ts.ts_total_count,0) as ts_total_count',
			'ifnull(ts.ts_reply_count,0) as ts_reply_count',
			'wu_address_status'
		],sprintf('AND wu1.wu_isaccout = 1'));
		$userTxlList = $res['data'];
		LibTpl::Set('title','通讯录');
		LibTpl::Set('userTxlList',$userTxlList);
		LibTpl::Put();
	}
}
