<?php
class indexAction extends baseAction
{
    /**
     * @method 管理中心
     * @author soul 2017/6/16
     */
    function index()
    {
		$B2cProduct = new B2cProduct();
		$res = $B2cProduct->get('sh_modtype', ['smt_code', 'smt_name'], ' order by smt_seq');
		LibTpl::Set('modTypeArr', array_column($res['data'], null, 'smt_code'));

        $show = 1;
        // 最近1个月内是否有VIN记录
        $where  = sprintf(" and suv_shop_id = %d and suv_date > %d group by suv_from",(int)$_SESSION['_shopid'], date('Ymd', strtotime('-1 month')));
        $OthBase = new OthBase();
        $vinTjRes = $OthBase->get('tj_shop_vin',['suv_from'],$where);
        if(empty($vinTjRes['data'])){
            $show = 0;  
        }
        $vinTjArr =  array_column($vinTjRes['data'],'suv_from');
        if(count($vinTjArr) == 1 && $vinTjArr[0] == 'superpjl')
        {
            $show = 0;
        }
        LibTpl::Set('show',$show);
        //查是否存在文章分类
        $OthBase = new OthBase();
        $res = $OthBase->get('cms_category',['count(*) as counts'],sprintf(" AND cat_shop_id=%d",(int)$_SESSION['_shopid']),true);
        LibTpl::Set('showArticle',$res['data']['counts']);


        //机器人
        $B2cBase = new B2cBase();
        $res = $B2cBase->get('wx_robot',["*"],sprintf(" and wr_totype!='pjlshop' and wr_uid = %d order by wr_type asc",$_SESSION['_shopid']));
        if($res['data']){
            $cntarr = [];
            foreach ($res['data'] as $key => $val) {
                if (isset($cntarr[$val['wr_type']])) {
                    $cntarr[$val['wr_type']] += 1;
                } else {
                    $cntarr[$val['wr_type']] = 1;
                }
            }
            $typeArr = ['wxgzh'=>'微信公众号','wxgr'=>'微信群聊','wxkf'=>'企微客服'];
            // 为 wr_type 添加序号（如果数量大于 1）
            $wrTypeCounter = [];
            $lastWxgrIndex = 0;
            foreach ($res['data'] as $key => $val) {
                $wrType = $val['wr_type'];
                if ($cntarr[$wrType] > 1) {
                    if (!isset($wrTypeCounter[$wrType])) {
                        $wrTypeCounter[$wrType] = 1;
                    }
                   
                    $res['data'][$key]['name'] = $typeArr[$wrType] . ' ' . $wrTypeCounter[$wrType];
                    $wrTypeCounter[$wrType]++;
                     // 如果是微信群聊，存储到 wxgrData 数组
                    if ($wrType == 'wxgr') {
                        $lastWxgrIndex = $key;
                    }
                }else{
                    $res['data'][$key]['name'] = $typeArr[$wrType];
                }
            }
        }
        // 如果微信群聊数目大于1，则添加一个微信总群聊的链接
        if (isset($cntarr['wxgr']) && $cntarr['wxgr'] > 1) {
            $wxgrData[] = [
                'type' => 'totalGroup', // 用于标识总群聊
                'name' => '微信总群聊'
            ];
             // 如果找到 wxgr 类型的最后一个位置，则插入 wxgrData
            if ($lastWxgrIndex !== null) {
                array_splice($res['data'], $lastWxgrIndex + 1, 0, $wxgrData);
            }
        }
       

        LibTpl::Set('wxRobotArr',$res['data']);

        LibTpl::Set('title', $this->supData['ssu_name'] . '-品牌目录');
        LibTpl::Put();
    }

