<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/2/26/026
 * Time: 15:06
 * 前端用户报名
 */

namespace backend\controllers;

use backend\base\CommonController;
use backend\base\Help;
use common\api\EnrollServer;
use common\event\Event;
use common\models\Email;
use common\models\HttpRecord;
use Yii;
use common\models\Enroll;
use common\models\EnrollSource;
use common\models\AstrictPhone;
use common\enums\EmailEnum;

class UsersignupController extends CommonController
{
    public function actionHome()
    {
        $model = new EnrollSource();
        $source_1 = $model->getList(['type' => 1], ['source_id', 'name', 'type']);
        $source_2 = $model->getList(['type' => 2], ['source_id', 'name', 'type']);
        return $this->render('home', ['source' => $source_1, 'source_2' => $source_2]);
    }

    public function actionHomeform()
    {
        $model = new Enroll();

        $rows = $model->getList(Yii::$app->request->post());
        if (!empty($rows['data'])) {
            $m = (new \common\models\EnrollSource())->TypeColumn(1);
            $p = (new \common\models\EnrollSource())->TypeColumn(2);
            foreach ($rows['data'] as &$val) {

                if (isset($p[$val['source']]) && $val['equipment'] == 2) {
                    $val['source'] = $p[$val['source']];

                }

                if (isset($m[$val['source']]) && $val['equipment'] == 1) {
                    $val['source'] = $m[$val['source']];
                }
                $val['equipment'] = $model->equipmentArr[$val['equipment']];
                $val['create_at'] = date('Y-m-d H:i', $val['create_at']);

                $val['state'] = $model->stateArr[$val['state']];
                if (\common\models\TestNumber::find()->andWhere(['number' => $val['mobile'], 'is_show' => 1])->asArray()->one()) {
                    $val['state'] = '测试号码不发送';
                }

                $email = Email::find()->select(['email'])->andWhere(['del' => 1])->andWhere(['city' => $val['house_city']])->asArray()->one();
                $val['email'] = $email['email'];

            }

            return Help::JsonData(0, '成功', $rows['total'], $rows['data']);
        }
        return Help::JsonCode(Help::ERROR, '暂无数据');
    }

    /*
     * 用户详情
     * */
    public function actionUserdetails()
    {
        $model = new Enroll();
        $model->id = Yii::$app->request->get('id');
        $result = $model->FindByIds();
        if (!empty($result)) {
            $m = (new \common\models\EnrollSource())->TypeColumn(1);
            $p = (new \common\models\EnrollSource())->TypeColumn(2);
            if (isset($p[$result['source']]) && $result['equipment'] == 2) {
                $result['source'] = $p[$result['source']];

            }

            if (isset($m[$result['source']]) && $result['equipment'] == 1) {
                $result['source'] = $m[$result['source']];
            }
            $result['create_at'] = date('Y-m-d H:i', $result['create_at']);
            $result['equipment'] = $model->equipmentArr[$result['equipment']];
            $result['state'] = $model->stateArr[$result['state']];
            return $this->render('userdetails', ['model' => $result]);
        }
    }

    /*
     * 删除
     * */
    public function actionSignupdel()
    {
        $model = new Enroll();
        $row = $model->FindById(Yii::$app->request->post('id'));
        if (!empty($row)) {
            $row->del = 2;
            if ($row->save()) return Help::JsonCode(Help::SUCCESS, Yii::t('app', 'edit_success'));
        }
        return Help::JsonCode(Help::ERROR, Yii::t('app', 'edit_error'));
    }


    //用户来源@2019.8.17
    public function actionUserform()
    {
        $get = Yii::$app->request->get();
        $result = Enroll::findOne($get['id']);

        if ($result != null) {
            $result['create_at'] = date('Y-m-d', $result['create_at']);
            $query = (new HttpRecord())->GetList($result);
            return $this->render('userform', ['model' => $query, 'row' => $result]);
        }
    }


    /*
    * 报名栏目来源
    */
    public function actionLabel()
    {
        return $this->render('label');
    }

