<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Sms as Smslib;
use app\common\model\CompanyStaff;
use app\common\model\User;
use app\common\service\SmsService;
use think\Db;
use think\Exception;
use think\Hook;
use think\Log;

/**
 * 手机短信接口
 */
class Sms extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    /**
     * 发送验证码
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $event 事件名称
     */
    public function send($params=[])
    {
        $mobile = $this->request->post("mobile");
        $event = $this->request->post("event");
        $event = $event ? $event : 'register';
        $this->success(__('发送成功'));
        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }
        $last = Smslib::get($mobile, $event);
        if ($last && time() - $last['createtime'] < 60) {
            $this->error(__('发送频繁'));
        }
        $ipSendTotal = \app\common\model\Sms::where(['ip' => $this->request->ip()])->whereTime('createtime', '-1 hours')->count();
        if ($ipSendTotal >= 5) {
            $this->error(__('发送频繁'));
        }
        if ($event) {
            $userinfo = User::getByMobile($mobile);
            if (isset($params['is_company']) && $params['is_company'] ==1) {//兼容商家端获取验证码
                $userinfo = CompanyStaff::getByMobile($mobile);
            }
            if ($event == 'register' && $userinfo) {
                //已被注册
                $this->error(__('已被注册'));
            } elseif (in_array($event, ['changemobile']) && $userinfo) {
                //被占用
                $this->error(__('已被占用'));
            } elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
                //未注册
                $this->error(__('未注册'));
            }
        }
        if (!Hook::get('sms_send')) {
            $this->error(__('请在后台插件管理安装短信验证插件'));
        }
        $ret = Smslib::send($mobile, null, $event);
        if ($ret) {
            $this->success(__('发送成功'));
        } else {
            $this->error(__('发送失败,请检查短信配置是否正确'));
        }
    }

    /**
     * 商家端短信
     * @return void
     */
    public function companySend()
    {
        $params = [
            'is_company' => 1,
        ];
        $this->send($params);
    }

    /**
     * 检测验证码
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $event 事件名称
     * @param string $captcha 验证码
     */
    public function check()
    {
        $mobile = $this->request->post("mobile");
        $event = $this->request->post("event");
        $event = $event ? $event : 'register';
        $captcha = $this->request->post("captcha");

        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }
        if ($event) {
            $userinfo = User::getByMobile($mobile);
            if ($event == 'register' && $userinfo) {
                //已被注册
                $this->error(__('已被注册'));
            } elseif (in_array($event, ['changemobile']) && $userinfo) {
                //被占用
                $this->error(__('已被占用'));
            } elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
                //未注册
                $this->error(__('未注册'));
            }
        }
        $ret = Smslib::check($mobile, $captcha, $event);
        if ($ret) {
            $this->success(__('成功'));
        } else {
            $this->error(__('验证码不正确'));
        }
    }

    /**
     * 保养提醒短信发送
     * @return void
     */
    public function remindSend()
    {
        try {
            $startTime = strtotime('00:00:00'); //今天开始时间戳
            $endTime = strtotime('+ 1day',$startTime);
            $where['remind_time'] = ['between',[$startTime,$endTime]];
            $where['status'] = 1;
            $where['is_remind'] = 0;
            $remindCount = Db::name('user_car_remind')->where($where)->count();
            if (!empty($remindCount)) {
                $remindIds = [];
                $limit = 10;
                $total = intval(ceil($remindCount / $limit));
                $service = new SmsService();
                $templateArr = config('ali_sms_template');
                $template = isset($templateArr['service_expire']) ? $templateArr['service_expire'] : '';
                for ($i=1; $i <= $total;$i++) {
                    $page = $i;
                    $offset = ($page - 1) * $limit;
                    $remindData = model('UserCarRemind')->with(['order'=>function($oQuery){
                        $oQuery->field('id,user_mobile,user_name');
                    }])->where($where)->limit($offset,$limit)->select();
                    $remindData = collection($remindData)->toArray();
                    if (!empty($remindData)) {
                        //尊敬的${name}先生/女士,您的爱车${chepai}要到保养周期了,预计保养时间为:${time},不要错过爱车的黄金保养时间哦!
                        foreach ($remindData as $key => $value) {
                            $order  = isset($value['order']) ? $value['order'] : [];
                            $mobile = isset($order['user_mobile']) ? $order['user_mobile'] : '';//手机号
                            $name   = isset($order['user_name']) ? $order['user_name'] : '';    //联系人
                            $params = [
                                'template'    => $template,//短息模版
                                'mobile'      => $mobile,  //手机号
                                'data_params' => [
                                    'name'   => $name,     //联系人
                                    'chepai' => $value['car_number'], //车牌号
                                    'time'   => date('Y-m-d',$value['upkeep_time']), //保养时间
                                ],//短信参数
                            ];
                            $smsRes = $service->send($params);
                            if (!$smsRes['status']) {
                                Log::error('短信发送失败:params:'.json_encode($params));
                            } else {
                                $remindIds[] = $value['id'];
                            }
                        }
                    }
                }
                if (!empty($remindIds)) {
                    $updateWhere['id'] = ['in',$remindIds];
                    $remindRes = model('UserCarRemind')->where($updateWhere)->update(['is_remind'=>1]);
                }
            }
            $this->success();
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }
}