<?php
/**
 * 修车财务控制器
 */

namespace frontend\controllers;

use common\models\FixCarItemT;
use common\models\FixCarReport;
use Yii;
use common\libs\MyLib;
use yii\base\ErrorException;
use yii\data\Pagination;
use common\models\FixCarT;
use common\models\UserT;
use common\models\CarFinanceT;
use common\models\GiftTicketT;
use yii\filters\VerbFilter;
use yii\helpers\ArrayHelper;
use yii\web\Response;

class FixCarFinanceController extends BaseController{
    public function behaviors()
    {
        return [
            [
              'class' => 'yii\filters\ContentNegotiator',
              'only' => ['create','update','cashier-to-acc'],
              'formats' => [
                  'application/json' => Response::FORMAT_JSON,
              ],
          ],
            'verbs'=>[
                'class'=>VerbFilter::className(),
                'actions'=>[
                    'list'=>['get'],
                    'list-accounts'=>['get'],
                    'list-accounts2'=>['get'],
                    'settle-accounts'=>['get'],
                    'create'=>['post']
                ]
            ],
            [
                'class'=>'yii\filters\HttpCache',
                'only' => ['list-accounts','list-accounts2'],
                'etagSeed' => function ($action) {
                    $q = new \yii\db\Query();
                    if('list-accounts' === $action->id){
                        $model = $q->from('fix_car_t');
                    }elseif('list-accounts2' === $action->id){
                        $model = $q->from('car_finance_t');
                    }
                    return $model->max('updated_at').$model->count();
                }
            ]
        ];
    }

    /**
     ***********************************
     * 根据id获取所有修车信息
     * $acc_id 修车表的id
     * @author liukangle
     ***********************************
     */
    public function getList($fix_id=-1){
       return FixCarT::findOne($fix_id);
    }

    /************************************
     * 账单结算（出纳）
     * 账单结算（出纳）
     * @author liukangle
     ************************************/
    public function actionListAccounts(){

        $op = $this->requestType('get','op',1);
        $page = $this->requestType('get','page',1);
        $car_no = $this->requestType('get','car_no');
        if($page < 1) $page = 1;
        $car_list = [];
        $page_info = '';
        if($op != 0){

            $model = FixCarT::find()->where('status BETWEEN 6 AND 15');
            //车牌号
            if($car_no != '') {
                $model = $model->andWhere('car_no LIKE "'.$car_no.'"');
            }
            $total = $model->count();

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

            $model = $model->offset($pagination->offset)->limit($pagination->limit);
            $car_list = $model->all();

            $page_info = MyLib::getPageInfo($pagination);
        }
        return $this->render('list-accounts',[
            'car_list' => $car_list,
            'page_info' => $page_info,
            'car_no' => $car_no,
        ]);
    }

    /**
     ***********************************
     * 财务结算（会计）
     * 财务结算（会计）
     * @author liukangle
     *********************************
     */
    public function actionListAccounts2(){

        $op = $this->requestType('get','op',1);
        $page = $this->requestType('get','page',1);
        $car_no = $this->requestType('get','car_no');
        if($page < 1) $page = 1;
        $car_list = [];
        $page_info = '';
        if($op != 0){
            $model = CarFinanceT::find()->joinWith('fixCarT')->where('fix_car_t.status=16');

            if('' !== $car_no){
                $model = $model->andWhere('fix_car_t.car_no LIKE \''.$car_no.'\'');
            }

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

            $model = $model->offset($pagination->offset)->limit($pagination->limit);
            $car_list = $model->all();

            $page_info = MyLib::getPageInfo($pagination);
        }
        return $this->render('list-accounts2',[
            'car_list' => $car_list,
            'page_info' => $page_info,
            'car_no' => $car_no,
        ]);
    }

