<?php

namespace app\common\service;

use app\common\model\WorkerThird;
use think\facade\Log;
use app\common\model\Comjobs as ComjobsModel;

class RensheService
{
    //网址
    const BASE_URL = 'https://12333.jinjiang.gov.cn/interface-jjlgsc-wbjk';
    //密钥
    const KEY = 'be2daba9afed4b75';
    //偏移量
    const IV = 'b33f8ac8cca782b9';
    //版本号
    const VERSION = 'lgyz1.0';

    //要发送的数据
    private $_data = [];
    //当前时间
    private $_time = 0;
    //日志名称
    private $_log_name = '';

    /**
     * 构造函数
     * @param array $data 要发送的数据
     */
    public function __construct($data = [])
    {
        $this->_data = $data;
        $this->_time = date('YmdHis');
    }

    /**
     * 设置参数
     * @param $data
     */
    public function setData($data)
    {
        foreach ($data as $k => $v) {
            $this->_data[$k] = $v;
        }
    }

    private function _jobInfoData($id)
    {
        $info = ComjobsModel::with([
            'worker',
            'comjobsCate',
            'ageCode'          => function ($query) {
                $query->where('type', 'age');
            }, 'educationCode' => function ($query) {
                $query->where('type', 'education');
            }])->find($id);


        //数据重组
        $list           = $item = [];
        $item['baz367'] = $info['id'];
        if (!empty($info['comjobsCate']['code'])) {
            $item['aca111'] = $info['comjobsCate']['code'];
        }
        $item['aca112'] = $info['title'];
        $item['bcz002'] = $info['wtype'];
        $item['bcz017'] = $info['zwagall'];
        if (!empty($info['community'])) {
            $item['cae006'] = $info['community'];
        }
        $item['cae007'] = $info['province'] . $info['city'] . $info['district'] . $info['address'];
        if (!empty($info['educationCode']['code'])) {
            $item['aac011'] = $info['educationCode']['code'];
        }
        if (!empty($info['ageCode']['code'])) {
            $item['bcz006'] = $info['ageCode']['code'];
        } else {
            $item['bcz021'] = $info['agegroup'];
        }
        $item['bcz019'] = implode(',', $info['tags']);
//        $item['caa004s'] = $info['tags_code'];
        $item['bcz007'] = $info['comdetails'];
        $item['bcz008'] = $info['requirement'];
        $item['bcz009'] = $info['worker']['wtype'];
        if (empty($info['third_id'])) {
            $item['aab069'] = $info['worker']['title'];
            $item['aae004'] = $info['worker']['realname'];
            $item['aae006'] = $info['worker']['province'] . $info['worker']['city'] . $info['worker']['district'] . $info['worker']['address'];
        } else {
            $third          = WorkerThird::where('id', $info['third_id'])->find();
            $item['aab069'] = $third['name'];
            $item['aae004'] = $third['contact'];;
            $item['aae006'] = $info['worker']['province'] . $info['worker']['city'] . $info['worker']['district'] . $info['worker']['address'];
        }
        $item['aae005'] = $info['telephone'];
        $item['bcz005'] = $info['recruit_num'];
        $item['bcz018'] = $info['emp_code'];
        $item['bcz011'] = $info['is_worry'];
        $item['bcz015'] = $info['longitude'];
        $item['bcz016'] = $info['latitude'];
        $item['bye002'] = $info['updatetime'];
        $item           = array_filter($item);
        $item['aae100'] = $info['status'] == 3 ? 1 : 0;
        $list[]         = $item;
        $send['list']   = $list;

        $this->setData($send);
    }

    /**
     * 岗位信息库提交
     */
    public function jobInfo()
    {
        $this->_log_name = '岗位信息库';
        $url             = self::BASE_URL . '/dayjob/submitJobInfo.html';
        $res             = $this->_send($url);

        return $res;
    }

    /**
     * 岗位信息库提交ComId
     */
    public function jobInfoByComId($id)
    {
        //线上环境才同步
        if (env('APP_DEBUG')) {
            return ['code' => 200];
        }
        $this->_jobInfoData($id);
        $res = $this->jobInfo();

        return $res;
    }

    /**
     * 岗位撮合信息结果信息提交
     */
    public function matchSubmit()
    {
        $this->_log_name = '岗位撮合';
        $url             = self::BASE_URL . '/dayjob/submitLaborRelations.html';
        $res             = $this->_send($url);

        return $res;
    }

    /**
     * 参数加密
     * @return string
     */
    private function _enDataCbc()
    {
        $data = $this->_time . json_encode($this->_data);
        return base64_encode(http_request('http://sm4.jinjianghc.com/encode.php', 'POST', ['data' => $data]));
//        return base64_encode(openssl_encrypt($data, "SM4", self::KEY, 0, self::IV));
    }

    /**
     * 参数解密
     * @param $data
     * @return mixed
     */
    private function _deDataCbc($data)
    {
        $res = http_request('http://sm4.jinjianghc.com/decode.php', 'POST', ['data' => base64_decode($data)]);
//        $res = openssl_decrypt(base64_decode($data), "SM4", self::KEY, 0, self::IV);
        if ($res[0] != "{") {
            $res = mb_substr($res, 14, strlen($res), 'UTF-8');
        }

        return json_decode($res, true);
    }

    /**
     * 发送数据
     * @param $url
     * @return mixed
     */
    private function _send($url)
    {
        Log::info($this->_log_name . '：' . json_encode($this->_data));

        //请求头
        $enTime = base64_encode(http_request('http://sm4.jinjianghc.com/encode.php', 'POST', ['data' => $this->_time]));
        // $enTime = base64_encode(openssl_encrypt($this->_time, "SM4", self::KEY, 0, self::IV));
        $header = [
            'Content-Type: application/json',
            'Author-source: 1',
            'Author-token: ' . $enTime,
            'Author-version: ' . self::VERSION,
        ];

        //发送数据
        $enData   = $this->_enDataCbc();
        $response = http_request($url, 'POST', $enData, $header);
        $deData   = $this->_deDataCbc($response);

        Log::info($this->_log_name . '返回数据：' . json_encode($deData));

        //重置默认值，方便下一次使用
        $this->_data = [];
        $this->_time = date('YmdHis');

        return $deData;
    }
}