<?php
namespace app\admin\controller;
use app\model\SmsStyle;
use think\facade\View;
use app\common\sms\Sms as SmsClass;
/**
 * 短信配置
 * Class Sms
 * @package app\admin\controller
 */
class Sms extends AdminController {

    public function index(){

        $sms = config('sms') ;
        $style = SmsStyle::select();
        $templates = [] ;
        if( !$style->isEmpty() ){
            foreach ($style as $key=>$value){
                if( !isset($templates[$value->type]) ){
                    $templates[$value->type] = $value ;
                }
            }
        }
        View::assign('sms1',$sms['sms1'] ?? []);
        View::assign('sms2',$sms['sms2'] ?? []);

        View::assign('lost',$templates[0] ?? []);
        View::assign('order',$templates[1] ?? []);

        View::assign('sms',$sms) ;
        return View::fetch();
    }

    public function store(){

        $sms1 = request()->post('sms1/a',[]);
        $sms2 = request()->post('sms2/a',[]);
        $smsType = request()->post('type',0);

        $rs = setConfig([
            'sms1'=>$sms1,
            'sms2'=>$sms2,
            'type'=>$smsType,
            'test'=>request()->post('test','')
        ],'sms');

        $lost = request()->post('lost',[]);
        $order = request()->post('order',[]);

        $templates = [$lost,$order] ;
        $returnArray = [] ;

        foreach($templates as $key=>$value ){
            if( empty( $value['id'] ) ){
                $data = $value;
                unset($data['id']);
                $rs = SmsStyle::create($data);
                $returnArray[$key]= $rs->id ;
            }else{
                $rs = SmsStyle::update($value);
            }
        }
        if( $rs ){
            return $this->responseSuccess();
        }

        return $this->responseError();
    }

    // 测试短信
    public function test(){

        $type = request()->post('type');
        $params = request()->post($type);
        $params['to'] = request()->post('test');
        $params['content'] = '只是一条测试短信';

        // 获取短信实例
        $sms = SmsClass::init($type);
        // 设置短信参数
        //$data = SmsClass::initParams($params);
        // 发送短信
        $rs = $sms->send($params);

        if( $rs !== FALSE ){
            return $this->responseSuccess($rs);
        }

        return $this->responseError($sms->error()) ;
    }

}
