<?php
/**
 * 系统查询接口
 * @date: 2019年7月16日 下午12:36:43
 * @author: 龚华尧
 * @param: $GLOBALS
 * @return:
 */

class indexController extends baseController {

    /**

     * 统一查询方法

     * @date: 2019年1月28日 下午2:53:06

     * @author: 龚华尧

     * @param: variable

     * @return:

     */
    public function searchAction(){
        //接口安全验证开始
        //$this->apisafefilter();

        $commonClass = $this->common;
        //处理查询表
        $t=$this->TablenameFilter($commonClass->Requert("t")  );

        //处理返回的列名称，用于多表查询
        $liemingcheng=$this->LiemingchengFilter($commonClass->Requert("liemingcheng"));
        //返回条数
        $number=$this->NumberFilter($commonClass->Requert("number") );
        //当前页数
        $page=$this->NumberFilter($commonClass->Requert("page") );

        // 		   ordertype：排序字段，默认已有ID，如不需要排序请为空
        $ordertype=$commonClass->SafeFilterStr( $commonClass->Requert("ordertype") );
        // 		   orderby：排序方式，升序和降序
        $orderby=$commonClass->SafeFilterStr( $commonClass->Requert("orderby") );
        // 		   sqlvalue：默认查询方式,如果有多个用逗号分隔，“|”会替换成=号
        $sqlvalue=$this->SqlvalueFilter( $commonClass->Requert("sqlvalue") );
        // Print 打印测试，如需把sql打印出来，把改成yes，需要显示结果可不传或为空。
        $print=$commonClass->Requert("print")  ;

        //拼接为sql语句
        $_sql=$this->getSql($t,$liemingcheng,$number,$page,$ordertype,$orderby,$sqlvalue);
        if($print=="yes")
        {
            echo $_sql;
            die();
        }

        $temp_model = new Model($t);
        $temp_arr=$temp_model->findBySql($_sql);
        //挂载控件类
        $this->library("Component");
        $ComponentClass = new Component();
        $tableModel = new tableModel();
        $filedModel=new filedModel();
        $table_id = $tableModel->gettableidBytablename($t);
        $filedAraay=$filedModel->getallFiledByTableid($table_id);

        foreach ($filedAraay as $v)
        {
            //处理不同字段的显示数据
            foreach ($temp_arr as $k1=>$v1) {
                $v1[$v['u1']] =$ComponentClass->showvalueKj($v['u7'],$v['u2'],$v['u1'] ,$v1[$v['u1']],$v['u3'] ,$v['id']) ;
                $temp_arr[$k1]=$v1;
            }
        }
        $_tableList["data"]=$temp_arr;
        $_tableList["count"]=$temp_model->total($sqlvalue);

        returnSuccess($_tableList, "成功",$code=0);

    }

    /**

     * 添加数据统一接口

     * @date: 2019年2月14日 下午5:50:41

     * @author: 龚华尧

     * @param: variable

     * @return:

     */
    public function addAction(){
        //接口安全验证开始
        //$this->apisafefilter();

        $commonClass = $this->common;
        //处理查询表
        $t=$this->TablenameFilter($commonClass->Requert("t")  );

        $tableName=str_replace("sl_","",$t);
        //待处理的表
        $tableModel = new Model($tableName);
        $moxingModel = new tableModel();
        $model_id=$moxingModel->gettableidBytablename($tableName);
        //1.收集表单数据
        $data=$tableModel->getFieldArray();
        //2.验证和处理
        $this->helper('input');
        $data = deepspecialchars($data);

        //时间默认为空则为当前时间
        if(!isset($data['dtime']))
        {
            $data['dtime']=date("Y-m-d H:i:s");
        }

        if($tableModel->insert($data)){

            returnSuccess("更新成功", "成功",$code=0);

        }else{

            returnFail("更新失败");
        }

    }

