<?php

namespace frontend\controllers;

use common\libs\MyLib;
use common\models\AppointmentHistoryT;
use common\models\AppointmentT;
use common\models\CarBT;
use common\models\CarCT;
use common\models\CarDT;
use common\models\CarInvalidT;
use common\models\CarT;
use common\models\MeetT;
use common\models\EmsT;
use common\models\GiftGroupT;
use common\models\GiftT;
use common\models\InsurerTypeT;
use common\models\InvalidT;
use common\models\OrderGiftT;
use common\models\OrderT;
use common\models\UserT;
use Yii;
use yii\data\Pagination;
use yii\db\Exception;
use yii\web\Response;

class RenewalController extends BaseController
{
    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;
        }
    }

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

        $index = $request->get('index');
        $type = $request->get('type');

        $sql = null;
        if($type == 1) {
            $sql = $session->get('appointment_first',array());
        }
        if($type == 2) {
            $sql = $session->get('appointment_today',array());
        }
        if($type == 3) {
            $sql = $session->get('appointment_all',array());
        }
        $car_id = 0;
        $item = Yii::$app->db->createCommand($sql.' limit '.$index.',1')
            ->queryOne();
        if($item) {
            $car_id = $item['car_id'];
        }

        $result = array();
        $result['success'] = true;
        $result['car_id'] = $car_id;

        return $result;
    }

    //首拨
    public function actionFirst() {
        $invalid_items = InvalidT::getTree();
        $user_items = $this->my->getChildren();

        return $this->render('first',[
            'invalid_items' => $invalid_items,
            'user_items' => $user_items
        ]);
    }
    public function actionFirstJson()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $session = Yii::$app->session;
        $request = Yii::$app->request;
        $car_man = $request->get('car_man');
        $phone = $request->get('phone');
        $car_no = $request->get('car_no');
        $username = $request->get('username');
        $sort_key = $request->get('sort_key','appointment_t.pdate');
        $sort_value = $request->get('sort_value','ASC');
        $offset = $request->get('offset',0);
        $limit = $request->get('limit', 10);

        $query = AppointmentT::find()
            ->leftJoin('car_t','`car_t`.`id`=`appointment_t`.`car_id`')
            ->where('appointment_t.is_first=1 and car_t.location=4');

        if($username == '') {
            $user_ids = $this->getChildrenUserIDs();
            $query->andWhere(['in','appointment_t.user_id',$user_ids]);
        }

        if($car_man != '') {
            $query->andWhere('car_t.car_man like "'.$car_man.'"');
        }
        if($phone != '') {
            $query->andWhere('car_t.car_man_phone like "'.$phone.'"');
        }
        if($car_no != '') {
            $query->andWhere('car_t.car_no like "'.$car_no.'"');
        }
        if($username != '') {
            $user_query = UserT::find()
                ->where('username="'.$username.'"')
                ->all();
            foreach($user_query as $user_info) {
                $user_ids[] = $user_info->id;
            }
            if(count($user_ids) > 0)
                $query->andWhere(['in','appointment_t.user_id',$user_ids]);
        }
        if($sort_key != '') {
            $query->orderBy($sort_key.' '.$sort_value.',appointment_t.id '.$sort_value);
        }
        $sql = $query->createCommand()->rawSql;
