<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Class Email
 * Created by: Owen
 * Created on: 2020/7/13 17:31
 */
class Email extends MY_Controller
{
    public function task(){
//        var_dump(oo::logs()->commlog('123','test'));
        $st = microtime(true);
//        var_dump(oo::commonOprModel('Email')->verifyEmail(3));
//        var_dump(oo::commonOprModel('Email')->sendMailNew('zhaoyihui1203@163.com',"测试标题","666666"));
        oo::commonOprModel('Email')->callBackEmail();
        $et = microtime(true);
        var_dump($et-$st);
    }
    //查看邮件任务列表及详情
    public function eamilTask(){
        $taskCfg['mtype'] = 1;
        $taskCfg['type'] = 1;
        $taskCfg['utype'] = 1;
        $taskCfg['send_time'] = strtotime(date("Y-m-d H:i",time()));
        $taskCfg['cid'] = 1;
        $taskCfg['title'] = '立即发送';

        $tb2 = otable::EmailClassConf();
        $sql2 = "select * from {$tb2}";
        $emailClass= oo::commonOprDb('slavedb')->getAll($sql2,1);

        $tb3 = otable::EmailSendLog();
        $sql3 = "select * from {$tb3} order by id desc";
        $emailLog= oo::commonOprDb('slavedb')->getAll($sql3,1);
        $key =okeys::waitSendVerifyUidList();
        $len = oo::commonOprRedis('games')->lSize($key);
        $data['taskCfg'] = $taskCfg;
        $data['emailClass'] = $emailClass;
        $data['emailLog'] = $emailLog;
        $data['len'] = $len;
        $this->load->view('email/task', $data);
    }
    //保存邮件任务
    public function saveEmail(){
        $data = $this->input->post();
        $insertData['title'] = $data['title'];
        $insertData['create_time'] = time();
        $insertData['send_time'] =  strtotime(date('Y-m-d H:i',time()));
        $insertData['status'] =0;
        $insertData['type']  =intval($data['type']);//发送类型
        $insertData['utype']  =intval($data['utype']);//用户类型
        $insertData['mtype']  =intval($data['mtype']);//邮件类型
        $insertData['cid'] = intval($data['cid']);
        $insertData['ext'] = is_array($data['ext'])?json_encode($data['ext']):$data['ext'];
        if($data['type']==1){//立即发送
            $insertData['status']=1;
        }else if($data['type']==2){//定时发送
            $insertData['send_time'] = strtotime($data['send_time']);
        }else if($data['type']==3){//自动发
            $insertData['status']=1;
        }
        $tb = otable::EmailSendLog();
        if($data['mtype']==2){
            $sql = "SELECT * FROM {$tb} where mtype=2 and status=1";
            $haveData = oo::commonOprDb('games')->getOne($sql,1);
            if($haveData){
                return $this->response(0, '操作失败,当前有一条召回任务进行中,关闭后可新增');
            }
        }

        $sql =funs::db_insertSQL($tb,$insertData);
        $ret['insertRes'] = oo::commonOprDb('games')->query($sql);
        if($ret['insertRes']){
            $insertId = oo::commonOprDb('games')->insertID();
            if($data['type']==1){
                switch ($data['utype']){//用户群
                    case 1://指定uid列表
                        $ret['a'] =oo::commonOprModel('Email')->commonEmail($insertId);
                        break;
                    case 2://待验证邮箱的用户
                        break;
                    case 3://已验证过邮箱的用户
                        break;
                }
                if($data['mtype']==2){
                   $ret['b'] =  oo::commonOprModel('Email')->callBackEmail();
                }
            }
            oo::logs()->adminlog($this->router->fetch_method()."创建了邮群发任务,任务Id:{$insertId}");
           return $this->response(1, '操作成功',["data"=>$data,"ret"=>$ret]);
        }else{
            return $this->response(0, '操作失败',["ret"=>$ret]);
        }
    }
    //邮件模板展示
    public function showEmailClass($class = 1){

        $tb2 = otable::EmailClassConf();
        $sql2 = "select * from {$tb2}";
        $emailClass= oo::commonOprDb('slavedb')->getAll($sql2,1);

        $tb = otable::EmailConfig();
        $ret= oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb} WHERE class='{$class}'",MYSQLI_ASSOC);
        $list = array_column($ret,null,"lang");
        //自动新增国家
        foreach ($this->_langList as $item=>$v){
            if(!in_array($item,array_keys($list))){
                $insertData = [
                    "class"=>$class,
                    "lang"=>$item,
                    "content"=>"<p>123</p>",
                    "title" =>"title"
                ];
                $sql = funs::db_insertSQL($tb,$insertData);
                oo::commonOprDb('games')->query($sql);
                $insertData['id'] = oo::commonOprDb('games')->insertID();
                $list[$item] =  $insertData;
            }
        }
        foreach ($list as $k=>$v){
            $list[$k]['content'] = $this->escape($v['content']);
        }
        $data['emailClass'] = $emailClass;
        $data['list'] = json_encode($list);
        $data['class'] = $class;
        $data['selLang'] = 'zh';
        $data['langs'] =$this->_langList;
        $this->load->view('email/editClass', $data);
    }
    //新增邮件模板
    public function addEmailClass($class = 0){
        $data['list'] ='';
        if($class){
            $tb = otable::EmailConfig();
            $ret= oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb} WHERE class='{$class}'",MYSQLI_ASSOC);
            $list = array_column($ret,null,"lang");
            foreach ($list as $k=>$v){
                $list[$k]['content'] = $this->escape($v['content']);
            }

            $data['list'] = json_encode($list);
        }
        $data['selLang'] = 'zh';
        $data['langs'] =$this->_langList;
        $this->load->view('email/addClass', $data);
    }
    //新增保存邮件模板
    public function saveEmailClass(){
        $res=0;
        $data = $this->input->post();
        if(empty($data)){
            return $this->response(1, '数据不为空',["a"=>1,"conf"=>$data['conf']]);
        }
        $tb = otable::EmailClassConf();
        $insert_class = ["title"=>$data['title'],"create_time"=>time()];
        $sql1 = funs::db_insertSQL($tb,$insert_class);
        $res1 = oo::commonOprDb('games')->query($sql1);
        $cid = oo::commonOprDb('games')->insertID();
        $tb2 = otable::EmailConfig();
        foreach ($data['conf'] as $v){
//            $v['content'] = $this->escape($v['content']);
            unset($v['id']);
            $v['class'] = $cid;
            $insert_email = $v;
            $sql = funs::db_insertSQL($tb2,$insert_email);
            $res = oo::commonOprDb('games')->query($sql);
        }
        if($res == 0){
            return $this->response(1, '操作失败',["a"=>2,"conf"=>$data['conf']]);
        }else{
            return $this->response(0, '操作成功',["a"=>3,"conf"=>$data['conf']]);
        }
    }
    //编辑邮件模板
    function editSaveEmailClass(){
        $res=false;
        $data = $this->input->post();
        $tb = otable::EmailConfig();
        foreach ($data['conf'] as $v){
            $updata = [];
            $w ="id={$v['id']}";
            $updata['content'] = $v['content'];
            $updata['title'] = $v['title'];
            $sql = funs::db_updateSQL($tb,$updata,$w);
            $res = oo::commonOprDb('games')->query($sql);
        }
        if($res){
            return $this->response(0, '操作成功');
        }else{
            return $this->response(1, '操作失败');
        }
    }

    //暂停邮件任务
    function closeEmail($tid = 0){
        if($tid>0){
            $tb = otable::EmailSendLog();
            $w ="id={$tid}";
            $updata['status'] = 3;
            $sql = funs::db_updateSQL($tb,$updata,$w);
            $res = oo::commonOprDb('games')->query($sql);
        }
        $this->eamilTask();
    }

    function sendNew($tid=0){
        if($this->config->item('oos_debug')){
            oo::commonOprModel('email')->callBackEmail();
            var_dump("执行成功");
        }else{
            var_dump("正式环境不支持次操作");
        }

    }

    function escape($string, $in_encoding = 'UTF-8',$out_encoding = 'UCS-2') {
        $return = '';
        if (function_exists('mb_get_info')) {
            for($x = 0; $x < mb_strlen ( $string, $in_encoding ); $x ++) {
                $str = mb_substr ( $string, $x, 1, $in_encoding );
                if (strlen ( $str ) > 1) { // 多字节字符
                    $return .= '%u' . strtoupper ( bin2hex ( mb_convert_encoding ( $str, $out_encoding, $in_encoding ) ) );
                } else {
                    $return .= '%' . strtoupper ( bin2hex ( $str ) );
                }
            }
        }
        return $return;
    }
