<?php

class tsAction extends baseAction
{

    /**
     * @method 推送模板列表
     * @author zhengweihua 
     * @copyright 2026-05-16
     */
    public function tsTpl()
    {   
        LibFc::checkDlRule('DL19', true);
        $params = mvc::$URL_PARAMS;
        $page = empty($Params['page']) || $Params['page'] < 1? 1: (int) $Params['page'];
		$perPage = isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;
        $where = '';
        foreach ($params as $field => $val) {
            if($val == '') continue;
            switch ($field) {
                case 'tm_status':
                    $where .= " and tm_status = '{$val}'";  
                    break;
                case 'tm_type':
                    $where .= " and tm_type = '{$val}'";
                    break;
                case 'tm_name':
                    $where .= " and tm_name like '%{$val}%'";
                    break;
                case 'tm_msg_type':
                    $where .= " and tm_msg_type = '{$val}'";
                    break;
                case 'tm_dataid':
                    $where .= " and tm_dataid = '{$val}'";
                    break;
            }
        }
        $CrmBase = new CrmBase();
        $cntres = $CrmBase->get('ts_msg_tpl',['count(*) as counts'],$where,true);
        if($cntres['data']['counts']>0){
            $where .= sprintf(" limit %d, %d", ($page-1)*$perPage, $perPage);
            $res = $CrmBase->get('ts_msg_tpl',['*'],$where);
            foreach ($res['data'] as $key => &$val) {
                $val['tm_tpl'] = json_decode($val['tm_tpl'],true);
            }
            unset($val);
            LibTpl::Set('listArr',$res['data']);        
        }
        $Pages = LibPage::Show($cntres['data']['counts'],$perPage,true);
        // 广告名称
        $ads = new AdsBase();
        $area = $ads->get('pj_place', ['pa_id', 'pa_name', 'pa_size'], 'order by pa_id');
        $area = array_column($area['data'], null, 'pa_id');
      
		LibTpl::Set('Pages',$Pages);
        LibTpl::Set('area',$area);            
        LibTpl::Set('params',$params);
        LibTpl::Put();
    }

    /**
     * @method 添加/修改模板
     * @author zhengweihua 
     * @copyright 2026-05-16
     */
    public function editTpl()
    {
        $params = mvc::$URL_PARAMS;

        $ads = new AdsBase();
        $area = $ads->get('pj_place', ['pa_id', 'pa_name', 'pa_size'], 'order by pa_id');
        $area = array_column($area['data'], null, 'pa_id');
        LibTpl::Set('area',$area);

        if(isset($params['tm_id'])){
            $CrmBase = new CrmBase();
            $res = $CrmBase->get('ts_msg_tpl',['*'],sprintf(" and tm_id=%d",$params['tm_id']),true);
            if(!empty($res['data'])){
                $res['data']['tm_tpl'] = json_decode($res['data']['tm_tpl'], true);
            }
            LibTpl::Set('tpl',$res['data']);
        }
        LibTpl::Put();
    }

    /**
     * @method 保存模板
     * @author zhengweihua 
     * @copyright 2026-05-16
     */
    public function saveTpl()
    {
        if($_SERVER['REQUEST_METHOD'] != 'POST'){
            LibFc::ajaxJsonEncode(['status'=>0,'msg'=>'请使用POST方式提交数据']);
        }
        $params = $_POST;
        $dataArr = [
            'tm_dataid'=>$params['tm_dataid']?:0,
            'tm_name' => $params['tm_name'],
            'tm_type' => $params['tm_type'],
            'tm_status' => $params['tm_status'],
            'tm_msg_type' => $params['tm_msg_type'],
            'tm_tpl' => json_encode($params['tm_tpl']?:[]),
        ];
        $CrmBase = new CrmBase();
        if(isset($params['tm_id']) && $params['tm_id'] > 0){
            $exist = $CrmBase->get('ts_msg_tpl',['tm_id'],sprintf(" AND tm_id=%d",$params['tm_id']),true);
        }
        //还要验证是否重复  tm_dataid 跟 tm_type 联合唯一
        // $exist2 = $CrmBase->get('ts_msg_tpl',['tm_id'],sprintf(" AND tm_status= AND tm_dataid='%s' AND tm_type='%s' AND tm_id!=%d",$params['tm_status'],$params['tm_dataid'],$params['tm_type'],$exist['data']['tm_id']),true);            
        // if($exist2['data']){    
        //     LibFc::ReturnJson(false, '已存在同状态同广告位同类型的模板');
        // }
        if(!empty($exist['data'])){
            $res = $CrmBase->set('ts_msg_tpl',$dataArr,sprintf(" AND tm_id=%d",$params['tm_id']));
            $tm_id = $params['tm_id'];
        }else{
            $res = $CrmBase->add('ts_msg_tpl',$dataArr);
            $tm_id = $res['data'];
        }
       LibFc::ReturnJson(true,['tm_id'=>$tm_id]);

    }

