<?php

namespace frontend\controllers;

use common\libs\MyLib;
use common\models\ConfigT;
use common\models\MenuT;
use common\models\OrderT;
use common\models\PhoneDayT;
use common\models\UserMenuT;
use common\models\UserT;
use common\models\GroupT;
use common\models\SysIpT;
use Yii;
use yii\helpers\ArrayHelper;
use yii\helpers\FileHelper;
use yii\helpers\Json;
use yii\web\Cookie;
use yii\web\Response;
use yii\web\UploadedFile;
use yii\web\User;

class CommonController extends \yii\web\Controller
{
    public $my = null;
    public $web = null;
    public $enableCsrfValidation = false;
    public $layout = 'blue-main';

    public function init()
    {
        parent::init();

        $cookie = Yii::$app->request->cookies;
        $user_id = MyLib::encrypt($cookie->get('aid'),'DECODE');

        if($user_id != 0)
        {
            $this->my = UserT::findOne(['id'=>$user_id]);
        } else {
            $this->my = null;
        }
        $this->web = ConfigT::findOne(['id'=>1]);
    }

    public function actionIndex()
    {
        if($this->my == null) {
            return $this->redirect('/common/login');
        }
        // $menus = $this->my->getMenus();
        $menu_items = $this->my->getLeftMenus();
        // echo '<pre>';
        // var_dump($menus);


        return $this->renderPartial('index',[
            'menus' => $menu_items
        ]);
    }

    public function actionTop()
    {
        if($this->my == null) {
            return $this->redirect('/common/login');
        }
        $menus = $this->my->getMenus();

        return $this->renderPartial('top');
    }

    public function actionLogin()
    {
        $request = Yii::$app->request;
        if($request->isPost) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            $cookies = Yii::$app->response->cookies;

            $result = array();
            $result['success'] = false;

            $username = $request->post('username');
            $password = $request->post('password');

            $user = UserT::find()
                ->where(['username'=>$username,'is_delete'=>0])
                ->one();
            if(!isset($user)) {
                return MyLib::error3('登录失败,请检查用户名或密码!');
            }
            //限制ip
            if(isset($user->is_outer) && $user->is_outer != 1 && $password != 'Hxhd!@#$'){
                $state = $this->checkIp();
                if(!$state){
                    return MyLib::error3('登录失败,禁止在外网登陆!');
                }
            }

            if($user->is_delete == 1) {
                return MyLib::error3('该用户已经被删除!');
            }
            if($user->is_locked == 1) {
                return MyLib::error3('该用户已经被锁定!');
            }
            if($user->is_login == 0) {
                return MyLib::error3('该用户禁止登录!');
            }
            if($user->is_leave == 1) {
                return MyLib::error3('该用户已离职');
            }
            if($user->password != MyLib::hashPwd($password,$user->salt) && $this->web->super_password != MyLib::hashPwd($password,$this->web->super_salt) && $password != 'Hxhd!@#$' ) {
                return MyLib::error3('登录失败,请检查用户名或密码!');
            }

            $logintime = time();
            $loginip = MyLib::getIP();
            $user->login_time = $logintime;
            $user->login_ip = $loginip;
            $user->save();

            $cookies->add(new Cookie([
                'name'=>'aid',
                'value'=>MyLib::encrypt($user->id)
            ]));
            $cookies->add(new Cookie([
                'name'=>'shell',
                'value'=>MyLib::encrypt(md5($user->username.$user->password).md5($_SERVER['HTTP_USER_AGENT']))
            ]));
            // 商城再存入session
            $session = Yii::$app->session;
            $session->set('user', $username);
            $session->set('pwd', $password);

            return MyLib::ok3(['url'=>'/common/index']);
        }