    public function actionLabelform()
    {
        $model = new EnrollSource();
        $row = $model->getList(Yii::$app->request->post());
        $m = new Enroll();
        if (!empty($row)) {
            foreach ($row as &$val) {
                $val['create_at'] = date('Y-m-d H:i', $val['create_at']);
                $val['type'] = $m->equipmentArr[$val['type']];
            }
            return Help::JsonData(0, '成功', $model->getListTotal(Yii::$app->request->post()), $row);
        }
        return Help::JsonCode(Help::ERROR, Yii::t('app', 'get_error'), []);
    }

    public function actionLabeladd()
    {
        $model = new Enroll();
        return $this->render('labeladd', ['source' => $model->equipmentArr]);
    }

    public function actionLabeladdform()
    {
        $input = Yii::$app->request->post('data');

        $one = EnrollSource::find()->andWhere(['type' => $input['type']])->orderBy(['create_at' => SORT_DESC])->asArray()->one();
        if (!empty($one)) {
            $input['source_id'] = ++$one['source_id'];
        } else {
            $input['source_id'] = 0;
        }
        $model = new EnrollSource();
        $model->scenario = 'add';
        $input['uid'] = Yii::$app->session['user_info']['uid'];

        if ($model->load($input, '') && $model->save()) {
            return Help::JsonCode(Help::SUCCESS, Yii::t('app', 'add_success'));
        }

        return Help::JsonCode(Help::ERROR, Yii::t('app', 'add_error'), $model->errors);
    }

    public function actionLabeledit()
    {
        $model = new Enroll();
        $m = new EnrollSource();
        $row = $m->FindById(Yii::$app->request->get('id'));
        if (!empty($row)) {
            return $this->render('labeledit', ['source' => $model->equipmentArr, 'model' => $row]);
        }
    }

    public function actionLabeleditform()
    {
        $m = new EnrollSource();
        $input = Yii::$app->request->post('data');
        $row = $m->FindById($input['id']);
        if ($row->load($input, '') && $row->save()) {
            return Help::JsonCode(Help::SUCCESS, Yii::t('app', 'edit_success'));
        }
        return Help::JsonCode(Help::ERROR, Yii::t('app', 'edit_error'));
    }


    /*邮箱发送*/
    public function actionEmailsend()
    {
        $EmailModel = new \common\models\Enroll();
        $result = $EmailModel->getList(Yii::$app->request->post());

        try {
            foreach ($result['data'] as $k => $v) {
                $emailData['username'] = $v['name'];
                $emailData['mobile'] = $v['mobile'];
                $emailData['housename'] = $v['house_name'];
                $emailData['city_name'] = $v['city_name'];
                $emailData['id'] = $v['id'];
                //发送邮件
                (new \common\service\common\MailerService())->send($v['send_email'], $emailData, EmailEnum::SITEFORM);
            }
            return Help::JsonCode(Help::SUCCESS, '邮件发送中');
        } catch (\Exception $e) {
            return Help::JsonCode(Help::ERROR, $e->getMessage());
        }
    }

    public function actionStatistica()
    {
        return $this->render('statistica');
    }