//=================================================================
    public function index($class = 1){
        $tb = otable::EmailConfig();
        $ret= oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb} WHERE class='{$class}'",MYSQLI_ASSOC);
        $this->load->view('email/index', ['data'=>$ret]);
    }

    public function edit($id = 1){
        $tb = otable::EmailConfig();
        $ret= oo::commonOprDb('slavedb')->getOne("SELECT * FROM {$tb} WHERE id='{$id}'",MYSQLI_ASSOC);
        $this->load->view('email/edit', ['data'=>$ret]);
    }

    public function actionEdit(){
        $data = $this->input->post();
        $id = $data['id'];
        $content = $data['content'];
        $tb = otable::EmailConfig();
        $res  = oo::commonOprDb('games')->query("UPDATE {$tb} SET content='{$content}' WHERE id={$id}");
        if($res == 0){
            return $this->response(1, '操作失败');
        }else{
            return $this->response(0, '操作成功');
        }
    }

    public function actionRecall(){
//        var_dump(112222222);
        //召回邮件
//        oo::commonOprModel('Email')->actionRecall();
    }

    //邮箱填写弹出配置
    public function emailPopConfig()
    {
        $config = oo::commonOprModel('config')->getCon("email", "emailPopConfig") ?? '[]';

        $this->load->view('email/emailPopConfig', json_decode($config, true));
    }

    //邮箱填写弹出配置更新
    public function emailPopConfigUpdate()
    {
        $data = $this->input->post();

        oo::commonOprModel('config')->updateCon("email", "emailPopConfig", json_encode($data, JSON_NUMERIC_CHECK), '邮箱填写弹出配置');

        $filename = 'EmailPopConfig' . time() . '.json';

        oo::commonOprModel("json")->SaveJson($data, $filename);
        oo::commonOprModel("json")->setStaticConfig("EmailPopConfig", $filename);

        return $this->response(0, '操作成功');
    }
}