//        echo $query->createCommand()->rawSql;
        $total = $query->count();
        $session->remove('appointment_first');
        $session->set('appointment_first',$sql);

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

        $data = [];
        $data['total'] = $total;
        $data['rows'] = [];
        foreach($items as $item) {
            $car_info = $item->car;
            $row = $item->toArray();
            $row['car_id'] = $car_info->id;
            $row['car_no'] = $car_info->car_no;
            $row['car_man'] = $car_info->car_man;
            $row['register_date'] = $car_info->register_date;
            $row['insurer1_date'] = $car_info->insurer1_date;
            $row['insurer2_date'] = $car_info->insurer2_date;
            $row['user_name'] = $item->user ? $item->user->getShowName():'';
            $data['rows'][] = $row;
        }
        return $data;
    }

    //今日预约
    public function actionToday() {
        $invalid_items = InvalidT::getTree();
        $user_items = $this->my->getChildren();

        return $this->render('today',[
            'invalid_items' => $invalid_items,
            'user_items' => $user_items
        ]);
    }
    public function actionTodayJson()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $session = Yii::$app->session;
        $request = Yii::$app->request;
        $car_man = $request->get('car_man');
        $phone = $request->get('phone');
        $car_no = $request->get('car_no');
        $sort_key = $request->get('sort_key','appointment_t.pdate');
        $sort_value = $request->get('sort_value','ASC');
        $ptype = $request->get('ptype');
        $offset = $request->get('offset',0);
        $limit = $request->get('limit', 10);

        $query = AppointmentT::find()
            ->leftJoin('car_t','`car_t`.`id`=`appointment_t`.`car_id`')
            ->where('appointment_t.is_first=0 and car_t.location=4')
            ->andWhere('appointment_t.pdate<="'.date('Y-m-d').'"');

        $user_ids = $this->getChildrenUserIDs();
        $query = $query->andWhere(['in','appointment_t.user_id',$user_ids]);

        if($car_man != '') {
            $query = $query->andWhere('car_t.car_man like "'.$car_man.'"');
        }
        if($phone != '') {
            $query = $query->andWhere('car_t.car_man_phone="'.$phone.'"');
        }
        if($ptype > 0) {
            $query = $query->andWhere('appointment_t.ptype='.$ptype);
        }
        if($car_no != '') {
            $query = $query->andWhere('car_t.car_no like "'.$car_no.'"');
        }
        if($sort_key != '') {
            $query = $query->orderBy($sort_key.' '.$sort_value.', appointment_t.id '.$sort_value);
        }
        $sql = $query->createCommand()->rawSql;
//        echo $query->createCommand()->rawSql;
        $total = $query->count();
        $session->remove('appointment_today');
        $session->set('appointment_today',$sql);

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

        $data = [];
        $data['total'] = $total;
        $data['rows'] = [];
        foreach($items as $item) {
            $car_info = $item->car;
            $row = $item->toArray();
            $row['car_id'] = $car_info->id;
            $row['car_no'] = $car_info->car_no;
            $row['car_man'] = $car_info->car_man;
            $row['register_date'] = $car_info->register_date;
            $row['insurer1_date'] = $car_info->insurer1_date;
            $row['insurer2_date'] = $car_info->insurer2_date;
            $row['user_name'] = $item->user ? $item->user->getShowName():'';
            $data['rows'][] = $row;
        }
        return $data;
    }

    //全部预约
    public function actionAll() {
        $invalid_items = InvalidT::getTree();
        $user_items = $this->my->getChildren();

        return $this->render('all',[
            'invalid_items' => $invalid_items,
            'user_items' => $user_items
        ]);
    }
    public function actionAllJson()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $session = Yii::$app->session;
        $request = Yii::$app->request;
        $car_man = $request->get('car_man');
        $phone = $request->get('phone');
        $car_no = $request->get('car_no');
        $username = $request->get('username');
        $sort_key = $request->get('sort_key','appointment_t.pdate');
        $sort_value = $request->get('sort_value','ASC');
        $user_id = $request->get('user_id');
        $ptype = $request->get('ptype');
        $offset = $request->get('offset',0);
        $limit = $request->get('limit', 10);

        $query = AppointmentT::find()
            ->leftJoin('car_t','`car_t`.`id`=`appointment_t`.`car_id`')
            ->where('appointment_t.is_first=0 and car_t.location=4');

        if($username == '') {
            $user_ids = $this->getChildrenUserIDs();
            $query = $query->andWhere(['in','appointment_t.user_id',$user_ids]);
        }

        if($car_man != '') {
            $query = $query->andWhere('car_t.car_man like "'.$car_man.'"');
        }
        if($phone != '') {
            $query = $query->andWhere('car_t.car_man_phone="'.$phone.'"');
        }
        if($ptype > 0) {
            $query = $query->andWhere('appointment_t.ptype='.$ptype);
        }
        if($car_no != '') {
            $query = $query->andWhere('car_t.car_no like "'.$car_no.'"');
        }
        if($username != '') {
            $user_ids = array();
            $user_query = UserT::find()
                ->where('username="'.$username.'"')
                ->all();
            foreach($user_query as $user_info) {
                $user_ids[] = $user_info->id;
            }
            if(count($user_ids) > 0)
                $query = $query->andWhere(['in','appointment_t.user_id',$user_ids]);
            else
                $query = $query->andWhere('appointment_t.user_id=-1');
        }
        if($sort_key != '') {
            $query = $query->orderBy($sort_key.' '.$sort_value.',appointment_t.id '.$sort_value);
        }
        $sql = $query->createCommand()->rawSql;
