<?php

namespace frontend\controllers;

use common\libs\MyLib;
use common\models\GroupT;
use common\models\PayT;
use common\models\UserT;
use common\models\WorkDayT;
use common\models\UserLogT;
use Yii;
use yii\data\Pagination;
use yii\web\Response;
use yii\web\UploadedFile;
use common\models\CompanyT;

class PersonnelController extends \frontend\controllers\UserBaseController
{
    public $my = 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 {
            Yii::$app->response->redirect('/common/login')->send();
            exit;
        }
    }

    /**
     * 人事工资列表
     * @return string
     */
    public function actionPayList() {
        $group_items = GroupT::getTree();
        return $this->render('pay-list',[
            'group_items' => $group_items
        ]);
    }

    public function actionPayListJson()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $username = $request->get('username');
        $name = $request->get('name');
        $pay_date = $request->get('pay_date',date('Y-m'));
        $group_id = $request->get('group_id',0);
        $is_leave = $request->get('is_leave',0);
        $status_id = $request->get('status_id',0);

        $offset = $request->get('offset', 0);
        $limit = $request->get('limit', 10);

        $query = UserT::find()
            ->leftJoin('pay_t','pay_t.user_id=user_t.id')
            ->where('user_t.group_id>0 and is_delete=0');
        if($username != '') {
            $query->andWhere('user_t.username like "'.$username.'"');
        }
        if($name != '') {
            $query->andWhere('user_t.name like "'.$name.'"');
        }
        if($is_leave != ''){
            $query->andWhere(['user_t.is_leave' => $is_leave]);
        }
        if($group_id > 0) {
            $query->andWhere('user_t.group_id='.$group_id);
        }
        if($status_id > 0) {
            $query->andWhere('pay_t.status_id='.$status_id);
        }
        $query->orderBy('user_t.username ASC,user_t.id ASC');
        $total = $query->count();

        $query->offset($offset)->limit($limit);
        $items = $query->all();

        $data = [];
        $data['total'] = $total;
        $data['rows'] = [];
        foreach($items as $item) {
            $row = $item->toArray();
            $row['pay_date'] = $pay_date;
            $row['group_name'] = $item->group ? $item->group->path : '';
            $row['is_leave'] = $item->is_leave ? '已离职':'';
            $pay_info = $item->getPay($pay_date);
            $row['status_name'] = $pay_info ? $pay_info->getStatus($pay_info->status_id) : '';
            $row['real_pay'] = $pay_info ? $pay_info->base_real_pay : 0 ;
            $data['rows'][] = $row;
        }

        return $data;
    }

    /**
     * 人事工资-详情
     * @return string
     */
    public function actionPayInfo()
    {
        $request = Yii::$app->request;
        $user_id = $request->get('id',0);
        $pay_date = $request->get('pay_date',date('Y-m'));
        $back_params = $request->get('back_params');

        $user_info = UserT::findOne(['id'=>$user_id]);

        $work_day = WorkDayT::findOne(['date' => $pay_date]);

        $group_info = $user_info->group;

        if($user_info->is_double == 1) {
            $day_num = $work_day ? $work_day->double_break : '0';
        }else{
            $day_num = $work_day ? $work_day->single_break : '0';
        }

        if($day_num == '0'){
            echo '请填写工作天数!';
            echo '[<a href="/personnel/pay-list?'.$back_params.'">返回</a>]';
            die;
        }

        $pay_info = PayT::findOne(['user_id'=>$user_id,'pay_date'=>$pay_date]);

        if($pay_info){
            $try_pay = $user_info->worktype?round(($pay_info->try_pay) / $day_num, 2):'0';
            $true_pay = $user_info->worktype?round(($pay_info->formal_pay) / $day_num, 2):'0';
        }else{
            $try_pay = $user_info->worktype?round(($user_info->try_pay) / $day_num, 2):'0';
            $true_pay = $user_info->worktype?round(($group_info?($group_info->base_pay + $group_info->job_pay + $group_info->station_pay + $user_info->ext_pay):$user_info->ext_pay) / $day_num, 2):'0';

        }


        if(!$pay_info) {
            $pay_info = new PayT();
            $pay_info->user_id = $user_id;
            $pay_info->pay_date = $pay_date;
            $pay_info->formal_pay = ($group_info?($group_info->base_pay + $group_info->job_pay + $group_info->station_pay + $user_info->ext_pay):$user_info->ext_pay);
            $pay_info->try_pay = floatval($user_info->try_pay);

            $last_month = date('Y-m', strtotime($pay_date.'last month'));
            //获取上个月的提成计算
            $formulae = PayT::findOne(['user_id' => $user_id, 'pay_date' => $last_month]);

            if($formulae)
                $pay_info->formulae = $formulae->formulae;
            else
                $pay_info->formulae = '';

            if($group_info) {
                $pay_info->should_pay =floatval($group_info->base_pay + $group_info->job_pay + $group_info->station_pay + $user_info->ext_pay);
            } else {
                $pay_info->should_pay = floatval($user_info->ext_pay);
            }

            if(!$pay_info->save()) {
                var_dump($pay_info->errors);
                exit;
            }
            $pay_info = PayT::findOne(['user_id'=>$user_id,'pay_date'=>$pay_date]);
//            die;
        }

        return $this->render('pay-info',[
            'pay_date' => $pay_date,
            'user_info' => $user_info,
            'group_info' => $group_info,
            'pay_info' => $pay_info,
            'back_params' => $back_params,
            'try_pay' => $try_pay,
            'true_pay' => $true_pay
        ]);
    }

    /**
     * 人事工资-保存
     * @return array
     */
    public function actionPaySave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        if($request->isPost) {
            $id = $request->post('id',0);
            $assessment_pay = $request->post('assessment_pay',0);
            $goodjob_pay = $request->post('goodjob_pay',0);
            $pass_pay = $request->post('pass_pay',0);
            $incentive_pay = $request->post('incentive_pay',0);
            $bonus_pay = $request->post('bonus_pay',0);
            $extjob_pay = $request->post('extjob_pay',0);
            $group_pay = $request->post('group_pay',0);
            $grants_pay = $request->post('grants_pay',0);
            $late_pay = $request->post('late_pay',0);
            $leave_pay = $request->post('leave_pay',0);
            $sick_pay = $request->post('sick_pay',0);
            $social_pay = $request->post('social_pay',0);
            $fine_pay = $request->post('fine_pay',0);
            $electricity_pay = $request->post('electricity_pay',0);
            $deposit = $request->post('deposit',0);
            $public_pay = $request->post('public_pay',0);
            $extjob_days = $request->post('extjob_days',0);
            $attendance_days = $request->post('attendance_days');
            $try_attendance_days = $request->post('try_attendance_days');
            $try_extjob_pay = $request->post('try_extjob_pay');
            $give_social_pay = $request->post('give_social_pay');
            $full_attendance_pay = $request->post('full_attendance_pay');
            $pass_time_pay = $request->post('pass_time_pay');
//            $formulae = $request->post('formulae');
            $get_full_attendance_pay = $request->post('get_full_attendance_pay', 0);
            $get_pass_time_pay = $request->post('get_pass_time_pay', 0);
            $try_pay = $request->post('try_pay', 0);
            $formal_pay = $request->post('formal_pay', 0);



            $calls = $request->post('calls', 0);
            $bus = $request->post('bus', 0);
            $bonus = $request->post('bonus', 0);
            $turnover = $request->post('turnover', 0);
            $tax = $request->post('tax', 0);


            $pay_info = PayT::findOne(['id'=>$id]);
            if($pay_info) {
                $pay_info->assessment_pay = $assessment_pay;
                $pay_info->goodjob_pay = $goodjob_pay;
                $pay_info->pass_pay = $pass_pay;
                $pay_info->incentive_pay = $incentive_pay;
                $pay_info->bonus_pay = $bonus_pay;
                $pay_info->extjob_pay = $extjob_pay;
                $pay_info->group_pay = $group_pay;
                $pay_info->grants_pay = $grants_pay;
                $pay_info->late_pay = $late_pay;
                $pay_info->leave_pay = $leave_pay;
                $pay_info->sick_pay = $sick_pay;
                $pay_info->social_pay = $social_pay;
                $pay_info->fine_pay = $fine_pay;
                $pay_info->electricity_pay = $electricity_pay;
                $pay_info->deposit = $deposit;
                $pay_info->public_pay = $public_pay;
                $pay_info->extjob_days = $extjob_days;
                $pay_info->attendance_days = $attendance_days;
                $pay_info->try_attendance_days = $try_attendance_days;
                $pay_info->try_extjob_pay = $try_extjob_pay;
                $pay_info->give_social_pay = $give_social_pay;
                $pay_info->full_attendance_pay = $full_attendance_pay;
                $pay_info->pass_time_pay = $pass_time_pay;
//                $pay_info->formulae = $formulae;
                $pay_info->get_full_attendance_pay = $get_full_attendance_pay;
                $pay_info->get_pass_time_pay = $get_pass_time_pay;
                $pay_info->try_pay = $try_pay;
                $pay_info->formal_pay = $formal_pay;


                $pay_info->calls = $calls;
                $pay_info->bus = $bus;
                $pay_info->bonus = $bonus;
                $pay_info->turnover = $turnover;
                $pay_info->tax = $tax;
                $pay_info->renshi_status_id = 1;
                $pay_info->status_id = $pay_info->chuna_status_id + 1;

                $pay_info->save();
                $pay_info->calPay();

                $content = '人事:'.$this->my->showName.'提交'.$pay_info->pay_date.'工资';
                $this->addUserLog($pay_info->id, $content);

                $result['success'] = true;
                $result['msg'] = '保存成功';
            }
        }
        return $result;
    }

    /**
     * @return array
     * 获取表格数据
     * xzz
     * 2017-12-29
     */
    public function actionImport()
    {
        set_time_limit(0);

        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;

        $result = [
            'success' => false,
            'msg' => '操作失败'
        ];

        $time = $request->post('time');
        $file_url = $request->post('urlfile');

        if($time == '' || $file_url == ''){
            $result['msg'] = '时间和文件为必填项!';
            return $result;
        }

        $web_path = Yii::$app->getBasePath().'/../frontend/web';
        $file_path = realpath($web_path.$file_url);

        //实例化Excel表格
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if(!$PHPReader->canRead($file_path)){
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if(!$PHPReader->canRead($file_path)){
                return $result;
            }
        }

        $PHPExcel = $PHPReader->load($file_path);

        $currentSheet = $PHPExcel->getSheet(0);

        $data = $currentSheet->toArray('', true, true);

        $ii = count($data);

        for($i = 2; $i < $ii; $i++){
            if(empty($data[$i][1]) || empty($data[$i][2]))
                return $result;

            $user_info = UserT::findOne(['username'=>$data[$i][1],'name'=>$data[$i][2]]);

            if($user_info->id < 0)
                return $result;

            $pay_info = PayT::findOne(['user_id' => $user_info->id, 'pay_date' => $time]);
            if(!$pay_info){
                $pay_info = new PayT();

                $pay_info->user_id = $user_info->id;
                $pay_info->pay_date = $time;

                $group_info = $user_info->group;

                if($group_info) {
                    $pay_info->should_pay =floatval($group_info->base_pay + $group_info->job_pay + $group_info->station_pay + $user_info->ext_pay);
                } else {
                    $pay_info->should_pay = floatval($user_info->ext_pay);
                }
            }

            $pay_info->try_attendance_days = round(trim($data[$i][3]), 1);
            $pay_info->try_extjob_pay = round(trim($data[$i][4]), 2);
            $pay_info->attendance_days = round(trim($data[$i][5]), 1);
            $pay_info->extjob_pay = round(trim($data[$i][6]), 2);
            $pay_info->give_social_pay = round(trim($data[$i][7]), 2);
            $pay_info->late_pay = round(trim($data[$i][8]), 2);
            $pay_info->leave_pay = round(trim($data[$i][9]), 2);
            $pay_info->sick_pay = round(trim($data[$i][10]), 2);
            $pay_info->social_pay = round(trim($data[$i][11]), 2);
            $pay_info->electricity_pay = round(trim($data[$i][12]), 2);
            $pay_info->full_attendance_pay = $data[$i][13];
            $pay_info->pass_time_pay = $data[$i][14];
            $pay_info->formulae = PayT::findOne(['user_id' => $user_info->id, 'pay_date' => '2017-11'])->formulae;
            $pay_info->save();
            $pay_info->calPay();
        }

        $result = [
            'success' => true,
            'msg' => '操作成功'
        ];

        return $result;
    }

    /**
     * @return string
     * 上传文件
     * xzz
     * 2017-12-29
     */
    public function actionUpload()
    {
        Yii::$app->response->format = Response::FORMAT_RAW;

        $result = [
            'success' => false
        ];

        $file = UploadedFile::getInstanceByName('file');

        if(!empty($file)){
            $name = md5(rand(100, 200));
            $ext = $file->extension;
            $filename = $name.'.'.$ext;

            $destination = '/upload';

            $web_path = Yii::$app->getBasePath().'/../frontend/web';

            if(!is_dir($web_path.$destination))
                mkdir($web_path.$destination);

            $destination .= '/gz';

            if(!is_dir($web_path.$destination))
                mkdir($web_path.$destination);

            $destination .= '/'.date('Ym');

            if(!is_dir($web_path.$destination))
                mkdir($web_path.$destination);

            $destination .= '/'.$filename;

            $file->saveAs($web_path.$destination);

            $row['name'] = $file->name;
            $row['size'] = $file->size;
            $row['url'] = $destination;
            $row['thumbnailUrl'] = $destination;
            $row['deleteUrl'] = '';
            $row['deleteType'] = 'DELETE';

            $result['success'] = true;
            $result['files'][] = $row;

            return json_encode($result);
        }

        $result['files'][0]['error'] = '上传文件失败';
        return json_encode($result);
    }


    public function actionAjaxHistoryIndex()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $pay_id = $request->get('pay_id');
        $page = $request->get('page',1);

        $result = array();
        $result['success'] = false;
        $result['msg'] = '读取失败';

        $query = UserLogT::find()
            ->where(['pay_id'=>$pay_id])
//            ->andWhere('op_time>='.strtotime("-6 months"))
            ->orderBy('id DESC');

        $total = $query->count();

        $pagination = new Pagination(['totalCount' => $total,'pageSize'=>20]);
        $pagination->setPage($page-1);

        $query = $query->offset($pagination->offset)->limit($pagination->limit);
        $items = $query->all();

        $page_info = MyLib::getAjaxPageInfo($pagination,'car_history_list');
        $html = $this->renderPartial('ajax-history-index',[
            'pay_id' => $pay_id,
            'items' => $items,
            'page' => $page,
            'page_info' => $page_info
        ]);
        $result['success'] = true;
        $result['msg'] = '读取成功';
        $result['html'] = $html;
        return $result;
    }
}