<?php

namespace app\admin\controller;

use app\admin\common\AdminController;
use app\common\api\ChuanglanSmsApi;
use app\common\api\MessageRecordApi;
use app\common\model\MessageRecord as MessageRecordModel;

class MessageRecord extends AdminController {

    public function index() {
        return view();
    }

    /**
     * 短信日志列表数据
     * @return \think\response\Json
     */
    public function list(){
        $res = MessageRecordApi::getList($this->request->param());
        return json($res);
    }

    public function sendMessage(){
        $content = trim($this->request['content']);
        $title = trim($this->request['title']);
        $time_day = date("Ymd",time());
        if(\StrUtil::isEmpOrNull($content)){
            return json(["msg" => '请填写信息后发送!']);
        }
        $phone_str = trim($this->request['params']);
        $phone_arr = explode(',',$phone_str);
        $template = "【晋江市人才服务平台】{$content}";
        $bizId = getStringId();
        foreach ($phone_arr as $k => $v){
            if (!preg_match("/^1[3456789]\d{9}$/", $v)) {
                unset($phone_arr[$k]);
                continue;
            }
            $id = getStringId();
            $item = [
                'id' => $id,
                'userId' => null,
                'bizId' => $bizId,
                'type' => 2,
                'smsType' => 2,
                'name' => "批量发送({$title}{$time_day})",
                'phone' => $v,
                "params" => $v,
                "templateCode" => $template,
                'state' => 3,
                'sendingDate' => date("Y-m-d H:i:s",time()),
                'createTime' => date("Y-m-d H:i:s",time())
            ];
            MessageRecordModel::create($item);
        }

        $smsapi = new ChuanglanSmsApi();

        $result = $smsapi->sendSMS(implode(',',$phone_arr), $template, true);

        $result = json_decode($result, true);

        if($result['code'] != 0 || !$result){
            return json(["msg" => '发送失败，原因：'.$result['errorMsg']]);
        }

        return json(["msg" => '操作成功(但不代表发送成功)'], 200);
    }

    public function resendMessage(){
        $messageRecordId = $this->request['messageRecordId'];
        if(empty($messageRecordId)){
            return json(["msg" => '请选择重新发送的记录']);
        }
        $message = \app\common\model\MessageRecord::where('id',$messageRecordId)->findOrEmpty();
        if(!$message || empty($message)){
            return json(["msg" => '找不到重发记录']);
        }
        if($message['state']!=2){
            return json(["msg" => '当前记录未发送失败，无法重发']);
        }

        $smsapi = new ChuanglanSmsApi();

        $result = $smsapi->sendSMS($message['phone'], $message['templateCode'], true);

        $result = json_decode($result, true);

        if($result['code'] != 0 || !$result){
            return json(["msg" => '发送失败，原因：'.$result['errorMsg']]);
        }

        return json(["msg" => '操作成功(但不代表发送成功)'], 200);
    }


}