<?php
namespace hook\listeners\user;

use app\admin\model\UserMedicalExaminationReport;
use Symfony\Contracts\EventDispatcher\Event;

/**
 * 同步会员体检报告
 * Class SynUserReportListen
 * @package listeners\user
 */
class SynUserReportListen extends Event
{
    public $data;

    public function __construct(array $data)
    {
        $this->data = $data;
    }

    public function handle()
    {
        try {
            if(!isset($this->data['member_cartno']) || empty($this->data['member_cartno']))
            {
                throw new \Exception('缺少member_cartno参数');
            }
            if(!isset($this->data['user_id']) || empty($this->data['user_id']))
            {
                throw new \Exception('缺少user_id参数');
            }
            $url = config('app.user_synchronization_report');
            $param = array(
                'func' => 'api.app.funcDeviceJson',
                'member_key' => 'member_certno',
                'member_val' => $this->data['member_cartno']
            );
            $result = json_decode(curlPost($url . '/api.php', $param), true);
            if(!empty($result) && $result['success'] && !empty($result['data']))
            {
                $detail_url = $result['data']['basepath'];
                $time = time();
                foreach ($result['data']['data'] as $item)
                {
                    //检测是否存在  存在则不在执行
                    if(UserMedicalExaminationReport::checkStatus($item['basename']))
                    {
                        continue;
                    }
                    //插入记录及详情
                    $insert = array(
                        'report_title' => $item['device']['devicename'],
                        'report_group' => $item['basename'],
                        'report_user_id' => $this->data['user_id'],
                        'report_content' => file_get_contents($url . '/' . $detail_url . '/' . $item['filename']),
                        'report_time'    => $item['times'],
                        'report_add_time' => $time
                    );
                    UserMedicalExaminationReport::insertData($insert);
                }
            }
            return true;
        }catch (\Exception $exception){
            throw new \Exception($exception->getMessage(), $exception->getCode());
        }
    }

}
