<?php

namespace common\models;

use common\libs\MyLib;
use Yii;

/**
 * This is the model class for table "user_t".
 *
 * @property integer $id
 * @property string $username
 * @property string $password
 * @property string $salt
 * @property string $name
 * @property string $phone
 * @property integer $login_time
 * @property string $login_ip
 * @property integer $is_delete
 * @property integer $is_locked
 * @property integer $is_login
 * @property integer $is_send
 * @property integer $group_id
 * @property integer $phone_server_id
 * @property string $ext_phone
 * @property integer $role_id
 * @property string $enter_date
 * @property string $job_date
 * @property string $ext_pay
 * @property string $try_pay
 * @property string $try_rate
 * @property integer $worktype_id
 * @property integer $is_leave
 * @property string $created_at
 * @property string $updated_at
 * @property integer $is_double
 * @property integer $is_outer
 */
class UserT extends \common\models\Base
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'user_t';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'password', 'salt','role_id'], 'required'],
            [['login_time', 'is_delete', 'is_locked', 'is_login', 'is_send', 'group_id','phone_server_id','role_id','worktype_id','is_leave', 'is_double'], 'integer'],
            [['created_at', 'updated_at'], 'safe'],
            [['username', 'password', 'name'], 'string', 'max' => 100],
            [['salt'], 'string', 'max' => 4],
            [['phone', 'login_ip','ext_phone','enter_date','job_date','ext_pay','try_pay','try_rate'], 'string', 'max' => 50],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'username' => 'Username',
            'password' => 'Password',
            'salt' => 'Salt',
            'name' => 'Name',
            'phone' => 'Phone',
            'login_time' => 'Login Time',
            'login_ip' => 'Login Ip',
            'is_delete' => 'Is Delete',
            'is_locked' => 'Is Locked',
            'is_login' => 'Is Login',
            'is_send' => 'Is Send',
            'group_id' => 'Group ID',
            'phone_server_id' => 'Phone Server ID',
            'ext_phone' => 'Ext Phone',
            'role_id' => 'Role ID',
            'is_double' => 'Is Double',
            'enter_date' => 'Enter Date',
            'job_date' => 'Job Date',
            'ext_pay' => 'Ext Pay',
            'try_pay' => 'Try Pay',
            'try_rate' => 'Try Rate',
            'worktype_id' => 'Work Type',
            'is_leave' => 'Is Leave',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
        ];
    }

    public function getGroup()
    {
        return $this->hasOne(GroupT::className(),['id'=>'group_id']);
    }

    public function getLeftMenus()
    {
        $menus = array();
        if($this->id == 1) {
            $menu_items = MenuT::find()
                ->where('parent_id=0')
                ->orderBy('order_id ASC')
                ->all();
            foreach($menu_items as $item) {
                $row = $item->toArray();
                $child_items = MenuT::find()
                    ->where('parent_id='.$item->id)
                    ->orderBy('order_id ASC')
                    ->all();
                $sub = array();
                foreach($child_items as $child) {
                    $sub_row = $child->toArray();
                    $sub[] = $sub_row;
                }
                $row['children'] = $sub;
                $menus[] = $row;
            }
        } else {
            $menu_items = $this->getMenus()
                ->where('parent_id=0')
                ->orderBy('order_id ASC')
                ->all();
            foreach($menu_items as $item) {
                $row = $item->toArray();
                $child_items = $this->getMenus()
                    ->where('parent_id='.$item->id)
                    ->orderBy('order_id ASC')
                    ->all();
                $sub = array();
                foreach($child_items as $child) {
                    $sub_row = $child->toArray();
                    $sub[] = $sub_row;
                }
                $row['children'] = $sub;
                $menus[] = $row;
            }
        }
        return $menus;
    }

    public function getAllMenus()
    {
        $menus = array();
        $menu_items = MenuT::find()
            ->where('parent_id=0')
            ->orderBy('order_id ASC')
            ->all();
        foreach($menu_items as $item) {
            $row = $item->toArray();
            $child_items = MenuT::find()
                ->where('parent_id='.$item->id)
                ->orderBy('order_id ASC')
                ->all();
            $sub = array();
            foreach($child_items as $child) {
                $sub_row = $child->toArray();
                $sub[] = $sub_row;
            }
            $row['children'] = $sub;
            $menus[] = $row;
        }
        return $menus;
    }

    public function getShowName()
    {
        return $this->username.'('.$this->name.')';
    }

    public function getChildren($otherSql = '',$isAdmin=0)
    {
        if($otherSql != '')
            $otherSql = ' and '.$otherSql;
        if($this->id == 1 || $isAdmin == 1) {
            $items = UserT::find()
                ->where('is_delete=0'.$otherSql)
                ->orderBy('username ASC')
                ->all();
            return $items;
        } else {
            $items = GroupT::getTree($this->group_id);
            $group_ids = array();
            foreach($items as $item) {
                $group_ids[] = $item->id;
            }
            $items = UserT::find()
                ->where(['in','group_id',$group_ids])
                ->andWhere('is_delete=0'.$otherSql)
                ->orderBy('username ASC')
                ->all();
            return $items;
        }
    }

    public function getPhoneServer()
    {
        return $this->hasOne(PhoneServerT::className(),['id'=>'phone_server_id']);
    }

    public function getRole()
    {
        return $this->hasOne(RoleT::className(),['id'=>'role_id']);
    }

    public function getPermissions()
    {
        return $this->hasMany(PermissionsT::className(),['id'=>'permission_id'])
            ->viaTable('permissions_user_t',['user_id'=>'id']);
    }

    public function getMenus()
    {
        return $this->hasMany(MenuT::className(),['id'=>'menu_id'])
            ->viaTable('menu_user_t',['user_id'=>'id']);
    }

    public function getWorktype()
    {
        return $this->hasOne(WorktypeT::className(),['id'=>'worktype_id']);
    }

    public function getPay($pay_date) {
        $pay = PayT::findOne(['user_id'=>$this->id,'pay_date'=>$pay_date]);
        return $pay;
    }

    public function getChildrenUserIDs()
    {
        $user_ids = array();
        $user_items = $this->getChildren();
        if($user_items) {
            foreach($user_items as $item) {
                $user_ids[] = $item->id;
            }
        }
//        $user_ids[] = $this->my->id;
        return $user_ids;
    }

    public function getChildrenClean($otherSql = '',$isAdmin=0)
    {
        if($otherSql != '')
            $otherSql = ' and '.$otherSql;
        if($this->id == 1 || $isAdmin == 1) {
            $items = UserT::find()
                ->where('is_delete=0'.$otherSql)
                ->andWhere('group_id in(123)')
                ->orderBy('username ASC')
                ->all();
            return $items;
        } else {
            $items = GroupT::getTree($this->group_id);
            $group_ids = array();
            foreach($items as $item) {
                $group_ids[] = $item->id;
            }
            $items = UserT::find()
                ->andWhere('group_id in(123)')
//                ->andWhere('id in(656,657,658,659,155)')
                ->andWhere('is_delete=0'.$otherSql)
                ->orderBy('username ASC')
                ->all();
            return $items;
        }
    }

    public function getChunaShouldPay($pay_date){
        $user_id = $this->id;
        $pay_chexian = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and type<>7 and type<>8 and type<>10 and user_id=' . $user_id)
            ->sum('real_pay');

        $pay_nochexian = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and type=7 and user_id=' . $user_id)
            ->orWhere('pay_date="' . $pay_date . '" and type=8 and user_id=' . $user_id)
            ->sum('real_pay');

        $pay_dz = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and type=10 and user_id=' . $user_id)
            ->sum('real_pay');

        return $pay_chexian + $pay_nochexian + $pay_dz;
    }

    public function totalCallNum($begin_date,$end_date)
    {
        $query = NetworkPhoneT::find()->where('user_id='.$this->id);
        if($begin_date != ''){
            $query = $query->andWhere('begin_date>="'.$begin_date.'"');
        }
        if($end_date != ''){
            $query = $query->andWhere('begin_date<="'.$end_date.'"');
        }

        return $query->count();
    }

    static public function totalCallTotallNum($begin_date,$end_date,$company_id,$user_id)
    {
        $query = NetworkPhoneT::find()
            ->leftJoin('user_t','user_t.id=network_phone_t.user_id');
        if($begin_date != ''){
            $query = $query->andWhere('network_phone_t.begin_date>="'.$begin_date.'"');
        }
        if($end_date != ''){
            $query = $query->andWhere('network_phone_t.begin_date<="'.$end_date.'"');
        }
        if($company_id != 0){
            $query = $query->andWhere('user_t.company_id='.$company_id);
        }
        if($user_id != 0){
            $query = $query->andWhere('user_t.id='.$user_id);
        }

        return $query->count();
    }

    public function totalCallTime($begin_date,$end_date)
    {
        $query = NetworkPhoneT::find()->where('user_id='.$this->id);
        if($begin_date != ''){
            $query = $query->andWhere('begin_date>="'.$begin_date.'"');
        }
        if($end_date != ''){
            $query = $query->andWhere('begin_date<="'.$end_date.'"');
        }
        $time =  $query->sum('call_duration');

        return MyLib::HMSByTime($time);
    }

    public function totalCallTimeOut($begin_date,$end_date)
    {
        $query = NetworkPhoneT::find()->where('user_id='.$this->id)->andWhere('is_called=0 or is_called is null');
        if($begin_date != ''){
            $query = $query->andWhere('begin_date>="'.$begin_date.'"');
        }
        if($end_date != ''){
            $query = $query->andWhere('begin_date<="'.$end_date.'"');
        }
        $time =  $query->sum('call_duration');

        return MyLib::HMSByTime($time);
    }

    static public function allCallTime($begin_date,$end_date,$company_id,$user_id)
    {
        $query = NetworkPhoneT::find()
            ->leftJoin('user_t','user_t.id=network_phone_t.user_id');
        if($begin_date != ''){
            $query = $query->andWhere('network_phone_t.begin_date>="'.$begin_date.'"');
        }
        if($end_date != ''){
            $query = $query->andWhere('network_phone_t.begin_date<="'.$end_date.'"');
        }
        if($company_id != 0){
            $query = $query->andWhere('user_t.company_id='.$company_id);
        }
        if($user_id != 0){
            $query = $query->andWhere('user_t.id='.$user_id);
        }
        $time =  $query->sum('network_phone_t.call_duration');

        return MyLib::HMSByTime($time);
    }
    static public function allCallTimeOut($begin_date,$end_date,$company_id,$user_id)
    {
        $query = NetworkPhoneT::find()->where('is_called=0')
            ->leftJoin('user_t','user_t.id=network_phone_t.user_id');
        if($begin_date != ''){
            $query = $query->andWhere('network_phone_t.begin_date>="'.$begin_date.'"');
        }
        if($end_date != ''){
            $query = $query->andWhere('network_phone_t.begin_date<="'.$end_date.'"');
        }
        if($company_id != 0){
            $query = $query->andWhere('user_t.company_id='.$company_id);
        }
        if($user_id != 0){
            $query = $query->andWhere('user_t.id='.$user_id);
        }
        $time =  $query->sum('network_phone_t.call_duration');

        return MyLib::HMSByTime($time);
    }

    static public function allCallTimeOutBuy($begin_date,$end_date,$company_id,$user_id)
    {
        $query = NetworkPhoneT::find()
            ->leftJoin('user_t','user_t.id=network_phone_t.user_id');
        if($begin_date != ''){
            $query = $query->andWhere('network_phone_t.begin_date>="'.$begin_date.'"');
        }
        if($end_date != ''){
            $query = $query->andWhere('network_phone_t.begin_date<="'.$end_date.'"');
        }
        if($company_id != 0){
            $query = $query->andWhere('user_t.company_id='.$company_id);
        }
        if($user_id != 0){
            $query = $query->andWhere('user_t.id='.$user_id);
        }
        $items =  $query->all();
        $i_all = 0;
        foreach ($items as $item){
            $i = $item->call_duration;
            $i_all += MyLib::HMSByTimeBuy($i);

        }

        return $i_all;
    }

    public function callInTotalNum($begin_date,$end_date)
    {
        $t = NetworkPhoneAssignT::find()->where('user_id='.$this->id)->one();
        $phone = $t?$t->phone:0;

        $query = NetworkPhoneT::find()->where('user_id='.$this->id);
        if($begin_date != ''){
            $query = $query->andWhere('begin_date>="'.$begin_date.'"');
        }
        if($end_date != ''){
            $query = $query->andWhere('begin_date<="'.$end_date.'"');
        }

        return $query->andWhere('is_called=1')->count();
    }

    public function callInSucNum($begin_date,$end_date)
    {
        $t = NetworkPhoneAssignT::find()->where('user_id='.$this->id)->one();
        $phone = $t?$t->phone:0;

        $query = NetworkPhoneT::find()->where('user_id='.$this->id);
        if($begin_date != ''){
            $query = $query->andWhere('begin_date>="'.$begin_date.'"');
        }
        if($end_date != ''){
            $query = $query->andWhere('begin_date<="'.$end_date.'"');
        }

        return $query->andWhere('is_called=1')->andWhere('call_result="ANSWERED"')->count();
    }

    public function callOutTotalNum($begin_date,$end_date)
    {
        $t = NetworkPhoneAssignT::find()->where('user_id='.$this->id)->one();
        $phone = $t?$t->phone:0;

        $query = NetworkPhoneT::find()->where('user_id='.$this->id);
        if($begin_date != ''){
            $query = $query->andWhere('begin_date>="'.$begin_date.'"');
        }
        if($end_date != ''){
            $query = $query->andWhere('begin_date<="'.$end_date.'"');
        }

//        return $query->andWhere('caller="'.$phone.'"')->count();

        return $query->andWhere('is_called=0  or is_called is null')->count();
    }

    public function callOutSucNum($begin_date,$end_date)
    {
        $t = NetworkPhoneAssignT::find()->where('user_id='.$this->id)->one();
        $phone = $t?$t->phone:0;

        $query = NetworkPhoneT::find()->where('user_id='.$this->id);
        if($begin_date != ''){
            $query = $query->andWhere('begin_date>="'.$begin_date.'"');
        }
        if($end_date != ''){
            $query = $query->andWhere('begin_date<="'.$end_date.'"');
        }

        return $query->andWhere('is_called=0  or is_called is null')->andWhere('call_result="ANSWERED"')->count();
    }

    public function getPhoneStatus()
    {
        return $this->hasOne(NetworkPhoneAssignT::className(),['user_id'=>'id']);
    }
}