    /**

     * 统一修改接口

     * @date: 2019年2月21日 下午5:27:50

     * @author: 龚华尧

     * @param: variable

     * @return:

     */
    public function editAction(){
        //接口安全验证开始
        //$this->apisafefilter();

        $commonClass = $this->common;
        //处理查询表
        $t=$this->TablenameFilter($commonClass->Requert("t")  );

        $tableName=str_replace("sl_","",$t);
        //待处理的表
        $tableModel = new Model($tableName);
        $moxingModel = new tableModel();
        $model_id=$moxingModel->gettableidBytablename($tableName);
        //1.收集表单数据
        $data=$tableModel->getFieldArray();
        //2.验证和处理
        $this->helper('input');
        $data = deepspecialchars($data);

        if($tableModel->update($data)){

            returnSuccess("更新成功", "成功",$code=0);
        }else{
            returnFail("更新失败");
        }

    }

    /**

     * 统一删除接口

     * @date: 2019年2月21日 下午5:27:50

     * @author: 龚华尧

     * @param: variable

     * @return:

     */
    public function delAction(){
        //接口安全验证开始
        //$this->apisafefilter();

        $commonClass = $this->common;
        //处理查询表
        $t=$this->TablenameFilter($commonClass->Requert("t")  );

        $tableName=str_replace("sl_","",$t);
        //待处理的表
        $tableModel = new Model($tableName);
        $moxingModel = new tableModel();
        $model_id=$moxingModel->gettableidBytablename($tableName);
        //1.收集表单数据
        $data=$tableModel->getFieldArray();
        //2.验证和处理
        $this->helper('input');
        $data = deepspecialchars($data);

        $detail = $tableModel->findOne($data['id']);
        if($detail){
            if($detail['yonghu']!=$data['yonghu']){
                returnFail("不能删除其他用户的数据");

            }else{
                if($tableModel->delete($data['id'])){

                    returnSuccess("删除成功", "成功",$code=0);
                }else{
                    returnFail("删除失败");
                }

            }

        }else{
            returnFail("当前记录不存在");
        }



    }

    /**
     * Name:获取微信用户授权后的信息
     * Notes:
     * User: gonghuayao
     * Date: 2019-11-04
     * Time: 20:21
     */
    public  function getwxuserinfoAction() {
        $code = RequertBody("code");
        $APPID=$GLOBALS['config_account']['WX_APPID'];
        $SECRET=$GLOBALS['config_account']['WX_SECRET'];
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$APPID}&secret={$SECRET}&js_code={$code}&grant_type=authorization_code";
//	    var_dump($url);
        $UserInfo =  json_decode($this->common->get_webHtml($url), true);
//        var_dump($UserInfo);die();
        //var_dump($UserInfo);die();
        //挂载微信小程序解密文件
        include_once LIB_PATH. "Wx/xcx/"."wxBizDataCrypt.php"; #此文件见下方
        $sessionKey = $UserInfo['session_key'];
        #上图getuserinfo接口里返回的数据
        $encryptedData=RequertBody("encryptedData");
        $iv = RequertBody("iv");
        $pc = new WXBizDataCrypt($APPID, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data );
        if ($errCode == 0) {
            //var_dump($data);die();

            //更新用户数据
            $ImUserM = new ImUserModule();
            $wxInfo = json_decode($data, true);
            $ImUserWxdata = $ImUserM->getUserDataByWxopenid($wxInfo["openId"]);
//            var_dump(count($ImUserdata));
            $userdata = $ImUserM->getCurrentLoginedUser();
            if(count($ImUserWxdata)==0){
                $ImUserM->updateUserByWxinfo($userdata["number"],$wxInfo );
            }else{
                //删除掉临时用户
//                $ImUserM->delete($userdata['id']);
            }

            returnSuccess($ImUserM->wx_login($wxInfo["openId"]));

        } else {
            //var_dump($errCode);die();
            returnFail($errCode);
        }

