<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "pay_t".
 *
 * @property integer $id
 * @property integer $user_id
 * @property string $pay_date
 * @property integer $attendance_days
 * @property integer $try_attendance_days
 * @property string $assessment_pay
 * @property string $goodjob_pay
 * @property string $pass_pay
 * @property string $incentive_pay
 * @property string $bonus_pay
 * @property string $extjob_pay
 * @property string $commission
 * @property string $group_pay
 * @property string $try_extjob_pay
 * @property string $grants_pay
 * @property string $give_social_pay
 * @property string $late_pay
 * @property string $leave_pay
 * @property string $sick_pay
 * @property string $social_pay
 * @property string $fine_pay
 * @property string $electricity_pay
 * @property string $deposit
 * @property string $public_pay
 * @property string $calls
 * @property string $bus
 * @property string $bonus
 * @property string $turnover
 * @property string $full_attendance_pay
 * @property string $pass_time_pay
 * @property string $formulae
 * @property string $absence_pay
 * @property string $absenteeism_pay
 * @property string $driver_num
 * @property string $driver_price
 * @property string $fix_total
 * @property string $fix_rate
 * @property string $tax
 * @property integer $get_full_attendance_pay
 * @property integer $get_pass_time_pay
 * @property integer $try_pay
 * @property integer $formal_pay
 * @property string $real_pay
 * @property string $should_pay
 * @property string $created_at
 * @property string $updated_at
 */