//        echo $query->createCommand()->rawSql;
        $total = $query->count();
        $session->remove('appointment_all');
        $session->set('appointment_all',$sql);

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

        $data = [];
        $data['total'] = $total;
        $data['rows'] = [];
        foreach($items as $item) {
            $car_info = $item->car;
            $row = $item->toArray();
            $row['car_id'] = $car_info->id;
            $row['car_no'] = $car_info->car_no;
            $row['car_man'] = $car_info->car_man;
            $row['register_date'] = $car_info->register_date;
            $row['insurer1_date'] = $car_info->insurer1_date;
            $row['insurer2_date'] = $car_info->insurer2_date;
            $row['user_name'] = $item->user ? $item->user->getShowName():'';
            $data['rows'][] = $row;
        }
        return $data;
    }

    public function actionMyList()
    {
        $request = Yii::$app->request;
        $car_man = $request->get('car_man');
        $phone = $request->get('phone');
        $car_no = $request->get('car_no');
        $page = $request->get('page',1);
        if($page < 1) $page = 1;

        $query = OrderT::find()
            ->leftJoin('car_t','`car_t`.`id`=`order_t`.`car_id`')
            ->where('status_id>1 and car_t.location=4')
            ->orderBy('submit_date DESC, id DESC');
        $user_items = $this->my->getChildren();
        $user_ids[] = $this->my->id;
        if($user_items) {
            foreach($user_items as $user_item) {
                $user_ids[] = $user_item->id;
            }
        }
        $query = $query->andWhere(['in','order_t.user_id',$user_ids]);
        if($car_man != '') {
            $query = $query->andWhere('order_t.car_man="'.$car_man.'"');
        }
        if($phone != '') {
            $query = $query->andWhere('order_t.link_phone="'.$phone.'"');
        }
        if($car_no != '') {
            $query = $query->andWhere('order_t.car_no="'.$car_no.'"');
        }
//        echo $query->createCommand()->rawSql;
        $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::getPageInfo($pagination);

        return $this->render('my-list',[
            'items' => $items,
            'car_man' => $car_man,
            'phone' => $phone,
            'car_no' => $car_no,
            'page' => $page,
            'page_info' => $page_info
        ]);
    }

    public function actionMyListInfo()
    {
        $request = Yii::$app->request;
        $id = $request->get('id',0);
        $order_info = OrderT::findOne(['id'=>$id]);
        $car_info = $order_info->car;

        //快递
        $ems_items = EmsT::find()
            ->where(['car_id'=>$car_info->id,'order_id'=>$order_info->id])
            ->orderBy('id ASC')
            ->all();
        //礼品
        $gift_items = GiftT::find()
            ->where('type_id=1')
            ->all();
        //礼品
        $gift_group_items = GiftGroupT::find()->all();
        //获取礼品数据
        $sel_gifts = array();
        $tmp_items = OrderGiftT::find()
            ->where('order_id='.$order_info->id)
            ->all();
        foreach($tmp_items as $item) {
            $sel_gifts[$item->group_id] = $item;
        }

        $insurer_type_items = InsurerTypeT::find()
            ->all();

        return $this->render('my-list-info',[
            'car_info' => $car_info,
            'insurer_type_items' => $insurer_type_items,
            'order_info' => $order_info,
            'ems_items' => $ems_items,
            'gift_items' => $gift_items,
            'gift_group_items' => $gift_group_items,
            'sel_gifts' => $sel_gifts,
        ]);
    }
    /**
     ***********************************
     * 续保平移功能
     * @author liukangle
     ***********************************
     */
     public function actionAssignOther(){

         Yii::$app->response->format = Response::FORMAT_JSON;
         $request = Yii::$app->request;
         $result = array();
         $result['success'] = false;
         $result['msg'] = '操作失败';

         if($request->isPost) {
             $ids = $request->post('ids',array());
             $user_id = $request->post('user_id');
             if($user_id == 0) {
                 $result['msg'] = '请选择业务员';
                 return $result;
             }
             if(count($ids) == 0) {
                 $result['msg'] = '请先钩选车辆';
                 return $result;
             }

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

             $tran = CarT::getDb()->beginTransaction();
             try {
                 foreach($ids as $id) {
                     $car_info = CarT::findOne(['id'=>$id]);

                     $old_user_info = '';
                     if($car_info->location == 2) {
                         $b_info = CarBT::findOne(['id'=>$car_info->id]);
                         $old_user_info = $b_info->user;
                         $b_info->user_id = $user_id;
                         $b_info->save();
                         $user = $user_info;
                         if($user) {
                             $car_info->op_user1 = $user->getShowName();
                         }
                     }
                     if($car_info->location == 3) {
                         $c_info = CarCT::findOne(['id'=>$car_info->id]);
                         $old_user_info = $c_info->user;
                         $c_info->user_id = $user_id;
                         $c_info->save();
                         $user = $user_info;
                         if($user) {
                             $car_info->op_user2 = $user->getShowName();
                         }
                     }
                     if($car_info->location == 4) {
                         $d_info = CarDT::findOne(['id'=>$car_info->id]);
                         $old_user_info = $d_info->user;
                         $d_info->user_id = $user_id;
                         $d_info->save();
                         $user = $user_info;
                         if($user) {
                             $car_info->op_user3 = $user->getShowName();
                         }
                     }
                     //库保存
                     $car_info->save();
                     $this->addLog($car_info->id,'从'.$old_user_info->getShowName().' 平移车辆给 '.$user_info->getShowName(),1);

                     //添加保单
                     OrderT::deleteAll('car_id='.$car_info->id.' and status_id<2');
                     $order_row = new OrderT();
                     $order_row->car_id = $car_info->id;
                     $order_row->car_no = $car_info->car_no;
                     $order_row->engine_no = $car_info->engine_no;
                     $order_row->car_frame_no = $car_info->car_frame_no;
                     $order_row->car_man = $car_info->car_man;
                     $order_row->user_id = $user_id;
                     $order_row->status_id = 1;
                     $order_row->id_man = $car_info->car_man;
                     $order_row->link_man = $car_info->car_man;
                     $order_row->link_phone = $car_info->phone;
                     $order_row->save();

                     //添加预约
                     AppointmentT::deleteAll('car_id='.$car_info->id);
                     $row = new AppointmentT();
                     $row->car_id = $car_info->id;
                     $row->user_id = $user_id;
                     $row->pdate = date('Y-m-d');
                     $row->ptime = '09:00';
                     $row->remark = '首次分配';
                     $row->is_first = 1;
                     $row->save();

                     //添加历史预约
                     $h_row = new AppointmentHistoryT();
                     $h_row->car_id = $car_info->id;
                     $h_row->user_id = $user_id;
                     $h_row->pdate = date('Y-m-d');
                     $h_row->ptime = '09:00';
                     $h_row->remark = '首次分配';
                     $h_row->save();
                 }
                 $result['success'] = true;
                 $result['msg'] = '操作成功';

                 $tran->commit();
             } catch (\Exception $e) {
                 $tran->rollBack();
                 throw $e;
             }
         }
         return $result;
     }

    //回收数据
    public  function actionInvalidC(){
         Yii::$app->response->format = Response::FORMAT_JSON;
         $request = Yii::$app->request;

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

         if($request->isPost){
             $ids = $request->post('ids', array());

             if(count($ids) == 0){
                 $result['msg'] = '请先勾选车辆';
                 return $result;
             }

             $tran = CarDT::getDb()->beginTransaction();

             try{
                 foreach($ids as $id){
                     $car_info = CarT::findOne(['id'=>$id]);
                     $car_info->location = 3;
                     $car_info->op_user3 = '';
                     $car_info->save();

                     CarDT::deleteAll('id='.$id);
                     AppointmentT::deleteAll('car_id='.$id);

                     $c_info = new CarCT();
                     $c_info->id = $id;
                     $c_info->user_id = 0;
                     $c_info->save();
                     $this->addLog($car_info->id,'回收车辆数据到C库',1);
                 }
                 $tran->commit();
             }catch(\Exception $e){
                 $tran->rollBack();
                 return $result['msg'] = $e->getMessage();
             }

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

             return $result;
         }
    }
}