    /**
     * @method 删除模板
     * @author zhengweihua 
     * @copyright 2026-05-16
     */
    public function delTpl()
    {
        if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['tm_id']))
        {   
            $tmids = implode(',',explode(',',$_POST['tm_id']));
            if(empty($tmids)){
                LibFc::ajaxJsonEncode(['status'=>0,'msg'=>'请选择要删除的模板']);
            }
            $CrmBase = new CrmBase();
            $res = $CrmBase->del('ts_msg_tpl',sprintf(' AND tm_id IN (%s)',$tmids));
            LibFc::ajaxJsonEncode($res); 
        }
       
    }

    /**
     * @method 改变模板状态
     * @author zhengweihua 
     * @copyright 2026-05-16
     */
    public function changeStatus()
    {
        if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['tm_id'])){ 
            $CrmBase = new CrmBase();
            $res = $CrmBase->set('ts_msg_tpl',['tm_status'=>$_POST['status']],sprintf(' AND tm_id = %d',$_POST['tm_id']));
            LibFc::ajaxJsonEncode($res);
        }
    }

    /**
     * @method 推送列表
     * @author zhengweihua 
     * @copyright 2026-05-16
     */
    public function tsHistoryList()
    {  
        $hasRule = false;
        if(LibFc::checkDlRule('DL19', false)){
            $hasRule = true;
        }
        $params = mvc::$URL_PARAMS;
        $page = empty($Params['page']) || $Params['page'] < 1? 1: (int) $Params['page'];
		$perPage = isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;
        
        $where = '';
        //没有权限就显示自己的
        if(!$hasRule){
            $where .= sprintf(" and (tmh_au_id =%d OR tmh_from_au_id =%d)",$_SESSION['_userid'],$_SESSION['_userid'] );
        }
        
        if(!empty($params)){
            foreach ($params as $key => $val) {
                
                switch ($key) {
                    case 'tmh_status':
                        if($val)  $where .= " and tmh_status = '{$val}'";  
                       
                        break;
                    case 'tmh_from_au_id':
                        if($val)  $where .= " and tmh_from_au_id IN ({$val})";
                        break;
                    case 'tmh_unikey':
                        if($val)  $where .= " and tmh_unikey like '%{$val}%'";
                       
                        break;
                    case 'tmh_msg_type':
                       if($val)  $where .= " and tmh_msg_type = '{$val}'";
                        break;
                }
            }                                  
        }
        $orderBy = 'tmh_id desc';
        //发送时间倒序  发送时间顺序  添加时间倒序  添加时间顺序
        $orderArr = [
            'tmh_sendtime'=>'发送时间倒序',
            'tmh_sendtime_asc'=>'发送时间顺序',
            'tmh_addtime'=>'添加时间倒序',
            'tmh_addtime_asc'=>'添加时间顺序',
        ];
        libTpl::Set('orderArr',$orderArr);
        $orderSortArr = [
            'tmh_sendtime'=>'tmh_send_time desc',
            'tmh_sendtime_asc'=>'tmh_send_time asc',
            'tmh_addtime'=>'tmh_atime desc',
            'tmh_addtime_asc'=>'tmh_atime asc',
        ];
        if($params['order'] && $orderSortArr[$params['order']]) $orderBy = $orderSortArr[$params['order']];
                                                                                                                     
        $CrmBase = new CrmBase();
        $table = 'ts_msg_history 
        left join ts_msg_tpl on tmh_tm_id = tm_id
        left join crm_customer on ctr_uid =tmh_u_id
        left join ypdb_write.yp_user on tmh_u_id = u_id';
        $cntres = $CrmBase->get($table,['count(*) as counts'],$where,true);
        if($cntres['data']['counts']>0){
            $where .= sprintf(" order by  %s limit %d, %d",$orderBy,($page-1)*$perPage, $perPage);
            $res = $CrmBase->get($table,['*'],$where);

            $auUids = array_unique(array_column($res['data'],'tmh_from_au_id'));
            if(count($auUids)>0){
                $B2cBase = new B2cBase();
                $res1 = $B2cBase->get('an_user', ['au_uid', 'au_name'],sprintf(" AND au_uid IN (%s)",implode(',',$auUids)));
                $auArr = array_column($res1['data'], 'au_name', 'au_uid');
            }

            $fromwu = array_column($res['data'],'tmh_from_wu_id');
            $towu = array_column($res['data'],'tmh_to_wu_id');
            $allwu =  array_unique(array_merge($fromwu,$towu));   
            if(count($allwu)>0){
                $B2cBase = new B2cBase();
                $res2 = $B2cBase->get('wx_user', ['wu_id', 'wu_nickname'],sprintf(" AND wu_id IN (%s)",implode(',',$allwu)));
                $wuArr = array_column($res2['data'], 'wu_nickname', 'wu_id');
                
            }           
            if($res['data'])
            {   
                foreach ($res['data'] as $key => &$val) {
                   $val['tmh_msg'] = json_decode($val['tmh_msg'], true);
                   $val['from_au_name'] = $auArr[$val['tmh_from_au_id']];
                   $val['from_wu_nickname'] = $wuArr[$val['tmh_from_wu_id']];
                   
                   $val['to_wu_nickname'] = $wuArr[$val['tmh_to_wu_id']];
                   $val['tmh_reason'] = '';
                    $para = json_decode($val['tmh_para'],true);
                    if($para){
                       $val['tmh_reason'] = $para['reason']?:'';
                    }
                }
                unset($val);
            }
           
            LibTpl::Set('listArr',$res['data']);
        }
        $Pages = LibPage::Show($cntres['data']['counts'],$perPage,true);
        $res = $this->getSalesUser();
		LibTpl::Set('salesArr',$res['data']);
        LibTpl::Set('Pages',$Pages);
        LibTpl::Set('params',$params);
        LibTpl::Put();
    }
}