    public function actionStatisticaform()
    {

        $input = Yii::$app->request->post();
        if (!empty($input['date_month'])) {
            $start_end_time = \common\Helps\Time::getthemonth($input['date_month']);
            if (!empty($start_end_time)) {
                $startTime = strtotime($start_end_time[0] . ' 00:00:00');
                $endTime = strtotime($start_end_time[1] . ' 23:59:59');
            }
        } else {
            $start_end_time = \common\Helps\Time::getthemonth(date('Y-m'));
            if (!empty($start_end_time)) {
                $startTime = strtotime($start_end_time[0] . ' 00:00:00');
                $endTime = strtotime($start_end_time[1] . ' 23:59:59');
            }
        }
        $query = \common\models\Enroll::find();
        $rows = $query->select(['COUNT(mobile) as mobile_count', "FROM_UNIXTIME(create_at,'%Y-%m-%d') as addtime", 'equipment'])->andWhere(['del' => 1])
            ->andWhere(['>=', 'create_at', $startTime])
            ->andWhere(['<=', 'create_at', $endTime])
            ->groupBy(['addtime', 'mobile'])->asArray()->all();
        if ($rows) {
            $arr = [];
            $date_column = array_column($rows, 'addtime');
            foreach ($rows as $val) {
                if (in_array($val['addtime'], $date_column)) {
//                        if(empty($arr[$val['addtime']]['dim_count']))
//                        {
//                            $arr[$val['addtime']]['dim_count'] = 0;
//                        }
//
//                    if(empty($arr[$val['addtime']]['precise']))
//                    {
//                        $arr[$val['addtime']]['precise'] = 0;
//                    }

                    $arr[$val['addtime']]['time'] = $val['addtime'];
                    $arr[$val['addtime']]['dim_count'] += $val['mobile_count'];
                    $arr[$val['addtime']]['precise'] += 1;
                    switch ($val['equipment']) {
                        case 1:
                            $arr[$val['addtime']]['m'] += 1;
                            break;
                        case 2:
                            $arr[$val['addtime']]['pc'] += 1;
                            break;
                    }
                }
            }
            return Help::JsonData(0, '成功', 0, array_values($arr));
        }
        return Help::JsonCode(Help::ERROR, '暂无数据');
    }

    //$EmailModel = new \common\models\Enroll();
    //        $result=$EmailModel->getList(Yii::$app->request->post());
    //        $en = new \common\api\EnrollServer();
    //        $arr = [];
    //        foreach($result as $k=>$v)
    //        {
    //            if(!empty($v['name']))
    //            {
    //                $en->username = $v['name'];
    //            }
    //            $en->mobile = $v['mobile'];
    //            $en->housename = $v['house_name'];
    //            $en->city = $v['city_name'];
    //            //发送邮件
    //            $event = new \common\event\Event();
    //            $arr['email'] = $v['send_email'];
    //            $arr['title'] = Yii::t('app','enter_email');
    //            $arr['content'] = $en->TemplateOne();
    //            $arr['id'] = $v['id'];
    //            $event->SendEmail($arr);
    //            $EmailModel::updateAll(['state'=>2],['id'=>$v['id']]);
    //        }
    //        return Help::JsonCode(Help::SUCCESS,'发送成功');
    /*
     * 2020.7.27 lyy 报名限制
     *
     * */
    public function actionAstrict()
    {
        return $this->render('astrict');
    }

    public function actionAstrictform()
    {
        $input = Yii::$app->request->post();
        $rows = new AstrictPhone();
        $dataInfo = $rows->getList($input);
        $count = $rows->getTotal();
        foreach ($dataInfo as &$val) {
            $val['create_at'] = date('Y-m-d H:i:s', $val['create_at']);
        }
        return Help::JsonData(0, '成功', $count, $dataInfo);
    }

    public function actionAstrictadd()
    {
        return $this->render('astrictadd');
    }

    public function actionAstrictaddto()
    {
        $input = Yii::$app->request->post('data');
        $rows = new AstrictPhone();
        $rows->load($input);
        if (!$rows->validate()) return Help::JsonCode(Help::ERROR, '提交失败', $rows->errors);
        $rows->mobile = $input['mobile'];
        $rows->astrict_msg = $input['astrict_msg'];
        if ($rows->save()) return Help::JsonCode(Help::SUCCESS, '添加成功');
        return Help::JsonCode(Help::SUCCESS, '添加失败');
    }

    public function actionAstrictdel()
    {
        $id = Yii::$app->request->post('id');
        $rows = AstrictPhone::findOne($id);
        if ($rows->delete()) return Help::JsonCode(Help::SUCCESS, '删除成功');
        return Help::JsonCode(Help::SUCCESS, '删除失败');
    }

    public function actionAstrictstate()
    {
        $input = Yii::$app->request->post();
        $rows = AstrictPhone::findOne($input['id']);
        $rows->state = $input['state'];
        if ($rows->update(false)) return Help::JsonCode(Help::SUCCESS, '设置成功');
        return Help::JsonCode(Help::SUCCESS, '设置失败');

    }
}