    /**
     * @method 管理中心
     * @author soul 2017/6/16
     */
    function main()
    {
        $B2cPart = new B2cPart();
       

        $totalPro = 0;
        $itemWhere = sprintf(' and pro_shop_id=%d', $_SESSION['_shopid']);

        
        $res = $B2cPart->getShopSuperSPart($_SESSION['_shopid']);
        if($res['data'])
        {
            $allSupPartArr = array_column($res['data'], null, 'id');
            $spartIdArr = array_keys($allSupPartArr);
        }else{
            $shopId = $_SESSION['_shopid'];
            $where = sprintf(' and part_id in(select pro_part_id from bc_product where pro_shop_id=%d)',$shopId);
            $where .= ' order by pt_seq, part_initial ';
            $res = $B2cPart->get('bc_part 
            join bc_part_tree on part_id = pt_part_id and pt_ismain=1 
            left join bc_part_small on part_id = pas_part_id ', ['part_id', 'part_name','pas_id','pas_name'], $where);
            $allSupPartArr = [];
            $spartIdArr = [];
            foreach ($res['data'] as $key => $v) {
                if(empty($allSupPartArr[$v['part_id'].'_0']))
                {
                    $t = $v;
                    $t['id'] = $t['part_id'].'_0';
                    $t['name'] = $t['part_name'];
                    $t['pas_id'] = 0;
                    $t['pas_name'] = '';
                    $allSupPartArr[$t['id']] = $t;
                }
                $v['id'] = $v['part_id'].'_'.((int) $v['pas_id']);
                $v['name'] = empty($v['pas_name'])? $v['part_name']: $v['pas_name'];
                $allSupPartArr[$v['id']] = $v;
            }
            $spartIdArr = array_keys($allSupPartArr);
        }

        $comtable =  'bc_product';
        $twhere = $itemWhere . sprintf(" and concat(pro_part_id, '_', pro_pas_id) in ('%s') group by pro_part_id, pro_pas_id order by count(distinct pro_id) desc", implode("','", $spartIdArr));
        $res = $B2cPart->get($comtable, ["count(distinct pro_id) as pro_count, pro_part_id, pro_pas_id, concat(pro_part_id, '_', pro_pas_id) spartid"], $twhere);
        $supPartArr = [];
        
        foreach ($res['data'] as $v) 
        {   
            $supPartArr[$v['pro_part_id'].'_0']['pro_count'] +=$v['pro_count'];
            if(!isset($supPartArr[$v['spartid']])){
                $supPartArr[$v['spartid']] = $v;  
            } 
            $totalPro += $v['pro_count'];
        }
        $sort = [];
        foreach($allSupPartArr as $id=>&$v)
        {
            $sort[] =empty($supPartArr[$id]) ?0: $supPartArr[$id]['pro_count']; 
            $v['pro_count'] = empty($supPartArr[$id]) ?0: $supPartArr[$id]['pro_count'];
        }
        unset($v);

        array_multisort($sort,SORT_DESC,$allSupPartArr);
        $arr = [];
        foreach ($allSupPartArr as $key => $val) {
            if(!isset($arr[$val['part_id']])){
                $arr[$val['part_id']] = $val;
            }
            if(!empty($val['pas_id'])){
                $arr[$val['part_id']]['son'][] = $val;
            }
        }
        array_unshift($arr,['part_name'=>'总配件数','pro_count'=>$totalPro]);
        LibTpl::Set('partArr',$arr);
        $chckArr = [];

        //无图
        $twhere = $itemWhere . sprintf(" and pro_id not in (
			select distinct pp_pro_id from bc_product_pic join bc_product on pp_pro_id=pro_id and pro_shop_id=%d
		)", $_SESSION['_shopid']);
        $res = $B2cPart->get($comtable, ['count(distinct pro_id) as count'], $twhere, true);
        $chckArr['noimg'] = $res['data']['count'];

        //无参数
        $twhere = $itemWhere . sprintf(" and pro_id not in (
			select distinct ppf_pro_id from bc_product_param_float join bc_product on ppf_pro_id=pro_id and pro_shop_id=%d
		) and pro_id not in (
			select distinct pps_pro_id from bc_product_param_string join bc_product on pps_pro_id=pro_id and pro_shop_id=%d
		) and pro_id not in ( 
            select distinct prpv_pro_id from bc_product_para_val join bc_product on prpv_pro_id =pro_id and pro_shop_id=%d and prpv_value!=''
         ) ", $_SESSION['_shopid'], $_SESSION['_shopid'],$_SESSION['_shopid']);
        $res = $B2cPart->get($comtable, ['count(distinct pro_id) as count'], $twhere, true);
        $chckArr['nopara'] = $res['data']['count'];

        //无车型
        $twhere = $itemWhere . sprintf(" and pro_id not in (
			select distinct pml3_pro_id from bc_product_model3_link join bc_product on pml3_pro_id=pro_id and pro_shop_id=%d
		)", $_SESSION['_shopid']);
        $res = $B2cPart->get($comtable, ['count(distinct pro_id) as count'], $twhere, true);
        $chckArr['nomod3'] = $res['data']['count'];
        
        //车型智能匹配
        if($this->supData['shop_smt_code']=='all'||!$this->supData['shop_smt_code'])
        {
            $table = "bc_product_model_auto
            INNER JOIN (  
                SELECT `pma_pro_id` as pro_id, MAX(`pma_version`) as max_version  
                FROM `bc_product_model_auto` where pma_shop_id={$_SESSION['_shopid']}
                GROUP BY `pma_pro_id`  
            ) as sub ON pma_pro_id = sub.pro_id AND pma_version = sub.max_version";
            
            $res = $B2cPart->get($table,['count(*) as counts'],sprintf(" AND pma_shop_id=%d AND pma_status=0",$_SESSION['_shopid']),true); 
            $chckArr['autosearch'] = $res['data']['counts'];
        }

        //已失效车型关联的产品
        $ComModel = new ComModel();
        $table = sprintf('ypb2c.bc_product 
        join ypb2c.bc_product_model3_link on pro_id = pml3_pro_id and pro_shop_id=%d
        left join bc_model3 on mod3_id = pml3_mod3_id',$_SESSION['_shopid']);
        $res = $ComModel->get($table,['count(distinct pro_id) as counts'],'AND mod3_id IS NULL',true);
        $chckArr['invaildmod'] = $res['data']['counts']; 

        //最近30天车型
        $itemWhere = sprintf(' and pro_shop_id=%d', $_SESSION['_shopid']);
        $where = sprintf(" AND m3_atime >=%d", strtotime('-30days'));
        $table = 'bc_product_model3_link join bc_product on pro_id = pml3_pro_id';
        $twhere = $itemWhere . sprintf(" and concat(pro_part_id, '_', pro_pas_id) in ('%s') group by pml3_mod3_id, pro_part_id, pro_pas_id having count(*) >= %d", implode("','", $spartIdArr), count($spartIdArr));
        $res = $B2cPart->get($table, ['distinct pml3_mod3_id'], $twhere);
        if (!empty($res['data'])) {
            $where .= sprintf(" AND m3_id not in (%s)", implode(',', array_column($res['data'], 'pml3_mod3_id')));
        }
        $B2cShop = new B2cShop();
        $brandRes = $B2cShop->getShopBrand($_SESSION['_shopid']);
        $lWhere = '';
        if($brandRes['data']){
            $lWhere  = sprintf(" AND b_id in (%s)",implode(',',$brandRes['data']));
        }
        $YpcModel = new YpcModel();
        $res = $YpcModel->GetModel(3, ['*'], $where .$lWhere.' order by m3_atime desc limit 10');
        $newModelArr = $res['data'];

        $where = sprintf(" and art_status = 'pass' and arc_cat_id = %d order by art_add_time desc limit 10 ", $this->ypNoticeCatId);
        $res = $B2cPart->get('cm_article join cm_article_category on arc_art_id=art_id', ['art_id, art_title, art_add_time'], $where);
        //纠错统计
        $errorCorrection = (new OthBase())->get('ot_jiucuo ',['jc_id','jc_status'],sprintf(" and jc_shop_id = %d ", $_SESSION['_shopid']),false);
        $correction = [];
        $counts = count($errorCorrection['data']);
        if($counts > 0)
        {
            foreach ($errorCorrection['data'] as $value){
                $correction[$value['jc_status']] += 1;
            }
            $correction['total'] = $counts;
        }else{
            $correction = ['total' => 0,'0' => 0,'1' => 0];
        }
        //配件管理
        //计算出售中的宝贝
        $B2cBase =  new B2cBase();
		$sale = $B2cBase->get('bc_product',['count(*) count','pro_status'],sprintf('and pro_shop_id=%d and (pro_status=1 or pro_status=0) group by pro_status',$_SESSION['_shopid']));
		$sale = array_column($sale['data'],'count','pro_status');
		LibTpl::Set('onSale',$sale['1']);
		//计算等待上架的宝贝
		LibTpl::Set('notOnSale',$sale['0']);

		//计算待付款的订单
		$pay = $B2cBase->get('or_order',['count(*) count','ord_status'],sprintf("and ord_shop_id=%d and (ord_status='creat' or ord_status='paied') and ord_seller_delete=0 and ord_user_delete=0 group by ord_status",$_SESSION['_shopid']));
		$pay = array_column($pay['data'],'count','ord_status');
		LibTpl::Set('waitPay',$pay['creat']);
		//计算待发货的订单
		LibTpl::Set('waitSend',$pay['paied']);

		//计算售后中的订单
		$refund = $B2cBase->get('or_order ',['count(*) count'],sprintf("and ord_id in(select orp_ord_id from or_order left join or_order_product on ord_id=orp_ord_id where orp_refund_status in ('wait','confirm','refuse','refundpro') and ord_shop_id=%d and ord_status != 'cancel') ",$_SESSION['_shopid']),true);
		LibTpl::Set('refund',$refund['data']['count']);

        //资源包信息
        $MainBase =  new MainBase();
        $field = ["SUM(az_count_has) as countHas,az_type,SUM(az_count) as az_count"];
        $where = sprintf(" and az_uid = %d and az_style='vin' and az_status=1 and az_btime<= %d and az_etime>=%d group by az_type order by az_type",$_SESSION['_userid'],time(),time());
        $vinzybinfo = $MainBase->get('api_zyb', $field,$where);
        //店铺基础vin日查询次数
        $shopVin =$B2cBase->get('sh_shop',['shop_vin_count'],sprintf("and shop_uid=%d",$_SESSION['_userid']),true);
        $where = sprintf(" and az_uid = %d and az_style='common' and az_status=1 and az_btime<= %d and az_etime>=%d  order by az_etime ",$_SESSION['_userid'],time(),time(),true);
        $commonzybinfo = $MainBase->get('api_zyb', $field,$where,true);
        $vin['title'] = 'VIN解码';
        $vin['count'] = '';
        $vinPerCount = 0;
        $vinDayCount = intval($shopVin['data']['shop_vin_count']);
        if(count($vinzybinfo['data'])>0){
          foreach ($vinzybinfo['data'] as $key => $value) {
            if($value['az_type']=='per'){
                $vinPerCount = $vinPerCount + intval($value['countHas']);
            }else{
                $vinDayCount = $vinDayCount + intval($value['az_count']);
            }
          }
        }
        $vin['count'] =  $vinDayCount.'次/天'.($vinPerCount>0?' + '.$vinPerCount.'次':'');
        $commondata['title'] = '普通接口剩余数';
        $commondata['count'] = 0;
        if($commonzybinfo['data']['az_count']){
           $commondata['title'] = $commonzybinfo['data']['az_type']=='per'?'普通接口剩余数':'每日普通接口数'; 
           $commondata['count'] = $commonzybinfo['data']['az_type']=='per'?$commonzybinfo['data']['countHas']:$commonzybinfo['data']['az_count'];
        }
        LibTpl::Set('zybinfo',['vin'=>$vin,'common'=>$commondata]);

        //已购买服务列表（控制台卡片展示）
        $serviceList = [];
        //1. 商城目录 - sh_shop_app
        $res = $B2cBase->get('sh_shop_app', ['aps_etime'], sprintf(" and aps_shop_id=%d order by aps_etime desc limit 1", $_SESSION['_shopid']), true);
        if(!empty($res['data']['aps_etime'])){
            $serviceList[] = ['name' => '商城目录', 'etime' => $res['data']['aps_etime']];
        }
        //2. 品牌目录 - sh_super（supData中已有）
        if(!empty($this->supData['ssu_etime'])){
            $serviceList[] = ['name' => '目录', 'etime' => $this->supData['ssu_etime']];
        }
        //3. 机器人 - wx_robot
        $res = $B2cBase->get('wx_robot', ['wr_etime'], sprintf(" and wr_uid=%d order by wr_etime desc limit 1", $_SESSION['_userid']), true);
        if(!empty($res['data']['wr_etime'])){
            $serviceList[] = ['name' => '机器人', 'etime' => $res['data']['wr_etime']];
        }
        //4. TOKEN - wx_robot_token
        $B2cWxRobot = new B2cWxRobot();
        $res = $B2cWxRobot->get('wx_robot_token', ['wrt_endtime'], sprintf(" and wrt_uid=%d order by wrt_endtime desc limit 1", $_SESSION['_userid']), true);
        if(!empty($res['data']['wrt_endtime'])){
            $etime = is_numeric($res['data']['wrt_endtime']) ? $res['data']['wrt_endtime'] : strtotime($res['data']['wrt_endtime']);
            $serviceList[] = ['name' => 'TOKEN', 'etime' => $etime];
        }
        //5. 接口 - api_user（MAIN库）
        $res = $MainBase->get('api_user', ['au_etime'], sprintf(" and au_uid=%d order by au_etime desc limit 1", $_SESSION['_userid']), true);
        if(!empty($res['data']['au_etime'])){
            $serviceList[] = ['name' => '接口', 'etime' => $res['data']['au_etime']];
        }
        //6. 资源包 - api_zyb（MAIN库，按类型分别展示，过期15天内的）
        $styleName = ['vin' => 'VIN解码', 'common' => '公共', 'matchmod' => '号码匹配车型'];
        $res = $MainBase->get('api_zyb', ['az_style', 'az_etime as etime'], sprintf(" and az_uid=%d and az_status=1 and az_etime>=%d", $_SESSION['_userid'], time() - 15 * 86400));
        if(!empty($res['data'])){
            foreach ($res['data'] as $item) {
                if(isset($styleName[$item['az_style']])){
                    $serviceList[] = ['name' => '资源包-'.$styleName[$item['az_style']], 'etime' => $item['etime']];
                }
            }
        }
        //7. 商家入驻 - pl_shop（PJL库）
        $PjlBase = new PjlBase();
        $res = $PjlBase->get('pl_shop', ['shop_vip_etime'], sprintf(" and shop_pu_id=%d order by shop_vip_etime desc limit 1", $_SESSION['_userid']), true);
        if(!empty($res['data']['shop_vip_etime'])){
            $serviceList[] = ['name' => '商家入驻', 'etime' => $res['data']['shop_vip_etime']];
        }
        //8. PC会员 - pl_user_vip（PJL库）
        $res = $PjlBase->get('pl_user_vip', ['uvip_etime'], sprintf(" and uvip_uid=%d and uvip_paymoney <> 0 order by uvip_etime desc limit 1", $_SESSION['_userid']), true);
        if(!empty($res['data']['uvip_etime'])){
            $serviceList[] = ['name' => 'PC会员', 'etime' => $res['data']['uvip_etime']];
        }
        LibTpl::Set('serviceList', $serviceList);

        //待提醒服务：已过期 或 7天内即将过期（用于每日首次登录弹窗）
        $serviceAlertList = [];
        $alertThreshold = 7 * 86400;
        foreach ($serviceList as $svc) {
            $diff = $svc['etime'] - time();
            if ($diff > 0 && $diff <= $alertThreshold) {
                $svc['type'] = 'expiring';
                $serviceAlertList[] = $svc;
            } elseif ($diff <= 0 && abs($diff) <= $alertThreshold) {
                $svc['type'] = 'expired';
                $svc['days'] = ceil(abs($diff) / 86400);
                $serviceAlertList[] = $svc;
            }
        }
        LibTpl::Set('serviceAlertList', $serviceAlertList);
        
        //订单提醒
        LibTpl::set('correction',$correction);

        LibTpl::Set('ypNoticeArr', $res['data']);
        LibTpl::Set('newModelArr', $newModelArr);
        LibTpl::Set('chckArr', $chckArr);
        LibTpl::Set('totalPro', $totalPro);
        LibTpl::Set('supPartArr', $supPartArr);
        LibTpl::Set('title', '控制台-品牌目录');
        LibTpl::Put();
    }


    //配置品牌目录
    function superSet()
    {
        $Params = mvc::$URL_PARAMS;
        $B2cBase = new B2cBase();
        if (!empty($_POST['sup']) && !empty($_POST['sup']['ssu_name'])) {
            $dataArr = $_POST['sup'];
            unset($dataArr['ssu_btime']);
            unset($dataArr['ssu_etime']);
            $dataArr['ssu_model'] = base64_decode($dataArr['ssu_model']);
            $dataArr['ssu_conf'] = !empty($_POST['conf']) ? json_encode($_POST['conf']) : '{}';
            $dataArr['ssu_tags'] = !empty($dataArr['ssu_tags']) ? implode(',',array_filter($dataArr['ssu_tags'])):'';
            $dataArr['ssu_banner'] = !empty(array_filter($dataArr['ssu_banner']))?implode(',',array_filter($dataArr['ssu_banner'])):'';
            $dataArr['ssu_auto_tags'] = LibFc::Int($_POST['sup']['ssu_auto_tags']);
            $B2cShop = new B2cShop();
            $res = $B2cShop->setShopSuper($_POST['ssu_id'], $dataArr, null);
            LibFc::Go(mvc::$cfg['SELF_URI'] . 'index/superSet');
        }

        $res = $B2cBase->get('sh_super join sh_shop on shop_id = ssu_shop_id', ['*'], sprintf(" and ssu_shop_id=%d", $_SESSION['_shopid']), true);
        $superArr = $res['data'];
        $superArr['betime'] = date('Y-m-d H:i:s', $superArr['ssu_btime']) . ' ~ ' . date('Y-m-d  H:i:s', $superArr['ssu_etime']);
        $superArr['ssu_conf'] = !empty($superArr['ssu_conf']) ? json_decode($superArr['ssu_conf'], true) : [];
        $superArr['ssu_tags'] = !empty($superArr['ssu_tags']) ? explode(',',$superArr['ssu_tags']):array_pad([],5, '');
        $superArr['ssu_banner'] = !empty($superArr['ssu_banner']) ? explode(',',$superArr['ssu_banner']):[];
        $superArr['ssu_banner'] = array_pad((Array) $superArr['ssu_banner'],5,'');
       
        $modelSelectArr = mvc::$cfg['MODEL_OPTS'];
        LibTpl::Set('modelSelectArr', $modelSelectArr);
        LibTpl::Set('order','superSet');
        LibTpl::Set('superArr', $superArr);
        LibTpl::Set('title', '配置品牌目录');
        LibTpl::Put();
    }

    //平台公告
    function ypNotice()
    {
        $Params = mvc::$URL_PARAMS;
        $page = isset($Params['page']) ? $Params['page'] : 1;
        $perPage = isset($_COOKIE['perPage']) ? $_COOKIE['perPage'] : 25;
        $B2cBase = new B2cBase();
        $table = 'cm_article join cm_article_category on arc_art_id=art_id';
        $where = sprintf(" and art_status = 'pass' and arc_cat_id = %d", $this->ypNoticeCatId);
        if (!empty($Params['read']) && $Params['read'] == -1) {
            $where .= sprintf(" and art_id not in (select arr_art_id from cm_article_shop_read where arr_shop_id = %d)", $_SESSION['_shopid']);
        } else if (!empty($Params['read']) && $Params['read'] == 1) {
            $table .= sprintf(" join cm_article_shop_read on arr_art_id =art_id and arr_shop_id = %d", $_SESSION['_shopid']);
        }
        $res = $B2cBase->get($table, ['count(*) as count'], $where, true);
        $total = $res['data']['count'];
        $list = [];
        $readArr = [];
        if ($total > 0) {
            $where .= sprintf(" order by art_add_time desc limit %d,%d", ($page - 1) * $perPage, $perPage);
            $res = $B2cBase->get($table, ['art_id, art_title, art_add_time'], $where);
            if (!empty($res['data'])) {
                $list = $res['data'];
                //已读的公告ID
                $res = $B2cBase->get('cm_article_shop_read', ['arr_art_id'], sprintf(" and arr_art_id in (%s) and arr_shop_id = %d", implode(',', array_column($list, 'art_id')), $_SESSION['_shopid']));
                $readArr = array_column($res['data'], 'arr_art_id');
            }
        }

        //未读公告数量
        $table = sprintf("cm_article join cm_article_category on arc_art_id=art_id left join cm_article_shop_read on arr_art_id = art_id and arr_shop_id = %d", $_SESSION['_shopid']);
        $res = $B2cBase->get($table, ['count(*) as count'], sprintf(" and art_status = 'pass' and arc_cat_id = %d and arr_shop_id is null", $this->ypNoticeCatId), true);
        LibTpl::Set('notReadCount', $res['data']['count']);
        LibTpl::Set('pageMsg', LibPage::Show($total, $perPage, true));
        LibTpl::Set('list', $list);
        LibTpl::Set('Params', $Params);
        LibTpl::Set('readArr', $readArr);
        LibTpl::Set('title', '平台公告');
        LibTpl::Put();
    }

    function getNoticeDes()
    {
        $Params = mvc::$URL_PARAMS;
        $table = 'cm_article join cm_article_category on arc_art_id=art_id';
        $where = sprintf(" and art_id=%d and art_status = 'pass' and arc_cat_id = %d", $Params['art_id'], $this->ypNoticeCatId);
        $B2cBase = new B2cBase();
        $rres = $B2cBase->get($table, ['art_id, art_txt, art_title, art_add_time'], $where, true);
        if (!empty($rres['data'])) {
            $rres['data']['art_add_time'] = date('Y-m-d H:i', $rres['data']['art_add_time']);
            $tres = $B2cBase->get('cm_article_shop_read', ['arr_art_id'], sprintf(" and arr_art_id =%d and arr_shop_id = %d", $rres['data']['art_id'], $_SESSION['_shopid']));
            if (empty($tres['data'])) {
                $add = [
                    'arr_art_id' => $rres['data']['art_id'],
                    'arr_shop_id' => $_SESSION['_shopid'],
                ];
                $B2cBase->add('cm_article_shop_read', $add);
            }
        }
        LibFc::ajaxJsonEncode($rres);
    }


    /**
     * [superNotice 目录公告筛选列表]
     * @Author   yangxing
     * @DateTime 2019-10-14T14:39:46+0800
     * @return   [type]                   [description]
     */
    function superNotice()
    {
        $Params = mvc::$URL_PARAMS;
        $page = isset($Params['page']) ? $Params['page'] : 1;
        $perPage = isset($_COOKIE['perPage']) ? $_COOKIE['perPage'] : 25;
        $othBase = new OthBase();
        $table = 'super_notice ';
        $where = sprintf(" and not_shop_id =%d", $_SESSION['_shopid']);
        if (is_numeric($Params['not_status'])) {
            $where .= sprintf(" and not_status = %d", $Params['not_status']);
        }
        if (!empty($Params['keyword'])) {
            $where .= sprintf(" and not_title like '%%%s%%'",$Params['keyword']);
        }

        $res = $othBase->get($table, ['count(*) as count'], $where, true);
        $total = $res['data']['count'];
        $list = [];
        $readArr = [];
        if ($total > 0) {
            $where .= sprintf(' order by not_atime desc limit %d,%d', ($page - 1) * $perPage, $perPage);
            $res = $othBase->get($table, ['*'], $where);
            $lists = $res['data'];
            LibTpl::Set('proArr', $lists);
        }
        LibTpl::Set('notReadCount', $res['data']['count']);
        LibTpl::Set('pageMsg', LibPage::Show($total, $perPage, true));
        LibTpl::Set('list', $list ?: []);
        LibTpl::Set('Params', $Params);
        LibTpl::Set('readArr', $readArr ?: []);

        LibTpl::Set('title', '目录公告');
        LibTpl::Put();
    }


    /**
     * [addNotice 添加或编辑公告页面]
     * @Author   Yangxing
     * @DateTime 2019-10-14T14:46:30+0800
     */
    function addNotice()
    {
        $params = mvc::$URL_PARAMS;
        $othBase = new OthBase();
        if ($params['id']) {
            $notice = $othBase->get('super_notice ', ['*'], sprintf(' and not_shop_id = %d and not_id = %d', $_SESSION['_shopid'], $params['id']), true);
            if ($notice['data']['not_proids']) {
                $B2cBase = new B2cBase();
                $table = 'bc_product as a
			join bc_product_info as b on pri_pro_id = pro_id
			left join bc_probrand as c on pro_prb_id = prb_id
			';
                //a.pro_id,a.pro_name,b.pri_code,c.prb_name
                $result = $B2cBase->get($table, ['a.pro_id,a.pro_name,b.pri_code,c.prb_name'], sprintf(" and pro_id in (%s)", $notice['data']['not_proids']));
                $notice['data']['product'] = $result['data'];
            }

            //todo 公告开始时间==公告发布时间
            if ($notice['data']['not_btime'] == $notice['data']['not_atime']) {
                $notice['data']['set'] = 1;
            } else {
                $notice['data']['set'] = 2;
            }
            LibTpl::Set('data', $notice['data']);
        }
        LibTpl::Set('title', '添加公告');
        LibTpl::Set('artStatus', []);
        LibTpl::Put();
    }


    /**
     * [getSuperDes 获取公告内容]
     * @Author   Yangxing
     * @DateTime 2019-10-14T14:46:47+0800
     * @return   [type]                   [description]
     */
    function getSuperDes()
    {
        $Params = mvc::$URL_PARAMS;
        $othBase = new OthBase();
        $notice = $othBase->get('super_notice ', ['*'], sprintf(' and not_shop_id = %d and not_id = %d', $_SESSION['_shopid'], $Params['not_id']), true);
        if ($notice['data']['not_proids']) {
            $B2cBase = new B2cBase();
            $table = 'bc_product as a
			join bc_product_info as b on pri_pro_id = pro_id
			left join bc_probrand as c on pro_prb_id = prb_id
			';
            $result = $B2cBase->get($table, ['a.pro_id,a.pro_name,b.pri_code,c.prb_name'], sprintf(" and pro_id in (%s)", $notice['data']['not_proids']));
            $notice['data']['product'] = $result['data'];
        }
        $notice['data']['not_atime'] = date('Y-m-d h:i:s');
        LibFc::ajaxJsonEncode($notice);

    }


    /**
     * [add 添加公告]
     * @Author   Yangxing
     * @DateTime 2019-10-14T14:47:04+0800
     */
    function add()
    {
        if ($_POST['set'] == 2 && $_POST['date']) {
            $time = strtotime($_POST['date']); //公告开始时间
        }

        $othBase = new OthBase();
        if ($_POST['id']) {
            $where = sprintf(' and not_shop_id = %d and not_id= %d', $_SESSION['_shopid'], $_POST['id']);
            $notice = $othBase->get('super_notice ', ['*'], $where, true);
            if (empty($notice['data'])) {
                LibFc::ajaxJsonEncode(['status' => false,'data' => '参数错误']);
            }
            $data = [
                'not_status' => $_POST['set'] == 1 ? 1 : 0,
                'not_btime' => $time ?: time(),//公告开始时间
                'not_title' => $_POST['title'], //公告标题
                'not_txt' => $_POST['content'] ?: '', //公告内容
                'not_proids' => $_POST['numId'] ?: 0, //配件ID
                'not_atime' => time(), //最后编辑时间
                'not_euid' => $_SESSION['_userid'], //最后编辑人
            ];
            $result = $othBase->set('super_notice ', $data, $where);
        } else {
            $data = [
                'not_shop_id' => $_SESSION['_shopid'], //所属店铺ID
                'not_status' => $_POST['set'] == 1 ? 1 : 0,
                'not_btime' => $time ?: time(),//公告开始时间
                'not_title' => $_POST['title'], //公告标题
                'not_txt' => $_POST['content'], //公告内容
                'not_proids' => $_POST['numId'], //配件ID
                'not_atime' => time(), //发布时间
                'not_auid' => $_SESSION['_userid'], //发布人ID
                'not_etime' => time(), //最后编辑时间
                'not_euid' => $_SESSION['_userid'], //最后编辑人
            ];
            $result = $othBase->add('super_notice ', $data);
        }

        LibFc::ajaxJsonEncode($result);
    }

    /**
     * [searchNum 搜索商家编码]
     * @Author   Yangxing
     * @DateTime 2019-10-14T14:47:21+0800
     * @return   [type]                   [description]
     */
    function searchNum()
    {
        $Params = $_POST;
        $B2cBase = new B2cBase();
        $page = isset($Params['page']) ? $Params['page'] : 1;
        $perPage = isset($_COOKIE['perPage']) ? $_COOKIE['perPage'] : 20;

        $where = sprintf(' and pro_shop_id=%d', $_SESSION['_shopid']);
        $total = 0;
        if (!empty($Params['number'])) {
            $formatNum = LibFc::FormatNum($Params['number']);
            $where .= sprintf(" and (num_format like '%s%%' or num_reformat like '%s%%')", $formatNum, strrev($formatNum));
            $table = 'bc_number join bc_product on pro_id = num_pro_id  join bc_part on pro_part_id = part_id';
            $res = $B2cBase->get($table, ['count(distinct(pro_id)) count'], $where, true);
            $total = $res['data']['count'];
            if ($total > 0) {
                $orderBy = $res['data'];
                $twhere = sprintf(" %s group by pro_id order by part_name limit %d,%d", $where, ($page - 1) * $perPage, $perPage);
                $res = $B2cBase->get('bc_number join bc_product on pro_id = num_pro_id join bc_part on pro_part_id = part_id', ['pro_id'], $twhere);
                $proArr = array_column($res['data'], null, 'pro_id');
            }
        }

        //配件信息
        if (!empty($proArr)) {
            $table = 'bc_product 
			join bc_product_info on pri_pro_id = pro_id
			join bc_part on pro_part_id = part_id
			left join bc_probrand on pro_prb_id = prb_id
			left join bc_number on pro_id = num_pro_id and num_ismain =1
			left join bc_part_small on pro_pas_id = pas_id
			';
            $res = $B2cBase->get($table, ['*'], sprintf(" and pro_id in (%s)", implode(',', array_keys($proArr))));
            foreach ($res['data'] as $v) {
                $v['para'] = [];
                $v['nums'] = [];
                $v['m3_count'] = 0;
                $proArr[$v['pro_id']] = $v;
            }

            $where = sprintf(" and num_pro_id in (%s) and num_self = 0", implode(',', array_keys($proArr)));
            $where .= !empty($formatNum) ? sprintf(" and (num_format like '%s%%' or num_reformat like '%s%%')", $formatNum, strrev($formatNum)) : ' and num_ismain=1';
            $res = $B2cBase->get('bc_number', ['num_id, num_pro_id, num_factory, num_display'], $where);
            foreach ($res['data'] as $v) {
                $proArr[$v['num_pro_id']]['nums'][$v['num_id']] = $v;
            }

            $table = sprintf("bc_part_param_link 
			join bc_param_label on ppl_pal_id=pal_id 
			left join bc_product_param_float on ppf_pal_id=pal_id and ppf_pro_id in (%s)
			left join bc_product_param_string on pps_pal_id=pal_id and pps_pro_id in (%s) 
			left join bc_param_unit on ppl_pau_id = pau_id", implode(',', array_keys($proArr)), implode(',', array_keys($proArr)));
            $res = $B2cBase->get($table, ['ppf_pro_id, pps_pro_id, pal_name, ppl_style, pps_value, ppf_value, pau_name'], ' order by ppl_seq');
            foreach ($res['data'] as $v) {
                $proId = empty($v['ppf_pro_id']) ? $v['pps_pro_id'] : $v['ppf_pro_id'];
                if (empty($proId)) continue;
                $v['pau_name'] = empty($v['pau_name']) ? '' : $v['pau_name'];
                $v['val'] = empty($v['pps_value']) ? $v['ppf_value'] : $v['pps_value'];
                $proArr[$proId]['para'][] = ['name' => $v['pal_name'], 'val' => $v['val'], 'unit' => $v['pau_name']];
            }
        }
        $i = 0;
        $proArrs = array();
        if($proArr)
        {
            foreach ($proArr as $value) 
            {
                $proArrs[$i] = $value;
                $i++;
            }     
        }
        
        $array = [
            'code' => 0,
            'msg' => '获取成功',
            'count' => count($proArrs),
            'data' => $proArrs ?: [],
        ];
        LibFc::ajaxJsonEncode($array);
    }

    /**
     * [deleteNotice 删除公告接口]
     * @Author   Yangxing
     * @DateTime 2019-10-14T14:47:48+0800
     * @return   [type]                   [description]
     */
    function deleteNotice()
    {
        if (is_numeric($_POST['id']) || is_array($_POST['id'])) {
            $othBase = new OthBase();
            foreach ($_POST['id'] as $value) {
                $result = $othBase->del('super_notice ', sprintf(' and not_id = %d and not_shop_id = %d ', $value, $_SESSION['_shopid']));
            }
        }
        LibFc::ajaxJsonEncode($result);
    }


    /**
     * [upperShelf 上架接口]
     * @Author   Yangxing
     * @DateTime 2019-10-14T14:48:04+0800
     * @return   [type]                   [description]
     */
    function upperShelf()
    {
        if ($_POST['id']) {
            if ($_POST['index'] == 1) {
                $status = 1;
            }
            if ($_POST['index'] == 2) {
                $status = -1;
            }
            if (!$status) {
                echo json_encode(['code' => 0, 'msg' => '参数错误', 'data' => []]);
                exit();
            }
            $data = [
                'not_status' => $status, //状态
                'not_atime' => time(),//修改最后修改时间
                'not_euid' => $_SESSION['_userid'],//最后修改人
            ];
            $othBase = new OthBase();
            $result = $othBase->set('super_notice ', $data, sprintf(' and not_id = %d  ', $_POST['id']));
            LibFc::ajaxJsonEncode($result);
        }
        LibFc::ajaxJsonEncode(['status' => false,'data' => '参数错误']);
    }

    /**
     * [correctiveFeedback 纠错反馈筛选页面]
     * @Author   Yangxing
     * @DateTime 2019-10-15T10:13:54+0800
     * @return   [type]                   [description]
     */
    function correctiveFeedback()
    {
        $params = mvc::$URL_PARAMS;
        $page = isset($params['page']) ? $params['page'] : 1;
        $perPage = isset($_COOKIE['perPage']) ? $_COOKIE['perPage'] : 25;
        $othBase = new OthBase();
        $table = 'ot_jiucuo ';

        //普通index 产品item 车架号解码vin
        $jcType = [
            'index' => '普通',
            'item' => '产品',
            'vin' => '车架号解码'
        ];
        $where = sprintf(" and jc_shop_id =%d", $_SESSION['_shopid']);
        if (is_numeric($params['jc_status'])) {
            $where .= sprintf(" and jc_status = %d", $params['jc_status']);
        }
        if (!empty($params['jc_type'])) {
            $where .= sprintf(" and jc_type = %s ",'\''.$params['jc_type'].'\'');
        }

        $res = $othBase->get($table, ['count(*) as count'], $where, true);
        $total = $res['data']['count'];
        $list = [];
        $readArr = [];
        if ($total > 0) {
            $where .= sprintf(' order by jc_atime desc limit %d,%d', ($page - 1) * $perPage, $perPage);
            $res = $othBase->get($table, ['jc_id','jc_status','jc_type','jc_txt','jc_imgs','jc_atime','jc_check_time','jc_check_remark'], $where);
            $lists = $res['data'];
            foreach ($lists as &$value){
                if(!empty($value['jc_imgs'])){
                    $value['jc_imgs'] = explode(',',$value['jc_imgs']);
                }
            }
            LibTpl::Set('proArr', $lists);
        }
        LibTpl::set('jcType', $jcType);
        LibTpl::Set('notReadCount', $res['data']['count']);
        LibTpl::Set('pageMsg', LibPage::Show($total, $perPage, true));
        LibTpl::Set('list', $list ?: []);
        LibTpl::Set('params', $params);
        LibTpl::Set('readArr', $readArr ?: []);
        LibTpl::Set('title', '纠错反馈');
        LibTpl::Put();

    }

    /**
     * [audit 审核接口]
     * @Author   Yangxing
     * @DateTime 2019-10-15T11:30:49+0800
     * @return   [type]                   [description]
     */
    function audit()
    {
        $params = mvc::$URL_PARAMS;
        if ($_POST['jc_id']) {
            if(!is_numeric($_POST['jc_status'])) return LibFc::ajaxJsonEncode(['status' => false, 'data' => '参数错误']);
            if (empty($_POST['content'])) return LibFc::ajaxJsonEncode(['status' => false, 'data' => '处理意见不可为空']);
            $othBase = new OthBase();
            $where = sprintf(" and jc_shop_id = %d and jc_id = %d", $_SESSION['_shopid'], $_POST['jc_id']);
            $result = $othBase->get('ot_jiucuo ', ['*'], $where, true);
            if (!$result['data']) return LibFc::ajaxJsonEncode(['status' => false, 'data' => '不存在该记录']);
            //拼装需要更新的字段
            $data = [
                'jc_status' => $_POST['jc_status'] ?: 0,//更改状态
                'jc_check_time' => time(), //更改处理时间
                'jc_check_remark' => $_POST['content'], //更改处理意见
            ];
            $res = $othBase->Set('ot_jiucuo ', $data, $where);
            LibFc::ajaxJsonEncode($res);
        }
        LibFc::ajaxJsonEncode(['status'=>false,'data' => '参数错误']);
    }


    /**
     * [showDetails 查看详情页面]
     * @Author   Yangxing
     * @DateTime 2019-10-15T11:34:06+0800
     * @return   [type]                   [description]
     */
    function detailsPage()
    {
        $params = mvc::$URL_PARAMS;
        $jcType = [
            'index' => '普通',
            'item' => '产品',
            'vin' => '车架号解码'
        ];
        $othBase = new OthBase();
        $where = sprintf(" and jc_shop_id = %d and jc_id = %d", $_SESSION['_shopid'], $params['jc_id']);
        $result = $othBase->get('ot_jiucuo ', ['*'], $where, true);
        if($result['data']['jc_pro_id'] && $result['data']['jc_type'] == 'item')
        {
            $B2cBase = new B2cBase();
            $table = 'bc_product as a
			join bc_product_info as b on pri_pro_id = pro_id
			left join bc_probrand as c on pro_prb_id = prb_id';
            $proData = $B2cBase->get($table, ['a.pro_id,a.pro_name,b.pri_code,c.prb_name'], sprintf(" and pro_id = %d ", $result['data']['jc_pro_id']),true);
            $result['data']['number'] = $proData['data']['prb_name'].':'.$proData['data']['pri_code'];
        }
        $result['data']['jc_imgs'] = explode(',',$result['data']['jc_imgs']);
        if (!$result['data']) return LibFc::ajaxJsonEncode(['status' => false, 'data' => '不存在该记录']);
        LibTpl::Set('data', $result['data'] ?: []);
        LibTpl::Set('title', '纠错反馈');
        LibTpl::set('jcType', $jcType);
        $html = LibTpl::Fetch();
        LibFc::ajaxJsonEncode(['status' => true,'data' => $html]);
    }

    /**
     * [deleteFeedback 删除接口]
     * @Author   Yangxing
     * @DateTime 2019-10-15T18:27:31+0800
     * @return   [type]                   [description]
     */
    function deleteFeedback()
    {
        if((!$_POST['jc_id'] && $_POST['jc_id'] >=1 && is_numeric($_POST['jc_id'])) || empty($_POST['jc_id']))
        {
            LibFc::ajaxJsonEncode(['status' => false, 'data' => '参数错误']);
        }
        $othBase = new OthBase();
        $result = $othBase->del('ot_jiucuo ', sprintf(' and jc_id = %d and jc_shop_id = %d ', $_POST['jc_id'], $_SESSION['_shopid']));
        LibFc::ajaxJsonEncode($result);
    }

    //帮助中心
    public function help_center()
    {
        $B2cArticle = new B2cArticle();
        $Params = mvc::$URL_PARAMS;
        $NowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
        $PerPage = empty($_COOKIE['perPage'])? 20: (int) $_COOKIE['perPage'];

        // 取指定分类
        $catId = '1013'; 
        $where  = sprintf('and cat_pcat_id = %d',$catId);
        $res = $B2cArticle->get('cm_category left join cm_category_tree  on cat_id=cat_cat_id',['cat_id','cat_name','cat_pcat_id','cat_path'],$where.' order by cat_seq asc');
        $catData = array_column($res['data'], null,'cat_id');
		$catIdArr = array_column($res['data'],'cat_id');

        
        LibTpl::Set('Params',$Params);
        $catId =  $Params['catId'];
        //取指定分类文章

        $where = sprintf("and arc_cat_id in (%s) and art_status='pass'",implode(',',$catIdArr));
        $artData = $B2cArticle->get('cm_article left join cm_article_category on arc_art_id=art_id',['art_id','art_txt','art_title','arc_cat_id'],$where);
        
        LibTpl::Set('artTitleList',$artData['data']);
   
        foreach ($artData['data'] as $key => $artvalue) {
           
            if($catData[$artvalue['arc_cat_id']]){
                $catData[$artvalue['arc_cat_id']]['article'][] = $artvalue;
            }
        }
    
        //指定分类下搜索关键词的文章
        if(!empty($Params['keyword'])){
            
            $where = sprintf(" and arc_cat_id in (%s)",implode(',',$catIdArr));
            $where .= sprintf(" and (art_title like '%%%s%%' or art_txt like '%%%s%%')",$Params['keyword'],$Params['keyword']);
            $where .= sprintf(" and art_status='pass'"); //审核通过的
            $count = $B2cArticle->get('cm_article left join cm_article_category on arc_art_id=art_id',['count(*) as count'],sprintf("%s",$where),true);
            $total =  $count['data']['count']?:0;
            if($total>0){
                $where .= sprintf(" order by art_seq limit %s,%s",($NowPage-1)*$PerPage,$PerPage);
                $artInfoArr = $B2cArticle->get('cm_article left join cm_article_category on arc_art_id=art_id',['art_id','art_txt','art_title'],$where);
                LibTpl::Set('artInfo',$artInfoArr['data']);
            }
            $page = LibPage::Show($total, $PerPage,true);
            LibTpl::Set('Page', $page);
        }

        //查看更多时显示分类下的所有文章
        if(!empty($Params['catId'])){
            
            $where = sprintf("and arc_cat_id=%d and art_status='pass'",$catId);
            $count = $B2cArticle->get('cm_article left join cm_article_category on arc_art_id=art_id',['count(*) as count'],$where,true);
            $total =  $count['data']['count']?:0;
            if($total>0){
                $where .= sprintf(" order by art_seq limit %s,%s",($NowPage-1)*$PerPage,$PerPage);
                $artData = $B2cArticle->get('cm_article left join cm_article_category on arc_art_id=art_id',['art_id','art_txt','art_title'],$where);
                LibTpl::Set('artTitleList',$artData['data']);
            }
            $page = LibPage::Show($total, $PerPage,true);
            LibTpl::Set('Page', $page);
        }
        
        $navArr = explode(',',$catData[$catId]['cat_path']);
        if(!empty($navArr))
        {
            foreach ($navArr as $key => $value) 
            {
                if(!empty($catData[$value]))
                {
                    $navData[$value] = $catData[$value];
                }
            }
            if($catData[$catId])
            {
                $navData[$catId] = $catData[$catId];
            }
            LibTpl::Set('navArr',$navArr);
            LibTpl::Set('navList', $navData);
        }
        LibTpl::Set('catList',$catData);
        LibTpl::Put();
    }

	 /**
     * @method 省市区 取下一级
     * @author soul 2021/7/27
     */
	function getPctAddr()
	{
		$Params = mvc::$URL_PARAMS;
		$Pid = isset($Params['pid']) ? (int) $Params['pid']: 0;
		$YpwBase = new YpwBase();
		$Res = $YpwBase->get('yp_province_city', ['pc_id as id', 'pc_name as name'], sprintf(" and pc_pid=%d", $Pid));
		LibFc::ajaxJsonEncode($Res);
	}

    function actionLog()
    {
        $Params = array_filter(mvc::$URL_PARAMS);
        $B2cLog = new B2cLog();
        $NowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
        $PerPage = empty($_COOKIE['perPage'])? 20: (int) $_COOKIE['perPage'];
        $where = sprintf("and log_shop_id = %d", $_SESSION['_shopid']);
        //店主跟子账号
        $B2cBase =  new B2cBase();
        $userRes =  $B2cBase->get('sh_worker',['wor_uid,wor_real_name'],sprintf(" and wor_shop_id = %d ",$_SESSION['_shopid']));
        $userArr = array_column($userRes['data'],null,'wor_uid');
        $userIdArr =  $userRes['data'] ? array_column($userRes['data'],'wor_uid'):[];
        $userIdArr[] = $_SESSION['_shopid'];
        $where .= sprintf(" and log_uid in (%s)", implode(',',$userIdArr));

        if (isset($Params['time_begin'])) {
            $where .= sprintf(" and log_atime >= %d", strtotime($Params['time_begin'].' 00:00:00'));
        }
        if (isset($Params['time_end'])) {
            $where .= sprintf(" and log_atime <= %d", strtotime($Params['time_end'].' 23:59:59'));
        }
        if (isset($Params['userid'])) {
            $where .= sprintf(" and log_uid = %d", $Params['userid']);
        }
        if (isset($Params['content'])) {
            $where .= sprintf(" and LOCATE('%s', `log_txt`) > 0", $Params['content']);
        }
        $count = $B2cLog->get('sh_log',['count(*) as count'],sprintf("%s",$where),true);
        if($count['data']['count']>0)
        {
            $total = $count['data']['count']>0?$count['data']['count']:0;
            if($total>0){
                $where .= sprintf(" order by log_atime desc limit %s,%s",($NowPage-1)*$PerPage,$PerPage);
                $logArr = $B2cLog->get('sh_log',[
                    'log_id as id',
                    'log_shop_id as shop_id',
                    'log_uid as userid',
                    'log_uname as username',
                    'log_category as cat_id',
                    'log_atime as add_time',
                    'log_dataid as dataid',
                    'log_txt as content',
                ],$where);
                LibTpl::Set('logInfo',$logArr['data']);
            }
        }

        $userWhere = sprintf("and u_b2c_shopid = %d and u_id in (%s)", $_SESSION['_shopid'],implode(',',$userIdArr));
        $userList = (new YpwUser())->get('yp_user',['u_id as id','u_name','u_real_name','u_nickname','u_b2c_worker'],$userWhere);
        foreach ($userList['data'] as $key => &$value) {
            if(!empty($userArr[$value['id']]['wor_real_name'])){
                $value['name'] = $userArr[$value['id']]['wor_real_name'];
                continue;
            }
            $value['name'] = $value['u_real_name']?$value['u_real_name']:($value['u_real_name']?$value['u_real_name']:$value['u_name']);
        }
        unset($value);
        LibTpl::Set('userList', $userList["data"]);

        $page = LibPage::Show($total, $PerPage,true);
        LibTpl::Set('catMap', [
            0 => '普通',
            1 => '配件',
            2 => '配件价格',
            10 => '订单',
            11 => '订单价格',
            21 => '店铺',
        ]);
        LibTpl::Set('Page', $page);
        LibTpl::Set('params', $Params);
        LibTpl::Put();
    }

    function actionLogDetail()
    {
        $params = mvc::$URL_PARAMS;
        $id = (int)$params['id'];
        $B2cLog = new B2cLog();
        $where = sprintf("and log_id = %d", $id);
        $data = $B2cLog->get('sh_log',[
            'log_id as id',
            'log_txt as content',
        ],$where,true);
        LibFc::ajaxJsonEncode(['status' => true,'data' => '<textarea name="" class="layui-textarea" disabled>'.$data['data']['content'].'</textarea>']);
    }
    /* 
    * 帮助中心-文章详情
    */
    function article_detail()
    {
        $params = mvc::$URL_PARAMS;
        $artid = (int)$params['artid'];
        $B2cArticle = new B2cArticle();
        //获取指定文章
		if(LibFc::Int($artid))
		{
			$artData = $B2cArticle->get('cm_article left join cm_article_category on art_id=arc_art_id',['art_id','art_title','art_txt','art_add_time','art_last_time','arc_cat_id'],sprintf("and art_id=%d and art_status='pass' order by art_seq desc,art_id desc",$artid),true);
			LibTpl::Set('art', $artData['data']);
            LibTpl::Put();
		}
        
    }
    /**
     * @method 加盟申请
     * @author zhengweihua 
     * @copyright 2022-05-25
     */
    public function daiLiApply()
	{
		$Params = mvc::$URL_PARAMS;
        $B2cBase = new B2cBase();
        $listArr = [];
        $statusArr = ['0'=>'待处理','1'=>'已处理','-1'=>'无效'];
        $page = isset($Params['page']) ? $Params['page'] : 1;
        $perPage = isset($_COOKIE['perPage']) ? $_COOKIE['perPage'] : 20;
        $where  = sprintf(" and sda_shop_id = %d",$_SESSION['_shopid']);

        if (is_numeric($Params['sda_status'])) {
            $where .= sprintf(" and sda_status = %d", $Params['sda_status']);
        }
        $res = $B2cBase->get('sh_daili_apply', ['count(*) as count'], $where, true);
        $total = $res['data']['count'];
        if ($total>0) 
        {
            $where .= sprintf(" order by CASE WHEN sda_status =0 THEN 0 ELSE 1 END,sda_atime desc limit %d, %d", ($page - 1) * $perPage, $perPage);
            $res =  $B2cBase->get('sh_daili_apply', ['*'], $where);
            $listArr = $res['data'];
        }
        $title = '申请列表';
        LibTpl::Set('Params',$Params);
        LibTpl::Set('applyArr',$listArr);
        LibTpl::Set('pageMsg', LibPage::Show($total, $perPage, true));
        LibTpl::set('ticle',$title);
        LibTpl::Set('statusArr',$statusArr);
        LibTpl::Put();
	}
    /**
     * @method 编辑加盟申请
     * @author zhengweihua 
     * @copyright 2022-05-25
     */
    public function editDaiLiApply()
    {
        if(empty($_POST['sda_id']))
            LibFc::ReturnJson(false,'参数错误！');

        $B2cBase =  new B2cBase();
        $where = sprintf(' and sda_shop_id=%d and sda_id=%d ',$_SESSION['_shopid'],(int)$_POST['sda_id']);
        $data = [
            'sda_status' => (int)$_POST['sda_status'],
            'sda_status_remark' => LibFc::Escape($_POST['sda_status_remark']),
            'sda_etime' => time()
        ];
        $res = $B2cBase->set('sh_daili_apply',$data,$where);
        LibFc::ajaxJsonEncode($res); 
    }
    /**
     * @method 删除加盟申请
     * @author zhengweihua 
     * @copyright 2022-05-25
     */
    public function delDaiLiApply()
    {
        if(empty($_POST['sda_id']))
            LibFc::ReturnJson(false,'参数错误！');
        $B2cBase =  new B2cBase();
        $where = sprintf(' and sda_id=%d',(int)$_POST['sda_id']);
        $res = $B2cBase->del('sh_daili_apply',$where);
        LibFc::ajaxJsonEncode($res); 
    }
    /**
     * @method 机器人设置
     * @author zhengweihua 
     * @copyright 2022-06-02
     */
    public function robotSet()
    {       
        $OthCheck = new OthCheck();
        // 权限
        $OthCheck->rule('RB01');
        $Params = mvc::$URL_PARAMS;
        $B2cBase = new B2cBase();
        //保存
        if($_SERVER['REQUEST_METHOD']=='POST')
        {
            if(empty($_POST['rob']) || !is_array($_POST['rob'])) return LibFc::ReturnJson(false,'参数错误');
            $data = $_POST['rob'];
            if(!isset($data['wr_othcof'])) $data['wr_othcof'] = '';
            if(!isset($data['wr_vin_fileds'])) $data['wr_vin_fileds'] = '';
            if(!empty($data['wr_autotxt']) && is_array($data['wr_autotxt']))
			{
				$data['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));
				},$data['wr_autotxt']);
                $data['wr_autotxt'] = json_encode($data['wr_autotxt']);
			}
            $where = sprintf(" and wr_id=%d", (int)$_POST['wr_id']);
            $res =  $B2cBase->get('wx_robot',['*'],$where,true);
            if(empty($res['data'])) return LibFc::ReturnJson(false,'参数错误');

            $B2cWxRobot = new B2cWxRobot();
            // 群默认配置
            $data['wr_roomcof'] = json_encode([]);
            if(isset($_POST['roomcof']) && is_array($_POST['roomcof'])){
                //等级设置
                if(isset($_POST['roomcof']['wrr_mel_id'])){
                    if($_POST['roomcof']['wrr_mel_id']===''){
                        $_POST['roomcof']['wrr_mel_id'] = -1;
                    }else{
                        $tempLevel = is_array($_POST['roomcof']['wrr_mel_id']) ?$_POST['roomcof']['wrr_mel_id']:explode(',',$_POST['roomcof']['wrr_mel_id']);
                        // 去除数组中所有的-1
                        $tempLevel = array_filter($tempLevel, function($value) {  
                            return (int)$value !== -1;  
                        });  
                        
                        if (!empty($tempLevel)) {
                            $_POST['roomcof']['wrr_mel_id'] = implode(',',$tempLevel);   
                        } 
                    } 
                }
                
                $_POST['roomcof'] = array_filter($_POST['roomcof'], function($value) {
                    return $value !== '';
                });
                $data['wr_roomcof'] = json_encode($_POST['roomcof'], JSON_UNESCAPED_UNICODE);
            }
            $res = $B2cWxRobot->setWxRobot($_POST['wr_id'], $data);
            LibFc::ajaxJsonEncode($res);
        }
        //获取当前用户机器人
        $res = $B2cBase->get('wx_robot left join wx_robot_token on wr_wrt_id= wrt_id', ['*',"MD5(CONCAT('Y@', wrt_id, '@P', DATE_FORMAT(NOW(), '%Y-%m-%d'))) as md5key"], sprintf(" and wr_totype!='pjlshop' and wr_uid=%d and wr_id=%d",$_SESSION['_shopid'], $Params['wr_id']),true);
        if(empty($res['data'])) return LibFc::ReturnJson(false,'参数错误');
        $order = $res['data']['wr_type']; //机器人类型
        LibTpl::Set('order',$order);
         //微信号信息
        $wxinfo = $res['data']['wrt_wxinfo']?json_decode($res['data']['wrt_wxinfo'], true):[];
        LibTpl::Set('wxinfo',$wxinfo);
        $res['data']['wr_autotxt'] = $res['data']['wr_autotxt'] ? json_decode($res['data']['wr_autotxt'], true) : [];
        if($res['data']['wr_autotxt']){
            $res['data']['wr_autotxt'] =  array_map(function($item){
                return str_replace("\r\n","<br>",$item);
            },$res['data']['wr_autotxt']);
        }
        $res['data']['wr_vin_fileds'] = !empty($res['data']['wr_vin_fileds'])? explode(',',$res['data']['wr_vin_fileds']):[];
        $res['data']['wr_othcof'] = !empty($res['data']['wr_othcof']) ? explode(',',$res['data']['wr_othcof']):[];

        if (in_array($order,['wxgr','wxkf'])) {
            $wrwRes = $B2cBase->get('wx_robot_wx', ['wrw_wx'], sprintf(" and wrw_wr_id=%d", $res['data']['wr_id']));
            if($wrwRes['data'])
            {	
                $wrw_wx = array_column($wrwRes['data'],'wrw_wx');
                $res['data']['usedWxCount'] = count($wrw_wx); //已使用微信号个数
                $res['data']['wrw_wx'] = implode(',',$wrw_wx);
            }
            $wrrRes = $B2cBase->get('wx_robot_room', ['count(*) as count'], sprintf(" and wrr_wr_id=%d", $res['data']['wr_id']),true);
            $res['data']['usedRoomCount'] = $wrrRes['data']['count']?:0; //已使用微信群个数
        }
        $robotArr = $res['data'];
        
        // 群默认配置
        $robotArr['wr_roomcof'] = !empty($robotArr['wr_roomcof']) ? json_decode($robotArr['wr_roomcof'], true) : [];
        // var_dump($robotArr['wr_roomcof']);die;
        $selfmodArr = !empty($robotArr['wr_selfmod']) ? explode(',', $robotArr['wr_selfmod']) : [];
        LibTpl::Set('roomCof', $robotArr['wr_roomcof']);
        LibTpl::Set('selfmodArr', $selfmodArr);
        if(in_array('roomfactory', $selfmodArr)){
            $fres = $B2cBase->get('bc_number join bc_product on num_pro_id =pro_id',['num_factory'],sprintf(" AND pro_shop_id=%d group by num_factory order by num_factory",$_SESSION['_shopid']));
            $roomcofFactoryArr = $fres['data']?array_column($fres['data'],'num_factory'):[];
            LibTpl::Set('roomcofFactoryArr', $roomcofFactoryArr);
        }
        if(in_array('roomsort', $selfmodArr)){
            $B2cShopSort = new B2cShopSort();
            $roomcofTreeData = $B2cShopSort->getShopSortZtree($_SESSION['_shopid'], []);
            LibTpl::Set('roomcofTreeArr', $roomcofTreeData['data']);
        }
        if(in_array('roompbrand', $selfmodArr)){
            $B2cProduct = new B2cProduct();
            $pbrandRes = $B2cProduct->get('bc_product join bc_probrand on pro_prb_id = prb_id',['distinct prb_id,prb_name'],sprintf(" and pro_shop_id=%d order by prb_seq asc",$_SESSION['_shopid']));
            $roomcofBrandList = $pbrandRes['data']?:[];
            LibTpl::Set('roomcofBrandList', $roomcofBrandList);
        }

        // 会员级别
        $levelres = $B2cBase->get('sh_member_level',['mel_id','mel_name']," order by mel_id asc ");
        LibTpl::Set('levelArr', $levelres['data']);
        
        $where = ' AND wrl_super = 1 order by wrl_seq';
        if ($robotArr['wr_totype'] == 'pjlshop') {
            $where = " AND wrl_pjlshop = 1 order by wrl_seq ";
        }
		$tres = $B2cBase->get('wx_robot_label', ['*'],$where);
		$allLabelArr = [];
		foreach($tres['data'] as $v)
		{
			$allLabelArr[$v['wrl_type']][$v['wrl_code']] = $v['wrl_name'];
		}
        //请求总接口
        if($res['data']['wrt_id'])
        {
            $LibYpApi = new LibYpApi();
            $LibYpApi->Get('index/chkRobotStatus',['wrt_id'=>$res['data']['wrt_id']]);
        }
       
		LibTpl::Set('othCnfArr', $allLabelArr['othcfg']);
        LibTpl::Set('vinFieldsArr', $allLabelArr['vinfileds']);
        if (array_intersect(['roompart', 'roomsort'], $selfmodArr)) {
            $this->HEAD_CSSJS['plugin'][] = 'zTree';
            LibTpl::Set('HEAD_CSSJS', $this->HEAD_CSSJS);
        }
        LibTpl::Set('title', '机器人列表');
        LibTpl::Set('robotArr', $robotArr);  
        LibTpl::Put();
    }

    /**
    * @method 自动回复
    * @author zhengweihua 
    * @copyright 2022-06-06
    */
    public function autoWord()
    {
        $Params = mvc::$URL_PARAMS;
        $B2cBase = new B2cBase();
        $page = isset($Params['page']) ? $Params['page'] : 1;
        $perPage = isset($_COOKIE['perPage']) ? $_COOKIE['perPage'] : 25;
        //当前用户机器人
        $robotResult = $B2cBase->get('wx_robot',['wr_id,wr_wxname,wr_type'],sprintf(" and wr_uid=%d and wr_type !='wxgr'",$_SESSION['_userid']));

        if(empty($Params['wra_wr_id']) && empty($robotResult['data'])) exit('尚未开通机器人');
   
        if($robotResult['data'])
        {
            $wr_id = current(array_column($robotResult['data'],'wr_id'));
            $Params['wra_wr_id'] = !empty($Params['wra_wr_id'])?$Params['wra_wr_id']:$wr_id;
        }
        $where = sprintf(" and wra_wr_id=%d",(int)$Params['wra_wr_id']);
        if($Params['keyword'])
        {  
			//搜索关键词表
            $wordRes = $B2cBase->get('wx_robot_autoword',['distinct waw_wra_id'],sprintf(" and waw_word like '%%%s%%'",LibFc::Escape($Params['keyword'])));
            if($wordRes['data'])
            {   
                $wordResId = array_column($wordRes['data'],'waw_wra_id');
                $where .= sprintf(" and (wra_name like '%%%s%%' or wra_id in (%s))",LibFc::Escape($Params['keyword']),implode(',',$wordResId));  
            }
            else
            {
                $where .= sprintf(" and wra_name like '%%%s%%' ",LibFc::Escape($Params['keyword'])); 
            }
        }
        $table = 'wx_robot_auto join wx_robot on wr_id = wra_wr_id';
        $res = $B2cBase->get($table,['count(*) as count'],$where,true);
        $total = $res['data']['count']?$res['data']['count']:0;
        if($total>0)
        {
            $autoList = [];
            $where .= sprintf(" order by wra_id desc limit %d,%d ",($page - 1) * $perPage, $perPage);
            $res =  $B2cBase->get($table,['wx_robot_auto.*'],$where);
            if($res['data'])
            {   //相关联关键词
                $autoList = array_column($res['data'],null,'wra_id');
                $wra_id_arr = array_column($res['data'],'wra_id');
                $autoWordRes = $B2cBase->get('wx_robot_autoword',['waw_word,waw_wra_id'],sprintf(" and waw_wra_id in (%s)",implode(',',$wra_id_arr)));
                foreach ($autoWordRes['data'] as $item) 
                {
                    $autoList[$item['waw_wra_id']]['waw_word'] .= $item['waw_word'].',';     
                }
            }
            LibTpl::Set('autoList',$autoList);  
        }
        LibTpl::Set('robotArr',array_column($robotResult['data'],null,'wr_id'));
        Libtpl::Set('Params',$Params);
        LibTpl::Set('styleArr',['txt'=>'文字','img'=>'图片']);
        LibTpl::Set('pageMsg', LibPage::Show($total, $perPage, true));
        LibTpl::Set('ticle', '自动回复列表');
        LibTpl::Put();
    }
    /**
     * @method  添加/编辑自动回复页面
     * @author zhengweihua 
     * @copyright 2022-06-06
     */
    public function addAutoWord()
    {
        $Params = mvc::$URL_PARAMS;
        if($_SERVER['REQUEST_METHOD'] == 'POST')
        {
            $B2cRobotAuto = new B2cRobotAuto();
            $res = $B2cRobotAuto->setRobotAuto($_POST);
            LibFc::ajaxJsonEncode($res);
        }
        $title = $Params['wra_id'] ?'编辑自动回复': '添加自动回复';
        $B2cBase = new B2cBase();
        $data = [];
        if(!empty($Params['wra_id']))
        {
            $where =  sprintf(" and wra_id = %d",(int)$Params['wra_id']);
            $res = $B2cBase->get('wx_robot_auto',['*'],$where,true);
            $data = $res['data'];
            if(!empty($data['wra_answer'])){
                $data['wra_answer'] = str_replace("\r\n","<br>",$data['wra_answer']);
            }
            //关键词数组
            $where =  sprintf(" and waw_wra_id = %d",(int)$Params['wra_id']);
            $res = $B2cBase->get('wx_robot_autoword',['*'],$where);
            $data['autowordList'] = $res['data'];
        }
        $data['wra_wr_id'] = $data['wra_wr_id']?$data['wra_wr_id']:$Params['wra_wr_id'];
        LibTpl::Set('Params',$Params);
        LibTpl::Set('data',$data);
        LibTpl::Set('styleArr',['全匹配','半匹配']);
        LibTpl::Set('title',$title);
        $html = LibTpl::Fetch();
        LibFc::ajaxJsonEncode(['status' => true,'data' => $html]);
    }

    /**
     * @method 删除回复规则
     * @author zhengweihua 
     * @copyright 2022-06-06
     */
    public function delAutoWord()
    {
        if(empty($_POST['wra_id'])) LibFc::ReturnJson(false,'参数错误');
        $B2cRobotAuto = new B2cRobotAuto();
        $res = $B2cRobotAuto->delAutoWord($_POST['wra_id']);
        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_loginurl','wr_id','wrt_wxnickname'],sprintf(" and wr_id = %d",$wr_id),true);
			
			if(empty($res['data']['wrt_loginurl'])){
				
				$res =	$B2cBase->get('wx_robot_token',['wrt_loginurl','wrt_wxnickname'],sprintf(" and wrt_uid = %d",$_SESSION['_shopid']),true);
				if(empty($res['data']['wrt_loginurl'])){
					return LibFc::ReturnJson(false,'无需登陆');
				}
				
			}
            $data = [
                'loginurl' => $res['data']['wrt_loginurl'],
                'wrt_wxnickname'=>$res['data']['wrt_wxnickname']
            ];
            if ($forwardEwm && $forwardEwm == $res['data']['wrt_loginurl']) {
                return LibFc::ReturnJson(true, $data);
            }
            $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 2023-03-24
     */
    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 群列表
     * @author zhengweihua 
     * @copyright 2023-03-24
     */
    public function robotRoom()
    {   
        $OthCheck = new OthCheck();
        // 权限
        $OthCheck->rule('RB01');
        $Params = mvc::$URL_PARAMS;
        $page = isset($Params['page']) ? $Params['page'] : 1;
        $perPage = isset($_COOKIE['perPage']) ? $_COOKIE['perPage'] : 20;    
        $B2cBase = new B2cBase();
        $res = $B2cBase->get('wx_robot', ['wr_id,wr_type,wr_selfmod,wr_roomcof'], sprintf(" and wr_type='wxgr' and wr_totype!='pjlshop' and wr_uid=%d and wr_id=%d",(int)$_SESSION['_shopid'],$Params['wr_id']),true);
        $robotArr = $res['data'];
        
        $listArr = [];
        $trueFeild = [];
        $total = 0;
        $hasMem = ''; 
        if($robotArr){

            $canEdit = 0;
            $colspan = 7;
            $selfmodArr = explode(',',$robotArr['wr_selfmod']);
            LibTpl::Set('seflmodArr',$selfmodArr);
            if(in_array('showprice',$selfmodArr)){
                $hasMem = 'single';
                $canEdit =1;
                $trueFeild['wrr_mel_id'] = '会员等级';
            } 
            if(in_array('mulprices',$selfmodArr)){
                $hasMem ='mul';
                $canEdit =1;
                $trueFeild['wrr_mel_id'] = '会员等级';
            } 
            if($hasMem){ $colspan++;}
            $trueFeild['wrr_hideurl'] = '隐藏链接';
            if(in_array('roomfactory',$selfmodArr)){
                $numres = $B2cBase->get('bc_number join bc_product on num_pro_id =pro_id',['num_factory'],sprintf(" AND pro_shop_id=%d group by num_factory order by num_factory",$_SESSION['_shopid']));
                $factoryArr = $numres['data']?array_column($numres['data'],'num_factory'):[];
                LibTpl::Set('factoryArr',$factoryArr);
                $colspan++;
                $canEdit =1;
                $trueFeild['wrr_factory'] = '显示号码';
            }

            //启用了配件分类
            if(in_array('roompart',$selfmodArr)){
                $where = sprintf(' and part_id in(select pro_part_id from bc_product where pro_shop_id=%d)',$_SESSION['_shopid']);
                $B2cPart = new B2cPart();
                $res = $B2cPart->get('bc_part 
                    join bc_part_tree on part_id = pt_part_id and pt_ismain=1
                    left join bc_part_small on part_id = pas_part_id',
                 ['part_id', 'part_name','pt_parent_part_id','pas_id','pas_name'], $where);
               
                $parentArr = []; //一级分类的父级
                $t1 = [];//一级分类
                $t2 = [];//二级分类
                foreach($res['data'] as $v){
                    $t1[$v['part_id']] = $v['part_name'];
                    $parentArr[$v['part_id']] = $v['pt_parent_part_id'];
                    if($v['pas_id']){
                        $t2[$v['pas_id']] = $v['pas_name'];
                    }
                }
                $parentArr = array_values($parentArr);
		        $res1 = $B2cPart->get('bc_part', ['part_id', 'part_name'], sprintf(' and part_id in(%s)',implode(",",$parentArr)));
                $parentArr1 = array_column($res1['data'],'part_name','part_id');
                $partIdToNameArr = $t1+$t2 + $parentArr1;
                LibTpl::Set('partIdToNameArr', $partIdToNameArr);
                $colspan++;
                $canEdit =1;
                $trueFeild['wrr_part_ids'] = '配件分类';
            }
            //启用了店铺分类
            if(in_array('roomsort',$selfmodArr)){
                // 商品分类
                $B2cShopSort = new B2cShopSort();
                $treeData = $B2cShopSort->getShopSortZtree($_SESSION['_shopid'],[$Params['shopCate']]);
                LibTpl::Set('treeArr',$treeData['data']);
                $sortIdToNameArr = array_column($treeData['data'], 'name', 'id');
                LibTpl::Set('sortIdToNameArr', $sortIdToNameArr);
                $colspan++;
                $canEdit =1;
                $trueFeild['wrr_sort_ids'] = '店铺分类';
            }
            //启用了配件品牌
            if(in_array('roompbrand',$selfmodArr)){
                // 品牌
                $B2cProduct = new B2cProduct();
                $res = $B2cProduct->get('bc_product join bc_probrand on pro_prb_id = prb_id',['distinct prb_id,prb_name'],sprintf(" and pro_shop_id=%d order by prb_seq asc",$_SESSION['_shopid']));
                $brandList = $res['data']?:[];
                LibTpl::Set('brandList', $brandList);
                $brandIdToNameArr = array_column($brandList, 'prb_name', 'prb_id');
                LibTpl::Set('brandIdToNameArr', $brandIdToNameArr);
                $colspan++;
                $canEdit =1;
                $trueFeild['wrr_prb_ids'] = '配件品牌';
            }

            $where  = sprintf(" AND wrr_wr_id = %d", $robotArr['wr_id']);

            foreach ($Params as $key => $val) {
                switch ($key) {
                    case 'wrr_mel_id':
                        $where .= is_numeric($val)? sprintf(" AND wrr_mel_id = %d",LibFc::Int($val)):'';
                    break;
                    case 'wrr_status':
                        $where .= is_numeric($val)? sprintf(" AND wrr_status = %d",LibFc::Int($val)):'';
                    break;
                    case 'keyword':
                        $where .= sprintf(" AND wrr_room_name like '%%%s%%'",LibFc::Escape($val));
                    break;
                    case 'wrr_atime':
                        if($val){
                            $arr1 = explode('~',$val);
                            $where .=sprintf(" AND wrr_atime between %d AND %d",strtotime($arr1[0]),strtotime($arr1[1])+86399);
                        }
                        break;
                }
            }

            $countRes =  $B2cBase->get('wx_robot_room', ['count(*) as count'], $where, true);
            $total = $countRes['data']['count'];
            if ($total > 0) {
                $where .= sprintf(" order by wrr_atime desc limit %d,%d", ($page - 1) * $perPage, $perPage);
                $res = $B2cBase->get('wx_robot_room', ['*'], $where);
                foreach ($res['data'] as $rkey => $rval) {
                    $wrr_info = $rval['wrr_info'] ? json_decode($rval['wrr_info'], true) : [];
                    $rval['avatar'] = $wrr_info['avatar'] ?: '';
                    $rval['wrr_mel_id'] = explode(',',$rval['wrr_mel_id']);
                    $res['data'][$rkey] = $rval;
                }
                $listArr = $res['data'];
            }
            
        }
       
        LibTpl::Set('robotArr',$robotArr); 
        // 会员级别
        $B2cShop = new B2cShop();
        $res = $B2cShop->getShopMember($_SESSION['_shopid']);
        $level = [-1=>'非会员'];
        foreach ($res['data'] as $key => $val) {
            $level[$val['mel_id']] = $val['men_alias']?:$val['mel_name'];
        }
        
        // 添加zTree插件支持，用于partSort.js
        $this->HEAD_CSSJS['plugin'][] = 'zTree';
        LibTpl::Set('HEAD_CSSJS', $this->HEAD_CSSJS);
        LibTpl::Set('canEdit',$canEdit);
        LibTpl::Set('trueFeild',$trueFeild);
        LibTpl::Set('colspan',$colspan);
        LibTpl::Set('level',$level);
        LibTpl::Set('listArr',$listArr);
        LibTpl::Set('pageMsg', LibPage::Show($total, $perPage, true));
        LibTpl::Set('hasMem',$hasMem);
        LibTpl::Set('Params',$Params);
        LibTpl::Set('order','robotRoom');
        LibTpl::Set('title', '群列表');
        LibTpl::Put();
    }

    /**
     * @method 删除群列表
     * @author zhengweihua 
     * @copyright 2023-03-24
     */
    public function delRobotRoom()
    {   
        if($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['wrr_id'])
        {
            $B2cBase = new B2cBase();
            $wrr_ids = is_array($_POST['wrr_id'])? implode(',',$_POST['wrr_id']): LibFc::Int($_POST['wrr_id']);
            $result = $B2cBase->del('wx_robot_room ', sprintf(' and wrr_id in (%s)', $wrr_ids));
            LibFc::ajaxJsonEncode($result);
        }
        LibFc::ReturnJson(false,'参数错误');
    }

    /**
     * @method 变更群状态
     * @author zhengweihua 
     * @copyright 2024-05-11
     */
    public function changeRoomStatus()
    {
        if($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['wrr_id'])
        {
            $B2cBase = new B2cBase();
            if(!is_array($_POST['wrr_id'])){
                $wrr_id = [$_POST['wrr_id']];
            }else{
                $wrr_id = $_POST['wrr_id'];
            }
            
            $wrr_status = $_POST['wrr_status'];
            $result = $B2cBase->set('wx_robot_room',['wrr_status'=>$wrr_status] ,sprintf(' and wrr_id in (%s)',implode(',',$wrr_id)));
            LibFc::ajaxJsonEncode($result);
        }
        LibFc::ReturnJson(false,'参数错误');
    }

    /**
     * @method 编辑群列表
     * @author zhengweihua 
     * @copyright 2023-03-24
     */
    public function editRobotRoom()
    {
        if($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['wrr_id'])
        {
            $B2cBase = new B2cBase();
            $wrr_ids = is_array($_POST['wrr_id'])? implode(',',$_POST['wrr_id']): LibFc::Int($_POST['wrr_id']);
            $level = $_POST['level'];
            $hideurl = (int)$_POST['hideurl'];
            $wrr_factory = $_POST['wrr_factory'];
            $wrr_part_ids = $_POST['wrr_part_ids'];
            $wrr_sort_ids = $_POST['wrr_sort_ids'];
            $wrr_prb_ids = $_POST['wrr_prb_ids'];
            $setField = $_POST['setField'];
            if($level===''){
                $level = -1;
            }else{
                $tempLevel = explode(',',$level);
                // 去除数组中所有的-1
                $tempLevel = array_filter($tempLevel, function($value) {  
                    return (int)$value !== -1;  
                });  
                
                if (!empty($tempLevel)) {
                    $level = implode(',',$tempLevel);   
                } 
            } 
            // 自定义修改属性
            $fieldArr = [];
            if(strpos($setField,'wrr_mel_id')!==false){
                $fieldArr['wrr_mel_id'] = $level;
            }
            if(strpos($setField,'wrr_hideurl')!==false){
                $fieldArr['wrr_hideurl'] = $hideurl;
            }
            if(strpos($setField,'wrr_factory')!==false){
                $fieldArr['wrr_factory'] = $wrr_factory;
            }
            if(strpos($setField,'wrr_part_ids')!==false){
                $fieldArr['wrr_part_ids'] = $wrr_part_ids;
            }
            if(strpos($setField,'wrr_sort_ids')!==false){
                $fieldArr['wrr_sort_ids'] = $wrr_sort_ids;
            }
            if(strpos($setField,'wrr_prb_ids')!==false){
                $fieldArr['wrr_prb_ids'] = $wrr_prb_ids;
            }
            $result = $B2cBase->set('wx_robot_room ',
                $fieldArr,
                sprintf(' and wrr_id in (%s)', $wrr_ids));
            LibFc::ajaxJsonEncode($result);
        }
        LibFc::ReturnJson(false,'参数错误');
    }

    /**
     * @method 配件日志
     * @author zhengweihua 
     * @copyright 2023-05-16
     */
    public function actionLogItem()
    {
        $Params = array_filter(mvc::$URL_PARAMS);
        $B2cLog = new B2cLog();
        $NowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
        $PerPage = empty($_COOKIE['perPage'])? 20: (int) $_COOKIE['perPage'];
        $where = sprintf("and sli_shop_id = %d", $_SESSION['_shopid']);
        //店主跟子账号
        $B2cBase =  new B2cBase();
        $userRes =  $B2cBase->get('sh_worker',['wor_uid,wor_real_name'],sprintf(" and wor_status=1 and wor_shop_id = %d ",$_SESSION['_shopid']));
        $userArr = array_column($userRes['data'],null,'wor_uid');
        $userIdArr =  $userRes['data'] ? array_column($userRes['data'],'wor_uid'):[];
        $userIdArr[] = $_SESSION['_shopid'];
        $where .= sprintf(" and sli_uid in (%s)", implode(',',$userIdArr));

        if (isset($Params['time_begin'])) {
            $where .= sprintf(" and sli_etime >= %d", strtotime($Params['time_begin'].' 00:00:00'));
        }
        if (isset($Params['time_end'])) {
            $where .= sprintf(" and sli_etime <= %d", strtotime($Params['time_end'].' 23:59:59'));
        }
        if (isset($Params['userid'])) {
            $where .= sprintf(" and sli_uid = %d", $Params['userid']);
        }
        if (isset($Params['pricode'])) {
            $where .= sprintf(" and LOCATE('%s', `pri_code`) > 0", $Params['pricode']);
        }
        if (isset($Params['content'])) {
            $where .= sprintf(" and LOCATE('%s', `sli_txt`) > 0", $Params['content']);
        }
        $table = 'sh_log_item as sli join bc_product_info on pri_pro_id=sli.sli_pro_id';
        $count = $B2cLog->get($table,['count(*) as count'],sprintf("%s",$where),true);
        if($count['data']['count']>0)
        {
            $total = $count['data']['count']>0?$count['data']['count']:0;
            if($total>0){
                $where .= sprintf(" order by sli_etime desc limit %s,%s",($NowPage-1)*$PerPage,$PerPage);
                $logArr = $B2cLog->get($table,['sli.*'],$where);
                LibTpl::Set('logInfo',$logArr['data']);
                $proIdArr = array_unique(array_column($logArr['data'],'sli_pro_id'));
                $proArr = $B2cLog->get('bc_product join bc_product_info  on pri_pro_id =pro_id ',['pro_id','pro_name','pri_code'],sprintf(" AND pro_id in (%s)",implode(',', $proIdArr)));
                LibTpl::Set('proArr',array_column($proArr['data'],null,'pro_id'));
            }
        }

        $userWhere = sprintf("and u_b2c_shopid = %d and u_id in (%s)", $_SESSION['_shopid'],implode(',',$userIdArr));
        $userList = (new YpwUser())->get('yp_user',['u_id as id','u_name','u_real_name','u_nickname','u_b2c_worker'],$userWhere);
        foreach ($userList['data'] as $key => &$value) {
            if(!empty($userArr[$value['id']]['wor_real_name'])){
                $value['name'] = $userArr[$value['id']]['wor_real_name'];
                continue;
            }
            $value['name'] = $value['u_real_name']?$value['u_real_name']:($value['u_real_name']?$value['u_real_name']:$value['u_name']);
        }
        unset($value);
        LibTpl::Set('userList', $userList["data"]);
        LibTpl::Set('catMap',['add'=>'新增','del'=>'删除','num'=>'号码','model'=>'车型','para'=>'参数','oth'=>'其他']);
        $page = LibPage::Show($total, $PerPage,true);
        LibTpl::Set('Page', $page);
        LibTpl::Set('params', $Params);
        LibTpl::Put();
    }



    public function vinImage()
    {
        $arr = ['vin'=>'', 'chars'=>[]];
        if(!empty($_POST['data']))
        {
            $post =  ['data'=>substr(strstr($_POST['data'], ','), 1)];
            $post['name'] = empty($_POST['name'])? 'vinFile.jpg': $_POST['name'];
            $LibYpApi = new LibYpApi();
            $res = $LibYpApi->get('ocr/vin', [],['image' => $post]);
            $arr['vin'] = $res['data'];
            if(strlen($arr['vin']) == 17) $arr['chars'] = str_split($arr['vin'], 1);
        }
        LibFc::ajaxJsonEncode(['status'=>true,'data'=>$arr]);
    }

    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'];
		}
		if($wrt_id && $tokenres['data']['wrt_ispjd']!=1)
		{
			$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(false,'不可重启机器人');
    }

    /**
     * @method 检测机器人显示项目
     * @author zhengweihua 
     * @copyright 2024-07-18
     */
    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);
			
			$tokenres = $B2cBase->get('wx_robot_token', ['*'], sprintf(" and wrt_id = %d and wrt_ispjd!=1", $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($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($tokenres['data']['wrt_type']!='wxkf' && $tokenres['data']['wrt_ispjd']!=1 && time()-$tokenres['data']['wrt_restart_last']>120 && $tokenres['data']['wrt_uid']==$_SESSION['_shopid']){
					$data['showrestart']=1;
				}
			}
			
			return LibFc::ReturnJson(true,$data);
		}
	}

    /**
     * @method 取消静默状态
     * @author zhengweihua 
     * @copyright 2025-01-11
     */
    public function cancelSleep()
    {
        $Params = mvc::$URL_PARAMS;
        if($Params['wrt_id']){
            $B2cWxRobot = new B2cWxRobot();
            $res = $B2cWxRobot->set('wx_robot_token',['wrt_sleeptime'=>'#@NULL'],sprintf(" AND wrt_id=%d",LibFc::Int($Params['wrt_id'])));
            LibFc::ReturnJson(true,'操作成功');
        }
    }

	 /**
     * @method 变更微信
     */
    public function setWxTokenNull()
    {
        $Params = mvc::$URL_PARAMS;
        if($Params['wrt_id']){
            $B2cWxRobot = new B2cWxRobot();
			$res = $B2cWxRobot->get('wx_robot join wx_robot_token on wr_wrt_id=wrt_id',['wrt_id'], sprintf(" and wr_uid=%d and wrt_ispjd =0 AND wrt_id=%d", $_SESSION['_shopid'], LibFc::Int($Params['wrt_id'])), true);
			if(!empty($res)){
				$B2cWxRobot->set('wx_robot_token',['wrt_wxid'=>'','wrt_wxinfo'=>'#@NULL'],sprintf(" and wrt_ispjd =0 AND wrt_id=%d", $res['data']['wrt_id']));
			}
            LibFc::ReturnJson(true,'操作成功');
        }
    }

    /**
     * @method 微信总群聊列表
     * @author zhengweihua 
     * @copyright 2025-07-07
     */
    public function robotGroup()
    {   
        $OthCheck = new OthCheck();
        // 权限
        $OthCheck->rule('RB01');
        $Params = mvc::$URL_PARAMS;
        $page = isset($Params['page']) ? $Params['page'] : 1;
        $perPage = isset($_COOKIE['perPage']) ? $_COOKIE['perPage'] : 20; 

        $listArr = [];
        $total = 0;
        
        $where = sprintf(" and wr_uid=%d and wr_totype!='pjlshop' and wr_type='wxgr' ", $_SESSION['_shopid']);
        if($Params['keyword']){
            $where .=  $where .= sprintf(" AND wrr_room_name like '%%%s%%'",LibFc::Escape($Params['keyword']));
        }

        $table = sprintf('(SELECT
                    wx_robot_room.*,
                    COUNT(wrr_wr_id) AS counts
                FROM
                    wx_robot_room
                JOIN wx_robot on wrr_wr_id=wr_id
                where 1 %s
                GROUP BY
                    wrr_room_id
                ORDER BY
                    counts DESC
            ) AS dup',$where);

        $B2cWxRobot =  new B2cWxRobot();
        $res = $B2cWxRobot->get($table,['count(*) as counts'],'', true);
        $total = $res['data']['counts']?$res['data']['counts']:0;
        if($total>0){
            
            $swhere = sprintf(" limit %d,%d", ($page - 1) * $perPage, $perPage);
            $lisres = $B2cWxRobot->get($table, ['wrr_room_id,wrr_info,wrr_room_name'], $swhere);
            if($lisres['data']){
                $listArr = $lisres['data'];

                $roomidArr = array_column($listArr,'wrr_room_id');
                //获取token
                $robotArr = [];
                $allRobotArr = [];
                $table1 = 'wx_robot_room  
                join wx_robot on wrr_wr_id= wr_id
                join wx_robot_token on wr_wrt_id=wrt_id';
                $tokenres = $B2cWxRobot->get($table1,['wx_robot_token.*,wrr_wr_id,wrr_id,wrr_status,wr_wrt_id,wrr_room_id'],sprintf(" AND wrr_room_id IN ('%s') AND wr_uid=%d and wr_type='wxgr' and wr_totype!='pjlshop' and wr_wrt_id>0",implode("','",$roomidArr), $_SESSION['_shopid']));
                foreach ($tokenres['data'] as $key => $val) {
                    $name = $val['wrt_wxnickname'];
                    if($val['wrt_wxinfo']){
                        $wrt_wxinfo = json_decode($val['wrt_wxinfo'],true);
                        $name = $wrt_wxinfo['nickName'] ?: $val['wrt_wxnickname'];
                    }

                    $allRobotArr[$val['wrr_wr_id']] = '机器人-'.$name;
                    
                    $robotArr[$val['wrr_room_id']][] = [
                        'wrt_name'=>'机器人-'.$name,
                        'wrr_wr_id'=>$val['wrr_wr_id'],
                        'wrr_id'=>$val['wrr_id'],
                        'wrr_status'=>$val['wrr_status']
                    ];        
                }

                foreach ($listArr as &$item) {
                    $item['wrr_info'] = json_decode($item['wrr_info'], true);
                    if(empty($item['wrr_info']['avatar'])){
                        $item['wrr_info']['avatar'] = $item['wrr_wxavatar'];
                    }
                    $item['wrr_etime'] = date('Y-m-d H:i:s', $item['wrr_etime']);
                    $item['robotArr'] = $robotArr[$item['wrr_room_id']] ?: [];
                }
                unset($item);
            }
        }
        LibTpl::Set('allRobotArr',$allRobotArr);
        LibTpl::Set('listArr',$listArr);
        LibTpl::Set('pageMsg', LibPage::Show($total, $perPage, true));
        LibTpl::Set('Params',$Params);
        LibTpl::Set('title', '总群列表');
        LibTpl::Put();
    }

    public function changeRoomStatusByRoomId()
    {
        if($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['roomid'])
        {
            if(!is_array($_POST['roomid'])){
                $wrr_room_id = [$_POST['roomid']];
            }else{
                $wrr_room_id = $_POST['roomid'];
            }
            $wr_id = LibFc::Int($_POST['wrid']); 
            $B2cWxRobot = new B2cWxRobot();
            $result = $B2cWxRobot->changeRobotRoomStatus($wrr_room_id,$wr_id);
    
            LibFc::ajaxJsonEncode($result);
        }
        LibFc::ReturnJson(false,'参数错误');
    }
}
