<?php
/**
 * 广告落地页模块
 * 专门处理 广告落地页 相关的功能，可放到不同项目里，继承index/base
 * 
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 *
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * $Author: lilong<lilong@suxuantech.cn> 2019-08-23 $
 */
namespace app\Advert\controller;
use app\index\controller\Base;
use think\Request;
use think\Exception;
use think\Response;
use Endroid\QrCode\QrCode;
class Advert extends Base{
    //落地页列表
	function index(){
        $data = input();
        $page = $data['page'] ? $data['page'] : 1;
        $limit = $data['limit'] ? $data['limit'] : 10;
        $info = db('crm_s_advert_list')->where('add_shop_code',session('shop_code'))->order('create_time desc')->page($page)->limit($limit)->select();
        $count = db('crm_s_advert_list')->where('add_shop_code',session('shop_code'))->count();
        if(request()->isAjax()){
            if($info){
                $channel = db('crm_s_advert_channel')->where('shop_code',session('shop_code'))->order('sort')->limit(4)->select();
                foreach ($info as $key => $value) {
                    $info[$key]['yl'] = url('advert/Index/preview',['advert_code'=>$value['advert_code'],'channel_id'=>'0']);
                    foreach ($channel as $k => $v) {
                        $info[$key]['son'][$k]['qrcode'] = $value['advert_code'].$v['channel_id'].'.png';
                        $info[$key]['son'][$k]['advurl'] = getAppHost().url('advert/Index/preview',['advert_code'=>$value['advert_code'],'channel_id'=>$v['channel_id']]);
                    }
                }
                return array(
                    'code'=>200,
                    'data'=>array(
                        'info'=>$info,
                        'page'=>$page,
                        'limit'=>$limit,
                        'prev'=>$page-1<=0 ? $page : $page-1,
                        'next'=>$page+1>=ceil($count/$limit) ? ceil($count/$limit) : $page+1,
                        'count'=>$count,
                        'total'=>ceil($count/$limit),
                    )
                );
            }else{
                return array('code'=>100,'msg'=>'没有数据了。。。');
            }
        }else{
            $this->assign('count',$count);
            $this->assign('limit',$limit);
            $this->assign('prev',$page-1<=0 ? $page : $page-1);
            $this->assign('next',$page+1>=ceil($count/$limit) ? ceil($count/$limit) : $page+1);
            $this->assign('page',$page);
            $this->assign('total',ceil($count/$limit));
            
            //渠道
            $channel = db('crm_s_advert_channel')->where('shop_code',session('shop_code'))->order('sort')->limit(4)->select();
            $this->assign('channel',$channel);
            foreach ($info as $key => $value) {
                $info[$key]['yl'] = url('advert/Index/preview',['advert_code'=>$value['advert_code'],'channel_id'=>'0']);
                foreach ($channel as $k => $v) {
                	$info[$key]['son'][$k]['qrcode'] = $value['advert_code'].$v['channel_id'].'.png';
                	$info[$key]['son'][$k]['advurl'] = getAppHost().url('advert/Index/preview',['advert_code'=>$value['advert_code'],'channel_id'=>$v['channel_id']]);
                }
            }
            // var_dump($info);
            // exit;
            $this->assign('info',$info);
            $this->assign('host',getAppHost());
            return $this->fetch();
        }
    }
    //落地页提报客资列表
    public function customerList(){
        $code = input('advert_code');
        $this->assign('advert_code',$code);
        $this->assign('is_in',input('is_in'));
        return $this->fetch();
    }
    public function customerListJSON(){
        $data = input();
        $result['code'] = 0;
        $result['msg'] = '';
        if($data['advert_code']){
            $where['advert_code'] = trim($data['advert_code']);
        }
        if($data['customer_tel']){
            $where['customer_tel'] = trim($data['customer_tel']);
        }
        if($data['is_in']){
            $where['is_in'] = intval($data['is_in']);
        }
        $page = $data['page'] ? $data['page'] : 1;
        $limit = $data['limit'] ? $data['limit'] : 30;
        $res = db('crm_s_advert_customer')->where('add_shop_code',session('shop_code'))->where($where)->order('id desc')->page($page)->limit($limit)->select();
        $count = db('crm_s_advert_customer')->where('add_shop_code',session('shop_code'))->where($where)->count();
        if($res){
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return ($result);
    }
	function add(){
        return $this->fetch();   
    }

    //删除落地页
    public function delAdvert(){
        $id = input('id');
        db()->startTrans();
        db('crm_s_advert_list')->where('id',$id)->delete();
        try{
            db()->commit();
            return array('code'=>200,'msg'=>'删除成功');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'删除失败','data'=>$e->getMessage());
        }
    }
    //落地页渠道设定
    public function advertChannel(){
        $staff = controller('crm/Customer','lib')->get_staff_list(['shop_code'=>session('shop_code')]);
        $this->assign('staff',$staff);
        $staff_id = db('crm_s_advert_channel')->where('shop_code',session('shop_code'))->value('staff_id');
        $this->assign('staff_id',$staff_id);
        return $this->fetch();
    }
    //设置落地页登记人
    public function addChannelStaff(){
        $param = input();
        $data['staff_id'] = $param['staff_id'];
        $data['staff_name'] = $param['staff_name'];
//        $data['brandclass_id'] = session('brandclass_id');
//        $data['brandclass'] = session('brandclass');
        $info = db('crm_s_advert_channel')->where('shop_code',session('shop_code'))->find();
        if(empty($info)){
            return array('code'=>99,'msg'=>'未设置渠道，不能设置登记人');
        }else{
            $log = '由 '.session('staff_name').' 于'.date('Y-m-d H:i:s').' 设置登记人为：【'.$data['staff_name'].'】';
            db()->startTrans();
            try{
                db('crm_s_advert_channel')->where('shop_code',session('shop_code'))->update($data);
                action_log($log,[]);
                db()->commit();
                return array('code'=>200,'msg'=>'登记人设置成功');
            }catch (\Exception $e){
                db()->rollback();
                return array('code'=>100,'msg'=>'登记人设置失败','data'=>$e->getMessage());
            }
        }
    }
    public function channelJSON(){
        $data = input();
        $result['code'] = 0;
        $result['msg'] = '';
        if($data['channel_name']){
            $where['channel_name'] = trim($data['channel_name']);
        }
        $page = $data['page'] ? $data['page'] : 1;
        $limit = $data['limit'] ? $data['limit'] : 100;
        $res = db('crm_s_advert_channel')->where('shop_code',session('shop_code'))->where($where)->order('sort')->page($page)->limit($limit)->select();
        $count = db('crm_s_advert_channel')->where('shop_code',session('shop_code'))->where($where)->count();
        if($res){
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return ($result);
    }
    public function addChannel(){
        if(request()->isAjax()){
            $param = input();
            $channels = controller('crm/Customer','lib')->getChannel();
            $channel = [];
            foreach($channels as $k=>$v){
                $channel[$v['id']] = $v;
            }
            //删除原来设定
            $old = db('crm_s_advert_channel')->where('channel_id','in',$param['channel_id'])->where('shop_code',session('shop_code'))->select();
            $channel_ids = array_column($old,'channel_id');
            $data = [];
            $time = date('Y-m-d H:i:s');
            $log = '';
            foreach($param['channel_id'] as $k=>$v){
                if(in_array($v,$channel_ids)){
                    db('crm_s_advert_channel')->where('channel_id',$v)->where('shop_code',session('shop_code'))->update(['sort'=>$param['sort_'.$v]]);
                }else{
                    $log .= '由【'.session('staff_name').'】于【'.$time.'】添加落地页渠道：';
                    $data[$k]['channel_id'] = $v;
                    $data[$k]['channel_name'] = $channel[$v]['channel_name'];
                    $data[$k]['sort'] = $param['sort_'.$v] ? intval($param['sort_'.$v]) : $channel[$v]['order_sort'];
                    $data[$k]['shop_code'] = session('shop_code');
                    $data[$k]['shop_name'] = session('shop_name');
                    $data[$k]['brandclass'] = session('brandclass');
                    $data[$k]['brandclass_id'] = session('brandclass_id');
                    $data[$k]['create_time'] = $time;
                    $log .= '【'.$channel[$v]['channel_name'].'】,排序【'.intval($param['sort_'.$v]).'】';
                }
            }

           db()->startTrans();
            try{
                db('crm_s_advert_channel')->insertAll($data);
                action_log($log,[]);
                db()->commit();
                return array('code'=>200,'msg'=>'添加成功');
            }catch (\Exception $e){
                db()->rollback();
                return array('code'=>100,'msg'=>'添加失败','data'=>$e->getMessage());
            }
        }else{
            $channel = controller('crm/Customer','lib')->getChannel();
            $info = db('crm_s_advert_channel')->where('shop_code',session('shop_code'))->column('channel_id,sort,channel_name','channel_id');
            foreach($channel as $k=>$v){
                if($v['id'] == $info[$v['id']]['channel_id']){
                    $channel[$k]['checked'] = 1;
                    $channel[$k]['sort'] = $info[$v['id']]['sort'];
                }
            }
            $this->assign('channel',$channel);
            return $this->fetch();
        }
    }
    public function editChannel(){
        $param = input();
        $data['sort'] = intval($param['sort']);
        $data['staff_id'] = intval($param['staff_id']);
        $data['staff_name'] = trim($param['staff_name']);
        $data['brandclass'] = session('brandclass');
        $data['brandclass_id'] = session('brandclass_id');
        $info = db('crm_s_advert_channel')->where('id',$param['id'])->find();
        $time = date('Y-m-d H:i:s');
        db()->startTrans();
        try{
            db('crm_s_advert_channel')->where('id',$param['id'])->update($data);
            $log = '由【'.session('staff_name').'】于【'.$time.'】修改落地页渠道排序由【'.$data['order_sort'].'】改为【'.$info['sort'].'】，登记人为：【'.$data['staff_name'].'】';
            action_log($log,[]);
            db()->commit();
            return array('code'=>200,'msg'=>'修改成功');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'修改失败','data'=>$e->getMessage());
        }
    }
    public function otherChannel(){
    	$param = input();
    	$aid = (int)$param['aid'];
		if (!$aid) {
			return [];
		}
		$code = db('crm_s_advert_list')->where('id',$aid)->value('advert_code');
		if (!$code) {
			return [];
		}
        $info = db('crm_s_advert_channel')->where('shop_code',session('shop_code'))->order('sort')->limit(4,10)->select();
        if(!empty($info)){
        	foreach ($info as $key => $value) {
        		$info[$key]['qrcode'] = $code.$value['channel_id'].'.png';
        		$info[$key]['advurl'] = getAppHost().url('advert/Index/preview',['advert_code'=>$code,'channel_id'=>$value['channel_id']]);
        	}
            return $info;
        }else{
            return [];
        }
    }
    public function createEwm(){
        $code = input('advert_code');
        //添加表单对应的二维码
        $channel = db('crm_s_advert_channel')->where('shop_code',session('shop_code'))->select();
        foreach($channel as $k=>$v){
            $this->qr_code($code,$v['channel_id']);
        }
    }
    public function delChannel(){
        $param = input();
        $info = db('crm_s_advert_channel')->where('id',$param['id'])->find();
        $time = date('Y-m-d H:i:s');
        db()->startTrans();
        try{
            db('crm_s_advert_channel')->where('id',$param['id'])->delete();
            $log = '由【'.session('staff_name').'】于【'.$time.'】删除落地页渠道【'.$info['channel_name'].'】';
            action_log($log,[]);
            db()->commit();
            return array('code'=>200,'msg'=>'删除成功');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'删除失败','data'=>$e->getMessage());
        }
    }
    //添加表单
    public function createForm(){
        if(request()->isAjax()){
            $time = date('Y-m-d H:i:s');
            $param = input();
            $data = json_decode($param['DATA'],true);
            $template = json_decode($data['FIELDVALUES']['TEMPLATE'],true);
            foreach($template['component'] as $k=>$v){
                foreach($v as $kk=>$vv){
                    if($kk=='img' || $kk=='imglink'){
                        $template['component'][$k][$kk] = urldecode($vv);
                    }
                }
                if($v['name'] == 'id_pictureCheckbox'){
                    foreach($v['value'] as $kkk=>$vvv){
                        $template['component'][$k]['value'][$kkk]['img'] = urldecode($vvv['img']);
                    }
                }
                if($v['name'] == 'id_pictureRadio'){
                    foreach($v['value'] as $kkk=>$vvv){
                        $template['component'][$k]['value'][$kkk]['img'] = urldecode($vvv['img']);
                    }
                }
            }
            if($data['FRID'] != 'false'){
                $ins['update_time'] = $time;
                $ins['advert_code'] = db('crm_s_advert_list')->where('id',$data['FRID'])->value('advert_code');
            }else{
                $ins['create_time'] = $time;
                $ins['advert_code'] = think_encrypt(get_rand_string().time());
                $res = db('crm_s_advert_list')->where('advert_code',$ins['advert_code'])->value('id');
                if($res){
                    return array('code'=>99,'msg'=>'操作失败,已存在此编号的表单','data'=>''.$ins['advert_code']);
                }
            }
            $ins['name'] = $template['form']['title'];
            $ins['template'] = json_encode($template);

            $ins['style'] = $data['FIELDVALUES']['STYLE'];
            $ins['openfeedbackpwd'] = $data['FIELDVALUES']['openfeedbackpwd'];
            $ins['submitonce'] = $data['FIELDVALUES']['SUBMITONCE'];
            $ins['onlywechat'] = $data['FIELDVALUES']['ONLYWECHAT'];
            $ins['consumption_name'] = $param['cs_customer_types'];
            $ins['js_customer_service'] = $param['js_customer_service'];
            $ins['btn_name'] = $param['btn_name'];
            $ins['add_shop_code'] = session('shop_code');
            $ins['add_shop_name'] = session('shop_name');

            db()->startTrans();
            try{
                if($data['FRID'] != 'false'){
                    db('crm_s_advert_list')->where('id',$data['FRID'])->update($ins);
                    $log = '由【'.session('staff_name').'】于【'.$time.'】编辑表单【'.$ins['name'].'】';
                    action_log($log,[]);
                }else{
                    db('crm_s_advert_list')->insert($ins);
                    $sql = db()->getLastSql();
                    $log = '由【'.session('staff_name').'】于【'.$time.'】添加表单【'.$ins['name'].'】';
                    action_log($log,[]);
                }
                //添加表单对应的二维码
                $channel = db('crm_s_advert_channel')->where('shop_code',session('shop_code'))->select();
                foreach($channel as $k=>$v){
                    $this->qr_code($ins['advert_code'],$v['channel_id']);
                }
                db()->commit();
                return array('code'=>200,'msg'=>'操作成功','sql'=>$sql);
            }catch (\Exception $e){
                db()->rollback();
                return array('code'=>100,'msg'=>'操作失败','data'=>$e->getMessage());
            }
        }else{
            $consumptiontype = db('s_consumptiontype')->where('FIND_IN_SET("'.session('shop_code').'",shop_code)')->select();
            $this->assign('consumptiontype',$consumptiontype);
            $info = db('crm_s_advert_list')->where('id',input('id'))->find();
            $this->assign('info',$info);
            return $this->fetch();
        }
    }
    public function editForm(){
        $time = date('Y-m-d H:i:s');
        $param = input();
        $data = json_decode($param['DATA'],true);
        $template = json_decode($data['FIELDVALUES']['TEMPLATE'],true);
        $ins['advert_code'] = think_encrypt(get_rand_string().time());
        $res = db('crm_s_advert_list')->where('advert_code',$ins['add_shop_code'])->value('id');
        if($res){
            return array('code'=>99,'msg'=>'添加失败,已存在此编号的表单','data'=>'');
        }

        $ins['name'] = $template['form']['title'];
        $ins['template'] = $data['FIELDVALUES']['TEMPLATE'];
        $ins['style'] = $data['FIELDVALUES']['STYLE'];
        $ins['openfeedbackpwd'] = $data['FIELDVALUES']['openfeedbackpwd'];
        $ins['submitonce'] = $data['FIELDVALUES']['SUBMITONCE'];
        $ins['onlywechat'] = $data['FIELDVALUES']['ONLYWECHAT'];
        $ins['consumption_name'] = $param['cs_customer_types'];
        $ins['js_customer_service'] = $param['js_customer_service'];
        $ins['btn_name'] = $param['btn_name'];
        $ins['add_shop_code'] = session('shop_code');
        $ins['add_shop_name'] = session('shop_name');
        $ins['create_time'] = $time;
        // print_r($ins);die;
        db()->startTrans();
        try{
            db('crm_s_advert_list')->insertGetId($ins);
            $log = '由【'.session('staff_name').'】于【'.$time.'】添加表单【'.$ins['name'].'】';
            action_log($log,[]);
            db()->commit();
            return array('code'=>200,'msg'=>'添加成功');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'添加失败','data'=>$e->getMessage());
        }
    }
    public function handleGetForm(){
        $id = input('id');
        $data = db('crm_s_advert_list')->where('id',$id)->field('id,name,style,template,openfeedbackpwd,submitOnce,onlyWechat')->find();
        if(!empty($data)){
            $info['flag'] = true;
            $info['data'] = $data;
            return json($info);
        }else{
            $info['flag'] = true;
            $info['data'] = [];
            return json($info);
        }
    }
    //用于表单图片上传
    public function upload_photo(){
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('_FILE_');
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->move(ROOT_PATH.'public' . DS . 'upload/'.'advert/');
        if($info){
            // 成功上传后 返回上传信息
            $return['flag'] = true;
            $return['data']['url'] = '/upload/'.'advert/'.$info->getSaveName();
            $return['data']['fileUId'] =  '/upload/'.'advert/'.$info->getSaveName();
            return json($return);
        }else{
            // 上传失败返回错误信息
            $return['flag'] = false;
            $return['data']['url'] = $info->getSaveName()."?rand=".  get_rand_string();
            $return['data']['fileUId'] = $info->getSaveName()."?rand=".  get_rand_string();
            return json($return);
        }
    }
    //导出
    public function export(){
        $data=input();
        set_time_limit(0);
        $name = db('crm_s_advert_list')->where('advert_code',$data['advert_code'])->value('name');
        $file = $name.date('His').'.csv';
        // $title=['表单名称','店面','渠道','客资姓名','手机','微信','消费类型','咨询内容','是否存在于客资系统','ip','来源地址'];
        $title=['店面','渠道','客资姓名','手机','微信','消费类型','咨询内容','是否存在于客资系统','ip','来源地址'];
        foreach ($title as $key => $value) {
            $title[$key] = iconv("UTF-8", "GBK", $value);
        }
        $fp = fopen('php://output', 'a');
        fputcsv($fp, $title);

        header('Content-Type: application/vnd.ms-execl');
        header("Content-type:text/csv;charset=utf-8");
        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename='.$file);

        $pdo = db('crm_s_advert_customer')->getConnection()->getPdo();
        $pdo->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
        $customerSql=db('crm_s_advert_customer')->field('add_shop_name,customer_channel,customer_name,customer_tel,customer_wechat,consultation_type,form_content,is_in,ip,from_address')->where('advert_code',$data['advert_code'])->fetchSql()->select();

        $sth = $pdo->prepare($customerSql);
        $sth->execute();
        $count = 0;

        while ($value = $sth->fetch(\PDO::FETCH_ASSOC)) {
            // foreach ($value as $k => $v) {
                if($value['is_in'] == 1){
                    $value['is_in'] = '是';
                }else{
                    $value['is_in'] = '否';
                }
                foreach ($value as $k => $v) {
                    $value[$k] = iconv("UTF-8", "GBK", $v);
                }
            ++$count;
            fputcsv($fp, $value);
            unset($value);
            ob_flush();
            flush();
        }

        $log = '由【'.session('staff_name').'】于【'.date('Y-m-d H:i:s').'】导出表单名为【'.$name.'】的客资【'.$count.'】条，所在IP【'.get_client_ip().'】';
        //释放stmt内存
        db('crm_s_advert_customer')->getConnection()->free();
        action_log($log,$customerSql,0,session('staff_id'),session('staff_name'));
        exit;
    }
    public function qr_code($code='',$channel_id = ''){
        // $link = $_SERVER['HTTP_HOST'].'/advert/Index/preview.html?advert_code='.$code.'&channel_id='.$channel_id;
        $link = getAppHost().url('advert/Index/preview',['advert_code'=>$code,'channel_id'=>$channel_id]);
        $qrcode_dir = ROOT_PATH . '/public/qrcode/';
        if (!file_exists($qrcode_dir)) mkdir($qrcode_dir, 0777, true);
        $file_name = $code . $channel_id . '.png';
        // header('Content-Type: image/png');
        $qrCode = new QrCode($link);
        // $qrCode->writeString();
        $qrCode->writeFile($qrcode_dir.$file_name);
    }
}