<?php
namespace wechat\controllers;

use wechat\models\ScanQrcodeRecord;
use Yii;
use wechat\models\WechatGroup;

/**
 * 后台的接口
 * Class GroupController
 * @package wechat\controllers
 */
class GroupController extends BaseController
{
    /**
     * 管理员列表
     */
    public function actionList()
    {
        $get = Yii::$app->request->post();
        $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']) > 0 ? intval($get['pageSize']) : 20;
        $pageNumber = isset($get['pageNumber']) ? $get['pageNumber'] : 1;
        $orderBy = isset($get['orderBy']) ? strtolower($get['orderBy']) : '';
        $order = isset($get['order']) ? strtolower($get['order']) : '';
        
        $where = ['and'];
        if ($group_name) {
            $where[] = ['=', 'group_name', $group_name];    
        }
        
        if ($create_time_start) {
            $create_time_start_timestamp = strtotime($create_time_start);
            if ($create_time_start_timestamp) {
                $where[] = ['>=', 'create_time', $create_time_start_timestamp];
            }
        }
        if ($create_time_end) {
            $create_time_end_timestamp = strtotime($create_time_end);
            if ($create_time_end_timestamp) {
                $where[] = ['<', 'create_time', $create_time_end_timestamp + 86400];
            }
        }
        
        if ($update_time_start) {
            $update_time_start_timestamp = strtotime($update_time_start);
            if ($update_time_start_timestamp) {
                $where[] = ['>=', 'update_time', $update_time_start_timestamp];
            }
        }
        if ($update_time_end) {
            $update_time_end_timestamp = strtotime($update_time_end);
            if ($update_time_end_timestamp) {
                $where[] = ['<', 'update_time', $update_time_end_timestamp + 86400];
            }
        }
        
        if ($qrcode_expire_start) {
            $qrcode_expire_start_timestamp = strtotime($qrcode_expire_start);
            if ($qrcode_expire_start_timestamp) {
                $where[] = ['>=', 'qrcode_expire', $qrcode_expire_start_timestamp];
            }
        }
        if ($qrcode_expire_end) {
            $qrcode_expire_end_timestamp = strtotime($qrcode_expire_end);
            if ($qrcode_expire_end_timestamp) {
                $where[] = ['<', 'qrcode_expire', $qrcode_expire_end_timestamp + 86400];
            }
        }
        
        
        $query = WechatGroup::find()->where($where);
        $offset = $pageSize * ($pageNumber - 1);
        $query->offset($offset)->limit($pageSize);
        $totalCount = $query->count();
        $pageCount = ceil($totalCount / $pageSize);

        $data = [
            'totalCount' => $totalCount,
            'pageCount' => $pageCount,
            'dataList' => [],
        ];
        if ($totalCount) {
            // 排序
            $allowOrderColumn = ['id', 'group_name', 'group_logo', 'group_link', 'group_qrcode', 'qrcode_expire', 'scan_count', 'sort', 'is_enable', 'is_current', 'create_time', 'update_time'];
            if (in_array($orderBy, $allowOrderColumn) && in_array($order, ['asc', 'desc'])) {
                if ($order == 'asc') {
                    $orderCondition = [$orderBy => SORT_ASC];
                } else {
                    $orderCondition = [$orderBy => SORT_DESC];
                }
            } else {
                $orderCondition = ['create_time' => SORT_DESC];
            }
            
            $dataList = $query->orderBy($orderCondition)->asArray()->all();
            
            $groupModel = WechatGroup::getCurrentGroup(true);
            foreach ($dataList as $k => $v) {
                $dataList[$k]['is_enable'] = $v['is_enable'] ? '启用' : '不启用';
                $dataList[$k]['qrcode_expire'] = $v['qrcode_expire'] ? date('Y-m-d', $v['qrcode_expire']) : '-';
                $dataList[$k]['create_time'] = $v['create_time'] ? date('Y-m-d H:i:s', $v['create_time']) : '-';
                $dataList[$k]['update_time'] = $v['update_time'] ? date('Y-m-d H:i:s', $v['update_time']) : '-';
                
                $dataList[$k]['is_current'] = 0;
                if ($groupModel && $groupModel->id == $v['id']) {
                    $dataList[$k]['is_current'] = 1;
                }
            }
            
            $data['dataList'] = $dataList;
            return $this->outJson(1, $data);
        } else {
            return $this->outJson(1, $data, '没有数据');
        }
    }
    
    /**
     * 当前微信群
     */
    public function actionGetCurrentGroup()
    {
        $groupModel = WechatGroup::getCurrentGroup(true);
        if ($groupModel) {
            $group = $groupModel->toArray();
            $group['is_enable'] = $group['is_enable'] ? '启用' : '不启用';
            $group['qrcode_expire'] = $group['qrcode_expire'] ? date('Y-m-d', $group['qrcode_expire']) : '-';
            $group['create_time'] = $group['create_time'] ? date('Y-m-d', $group['create_time']) : '-';
            $group['update_time'] = $group['update_time'] ? date('Y-m-d', $group['update_time']) : '-';
            return $this->outJson(1, $group);
        } else {
            return $this->outJson(0, [], '没有数据');
        }
    }
    
    /**
     * 保存新增或编辑
     */
    public function actionSave()
    {
        $post = Yii::$app->request->post();
        
        $post['qrcode_expire'] = isset($post['qrcode_expire']) ? strtotime($post['qrcode_expire'] . ' 23:59:59') : strtotime('+7 days midnight');
        
        // 没有id为新增，有为编辑
        $time = time();
        if (!isset($post['id'])) {
            $model = new WechatGroup();
            $model->setAttributes($post);
            
            $count = WechatGroup::find()->where(['is_current' => 1])->count();
            $model->is_current = $count ? 0 : 1;
            
            $model->create_time = $time;
            $model->update_time = $time;
            $res = $model->save();
        } else {
            $post['id'] = (int) $post['id'];
            $model = WechatGroup::find()->where(['id' => $post['id']])->limit(1)->one();
            if (!$model) {
                return $this->outJson(0, [], '没有该条数据');
            }
            
            // 没有上传的话则不修改
            if (empty($post['group_logo'])) {
                unset($post['group_logo']);
            }
            
            $model->setAttributes($post);
            $res = $model->save();
        }
        
        
        if ($res) {
            return $this->outJson(1);
        } else {
            return $this->outJson(0, [], '保存失败');
        }
    }
    
    /**
     * 某个微信群
     */
    public function actionGetGroupById()
    {
        $id = (int) Yii::$app->request->post('id');
        if (!$id) {
            return $this->outJson(0, [], '参数错误');
        }
        
        $group = WechatGroup::find()->where(['id' => $id])->limit(1)->asArray()->one();
        if (!$group) {
            return $this->outJson(0, [], '没有该管理员');
        }
        
        $group['qrcode_expire'] = $group['qrcode_expire'] ? date('Y-m-d', $group['qrcode_expire']) : '-';
        $group['create_time'] = $group['create_time'] ? date('Y-m-d', $group['create_time']) : '-';
        $group['update_time'] = $group['update_time'] ? date('Y-m-d', $group['update_time']) : '-';
        
        return $this->outJson(1, $group);
    }
    
    /**
     * 删除微信群
     */
    public function actionDelete()
    {
        $ids = Yii::$app->request->post('ids');
        if (!$ids) {
            return $this->outJson(0, [], '参数错误');
        }
        
        WechatGroup::deleteAll(['id' => $ids]);
        ScanQrcodeRecord::deleteAll(['wechat_group_id' => $ids]);
        
        return $this->outJson(1);
    }
    
}