        //var_dump($UserInfo);
    }

    /**

     * 发送短信

     * @date: 2019年2月21日 下午3:05:35

     * @author: 龚华尧

     * @param: variable

     * @return:

     */
    public function sendsmsAction() {
        //接口安全验证开始
        $this->apisafefilter();

        $shoujihao = $this->common->Requert("shoujihao");
        $this->library("Sms");
        $smsClass = new Sms();

        //验证用户是否可以登录
        $daoruyonghuM = new daoruyonghuModule();
        if($daoruyonghuM->ableLogin()){

            $smsClass->lingkai($shoujihao, "","验证码");
            returnSuccess("短信已发送", "成功",$code=0);



        }else{
            returnSuccess("该手机号没有登录权限", "成功",1);
        }


    }

    /**

     * 验证验证码

     * @date: 2019年2月21日 下午4:28:56

     * @author: 龚华尧

     * @param: variable

     * @return:

     */
    public function checksmsAction() {
        //接口安全验证开始
        //$this->apisafefilter();
        $shoujihao = $this->common->Requert("shoujihao");
        $yzm= $this->common->Requert("yzm");
        $yonghu= $this->common->Requert("yonghu");

        $this->library("Sms");
        $smsClass = new Sms();
        $_data = $smsClass->checkyzm($shoujihao, $yzm);
        if($_data['status'])
        {
            $yonghuM = new yonghuModule();
            $yonghuM->update(['id'=>$yonghu,'shoujihao'=>$shoujihao]);
            $usreInfo = $yonghuM->getdetailByid($yonghu);


            returnSuccess($usreInfo, "成功",$code=0);
        }else{
            returnFail($_data['msg']);
        }

    }

    /**

     * 发送微信模板消息短信

     * @date: 2019年2月21日 下午3:05:35

     * @author: 龚华尧

     * @param: variable

     * @return:

     */
    public function sendwxsmsAction() {
// 	    //接口安全验证开始
        //$this->apisafefilter();

        $APPID=$GLOBALS['config_account']['WX_APPID'];
        $SECRET=$GLOBALS['config_account']['WX_SECRET'];

        include_once LIB_PATH. "Wx/xcx/"."wxTemplateSms.php"; #此文件见下方

        $WxTmplateSmsClass = new wxTemplateSms($APPID,$SECRET);

        $openid="oL15O5cpiXXcC0SDSOB3sbhErMUI";
        $template_id="AveEe47atNGL50YC_3p8z6Zk_0Nu1skclceFs1EXPAI";
        $formid="045f975f13e84bc694a8ad3880672df5";

        $post_data = array (
            // 用户的 openID，可用过 wx.getUserInfo 获取
            "touser"           => $openid,
            // 小程序后台申请到的模板编号
            "template_id"      => $template_id,
            // 点击模板消息后跳转到的页面，可以传递参数
            "page"             => "/pages/index/index",
            // 第一步里获取到的 formID
            "form_id"          => $formid,
            // 数据
            "data" =>
                [
                    "keyword1" =>
                        [
                            "value" => '123',

                        ],
                    "keyword2" =>
                        [
                            "value" => '321',

                        ],
                    "keyword3" =>
                        [
                            "value" => '123321',

                        ],

                ]


        );


        $WxTmplateSmsClass->sendSms($post_data);



    }

    /**

     * 定时任务

     * @date: 2019年2月21日 下午3:05:35

     * @author: 龚华尧

     * @param: variable

     * @return:

     */
    public function dingshiAction() {
        ini_set('display_errors',1);            //错误信息
        ini_set('display_startup_errors',1);    //php启动错误信息
        error_reporting(-1);                    //打印出所有的 错误信息

        set_time_limit(0);

        $APPID=$GLOBALS['config_account']['WX_APPID'];
        $SECRET=$GLOBALS['config_account']['WX_SECRET'];
        include_once LIB_PATH. "Wx/xcx/"."wxTemplateSms.php"; #此文件见下方
        $WxTmplateSmsClass = new wxTemplateSms($APPID,$SECRET);

        $cur_hour = date('H', time());
        if($cur_hour>='0' && $cur_hour<='24')
        {
            $yonghuM = new yonghuModule();
            $formidM = new Model("formid");
            $zhengcekuM = new Model("zhengceku");
            $dingyuejiluM = new dingyuejiluModule();
            $rizhiM = new rizhiModule();

            $yonghulist=$yonghuM->findBySql("SELECT id,wx_openid,(select formid from sl_formid as f where f.yonghu=y.id LIMIT 0,1) as formid ,(select id from sl_formid as f where f.yonghu=y.id LIMIT 0,1) as fid from sl_yonghu as y HAVING formid is not null");
            //循环发送
            foreach ($yonghulist as $k=>$v){
                $yonghudata=$v;

                //查询是否已经发送了
                $rizhiData["dtime"]=date("Y-m-d");
                $rizhiData["yonghu"]=$yonghudata["id"];
                $rizhiData["leixing"]=3;
                $_rizhidata = $rizhiM->where($rizhiData)->one();
                if(count($_rizhidata)>0){
                    continue;
                }

                $openid=$yonghudata["wx_openid"];
                $template_id="AveEe47atNGL50YC_3p8z6Zk_0Nu1skclceFs1EXPAI";
                $formid=$yonghudata["formid"];
                $keyword3_value="";

                $dingyuejiluArray = $dingyuejiluM->getdingyuelistByYonghu($yonghudata['id']);
                //拼接政策关键词
                $_whereStr=" date(fawenriqi) = curdate() and chaifenzhuangtai=3 ";
                $whereStr="";
                foreach ($dingyuejiluArray as $k1=>$v1){
                    if($whereStr==""){
                        $whereStr=" biaoqian like '%{$v1["name"]}%' ";
                    }else{
                        $whereStr=$whereStr." or "."biaoqian like '%{$v1["name"]}%' ";
                    }
                }
                if($whereStr!=""){
                    $whereStr=$_whereStr." and ({$whereStr}) ";
                }

                //查询用户订阅的政策更新
                $zcList = $zhengcekuM->find("id,biaoqian")->where($whereStr)->orderBy("fawenriqi desc,id desc")->all();
                if(count($zcList)==0){
                    continue;
                }
                //拼接订阅栏目
                foreach ($zcList as $k1=>$v1){
                    if(strlen($keyword3_value)>100){
                        $keyword3_value=$keyword3_value."...";
                        break;
                    }
                    if($keyword3_value==""){
                        $keyword3_value=$v1["biaoqian"];
                    }else{
                        $keyword3_value=$keyword3_value.",".$v1["biaoqian"];
                    }
                }
                //var_dump($keyword3_value);die();

                $post_data = array (
                    // 用户的 openID，可用过 wx.getUserInfo 获取
                    "touser"           => $openid,
                    // 小程序后台申请到的模板编号
                    "template_id"      => $template_id,
                    // 点击模板消息后跳转到的页面，可以传递参数
                    "page"             => "/pages/index/index",
                    // 第一步里获取到的 formID
                    "form_id"          => $formid,
                    // 数据
                    "data" =>
                        [
                            "keyword1" =>
                                [
                                    "value" => "您订阅的政策有".count($zcList)."条更新，快去看看吧",

                                ],
                            "keyword2" =>
                                [
                                    "value" => date("Y-m-d"),

                                ],
                            "keyword3" =>
                                [
                                    "value" => $keyword3_value,

                                ],

                        ]


                );

                $re_data=$WxTmplateSmsClass->sendSms($post_data);

                //删除已发送的formid
                $formidM->delete($yonghudata["fid"]);
                //插入模版消息
                $rizhiData["dtime"]=date("Y-m-d");
                $rizhiData["yonghu"]=$yonghudata["id"];
                $rizhiData["leixing"]=3;
                $rizhiM->insert($rizhiData);

                var_dump($re_data);flush();

            }

        }

    }

    /**
     * 获取全局状态码
     */
    public function getStatusCodeAction(){
        $code = $GLOBALS['config_code'];
        returnSuccess($code,getcodestr(200),200);
    }

    /**
     * 获取全局参数
     */
    public function getStatusParameterAction(){
        $parameter = (new parameterModel())->getParameterAllChildByClassId(330);
        returnSuccess($parameter,getcodestr(200),200);
    }

}