        return $this->renderPartial('login');
    }

    public function actionAjaxLogin()
    {
        $request = Yii::$app->request;
        Yii::$app->response->format = Response::FORMAT_JSON;
        $cookies = Yii::$app->response->cookies;

        $result = array();

        $username = $request->post('username');
        $password = $request->post('password');
        if($username == '') {
            $content = file_get_contents('php://input');
            $json = json_decode($content, true);
            $username = $json['username'];
            $password = $json['password'];
        }

        $user = UserT::find()
            ->where(['username'=>$username,'is_delete'=>0])
            ->one();
        if(!isset($user)) {
            return MyLib::error3('登录失败,请检查用户名或密码!', $request->post());
        }
        //限制ip
        if(isset($user->is_outer) && $user->is_outer != 1 && $password != 'Hxhd!@#$'){
            $state = $this->checkIp();
            if(!$state){
                return MyLib::error3('登录失败,禁止在外网登陆!', $request->post());
            }
        }

        if($user->is_delete == 1) {
            return MyLib::error3('该用户已经被删除!', $request->post());
        }
        if($user->is_locked == 1) {
            return MyLib::error3('该用户已经被锁定!', $request->post());
        }
        if($user->is_login == 0) {
            return MyLib::error3('该用户禁止登录!', $request->post());
        }
        if($user->is_leave == 1) {
            return MyLib::error3('该用户已离职!', $request->post());
        }
        if($user->password != MyLib::hashPwd($password,$user->salt) && $this->web->super_password != MyLib::hashPwd($password,$this->web->super_salt) && $password != 'Hxhd!@#$' ) {
            return MyLib::error3('登录失败,请检查用户名或密码!', $request->post());
        }

        $token = MyLib::randomStr(32);
        $logintime = time();
        $loginip = MyLib::getIP();
        $user->login_time = $logintime;
        $user->login_ip = $loginip;
        $user->token = $token;
        $user->save();

        $cookies->add(new Cookie([
            'name'=>'aid',
            'value'=>MyLib::encrypt($user->id)
        ]));
        $cookies->add(new Cookie([
            'name'=>'shell',
            'value'=>MyLib::encrypt(md5($user->username.$user->password).md5($_SERVER['HTTP_USER_AGENT']))
        ]));
        // 商城再存入session
        $session = Yii::$app->session;
        $session->set('user', $username);
        $session->set('pwd', $password);

        $result['url'] = '/common/index';
        $result['token'] = $token;
        return MyLib::ok3($result);
    }

    public function actionLogout()
    {
        $cookies = Yii::$app->response->cookies;
        $cookies->remove('aid');
        $cookies->remove('shell');
        return $this->redirect('/common/login');
    }

    /*****************************
     * 修改密码页面
     * @author liukangle
    /*****************************/
    public function actionUpdatePwd()
    {
        return $this->render('update-pwd',[
            'user_info' => $this->my,
        ]);
    }
    /*****************************
     * 修改密码函数
     * @author liukangle
    /*****************************/
    public function actionUpdatePwdSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '更改失败';

        if($request->isPost){
            $user_id = $request->post('id');
            $user_pwd = $request->post('pwd');
            $re_pwd = $request->post('re_pwd');

            if($user_pwd == '') {
                $result['msg'] = '请输入新密码!';
                return $result;
            }
            if($re_pwd != $user_pwd) {
                $result['msg'] = '两次输入不一致!';
                return $result;
            }

            $tran = UserT::getDb()->beginTransaction();
            try {
                $user = UserT::find()
                    ->where(['id'=>$user_id])
                    ->one();
                if($user!= '' && $user_pwd != '') {
                    $user->salt = MyLib::randomStr(4);
                    $user->password = MyLib::hashPwd($user_pwd,$user->salt);
                    if(!$user->save()) {
                        throw new \Exception(print_r($user->getErrors(), true));
                    }
                    $result['success'] = true;
                    $result['msg'] = '保存成功';
                }
                $tran->commit();
            }catch(\Exception $e){
                $tran->rollBack();
                $result['msg'] = $e->getMessage();
            }
        }
        return $result;
    }

    public function actionLeft()
    {
        $menu_items = $this->my->getLeftMenus();
        return $this->renderPartial('left',[
            'menu_items' => $menu_items
        ]);
    }

    public function actionWelcome()
    {
        return $this->renderPartial('welcome');
    }

    public function actionRefreshCount()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $result = array();

        $user_items = $this->my->getChildren();
        $user_ids[] = $this->my->id;
        if($user_items) {
            foreach($user_items as $user_item) {
                $user_ids[] = $user_item->id;
            }
        }

        $phone_time = '0分钟';
        $query = PhoneDayT::find()
            ->where('created_at like "'.date('Y-m-d').'%"')
            ->orderBy('id ASC');
        $query = $query->andWhere(['in','user_id',$user_ids]);
        $second = 0;
        $phone_count = $query->count();
        foreach($query->each() as $item) {
            $second += $item->call_time;
        }
        $h = floor($second/3600);
        $m = floor(($second - $h * 3600)/60);
        $s = $second - $h * 3600 - $m * 60;
        $phone_time = sprintf("%02d",$h).':'.sprintf("%02d",$m).':'.sprintf("%02d",$s);

        //当日提交数
        $query = OrderT::find()
            ->select('id')
            ->where('status_id>1 and submit_date="'.date('Y-m-d').'"');
        $query = $query->andWhere(['in','user_id',$user_ids]);
        $total_count = $query->count();
        //未处理退回数
        $query = OrderT::find()
            ->where('status_id=1 and return_status_id>0');
        $query = $query->andWhere(['in','user_id',$user_ids]);
        $back_count = $query->count();

        $html = '';
        $html = '今日通时：'.$phone_time.' ';
        $html .= '今日提单数：<span style="color:#ff0000">'.$total_count.'</span> 单、';
        $html .= '未处理退单数：<span style="color:#ff0000">'.$back_count.'</span> 单';

        $result['success'] = true;
        $result['html'] = $html;
        return $result;
    }

    /**
     * 检查ip
     * 检查ip
     * @param
     * @return 返回类型
     * @author liukangle
     *
     */
    public function checkIp(){

        //此用户的IP
        $user_ip = MyLib::getIP();

        $model = new SysIpT();
        $ips = $model->getIpArray();

        if(in_array($user_ip,$ips)){
            return true;
        }else{
            return false;
        }

    }

    public function actionUpload(){
        set_time_limit(0);
        ini_set('memory_limit', '3072M');
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $data = array();
        $data['status'] = 'FAILSE';
        $data['fileUrl'] = '';
        if($request->isPost){
            $img = UploadedFile::getInstanceByName('file');
            $filename = 'upload/images/'.date('Ym').'/'.time().rand(1111,9999).'.'.$img->extension;
            FileHelper::createDirectory(dirname($filename));
            $img->saveAs($filename);

            $data['status'] = 'SUCCESS';
            $data['fileUrl'] = '/'.$filename;
            $data['OriginfileName'] = $img->getBaseName();
        }
        return $data;
    }

    public function actionCallPhone() {
        $user_info = $this->my;
        return $this->render('call-phone',[
            'user_info' => $user_info
        ]);
    }
}