    /**
     ***********************************
     * 出纳详情页
     * 出纳详情页
     * @author liukangle
     *********************************/
    public function actionSettleAccounts(){
        $request = Yii::$app->request;

        $acc_id = $request->get('fix_id',0);
        $report_id = $request->get('report_id',null);

        $fixcar = $this->getList($acc_id);

        //新礼品
        $query = GiftTicketT::find()
            ->orderBy('id DESC');
        $query = $query->where('status=1');
        $gift_items = $query->andWhere('car_no like "'.$fixcar->car_no.'"')->all();

        //司机
        $driver_items = UserT::find()
            ->where('group_id=41')
            ->orderBy('username ASC')
            ->all();

        $fix_car_query = FixCarItemT::find()->where('fix_id='.$acc_id.' AND fix_group!=13');
        $fix_car_query = $report_id ? $fix_car_query->andWhere('report_id='.$report_id) : $fix_car_query->andWhere('report_id IS NULL');
        $items = $obj_items =  ($res = $fix_car_query->all()) ? $res : [];
        $items = ArrayHelper::index(ArrayHelper::toArray($items),null,'type');

        //保险理赔
        $report = null;
        $total_price = 0;

        $carfinance = CarFinanceT::find()->where('fix_id='.$acc_id);

        if(!empty($report_id) && $report_id > 0){
            $report = FixCarReport::findOne($report_id);
            $carfinance->andWhere('baoanhao=\''.$report->report_no.'\'');
        }else{
            foreach($obj_items as $item){
                $total_price += $item->price * $item->count;
            }
            $carfinance->andWhere('baoanhao=\''.'\'');
        }

        $carfinance = $carfinance->one();

        return $this->render('settle-accounts',[
            'fixcar' => $fixcar,
            'gift_items' => $gift_items,
            'carfinance' => $carfinance,
            'drivers'=>$driver_items,
            'items'=>$items,
            'report'=>$report,
            'total_price'=>$total_price
        ]);
    }

    /**
     ***********************************
     * 出纳提交到会计
     * 出纳提交到会计
     * @author liukangle
     *********************************
     */
    public function actionCashierToAcc(){

        $request = Yii::$app->request;
        $result = [];
        $result['success'] = false;
        $result['msg'] = '操作失败!';

        if($request->isPost) {
            $model = FixCarT::findOne(['id'=>$request->post('fix_id')]);
            $model->scenario = 'status';
            $model->status = 17;
            $car_state = $model->save();

            if(!$car_state){
                throw new \Exception('操作失败1！');
            }

            $result['success'] = true;
            $result['msg'] = '操作成功!';
            return $result;
        }
    }

    /**
     ***********************************
     * 会计详情页
     * 会计详情页
     * @author liukangle
     *********************************
     */
    public function actionSettleAccounts2(){

        $request = Yii::$app->request;

        $acc_id = $request->get('fix_id',0);

        $fixcar = $carfinance = CarFinanceT::findOne($acc_id);
        $fixcar = $fixcar->fixCarT;

        //新礼品
        $query = GiftTicketT::find()
            ->orderBy('id DESC');
        $query = $query->where('status=1');
        $gift_items = $query->andWhere('car_no like "'.$fixcar->car_no.'"')->all();

        //司机
        $driver_items = UserT::find()
            ->where('group_id=41')
            ->orderBy('username ASC')
            ->all();


        //保险理赔
        $report = null;
        $total_price = 0;


        return $this->render('settle-accounts2',[
            'fixcar' => $fixcar,
            'gift_items' => $gift_items,
            'carfinance' => $carfinance,
            'drivers'=>$driver_items,
            'report'=>$report,
            'total_price'=>$total_price
        ]);
    }

    /**
     ***********************************
     * 打印结算单
     * 打印结算单
     * @author liukangle
     ***********************************
     */
    public function actionPrintSend(){

        $acc_id = $this->requestType('get','acc_id',-1);

        $fixcar = $this->getList($acc_id);

        return $this->render('print-send',[
            'fixcar' => $fixcar,
        ]);
    }

    /**
     ***********************************
     * 打印送车单
     * 打印送车单
     * @author liukangle
     ***********************************
     */
    public function actionCarSend(){

        $acc_id = $this->requestType('get','acc_id',-1);

        $fixcar = $this->getList($acc_id);

        $items = ($res = FixCarItemT::find()->where('fix_id='.$acc_id.' AND fix_group!=13')->all()) ? $res : [];
        $items = ArrayHelper::index(ArrayHelper::toArray($items),null,'type');

        return $this->render('car-send',[
            'fixcar' => $fixcar,
            'items'  => $items
        ]);
    }

    public function actionCreate(){
        $request = Yii::$app->request;

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

        $finance_id = $request->post('finance_id');
        if($finance_id < 0) return $result;

        $model = CarFinanceT::findOne($finance_id);
        $model->scenario = 'create';
        $model->attributes = $request->post();
        if(!$model->validate()) {
            $errors = array_values($model->errors);
            $result['msg'] = $errors[0];
            return $result;
        }

        if($model->save()) {
            $result['success'] = true;
            $result['msg'] = '操作成功!';
            return $result;
        }

        return $result;
    }
    public function actionUpdate(){
        $request = Yii::$app->request;

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

        $fix_id = $request->post('fix_id');

        if($res = CarFinanceT::find()->where('fix_id='.$fix_id.' AND examine BETWEEN 0 AND 1')->one()) {
            $result['msg'] = '还有未审核的项目!';
            return $result;
        }

        $model = FixCarT::findOne($fix_id);
        $model->status = 16;
        $model->save();

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

        return $result;
    }
}