<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------


namespace app\adminapi\service;

use app\common\model\dict\DictData;
use think\facade\Log;



/**
 * 网易云商智能外呼service
 * Class WeCallService
 * @package app\adminapi\service
 */
class WeCallService
{
    protected $appKey;
    protected $appSecret;
    protected $taskId;
    protected $status = 0;

    public function __construct()
    {
        $config = DictData::where('type_value', 'wecall')->column('value','name');
        if ($config) {
            $this->appKey = isset($config['appKey']) ? $config['appKey'] : '';
            $this->appSecret = isset($config['appSecret']) ? $config['appSecret'] : '';
            $this->taskId = isset($config['taskId']) ? $config['taskId'] : '';
            $this->status = isset($config['status']) ? $config['status'] : 0;
        } 
    }

    /**
     * 生成sign签名
     * @param $requestQuery GET请求时的url参数数组
     * @param $requestBody POST请求时的body参数Json字符串
     * @param $timestamp 时间戳（毫秒级）
     * @return string
     */
    public function getSign($requestQuery,$requestBody,$timestamp) {        
        // 拼接值
        $queryStr = "";
        ksort($requestQuery);
        foreach($requestQuery as $value) {
            $queryStr .= $value;
        }
        
        // 得到签名值
        $needSign = $timestamp. $queryStr. $requestBody;
        $sign = hash_hmac('sha256', $needSign, $this->appSecret);
        return $sign;
    }
    
    /*
     * 向外呼任务导入客户
     */
    public function importUser($customerList){
        if ($this->status == 0) {
            return false;
        }
        $requestBody = [
            'taskId' => $this->taskId,
            'removeRepeat' => false,
            'encryptedPhone' => false,
            'customerList' => $customerList
        ];
        $requestBody = json_encode($requestBody);
        $timestamp = $this->get_millisecond_timestamp();
        $sign = $this->getSign([],$requestBody,$timestamp);

        //请求导入客户信息接口
        $header = [
            'Content-Type: application/json',
            'X-YS-APIKEY: '.$this->appKey,
            'X-YS-TIME: '.$timestamp,
            'X-YS-SIGNATURE: '.$sign,
        ];
        $response = http_request('https://b.163.com/open/api/wecall/v1/task/importCustomer', $requestBody, $header);
        Log::write("外呼导入用户");
        return $response;
    }

    /*
     * 开启外呼任务(仅手动任务可调用)
     */
    public function startTask(){
        if ($this->status == 0) {
            return false;
        }
        $requestBody = [
            'taskId' => $this->taskId
        ];
        $requestBody = json_encode($requestBody);
        $timestamp = $this->get_millisecond_timestamp();
        $sign = $this->getSign([],$requestBody,$timestamp);

        //请求导入客户信息接口
        $header = [
            'Content-Type: application/json',
            'X-YS-APIKEY: '.$this->appKey,
            'X-YS-TIME: '.$timestamp,
            'X-YS-SIGNATURE: '.$sign,
        ];
        $response = http_request('https://b.163.com/open/api/wecall/v1/task/start', $requestBody, $header);
        Log::write("外呼任务开始");
        return $response;
    }

    /*
     * 停止外呼任务(仅手动任务可调用)
     */
    public function stopTask(){
        if ($this->status == 0) {
            return false;
        }
        $requestBody = [
            'taskId' => $this->taskId
        ];
        $requestBody = json_encode($requestBody);
        $timestamp = $this->get_millisecond_timestamp();
        $sign = $this->getSign([],$requestBody,$timestamp);

        //请求导入客户信息接口
        $header = [
            'Content-Type: application/json',
            'X-YS-APIKEY: '.$this->appKey,
            'X-YS-TIME: '.$timestamp,
            'X-YS-SIGNATURE: '.$sign,
        ];
        $response = http_request('https://b.163.com/open/api/wecall/v1/task/stop', $requestBody, $header);
        Log::write("外呼任务停止");
        return $response;
    }

    /**
     * 数据回调接口
     */
    public function notify($params) {
        if ($params && isset($params['dataType'])) {
            if ($params['dataType'] == 'ROBOT_TASK_STATUS_CHANGE') {
                $this->taskStatusChange($params['data']);
            }    
        }
    }

    private function taskStatusChange($data)
    {
        $taskId = $data['taskId'];
        $status = $data['status'];
        if ($taskId == $this->taskId && $status == 'COMPLETE') {
            // TODO 任务状态改变
            $this->stopTask();
        }
    }

    /**
     * 获取时间戳（毫秒级）
     */
    public function get_millisecond_timestamp() {
        $microtime = microtime(true);
        $timestamp = floor($microtime * 1000);
        return $timestamp;
    }
}