<?php
/*
 本代码由 焕岱科技 创建
 技术支持 WX：15285007200
 严禁反编译、逆向等任何形式的侵权行为，违者将追究法律责任
*/

namespace app\common\model\bbfxshop;

use think\Model;

use think\Db;
use think\Cache;
use aliyun\sms\SignatureHelper;

class Sms extends Model
{
    public static function getSet(){
        global $_W;
        $base = $_W['base'];
        if(empty($base)){
            $base = \app\common\model\bbfxshop\Common::getConfig(true);
        }
        
        $sms = $base['sms'];
        $sms['admin'] = $base['admin'];
        
        return $sms;
    }
    
    
    // 新订单通知
    public static function sendNewOrderNotice($order){
        $config = self::getSet();
        if(empty($config["aliyun_neworder_admin_templatecode"])){
            return __json(0,"未配置短信新订单通知模板");  
        }
        if(empty($config['admin'])){
            return __json(0,"未配置通知管理员");  
        }
        if(!is_array($order)){
            $order = Db::name("bbfx_order")->where(["id"=>intval($order),'is_pay'=>1])->find();
        }
        
        if(empty($order)){
            return __json(0,"订单不存在");   
        }
        
        $goods = iunserializer($order['goods_info']);
        
        $variable_list = [
            "order_no"=>$order['order_no'],
            "order_price"=>$order['price'],
            "goods_name"=>$goods[0]['title'],
            "goods_total"=>$goods[0]['total'],
            "order_time"=>date("Y-m-d H:i:s",$order['createtime']),
        ];
        
        $data = Array();
        
        if(!empty($config["aliyun_neworder_admin_variable"])){
            foreach ($config["aliyun_neworder_admin_variable"] as $key => $val){
                $data[$val] = $variable_list[$val];
            }
        }
        
        $templatecode = $config["aliyun_neworder_admin_templatecode"];
        $admin = explode(",",$config['admin']);
        
        foreach($admin as $key => $val){
            $phone = Db::name("bbfx_user")->where("id",$val)->value("mobile");
            if(!empty($phone)){
                $result = self::sendsms($templatecode,$phone,$data);
            }
        }
        
        if(empty($result)){
            return __json(0,"通知管理员不存在");  
        }
        
        return $result;
    }
    
    // 订单发货通知
    public static function sendOrderDeliveryNotice($order){
        $config = self::getSet();
        if(empty($config["aliyun_delivery_user_templatecode"])){
            return __json(0,"未配置短信订单发货通知模板");  
        }
        if(!is_array($order)){
            $order = Db::name("bbfx_order")->where(["id"=>intval($order),'is_pay'=>1])->find();
        }
        
        if(empty($order)){
            return __json(0,"订单不存在");   
        }
        
        $goods = iunserializer($order['goods_info']);
        $express = iunserializer($order['express']);
        
        $variable_list = [
            "order_no"=>$order['order_no'],
            "express_no"=>$express[0]['express_no'],
            "express_name"=>$express[0]['express_name'],
            "order_price"=>$order['price'],
            "goods_name"=>$goods[0]['title'],
            "goods_total"=>$goods[0]['total'],
            "order_time"=>date("Y-m-d H:i:s",$order['createtime']),
        ];
        
        $data = Array();
        
        if(!empty($config["aliyun_delivery_user_variable"])){
            foreach ($config["aliyun_delivery_user_variable"] as $key => $val){
                $data[$val] = $variable_list[$val];
            }
        }
        $templatecode = $config["aliyun_delivery_user_templatecode"];
        $phone = $order['delivery_mobile'];
        $result = self::sendsms($templatecode,$phone,$data);
        
        return $result;
    }
    