class PayT extends \common\models\Base
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'pay_t';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['user_id'], 'required'],
            [['user_id'], 'integer'],
            [['assessment_pay', 'attendance_days', 'driver_num', 'try_attendance_days', 'goodjob_pay', 'pass_pay', 'incentive_pay', 'bonus_pay', 'extjob_pay', 'commission', 'group_pay', 'try_extjob_pay', 'grants_pay', 'give_social_pay', 'late_pay', 'leave_pay', 'sick_pay', 'social_pay', 'fine_pay', 'electricity_pay', 'deposit', 'public_pay', 'calls', 'bus', 'bonus', 'turnover', 'full_attendance_pay', 'pass_time_pay', 'driver_price', 'fix_total', 'fix_rate', 'real_pay', 'should_pay', 'tax', 'get_full_attendance_pay', 'get_pass_time_pay', 'try_pay', 'formal_pay'], 'number'],
            [['created_at', 'updated_at'], 'safe'],
            [['pay_date'], 'string', 'max' => 50],
            [['formulae'], 'string', 'max' => 100],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'user_id' => 'User ID',
            'pay_date' => 'Pay Date',
            'attendance_days' => 'Attendance Days',
            'try_attendance_days' => 'Try Attendance Days',
            'assessment_pay' => 'Assessment Pay',
            'goodjob_pay' => 'Goodjob Pay',
            'pass_pay' => 'Pass Pay',
            'incentive_pay' => 'Incentive Pay',
            'bonus_pay' => 'Bonus Pay',
            'extjob_pay' => 'Extjob Pay',
            'commission' => 'Commission',
            'group_pay' => 'Group Pay',
            'try_extjob_pay' => 'Try Extjob Pay',
            'grants_pay' => 'Grants Pay',
            'give_social_pay' => 'Give Social Pay',
            'late_pay' => 'Late Pay',
            'leave_pay' => 'Leave Pay',
            'sick_pay' => 'Sick Pay',
            'social_pay' => 'Social Pay',
            'fine_pay' => 'Fine Pay',
            'electricity_pay' => 'Electricity Pay',
            'deposit' => 'Deposit',
            'public_pay' => 'Public Pay',
            'calls' => 'Calls',
            'bus' => 'Bus',
            'bonus' => 'Bonus',
            'turnover' => 'Turnover',
            'full_attendance_pay' => 'Full Attendance Pay',
            'pass_time_pay' => 'Pass Time Pay',
            'formulae' => 'Formulae',
            'absence_pay' => 'Absence Pay',
            'absenteeism_pay' => 'Absenteeism Pay',
            'driver_num' => 'Driver Num',
            'driver_price' => 'Driver Price',
            'fix_total' => 'Fix Total',
            'fix_rate' => 'Fix Rate',
            'real_pay' => 'Real Pay',
            'tax' => 'Tax',
            'get_full_attendance_pay' => 'Get Full Attendance Pay',
            'get_pass_time_pay' => 'Get Pass Time Pay',
            'try_pay' => 'Try Pay',
            'formal_pay' => 'Formal Pay',
            'should_pay' => 'Should Pay',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
        ];
    }

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

    public function calPay()
    {
        $this->calCommission();
        $user_info = $this->user;
        $group_info = $user_info->group;
        if($user_info->worktype){
            $workday = WorkDayT::findOne(['date' => $this->pay_date]);
            if($user_info->is_double == 1){
                $worktype = $workday ? $workday->double_break : '0';
            }else{
                $worktype = $workday ? $workday->single_break : '0';
            }
        }else{
            $this->should_pay = 0;
            $this->real_pay = 0;
            if(!$this->save()) {
                throw new \Exception(print_r($this->getErrors(), true));
            }
            return;
        }

        if($worktype == 0){
            $this->should_pay = 0;
            $this->real_pay = 0;
            if(!$this->save()) {
                throw new \Exception(print_r($this->getErrors(), true));
            }
            return;
        }

        $ext_day_pay = 0;
        $ext_day_pay = $this->formal_pay / $worktype;
        $try_day_pay = $this->try_pay / $worktype;

        $should_pay = 0;

        $should_pay += $this->try_attendance_days * $try_day_pay;
        $should_pay += $this->attendance_days * $ext_day_pay;
        $should_pay += $this->try_extjob_pay;
        $should_pay += $this->extjob_pay;
        $should_pay += $this->give_social_pay;
        $should_pay += $this->commission;
        $should_pay += $this->calls;
        $should_pay += $this->bus;
        $should_pay += $this->bonus;
        $should_pay += $this->get_pass_time_pay;
        $should_pay += $this->get_full_attendance_pay;
        $this->should_pay = $should_pay;

        $real_pay = $should_pay - $this->late_pay;
        $real_pay -= $this->leave_pay;
        $real_pay -= $this->sick_pay;
        $real_pay -= $this->social_pay;
        $real_pay -= $this->fine_pay;
        $real_pay -= $this->electricity_pay;
        $real_pay -= $this->deposit;
        $real_pay -= $this->public_pay;
        $real_pay -= $this->tax;

        if($this->full_attendance_pay > 1){
            $real_pay -= $this->full_attendance_pay;
        }else{
            $real_pay -= ($this->commission * $this->full_attendance_pay);
        }

        if($this->pass_time_pay > 1){
            $real_pay -= $this->pass_time_pay;
        }else{
            $real_pay -= ($this->commission * $this->pass_time_pay);
        }

        $this->real_pay = $real_pay;

        if(!$this->save()) {
            throw new \Exception(print_r($this->getErrors(), true));
        }
        return true;
    }

    /**
     * 提成计算
     * @param null $ft
     * @return int
     */
    public function calCommission($ft = null)
    {
        $commission = 0;
        $formulae = $ft ? $ft : ($this->formulae ? $this->formulae : '');
        if($formulae != '') {
            $grticheng = $this->calGrticheng();
            if($grticheng == 0)
                $grticheng = 0;
            $grbaofei = $this->calGrbaofei();
            if($grbaofei == 0)
                $grbaofei = 0;
            $gsbaofei = $this->calGsbaofei();
            if($gsbaofei == 0)
                $gsbaofei = 0;
            $bmbaofei = $this->calBmbaofei();
            if($bmbaofei == 0)
                $bmbaofei = 0;
            $yyg = $this->turnover;
            if($yyg == 0)
                $yyg = 0;
            $new_data = str_replace('grTicheng',$grticheng,$formulae);
            $new_data = str_replace('grBaoFei',$grbaofei,$new_data);
            $new_data = str_replace('gsBaoFei',$gsbaofei,$new_data);
            $new_data = str_replace('bmBaoFei',$bmbaofei,$new_data);
            $new_data = str_replace('yyg',$yyg,$new_data);
//            echo '$commission=round('.$new_data.',2);';exit;
            eval('$commission=round('.$new_data.',2);');
        }
        $commission += $this->driver_num * $this->driver_price;
        $commission += $this->fix_total * $this->fix_rate / 100;
        $this->commission = $commission;
        $this->save();

        return $commission;
    }
    /**
     *  计算个人提成
     */
    public function calGrticheng()
    {
        //个人提成
        $grbaofei = 0;
        $pay_order_users = PayOrderUserT::find()
            ->where('pay_date="'.$this->pay_date.'" and user_id='.$this->user_id)
            ->all();
        foreach($pay_order_users as $pay_order_user) {
//            $pay_order_user->calPay();
//            var_dump($pay_order_user->real_pay);
            $grbaofei += $pay_order_user->real_pay;
        }
//        die;
        return round($grbaofei,2);
    }
    /**
     *  计算个人保费
     */
    public function calGrbaofei()
    {
        //个人保费
        $grbaofei = 0;
        $query = OrderT::find()
            ->leftJoin('pay_order_user_t','pay_order_user_t.order_id=order_t.id')
            ->where('pay_order_user_t.pay_date="'.$this->pay_date.'"')
            ->groupBy('order_t.car_no');
        $user = $this->user;
        $query = $query->andWhere(['in','order_t.user_id',$user->id]);
//        echo $query->createCommand()->rawSql;
        $grbaofei = $query->sum('total1_clear');

        return round($grbaofei,2);
    }

    /**
     * 计算全公司当月保费
     * @return int|mixed
     */
    public function calGsbaofei()
    {
        $gsbaofei = 0;
        $query = OrderT::find()
            ->leftJoin('pay_order_user_t','pay_order_user_t.order_id=order_t.id')
            ->where('pay_order_user_t.pay_date="'.$this->pay_date.'"')
            ->groupBy('order_t.car_no');
//        echo $query->createCommand()->rawSql;
        $gsbaofei = $query->sum('total1_clear');
        return round($gsbaofei,2);
    }

    public function calBmbaofei()
    {
        $bmbaofei = 0;
        $query = OrderT::find()
            ->leftJoin('pay_order_user_t','pay_order_user_t.order_id=order_t.id')
            ->where('pay_order_user_t.pay_date="'.$this->pay_date.'"')
            ->groupBy('order_t.car_no');

        $user = $this->user;
        $user_ids = $user->getChildrenUserIDs();
        $query = $query->andWhere(['in','order_t.user_id',$user_ids]);
        $bmbaofei = $query->sum('total1_clear');
        return round($bmbaofei,2);
    }

    public function getStatus($status_id){
        $res = '';
        if($status_id == 1){
            $res = '人事✔';
        }elseif ($status_id == 2){
            $res = '出纳✔';
        }elseif ($status_id == 3){
            $res = '人事✔，出纳✔';
        }elseif ($status_id == 4){
            $res = '财务✔';
        }elseif ($status_id == 5){
            $res = '老板✔';
        }elseif ($status_id == 6){
            $res = '已发放';
        }elseif ($status_id == 7){
            $res = '退回人事';
        }elseif ($status_id == 8){
            $res = '退回出纳';
        }elseif ($status_id == 10){
            $res = '退回财务';
        }
        return $res;
    }
}
