<?php

namespace wechat\modules\cp\controllers;

use Codeception\Util\Uri;
use Yii;
use yii\web\NotFoundHttpException;
use wechat\models\GroupApi;
use wechat\helpers\ImageUtil;
use wechat\helpers\Utils;

/**
 * 微信群活动
 */
class GroupController extends BaseController
{
    public $enableCsrfValidation = false;
    public $layout = false;
    public $qrcode = [
        'name' => '草料二维码扫描器',
        'link' => 'https://cli.im/deqr',
    ];

    /**
     * 群列表
     * @return string
     * @throws NotFoundHttpException
     */
    public function actionList()
    {
        $get = Yii::$app->request->get();
        $group_name = isset($get['group_name']) ? trim($get['group_name']) : '';
        $create_time_start = isset($get['create_time_start']) ? trim($get['create_time_start']) : '';
        $create_time_end = isset($get['create_time_end']) ? trim($get['create_time_end']) : '';
        $update_time_start = isset($get['update_time_start']) ? trim($get['update_time_start']) : '';
        $update_time_end = isset($get['update_time_end']) ? trim($get['update_time_end']) : '';
        $qrcode_expire_start = isset($get['qrcode_expire_start']) ? trim($get['qrcode_expire_start']) : '';
        $qrcode_expire_end = isset($get['qrcode_expire_end']) ? trim($get['qrcode_expire_end']) : '';
        $pageSize = isset($get['pageSize']) ? intval($get['pageSize']) : 20;
        $pageNumber = isset($get['pageNumber']) ? intval($get['pageNumber']) : 1;
        $orderBy = isset($get['orderBy']) ? trim($get['orderBy']) : '';
        $order = isset($get['order']) ? trim($get['order']) : '';

        $api = new GroupApi();
        $params = [
            'group_name' => $group_name,
            'create_time_start' => $create_time_start,
            'create_time_end' => $create_time_end,
            'update_time_start' => $update_time_start,
            'update_time_end' => $update_time_end,
            'qrcode_expire_start' => $qrcode_expire_start,
            'qrcode_expire_end' => $qrcode_expire_end,
            'pageSize' => $pageSize,
            'pageNumber' => $pageNumber,
            'orderBy' => $orderBy,
            'order' => $order,
        ];
        $result = $api->getList($params);
        if ($result['code'] != 1) {
            throw new NotFoundHttpException($result['message']);
        }

        $data = $result['data'];

        return $this->render('list', [
            'params' => $params,
            'data' => $data,
        ]);
    }

    /**
     * 当前微信群
     */
    public function actionGetCurrentGroup()
    {
        $api = new GroupApi();
        $result = $api->getCurrentGroup([]);
        return json_encode($result);
    }

    /**
     * 添加微信群
     * @return string
     */
    public function actionAdd()
    {
        return $this->render('add');
    }
    
    /**
     * 保存添加或编辑
     */
    public function actionSave()
    {
        // 添加时一定要上传图片，编辑时可以不上传
        $group_logo = null;
        if (empty(Yii::$app->request->post('id')) && empty($_FILES['group_logo']['size'])) {
            return $this->redirect(['common/error', 'tip' => '群logo不能为空']);    
        }
        if (!empty($_FILES['group_logo']['size'])) {
            try {
                $imageUtil = new ImageUtil();
                $imageUtil->echo_error = false;
                $group_logo = $imageUtil->upload($_FILES['group_logo']);
            } catch (\Exception $e) {
                return $this->redirect(['common/error', 'tip' => $e->getMessage()]);
            }
        }
        
        // dataURL
        $group_qrcode = $this->saveQrcode(Yii::$app->request->post('group_qrcode'));
        if ($group_qrcode === false) {
            return $this->redirect(['common/error', 'tip' => '保存二维码失败']);
        }
        
        $api = new GroupApi();
        $file_params = ['group_logo' => $group_logo, 'group_qrcode' => $group_qrcode];
        $params = array_merge(Yii::$app->request->post(), $file_params);
        $result = $api->save($params);
        if ($result['code'] == 1) {
            return $this->redirect('list');
        } else {
            return $this->redirect(['common/error', 'tip' => $result['message']]);   
        }
    }

    /**
     * 编辑微信群
     * @return string
     * @throws NotFoundHttpException
     */
    public function actionEdit()
    {
        $id = (int) Yii::$app->request->get('id');
        if (!$id) {
            throw new NotFoundHttpException('参数错误');
        }
        
        $api = new GroupApi();
        $result = $api->getGroupById(['id' => $id]);
        if ($result['code'] != 1) {
            throw new NotFoundHttpException('参数错误.');
        }
        $group = $result['data'];

        return $this->render('edit', ['group' => $group]);
    }
    
    /**
     * 删除微信群
     */
    public function actionDelete()
    {
        $ids = Yii::$app->request->post('ids');
        if (!$ids) {
            return $this->outJson(0, [], '参数错误');
        }
        $api = new GroupApi();
        $result = $api->deleteGroup(['ids' => $ids]);
        return json_encode($result);
    }

    /**
     * 保存二维码
     * @param string $dataUrl
     * @return string|false
     */
    public function saveQrcode($dataUrl)
    {
        $file_arr = Utils::convertDataUrl($dataUrl);
        if (!$file_arr) {
            return false;
        }
        
        // 保存文件的时候是绝对路径，返回的是相对路径
        $baseDir = Yii::getAlias('@webroot');
        $prefix = '/upload/' .date('Ym') . '/';
        $filename = 'qrcode_' . md5($file_arr['content']) . '.' . $file_arr['type'];
        $absolutePath = $baseDir . $prefix . $filename;
        $relativePath = $prefix . $filename;
        
        $res = file_put_contents($absolutePath, $file_arr['content']);
        return $res ? $relativePath : false;
    }

}