    // 提现结果通知
    public static function sendWithdrawalResultNotice($info){
        $config = self::getSet();
        if(empty($info)){
            return __json(0,"提现信息错误");  
        }
        if(empty($config["aliyun_withdrawal_user_templatecode"])){
            return __json(0,"未配置短信提现通知管理员模板");  
        }
        if(empty($config["aliyun_withdrawal_user_variable"])){
            // return __json(0,"未配置短信提现通知管理员模板变量");  
        }
        
        $realname = $info['realname'];
        if(empty($realname)){
            $realname = Db::name("bbfx_user")->where("id",$info['user_id'])->value("nickname");
        }
        $phone = Db::name("bbfx_user")->where("id",$info['user_id'])->value("mobile");
        if(empty($phone)){
            return __json(0,"用户未绑定手机号");  
        }
        
        if($info['status'] == 1){
            $status = "提现成功";
        }
        else{
            $status = "提现驳回";
        }
        
        $variable_list = [
            "realname"=>$realname,
            "money"=>$info['money'],
            "realmoney"=>$info['realmoney'],
            "status"=>$status
        ];
        
        $data = Array();
        
        if(!empty($config["aliyun_withdrawal_user_variable"])){
            foreach ($config["aliyun_withdrawal_user_variable"] as $key => $val){
                $data[$val] = $variable_list[$val];
            }
        }
        $templatecode = $config["aliyun_withdrawal_user_templatecode"];
        $result = self::sendsms($templatecode,$phone,$data);
        
        return $result;
    }
    
    
    // 提现通知
    public static function sendWithdrawalNotice($info){
        $config = self::getSet();
        if(empty($info)){
            return __json(0,"提现信息错误");  
        }
        if(empty($config["aliyun_withdrawal_admin_templatecode"])){
            return __json(0,"未配置短信提现通知管理员模板");  
        }
        if(empty($config["aliyun_withdrawal_admin_variable"])){
            // return __json(0,"未配置短信提现通知管理员模板变量");  
        }
        if(empty($config['admin'])){
            return __json(0,"未配置通知管理员");  
        }
        $realname = $info['realname'];
        if(empty($realname)){
            $realname = Db::name("bbfx_user")->where("id",$info['user_id'])->value("nickname");
        }
        $admin = explode(",",$config['admin']);
        
        $variable_list = [
            "realname"=>$realname,
            "money"=>$info['money'],
            "realmoney"=>$info['realmoney']
        ];
        
        $data = Array();
        if(!empty($config["aliyun_withdrawal_admin_variable"])){
            foreach ($config["aliyun_withdrawal_admin_variable"] as $key => $val){
                $data[$val] = $variable_list[$val];
            }
        }
        $templatecode = $config["aliyun_withdrawal_admin_templatecode"];
        foreach($admin as $key => $val){
            $phone = Db::name("bbfx_user")->where("id",$val)->value("mobile");
            if(!empty($phone)){
                $result = self::sendsms($templatecode,$phone,$data);
                break;
            }
        }
        
        if(empty($result)){
            return __json(0,"通知管理员不存在");  
        }
        
        return $result;
    }
    
    // 短信验证码
    public static function sendCode($phone,$type='login'){
        $config = self::getSet();

        $time = strtotime(date('Y-m-d 00:00:00'));
        $count = Db::name("bbfx_verifcode")->where(['uniacid'=>UNIACID,"mobile"=>$phone,'createtime'=>['>',$time]])->count();
        if($count >= 10){
            return __json(0,"请勿频繁发送短信验证码");  
        }
        $ip = request()->ip();
        $count = Db::name("bbfx_verifcode")->where(['uniacid'=>UNIACID,"ip"=>$ip,'createtime'=>['>',$time]])->count();
        if($count >= 20){
            return __json(0,"请勿频繁发送短信验证码");  
        }
 
        $code = rand(1111,9999);
        $data = ['code'=>$code];
        if(empty($config["aliyun_templatecode"])){
            return __json(0,"未配置短信验证码模板");  
        }
        $result = self::sendsms($config["aliyun_templatecode"],$phone,$data);
        if($result['code'] == 1){
            
            $data = array(
                "uniacid"=>UNIACID,
                "mobile"=>$phone,
                "code"=>$code,
                "type"=>$type,
                "ip"=>$ip,
                "expirestime"=>(time() + 300),
                "createtime"=>time()
            );
            
            Db::name("bbfx_verifcode")->insert($data);
        }
        
        return $result;
    }
    
