<?php

namespace app\job;

use think\queue\Job;
use think\facade\Log;
use think\facade\Db;
use app\common\api\ChuanglanSmsApi;
use app\common\model\MessageRecord;

/**
 * Description of Messenger
 *
 * @author sgq
 */
class Messenger {

    public function fire(Job $job, $data) {
        if ($this->deal($data)) {
            Log::info(json_encode($data));
            $job->delete();
            return true;
        }
        Log::error(json_encode($data));
        if ($job->attempts() >= 3) {
            $job->delete();
            return false;
        }
        $job->release(10); //10秒后重试
    }

    /**
     * 处理业务逻辑
     * @param type $data
     * @return bool
     */
    public function deal($data): bool {
        $type = $data["type"];
        switch ($type) {
            case 1:
                //通知单位审核注册
                break;
            case 2:
                //通知人才申报初审人员
                try {
                    $userId = $data["userId"];
                    $name = $data["name"];
                    $phone = $data["phone"];
                    $count = $data["count"];
                    $template = sprintf("【晋江市人才服务平台】您的部门有%d条人才认定申报记录待初审，请及时登录审批系统处理。", $count);
                    $smsapi = new ChuanglanSmsApi();
                    $result = $smsapi->sendSMS($phone, $template);
                    $result = json_decode($result, true);
                    $id = getStringId();
                    $record_data = [
                        'id' => $id,
                        'userId' => $userId,
                        'bizId' => $result["msgId"],
                        'type' => 1,
                        'smsType' => 2,
                        'name' => $name,
                        'phone' => $phone,
                        'params' => "初级审核",
                        'templateCode' => $template,
                        'state' => $result['code'] == 0 ? 2 : 3,
                        'sendingDate' => date("Y-m-d H:i:s", time()),
                        'createTime' => date("Y-m-d H:i:s", time()),
                        'msg' => $result['errorMsg']
                    ];

                    MessageRecord::create($record_data);
                    return true;
                } catch (\think\Exception $e) {
                    return false;
                }
                break;
        }
        return false;
    }

}
