<?php 
namespace wechat\controllers;

use wechat\models\ActivityApi;
use wechat\models\GroupApi;
use Yii;
use wechat\helpers\Utils;

/**
 * 活动
 */
class ActivityController extends BaseController
{
    public function beforeAction($action)
    {
        Yii::$app->session->open();
        return parent::beforeAction($action);
    }

    /**
     * 活动海报页面
     */
    public function actionIndex()
    {
        $info = $this->getDetailInfo();
        if (file_exists($info['file'])) {
            $regenerate = 0;
            $path = $info['path'];
        } else {
            $regenerate = 1;
            $path = '/static/images/ewm1.jpg';
        }
        
        return $this->render('index', [
            'link' => $info['link'],
            'path' => $path,
            'regenerate' => $regenerate,
        ]);
    }
    
    /**
     * 活动详情页面
     */
    public function actionDetail()
    {
        return $this->render('detail');
    }
    
    /**
     * 群二维码页面
     */
    public function actionQrcode()
    {
        $params = [
            'session_id' => Yii::$app->session->getId(),
        ];
        
        $api = new ActivityApi();
        $result = $api->getCurrentGroup($params);
        
        return $this->render('qrcode', ['group' => $result['data']]);
    }
    
    /**
     * 再次生成活动详情页的二维码，这是为了应对域名更换的情况
     */
    public function actionRegenerate()
    {
        $result = ['code' => 0, 'data' => [], 'message' => ''];
        
        $dataUrl = trim(Yii::$app->request->post('dataUrl'));
        if (!$dataUrl) {
            $result['message'] = '参数不能为空';
            return json_encode($result);
        }
        
        $file_arr = Utils::convertDataUrl($dataUrl);
        if (!$file_arr) {
            $result['message'] = '参数错误';
            return json_encode($result);
        }
        
        $info = $this->getDetailInfo();
        
        $res = file_put_contents($info['file'], $file_arr['content']);
        if ($res) {
            $result['code'] = 1;
        } else {
            $result['message'] = '生成失败';
        }
        return json_encode($result);
    }
    
    /**
     * 获取详情页网址和二维码文件地址
     * @return string
     */
    protected function getDetailInfo()
    {
        $link = Yii::$app->request->hostInfo . '/activity/detail';
        $path = '/static/images/activity_detail_' . md5($link) . '.png';
        $file = Yii::getAlias('@webroot') . $path;
        $info =  [
            'link' => $link,
            'path' => $path,
            'file' => $file,
        ];
        return $info;
    }
    
}