    public static function sendsms($templatecode,$phone,$data){
        $config = self::getSet();
        
        // $data = ['code'=>123456];//短信模板变量
        
        // return __json(-1,"5555");
        $params = array();
        
        // *** 需用户填写部分 ***
        // fixme 必填：是否启用https
        $security = false;
    
        // fixme 必填: 请参阅 https://ak-console.aliyun.com/ 取得您的AK信息
        $accessKeyId = $config["aliyun_accesskeyid"];
        $accessKeySecret = $config["aliyun_accesskeysecret"];
    
        // fixme 必填: 短信接收号码
        $params["PhoneNumbers"] = "$phone";
    
        // fixme 必填: 短信签名，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
        $params["SignName"] = $config["aliyun_signame"];
    
        // fixme 必填: 短信模板Code，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
        $params["TemplateCode"] = $templatecode;
        if(empty($params["TemplateCode"])){
            return __json(0,"未配置短信模板"); 
        }
    
        // fixme 可选: 设置模板参数, 假如模板中存在变量需要替换则为必填项
        // $params['TemplateParam'] = Array(
        //     "code" => $code,
        // );
        $params['TemplateParam'] = $data;
        // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
        if (!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
            $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
        }
    
        // 初始化SignatureHelper实例用于设置参数，签名以及发送请求
        $helper = new SignatureHelper();
        // 此处可能会抛出异常，注意catch
        $content = $helper->request(
            $accessKeyId,
            $accessKeySecret,
            "dysmsapi.aliyuncs.com",
            array_merge($params, array(
                "RegionId" => "cn-hangzhou",
                "Action" => "SendSms",
                "Version" => "2017-05-25",
            )),
            $security
        );
        
        $result = json_decode(json_encode($content),true);
        
        if($result["Code"] === "OK"){
            return __json(1,"短信发送成功");
        }
        return __json(0,"短信发送失败，请检查验证码参数是否正确。");
        // return __json(0,$result["Message"]);
    }
    
    public static function checkVerifcode($mobile,$code,$type='login'){
        
        $verifcode = Db::name("bbfx_verifcode")->where(['uniacid'=>UNIACID,'mobile'=>$mobile,'code'=>$code,'type'=>$type])->find();
        if(empty($code) || empty($verifcode)){
            return __json(0,"验证码错误");
        }
        if($verifcode['status'] != 0){
            return __json(0,"验证码已失效");
        }
        if($verifcode['expirestime'] < time()){
            return __json(0,"验证码已过期");
        }
        
        Db::name("bbfx_verifcode")->where(['id'=>$verifcode['id']])->update(['status'=>1]);
        
        return __json(1,"验证码验证成功");
    }

    public static function getVariableList($tpl = ""){
        
        $data = [
            "aliyun_neworder_admin_templatecode"=>[
                ["title"=>"订单编号","key"=>"order_no"],
                ["title"=>"订单金额","key"=>"order_price"],
                ["title"=>"商品名称","key"=>"goods_name"],
                ["title"=>"商品数量","key"=>"goods_total"],
                ["title"=>"下单时间","key"=>"order_time"],
            ],
            "aliyun_delivery_user_templatecode"=>[
                ["title"=>"订单编号","key"=>"order_no"],
                ["title"=>"快递单号","key"=>"express_no"],
                ["title"=>"快递名称","key"=>"express_name"],
                ["title"=>"订单金额","key"=>"order_price"],
                ["title"=>"商品名称","key"=>"goods_name"],
                ["title"=>"商品数量","key"=>"goods_total"],
                ["title"=>"下单时间","key"=>"order_time"],
            ],
            "aliyun_withdrawal_user_templatecode"=>[
                ["title"=>"用户姓名","key"=>"realname"],
                ["title"=>"提现金额","key"=>"money"],
                ["title"=>"实际到账","key"=>"realmoney"],
                ["title"=>"状态","key"=>"status"],
            ],
            "aliyun_withdrawal_admin_templatecode"=>[
                ["title"=>"用户姓名","key"=>"realname"],
                ["title"=>"提现金额","key"=>"money"],
                ["title"=>"实际到账","key"=>"realmoney"],
            ],
        ];
        
        if(empty($tpl)){
            return $data;
        }
        
        return $data[$tpl];
    }
}