<?php

namespace frontend\controllers;

use common\libs\MyLib;
use common\models\AppointmentHistoryT;
use common\models\AppointmentT;
use common\models\BankT;
use common\models\BrandT;
use common\models\CaiwuT;
use common\models\CaiwuT1;
use common\models\CarBT;
use common\models\CarCT;
use common\models\CarDT;
use common\models\CarGiftT;
use common\models\CarT;
use common\models\CarTypeT;
use common\models\CarUseT;
use common\models\CityT;
use common\models\CarLogT;
use common\models\DirectionT;
use common\models\DisplacementT;
use common\models\DistrictT;
use common\models\EmsT;
use common\models\ExpressT;
use common\models\GiftGroupT;
use common\models\GiftT;
use common\models\GiftTicketT;
use common\models\GiftTicketTUse;
use common\models\GiftType2T;
use common\models\GiftType3T;
use common\models\GroupT;
use common\models\InsurerCompany2T;
use common\models\InsurerCompanyT;
use common\models\InsurerTypeT;
use common\models\InvalidT;
use common\models\OrderCaiwuT;
use common\models\OrderCaiwuT1;
use common\models\OrderGiftT;
use common\models\OrderT;
use common\models\OrderWeizhi;
use common\models\OrderUserT;
use common\models\PayOrderUserT;
use common\models\PayT;
use common\models\PayeeT;
use common\models\Payment;
use common\models\PayTypeT;
use common\models\PriceT;
use common\models\RangeT;
use common\models\SendLogT;
use common\models\SeriesT;
use common\models\UserT;
use common\models\CaiwuStatusT;
use common\models\ZhongjiGiftT;
use Faker\Provider\Image;
use Yii;
use yii\data\Pagination;
use yii\helpers\FileHelper;
use yii\web\Response;
use yii\web\User;
use yii\helpers\ArrayHelper;
use common\models\NonAutoInsurance;

class InsurerController 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 actionIndex()
    {
        $request = Yii::$app->request;
        $car_id = $request->get('car_id');
        return $this->renderPartial('index',[
            'car_id' => $car_id
        ]);
    }

    public function actionEdit()
    {
        $request = Yii::$app->request;
        $car_id = $request->get('car_id',0);
        $id = $request->get('id',0);
        $info = OrderT::findOne(['id'=>$id]);
        $car_info = CarT::findOne(['id'=>$car_id]);
        if(empty($info)) {
            $info = OrderT::find()
                ->where('car_id='.$car_id.' and user_id='.$car_info->user_id.' and status_id=1')
                ->one();
            if(empty($info))
                $info = new OrderT();
        }

        $insurer_company_items = InsurerCompanyT::find()->all();
        $pay_type_items = PayTypeT::find()->all();
        $insurer_type_items = InsurerTypeT::find()->all();

        return $this->renderPartial('edit',[
            'info'=>$info,
            'car_info'=>$car_info,
            'pay_type_items'=>$pay_type_items,
            'insurer_type_items' => $insurer_type_items,
            'insurer_company_items' => $insurer_company_items
        ]);
    }

    public function actionInfo()
    {
        $request = Yii::$app->request;
        $id = $request->get('id',0);
        $order_info = OrderT::findOne(['id'=>$id]);
        $car_info = $order_info->car;
        
        $nonitems=null;
        if($order_info->non_id){
            $nonitems=NonAutoInsurance::findOne(['id'=>$order_info->non_id]);
        }
        //礼品
        $gift_free_group_items = GiftGroupT::find()
            ->where('is_free=1')
            ->all();
        $gift_group_items = GiftGroupT::find()
            ->where('is_free=0')
            ->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();
        //登陆用户ID
        $uid = $this->my->id;
        $order_caiwu = OrderCaiwuT::findOne(['order_id'=>$order_info->id]);
        $money_man='';
        $money_no='';
        $money_bank='';
        if($order_caiwu){
            $money_man=$order_caiwu->money_man;
            $money_no= $order_caiwu->money_no;
            $money_bank=$order_caiwu->money_bank;
        }
        return $this->render('info',[
            'order_info'=>$order_info,
            'car_info'=>$car_info,
            'money_man' => $money_man,
            'money_no' => $money_no,
            'money_bank' => $money_bank,
            'gift_free_group_items' => $gift_free_group_items,
            'gift_group_items' => $gift_group_items,
            'sel_gifts' => $sel_gifts,
            'uid' => $uid,
            'insurer_type_items' => $insurer_type_items,
            'nonitems' => $nonitems
        ]);
    }
    public function actionSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        if($request->isPost) {
            $order_id = $request->post('order_id',0);
            $car_id = $request->post('car_id',0);
            $car_no = $request->post('car_no');
            $engine_no = $request->post('engine_no');
            $car_frame_no = $request->post('car_frame_no');
            $car_man = $request->post('car_man');
            $id_man = $request->post('id_man');
            $id_number = $request->post('id_number');
            $link_man = $request->post('link_man');
            $link_phone = $request->post('link_phone');
            $send_date = $request->post('send_date');
            $company_id = $request->post('company_id');
            $pay_type_id = $request->post('pay_type_id');
            $insurer1_begin_date = $request->post('insurer1_begin_date');
            $insurer1_end_date = $request->post('insurer1_end_date');
            $insurer2_begin_date = $request->post('insurer2_begin_date');
            $insurer2_end_date = $request->post('insurer2_end_date');
            $gift_other = $request->post('gift_other');
            $remark = $request->post('remark');
            $total1 = $request->post('total1');
            $total2 = $request->post('total2');
            $total3 = $request->post('total3');
            $total_all = $request->post('total_all');
            $total_dis = $request->post('total_dis');
            $total_real = $request->post('total_real');
            $price_remark = $request->post('price_remark');
            $direction1_id = $request->post('direction1_id');
            $range1_id = $request->post('range1_id');
            $city1_id = $request->post('city1_id');
            $district1_id = $request->post('district1_id');
            $send_address1 = $request->post('send_address1');
            $direction2_id = $request->post('direction2_id');
            $range2_id = $request->post('range2_id');
            $city2_id = $request->post('city2_id');
            $district2_id = $request->post('district2_id');
            $send_address2 = $request->post('send_address2');
            $status_id = $request->post('status_id',1);


            $types = $request->post('types',array());
            $nopays = $request->post('nopays', array());

            if($car_no == '') {
                $result['msg'] = '请输入车牌号!';
                return $result;
            }
            if($engine_no == '') {
                $result['msg'] = '请输入发动机号!';
                return $result;
            }
            if($car_frame_no == '') {
                $result['msg'] = '请输入车架号!';
                return $result;
            }
            if($car_id == 0) {
                $result['msg'] = '车辆不存在!';
                return $result;
            }
            $car_info = CarT::findOne(['id'=>$car_id]);

            $tran = OrderT::getDb()->beginTransaction();
            try {
                $row = OrderT::findOne(['id'=>$order_id]);
                if(empty($row)) {
                    $row = new OrderT();
                    $row->car_id = $car_id;
                    $row->user_id = $this->my->id;
                    $row->status_id = 1;
                }

                $row->car_no = $car_no;
                $row->engine_no = $engine_no;
                $row->car_frame_no = $car_frame_no;
                $row->car_man = $car_man;
                $row->id_man = $id_man;
//                $row->id_number = $id_number;
                $row->link_man = $link_man;
                $row->link_phone = $link_phone;
                $row->send_date = $send_date;
                $row->company_id = $company_id;
                $row->pay_type_id = $pay_type_id;
                $row->insurer1_begin_date = $insurer1_begin_date;
                $row->insurer1_end_date = $insurer1_end_date;
                $row->insurer2_begin_date = $insurer2_begin_date;
                $row->insurer2_end_date = $insurer2_end_date;
                $row->gift_other = $gift_other;
                $row->remark = $remark;
                $row->total1 = $total1;
                $row->total2 = $total2;
                $row->total3 = $total3;
                $row->total_all = $total_all;
                $row->total_dis = $total_dis;
                $row->total_real = $total_real;
                $row->price_remark = $price_remark;

                $row->direction1_id = $direction1_id;
                $row->range1_id = $range1_id;
                $row->city1_id = $city1_id;
                $row->district1_id = $district1_id;
                $row->send_address1 = $send_address1;
                $row->direction2_id = $direction2_id;
                $row->range2_id = $range2_id;
                $row->city2_id = $city2_id;
                $row->district2_id = $district2_id;
                $row->send_address2 = $send_address2;

                $row->status_id = $status_id;
                if($status_id == 2) {
                    $row->submit_date = date('Y-m-d');
                    $tmp_row = AppointmentT::findOne(['car_id'=>$row->car_id]);
                    if(!empty($tmp_row)) {
                        $tmp_row->delete();
                    }
                    $this->addLog($car_id,'提交保单到核保管理',1);
                }
                $row->save();

                //更新车辆信息
                $car_info->car_no = $car_no;
                $car_info->engine_no = $engine_no;
                $car_info->car_frame_no = $car_frame_no;
                $car_info->car_man = $car_man;
                $car_info->save();

                foreach($types as $id=>$val) {
                    $price_row = PriceT::find()
                        ->where('order_id='.$row->id.' and type_id='.$id)
                        ->one();
                    if(empty($price_row)) {
                        $price_row = new PriceT();
                        $price_row->order_id = $row->id;
                        $price_row->type_id = $id;
                    }
                    $price_row->val = $val;
                    if(!empty($nopays[$id]))
                        $price_row->is_nopay = 1;
                    else
                        $price_row->is_nopay = 0;
                    $price_row->save();
                }

                $tran->commit();

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

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

    public function actionMyList() {
        return $this->render('my-list');
    }

    public function actionMyListJson()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $car_man = $request->get('car_man');
        $phone = $request->get('phone');
        $car_no = $request->get('car_no');
        $id_man = $request->get('id_man');
        $offset = $request->get('offset',0);
        $limit = $request->get('limit', 10);

        $query = OrderT::find()
            ->where('status_id>1')
            ->andWhere('return_status_id=0')
            ->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->andWhere(['in','user_id',$user_ids]);
        if($car_man != '') {
            $query->andWhere('car_man="'.$car_man.'"');
        }
        if($id_man != '') {
            $query->andWhere('id_man="'.$id_man.'"');
        }
        if($phone != '') {
            $query->andWhere('car_man_phone=:phone or id_man_phone=:phone or link_man_phone=:phone',[':phone'=>$phone]);
        }
        if($car_no != '') {
            $query->andWhere('car_no="'.$car_no.'"');
        }
//        echo $query->createCommand()->rawSql;
//        exit;
        $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['factory_model'] = $item->car->factory_model;
            $row['user_name'] = $item->user?$item->user->getShowName():'';
            $row['status_name'] = $item->status->name;
            if($item->status_id == 2) {
                $row['lock_name'] = $item->op1 ? $item->op1->getShowName():'';
            } else if($item->status_id < 10) {
                $row['lock_name'] = $item->op2 ? $item->op2->getShowName():'';
            } else {
                $row['lock_name'] = '';
            }
            $row['gift_status_name'] = $item->gift_status == 1 ? '已确认':'';
            $data['rows'][] = $row;
        }
        return $data;
    }

    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();
        $ems_items1=(object)array();
        if(!$ems_items){
            $ems_items1 = ExpressT::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();

        //登陆用户ID
        $uid = $this->my->role_id;
        $my_id = $this->my->id;
        //转账信息
        $caiwu_status = CaiwuStatusT::find()->asArray()->all();
        $caiwu_status= ArrayHelper::map($caiwu_status,'id', 'name');

        return $this->render('my-list-info',[
            'car_info' => $car_info,
            'caiwu_status' => $caiwu_status,
            'insurer_type_items' => $insurer_type_items,
            'order_info' => $order_info,
            'ems_items' => $ems_items,
            'ems_items1' => $ems_items1,
            'uid' => $uid,
            'my_id' => $my_id,
            'gift_items' => $gift_items,
            'gift_group_items' => $gift_group_items,
            'sel_gifts' => $sel_gifts,
        ]);
    }
    /**
     *补发礼品以后 Ajax 请求渲染页面
     */
    public function actionAjaxGiftInfo(){
        Yii::$app->response->format = Response::FORMAT_JSON;

        $request = Yii::$app->request;
        $id = $request->get('id',0);
        $order_info = OrderT::findOne(['id'=>$id]);

        //礼品
        $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;
        }

        $html =  $this->renderPartial('ajax-gift-info',[
            'order_info' => $order_info,
            'gift_group_items' => $gift_group_items,
            'sel_gifts' => $sel_gifts,
        ]);

        $result = array();
        $result['success'] = true;
        $result['html'] = $html;
        return $result;
    }
    /**
     * 业务员漏发礼品 并且 财务完结以后补发 补发
     */
    public function actionGiftEditSave(){
        Yii::$app->response->format = Response::FORMAT_JSON;

        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        if($request->isPost){
            $id = $request->post('order_id',0);
            $order_info = OrderT::findOne($id);
            $gifts = $request->post('gifts',array());

            if(is_array($gifts) && count($gifts) > 0 ) {

                $tableName = OrderGiftT::tableName();//批量插入表名
                $field =  ['order_id','group_id','gift_id','send_id','send_time','price','status'];//批量插入字段
                $insertData = [];//批量插入数据

                foreach($gifts as $tmp_str) {
                    $tmp = explode('_',$tmp_str);
                    $group_id = isset($tmp[0])?$tmp[0]:0;
                    $gift_id = isset($tmp[1])?$tmp[1]:0;
                    if($group_id == 0 && $gift_id == 0) {
                        $result['msg'] = "请先选择礼品";
                        continue;
                    }
                    $group_info = GiftGroupT::findOne(['id'=>$group_id]);
                    if(!isset($group_info)) {
                        continue;
                    }
                    $gift_info = GiftType3T::findOne(['id'=>$gift_id]);
                    if(!isset($gift_info)) {
                        continue;
                    }
                    $tmp_count = OrderGiftT::find()->where('order_id='.$order_info->id.' and group_id='.$group_id.' and status=1')->count();
                    if($tmp_count > 0) {
                        continue;
                    }

                    $insertData[] = [$order_info->id,$group_id,$gift_id,0,0,0,0];
                }

                $totalNum = Yii::$app->db->createCommand()->batchInsert($tableName,$field,$insertData)->execute();
                if($totalNum > 0 ){
                    $result['success'] = true;
                    $result['msg'] = '保存成功';
                }
            }else{
                $result['msg'] = '没有可选礼品';
            }
        }
        return $result;
    }

    /**
     * 核保管理-列表
     * @return string
     */
    public function actionOfficeMng() {
        $insurer_company_items = InsurerCompanyT::find()->all();

        return $this->render('office-mng',[
            'insurer_company_items' => $insurer_company_items
        ]);
    }
    public function actionOfficeMngJson()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $type = $request->get('type');
        $car_man = $request->get('car_man');
        $phone = $request->get('phone');
        $car_no = $request->get('car_no');
        $company2_id = $request->get('company2_id');
        $offset = $request->get('offset', 0);
        $limit = $request->get('limit', 10);

        $query = OrderT::find()
            ->where('status_id=2')
            ->orderBy('submit_date DESC, id DESC');
        if($type == 1) {
            $query->andWhere('lock_id=0');
        }
        if($type == 2) {
            $query->andWhere('lock_id>0');
        }
        if($car_man != '') {
            $query->andWhere('car_man="'.$car_man.'"');
        }
        if($phone != '') {
            $query->andWhere('car_man_phone like :phone1 or id_man_phone like :phone2 or link_man_phone like :phone3',[':phone1'=>$phone,':phone2'=>$phone,':phone3'=>$phone]);
        }
        if($car_no != '') {
            $query->andWhere('car_no="'.$car_no.'"');
        }
        if($company2_id > 0) {
            $query->andWhere('company2_id=:company2_id',[':company2_id'=>$company2_id]);
        }
//        echo $query->createCommand()->rawSql;
        $query = $query->orderBy('updated_at asc');
        $total = $query->count();

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

        $data = [];
        $data['total'] = $total;
        $data['rows'] = [];
        foreach($items as $item) {
            $row = $item->toArray();
            $row['company_name'] = $item->company?$item->company->name:'';
            $row['factory_model'] = $item->car?$item->car->factory_model:'';
            $row['user_name'] = $item->user?$item->user->getShowName():'';
            $row['status_name'] = $item->status->name;
            $row['pay_type'] = ($item->shoufei_id?MyLib::zhifufs($item->shoufei_id).'-':'').'&nbsp;'.($item->payType?$item->payType->name:'');
            $row['lock_name'] = $item->op1?$item->op1->getShowName():'';
            $data['rows'][] = $row;
        }

        return $data;
    }

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

        if($order_info->op1_id == 0) {
            $tran = OrderT::getDb()->beginTransaction();
            try {
                $order_info->op1_id = $this->my->id;
                $order_info->save();

                $tran->commit();

            } catch (\Exception $e) {
                $tran->rollBack();
                echo $e->getMessage();
                exit;
            }
        } else {
            if($order_info->op1_id != $this->my->id) {
                echo '该记录已经被别人锁定,【<a href="javascript:history.go(-1);">返回</a>】';
                exit;
            }
        }

        $insurer_type_items = InsurerTypeT::find()
            ->all();
        $insurer_company2_items = InsurerCompany2T::find()
            ->all();
        $payee_items=PayeeT::find()->all();
        $payment_items=Payment::find()->all();

        return $this->render('office-mng-edit',[
            'car_info' => $car_info,
            'insurer_type_items' => $insurer_type_items,
            'order_info' => $order_info,
            'insurer_company2_items' => $insurer_company2_items,
            'payee_items' => $payee_items,
            'payment_items' => $payment_items,
        ]);
    }
    /**
     * 放弃操作
     * @return array
     * @throws \Exception
     */
    public function actionOrderCancelSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $order_id = $request->post('order_id',0);
        $result = array();
        $result['success'] = false;
        $result['msg'] = '无法放弃';
        $order_info = OrderT::findOne(['id'=>$order_id]);
        if($order_info) {
            $tran = OrderT::getDb()->beginTransaction();
            try {
                if($order_info->status_id == 2) {
                    $order_info->op1_id = 0;
                } else {
                    $order_info->op2_id = 0;
                }
                if(!$order_info->save()) {
                    throw new \Exception(print_r($order_info->getErrors(), true));
                }

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

                $tran->commit();
            } catch (\Exception $e) {
                $tran->rollBack();
                $result['msg'] = $e->getMessage();
            }
        }
        return $result;
    }

    /**
     * 核保管理-保存
     * @return array
     * @throws \Exception
     */
    public function actionOfficeMngSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        if($request->isPost) {
            $car_id = $request->post('car_id',0);
            $order_id = $request->post('order_id',0);
            $status_id = $request->post('status_id',2);
            $total1_rate = $request->post('total1_rate','0.00');
            $total2_rate = $request->post('total2_rate','0.00');
            $pay_no = $request->post('pay_no',0);
            $company2_id = $request->post('company_id',0);

            if($total1_rate == '') {
                $result['msg'] = '请输入商业跟单手续费!';
                return $result;
            }
            if($total2_rate == '') {
                $result['msg'] = '请输入交强跟单手续费!';
                return $result;
            }
            if($company2_id == 0) {
                $result['msg'] = '请选择保险公司!';
                return $result;
            }
            if($pay_no == '') {
                $result['msg'] = '请输入缴费单号';
                return $result;
            }

            $tran = OrderT::getDb()->beginTransaction();
            try {
                $order_info = OrderT::findOne(['id'=>$order_id]);
                if(empty($order_info)) {
                    $result['msg'] = '保单错误!';
                    return $result;
                }

                $old_status_id = $order_info->status_id;
                $order_info->total1_rate = $total1_rate;
                $order_info->total2_rate = $total2_rate;
                $order_info->company2_id = $company2_id;
                $order_info->pay_no = $pay_no;

                $order_info->status_id = $status_id;

                $result['msg'] = '保存成功';
                if($status_id > $old_status_id) {
                    $result['msg'] = '提交成功';
                    $this->addLog($car_id,'核保结束,进入正本生成',1);
                }
                if(!$order_info->save()) {
                    throw new \Exception(print_r($order_info->getErrors(), true));
                }

                $result['success'] = true;
                $tran->commit();
            } catch(\Exception $e) {
                $tran->rollBack();
                $result['msg'] = $e->getMessage();
            }
        }
        return $result;
    }
    /**
     * 正本管理-列表
     * @return string
     */
    public function actionOriginalMng() {
        $pay_type_items = PayTypeT::find()->all();

        return $this->render('original-mng',[
            'pay_type_items' => $pay_type_items
        ]);
    }
    public function actionOriginalMngJson()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $id_man = $request->get('id_man');
        $phone = $request->get('phone');
        $car_no = $request->get('car_no');
        $pay_type_id = $request->get('pay_type_id');
        $offset = $request->get('offset',0);
        $limit = $request->get('limit',10);

        $query = OrderT::find()
            ->where('status_id=5')
            ->orderBy('submit_date DESC, id DESC');
        if($id_man != '') {
            $query->andWhere('id_man="'.$id_man.'"');
        }
        if($phone != '') {
            $query->andWhere('car_man_phone like :phone1 or id_man_phone like :phone2 or link_man_phone like :phone3',[':phone1'=>$phone,':phone2'=>$phone,':phone3'=>$phone]);
        }
        if($car_no != '') {
            $query->andWhere('car_no=:car_no',[':car_no'=>$car_no]);
        }
        if($pay_type_id > 0) {
            $query->andWhere('pay_type_id=:pay_type_id',[':pay_type_id'=>$pay_type_id]);
        }
        $query->orderBy('updated_at 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['company_name'] = $item->company2->name;
            $row['user_name'] = $item->user?$item->user->getShowName():'';
            $row['status_name'] = $item->status->name;
            $row['pay_type'] = ($item->shoufei_id?MyLib::zhifufs($item->shoufei_id).'-':'').'&nbsp;'.($item->payType?$item->payType->name:'');
            $row['lock_name'] = $item->op2?$item->op2->getShowName():'';
            $data['rows'][] = $row;
        }

        return $data;

    }
    /**
     * 正本管理-详情
     * @return string
     */

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

        if($order_info->op2_id == 0) {
            $tran = OrderT::getDb()->beginTransaction();
            try {
                $order_info->op2_id = $this->my->id;
                $order_info->save();

                $tran->commit();
            } catch (\Exception $e) {
                $tran->rollBack();
                echo $e->getMessage();
                exit;
            }
        } else {
            if($order_info->op2_id != $this->my->id) {
                echo '该记录已经被别人锁定,【<a href="/insurer/original-mng?'.$back_params.'">返回</a>】';
                exit;
            }
        }

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

        return $this->render('original-mng-edit',[
            'car_info' => $car_info,
            'insurer_type_items' => $insurer_type_items,
            'order_info' => $order_info,
            'insurer_company_items' => $insurer_company_items
        ]);
    }
    /**
     * 正本管理-保存
     * @return array
     * @throws \Exception
     */
    public function actionOriginalMngSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        if($request->isPost) {
            $order_id = $request->post('order_id',0);
            $status_id = $request->post('status_id',0);
            $insurer1_no = $request->post('insurer1_no');
            $insurer2_no = $request->post('insurer2_no');
            $payer = $request->post('payer');
            $payee_id = $request->post('payee_id');
            $payment_id = $request->post('payment_id');
            //上传商业和交强文件
            $shangye_src= $request->post('shangye_src');
            $fapiao_src= $request->post('fapiao_src');
            $jiaoqiang_src= $request->post('jiaoqiang_src');
            $jq_fapiao_src= $request->post('jq_fapiao_src');

            if($insurer1_no == '' && $insurer2_no == '') {
                $result['msg'] = '请输入商业或交强保单号!';
                return $result;
            }
            //去除首位空格和字符串中间的空格
            $insurer1_no= trim($insurer1_no);
            $insurer1_no=str_replace(" ","",$insurer1_no);
            $insurer2_no= trim($insurer2_no);
            $insurer2_no=str_replace(" ","",$insurer2_no);

            if($insurer1_no == $insurer2_no) {
                $result['msg'] = '商业保单号和交强保单号不能相同!';
                return $result;
            }
            $tmp_count = OrderT::find()
                ->where('insurer1_no=:insurer1_no or insurer2_no=:insurer1_no', [':insurer1_no'=>$insurer1_no])
                ->andWhere('id<>'.$order_id)
                ->count();
            if($tmp_count > 0) {
                $result['msg'] = '商业保单号已经存在!';
                return $result;
            }
            $tmp_count = OrderT::find()
                ->where('insurer1_no=:insurer2_no or insurer2_no=:insurer2_no', [':insurer2_no'=>$insurer2_no])
                ->andWhere('id<>'.$order_id)
                ->count();
            if($tmp_count > 0) {
                $result['msg'] = '交强保单号已经存在!';
                return $result;
            }

            $tran = OrderT::getDb()->beginTransaction();
            try {
                $order_info = OrderT::findOne(['id'=>$order_id]);
                if(empty($order_info)) {
                    $result['msg'] = '保单错误!';
                    return $result;
                }

                $old_status_id = $order_info->status_id;
                $order_info->insurer1_no = $insurer1_no;
                $order_info->insurer2_no = $insurer2_no;
                //上传文件
                $order_info->shangye_src = $shangye_src;
                $order_info->jiaoqiang_src = $jiaoqiang_src;
                $order_info->fapiao_src = $fapiao_src;
                $order_info->jq_fapiao_src = $jq_fapiao_src;
                $order_info->upload_status = 2;


                $order_info->payee_id = $payee_id;
                $order_info->payment_id = $payment_id;
                $order_info->status_id = $status_id;
                $order_info->payer = $payer;
                if($status_id == 10) {
                    $order_info->print_date = date('Y-m-d');
                }
                if(!$order_info->save()) {
                    throw new \Exception(print_r($order_info->getErrors(), true));
                }

                if($status_id == 10) {
                    //财务处理
                    CaiwuT::deleteAll(['order_id'=>$order_info->id]);
                    //商业
                    if($order_info->insurer1_no != '' && $order_info->total1_clear > 0) {
                        $row = null;
                        CaiwuT::deleteAll('insurer_no="'.$order_info->insurer1_no.'"');
                        $row = new CaiwuT();
                        $row->insurer_no = $order_info->insurer1_no;
                        $row->car_no = $order_info->car_no;
                        $row->factory_model = $order_info->car->factory_model;
                        $row->id_man = $order_info->id_man;
                        $row->company = $order_info->company2->name;
                        $row->total = sprintf("%.2f",$order_info->total1);
                        $row->total_clear = sprintf("%.2f",$order_info->total1_clear);
                        $row->total_clear_real = sprintf("%.2f",($order_info->total1_clear * $order_info->total1_rate/100));
                        $row->total_tax = sprintf("%.2f",$order_info->total1 - $order_info->total1_clear);
                        $row->total_tax_real = sprintf("%.2f",(($order_info->total1-$order_info->total1_clear) * $order_info->total1_rate/100));
                        $row->total_rate = $order_info->total1_rate;
                        $row->total_dis = $row->total_clear_real;
                        $row->user_id = $order_info->user_id;
                        $row->status = 0;
                        $row->insurer_type = 1;
                        $row->order_id = $order_info->id;
                        if(!$row->save()) {
                            throw new \Exception(print_r($row->getErrors(), true));
                        }
                    }

                    //交强
                    if($order_info->insurer2_no != '' && $order_info->total2_clear > 0) {
                        $row = null;
                        CaiwuT::deleteAll('insurer_no="'.$order_info->insurer2_no.'"');
                        $row = new CaiwuT();
                        $row->insurer_no = $order_info->insurer2_no;
                        $row->car_no = $order_info->car_no;
                        $row->factory_model = $order_info->car->factory_model;
                        $row->company = $order_info->company2->name;
                        $row->id_man = $order_info->id_man;
                        $row->total = sprintf("%.2f",$order_info->total2);
                        $row->total_clear = sprintf("%.2f",$order_info->total2_clear);
                        $row->total_tax = sprintf("%.2f",($order_info->total2 - $order_info->total2_clear));
                        $row->total_clear_real = sprintf("%.2f",($order_info->total2_clear * $order_info->total2_rate/100));
                        $row->total_tax_real = sprintf("%.2f",(($order_info->total2-$order_info->total2_clear) * $order_info->total2_rate/100));
                        $row->total_rate = $order_info->total2_rate;
                        $row->total_dis = $row->total_clear_real;
                        $row->user_id = $order_info->user_id;
                        $row->status = 0;
                        $row->insurer_type = 2;
                        $row->order_id = $order_info->id;
                        if(!$row->save()) {
                            throw new \Exception(print_r($row->getErrors(), true));
                        }
                    }

                    //生成财务分支 修改日期2018/5/18
                    $order_caiwu = OrderCaiwuT::findOne(['order_id'=>$order_info->id]);
                    if(!$order_caiwu) {
                        $order_caiwu = new OrderCaiwuT();
                        $order_caiwu->order_id = $order_info->id;
                        $order_caiwu->status_id = 12;
                        $order_caiwu->pay_date = substr($order_info->print_date,0,7);
                        if(!$order_caiwu->save()) {
                            throw new \Exception(print_r($order_caiwu->getErrors(), true));
                        }
                    }else{
                        $order_caiwu->status_id = 12;
                        $order_caiwu->pay_date = substr($order_info->print_date,0,7);
                        if(!$order_caiwu->save()) {
                            throw new \Exception(print_r($order_caiwu->getErrors(), true));
                        }
                    }
                    //B->C 或 D->C
                    $car_info = CarT::findOne(['id'=>$order_info->car_id]);

                    if($car_info->is_xubao == 0){
                        $car_info->op1_id = $order_info->user_id;

                    }elseif($car_info->is_xubao==1){//如果是续保
                        //查找上一年的保单
                        $car_info->op2_id = $order_info->user_id;
                    }



                    $car_info->location = 3;
                    $car_info->is_xubao = 1;
                    $car_info->print_date = date('Y-m-d');


                    $car_info->user_id = 0;
                    //更新保险日期
                    $car_info->insurer1_date = $order_info->insurer1_end_date;
                    $car_info->insurer2_date = $order_info->insurer2_end_date;
                    $car_info->company = $order_info->company->name;
                    //续保次数
                    if(!$car_info->save()) {
                        throw new \Exception(print_r($car_info->getErrors(), true));
                    }

                    CarBT::deleteAll(['id'=>$car_info->id]);
                    CarDT::deleteAll(['id'=>$car_info->id]);

                    $c_info = CarCT::findOne(['id'=>$car_info->id]);
                    if(!$c_info) {
                        $c_info = new CarCT();
                        $c_info->id = $car_info->id;
                        $c_info->user_id = 0;
                        if(!$c_info->save()) {
                            throw new \Exception(print_r($c_info->getErrors(), true));
                        }
                    }
                    $this->addLog($order_info->car_id,'正本生成结束',1);
                }
                $result['success'] = true;
                $result['msg'] = '保存成功';
                $tran->commit();

            } catch(\Exception $e) {
                $tran->rollBack();
                $result['msg'] = $e->getMessage();
            }
        }
        return $result;
    }

    /**
     * 出纳办结-列表
     * @return string
     */
    public function actionFinanceMng() {
        return $this->render('finance-mng');
    }
    public function actionFinanceMngJson()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        //新增正本日期
        $begin_date = $request->get('begin_date');
        $end_date = $request->get('end_date');
        //新增完成状态
        $status = $request->get('status');

        $car_man = $request->get('car_man');
        $phone = $request->get('phone');
        $car_no = $request->get('car_no');
        $send_date = $request->get('send_date');
        $insurer_no = $request->get('insurer_no');
        $caiwu_status_id = $request->get('caiwu_status_id');
        $offset = $request->get('offset',0);
        $limit = $request->get('limit', 10);

        //级别
        $group_id = $request->get('group_id');
        $group_items = GroupT::getTree((int)$this->my->group_id);
        if($this->my->id == 1 || $this->my->username=='6002')
            $group_items = GroupT::getTree();
        $group_ids[] = $group_id;

        if($group_id > 0) {
            $items = GroupT::getTree($group_id);
            foreach($items as $group_info) {
                $group_ids[] = $group_info->id;
            }
        }

        $query = OrderT::find()
            ->leftJoin('order_caiwu_t','order_caiwu_t.order_id=order_t.id')
            ->where('order_caiwu_t.status_id>0');
        if($car_man != '') {
            $query->andWhere('id_man="'.$car_man.'"');
        }
        if($phone != '') {
            $query->andWhere('link_phone="'.$phone.'"');
        }
        if($car_no != '') {
            $query->andWhere('car_no="'.$car_no.'"');
        }
        if($send_date != '') {
            $query->andWhere('send_date="'.$send_date.'"');
        }
        if($insurer_no != '') {
            $query->andWhere('(insurer1_no="'.$insurer_no.'" or insurer2_no="'.$insurer_no.'")');
        }
        //添加正本日期
        if($begin_date != '') {
            $query->andWhere('print_date>="'.$begin_date.'"');
        }
        if($end_date != '') {
            $query->andWhere('print_date<="'.$end_date.'"');
        }
        //添加完成状态
        if($status == 2) {
            $query->andWhere('order_caiwu_t.status_id=10 or order_caiwu_t.status_id=13');
        } else if($status == 1) {
            $query->andWhere('order_caiwu_t.status_id=12');
        } else {
            $query->andWhere('order_caiwu_t.status_id=13 or order_caiwu_t.status_id=10 or order_caiwu_t.status_id=12');
        }
        //转账状态
        if($caiwu_status_id > 0){
            switch($caiwu_status_id){
                case 1:
                    $query->andWhere('order_caiwu_t.caiwu_status_id=1');
                    break;
                case 2:
                    $query->andWhere('order_caiwu_t.caiwu_status_id=2');
                    break;
                case 3:
                    $query->andWhere('order_caiwu_t.caiwu_status_id=3');
                    break;
                case 4:
                    $query->andWhere('order_caiwu_t.caiwu_status_id=4');
                    break;
                default:
                    break;
            }
        }
        //      现在的搜索条件
        $userSql = '';

        $user_items = $this->my->getChildren($userSql);
        $user_items[] = $this->my;

        $row = array();
        foreach($user_items as $user_info) {
            if ($group_id > 0) {
                if (!in_array($user_info->group_id, $group_ids)) {
                    continue;
                }
            }
            $row[] = $user_info->id;
        }

        //加上级别筛选
        if($group_id > 0){
            $query = $query->andWhere(['in','order_t.user_id',$row]);
        }
        $total = $query->count();
        $query1 = clone $query;
        $sums = $query1->select([
            'sum_total1' => 'sum(order_t.total1)',
            'sum_total1_clear' => 'sum(order_t.total1_clear)',
            'sum_yuangong_money' => 'sum(order_t.yuangong_money)',
            'sum_non_total1_dis' => 'sum(order_t.non_total1_dis)',
            'sum_total1_dis' => 'sum(order_t.total1_dis)',
        ])->asArray()->one();
        $query = $query->orderBy('order_t.print_date asc')->offset($offset)->limit($limit);
        $items = $query->all();

        $data = [];
        $data['total'] = $total;
        $data['rows'] = [];
        foreach($items as $item) {
            $row = $item->toArray();
            $row['company_name'] = $item->company2 ? $item->company2->name : '';
            $row['path'] = ($item->user && $item->user->group) ? $item->user->group->getPath() : '';
            $row['user_name'] = $item->user ? $item->user->getShowName() : '';
            $row['total_user_real'] = number_format($item->total1_dis + $item->yuangong_money, 2);
            $row['transfer_date'] = $item->caiwu->transfer_date;
            $row['caiwu_status_name'] = $item->caiwu && $item->caiwu->caiwuStatus ? $item->caiwu->caiwuStatus->name : '';
            $row['shoufei_name'] = MyLib::zhifufs($item->shoufei_id);
            $row['status_name'] = $item->caiwu && $item->caiwu->status ? $item->caiwu->status->name : '';
            $row['lock_man'] = $item->caiwu->lock?$item->caiwu->lock->getShowName():'';
            $data['rows'][] = $row;
        }

        $data['rows'][] = array(
            ['商业保总额', number_format($sums['sum_total1'],2)],
            ['商业净保总额', number_format($sums['sum_total1_clear'],2)],
            ['业务自付', number_format($sums['sum_yuangong_money'],2)],
            ['公司代付非车险', number_format($sums['sum_non_total1_dis'],2)],
            ['公司返金额', number_format($sums['sum_total1_dis'],2)],
            ['实返现金额', number_format($sums['sum_yuangong_money'] + $sums['sum_total1_dis'],2)]
        );
        return $data;
    }

    /**
     * 非车险出纳办结-列表
     * @return string
     */
    public function actionNonFinanceMng()
    {
        $request = Yii::$app->request;
        //新增正本日期
        $begin_date = $request->get('begin_date');
        $end_date = $request->get('end_date');
        //新增完成状态
        $status = $request->get('status');

        $id_man = $request->get('id_man');


        $send_date = $request->get('send_date');
        $insurer_no = $request->get('insurer_no');

        $page = $request->get('page',1);
        if($page < 1) $page = 1;

        $query = OrderT::find()
            ->leftJoin('order_caiwu_t1','order_caiwu_t1.order_id=order_t.id')
            ->where('order_caiwu_t1.status_id>0')
            ->andWhere('insurance_status = 2')
            ->orderBy('order_t.print_date asc');
        if($id_man != '') {
            $query = $query->andWhere('id_man="'.$id_man.'"');
        }

        if($send_date != '') {
            $query = $query->andWhere('send_date="'.$send_date.'"');
        }
        if($insurer_no != '') {
            $query = $query->andWhere('(insurer1_no="'.$insurer_no.'" or insurer2_no="'.$insurer_no.'")');
        }
        //添加正本日期
        if($begin_date != '') {
            $query = $query->andWhere('print_date>="'.$begin_date.'"');
        }
        if($end_date != '') {
            $query = $query->andWhere('print_date<="'.$end_date.'"');
        }
        //添加完成状态
        if($status == 2) {
            $query = $query->andWhere('order_caiwu_t1.status_id=10 or order_caiwu_t1.status_id=13');
        } else if($status == 1) {
            $query = $query->andWhere('order_caiwu_t1.status_id=12');
        } else {
            $query = $query->andWhere('order_caiwu_t1.status_id=13 or order_caiwu_t1.status_id=10 or order_caiwu_t1.status_id=12');
        }

        $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('non-finance-mng',[
            'items' => $items,
            'id_man' => $id_man,

            'send_date' => $send_date,
            'page' => $page,
            'page_info' => $page_info,
            'insurer_no' => $insurer_no,
            'status' => $status,

            'begin_date' => $begin_date,
            'end_date' => $end_date
        ]);
    }

    /**
     * 非车险财务办结-列表
     * @return string
     */
    public function actionNonFinancialSettlementList()
    {
        $request = Yii::$app->request;
        //新增正本日期
        $begin_date = $request->get('begin_date');
        $end_date = $request->get('end_date');
        //新增完成状态
        $status = $request->get('status');

        $id_man = $request->get('id_man');

        $send_date = $request->get('send_date');
        $insurer_no = $request->get('insurer_no');

        $page = $request->get('page',1);
        if($page < 1) $page = 1;


        $query = OrderT::find()
            ->leftJoin('order_caiwu_t1','order_caiwu_t1.order_id=order_t.id')
            ->where('order_t.status_id>5')
            ->andWhere('insurance_status = 2');
        if($id_man != '') {
            $query = $query->andWhere('id_man="'.$id_man.'"');
        }

        if($send_date != '') {
            $query = $query->andWhere('send_date="'.$send_date.'"');
        }
        if($insurer_no != '') {
            $query = $query->andWhere('(insurer1_no="'.$insurer_no.'" or insurer2_no="'.$insurer_no.'")');
        }
        //添加正本日期
        if($begin_date != '') {
            $query = $query->andWhere('print_date>="'.$begin_date.'"');
        }
        if($end_date != '') {
            $query = $query->andWhere('print_date<="'.$end_date.'"');
        }
        //添加完成状态

        if($status == 2) {
            $query = $query->andWhere('order_caiwu_t1.status_id=10');
        } else if($status == 1) {
            $query = $query->andWhere('order_caiwu_t1.status_id=13');
        } else {
            $query = $query->andWhere('order_caiwu_t1.status_id=13 or order_caiwu_t1.status_id=10 ');
        }

        $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('non-financial-settlement-list',[
            'items' => $items,
            'id_man' => $id_man,
            'send_date' => $send_date,
            'page' => $page,
            'page_info' => $page_info,
            'insurer_no' => $insurer_no,
            'status' => $status,
            'begin_date' => $begin_date,
            'end_date' => $end_date
        ]);
    }

    /**
     * 出纳办结-详情
     * @return string
     */
    public function actionFinanceMngEdit()
    {
        $request = Yii::$app->request;
        $id = $request->get('id',0);
        $back_params = $request->get('back_params');
        $order_info = OrderT::findOne(['id'=>$id]);
        $car_info = $order_info->car;
        $caiwu_info = $order_info->caiwu;
        if($caiwu_info->lock_id == 0) {
            $tran = OrderCaiwuT::getDb()->beginTransaction();
            try {
                $caiwu_info->lock_id = $this->my->id;
                $caiwu_info->save();

                $order_user_info = new OrderUserT();
                $order_user_info->user_id = $this->my->id;
                $order_user_info->order_id = $caiwu_info->order_id;
                $order_user_info->type_id = $caiwu_info->status_id;
                $order_user_info->status = 0;
                $order_user_info->save();

                $tran->commit();
            } catch (\Exception $e) {
                $tran->rollBack();
                throw $e;
            }
        } else {
            if($caiwu_info->lock_id != $this->my->id && $this->my->username != 'admin') {
                echo '该记录已经被别人锁定,【<a href="/insurer/finance-mng?'.$back_params.'">返回</a>】';
                exit;
            }
        }
        //快递
        $ems_items = EmsT::find()
            ->where(['car_id'=>$car_info->id,'order_id'=>$order_info->id])
            ->orderBy('id ASC')
            ->all();
        //礼品
        $gift_group_items = [];
        $sel_gifts = [];

        $gift_group_items = GiftGroupT::find()
            ->where('is_free=0')
            ->all();
        $gift_free_group_items = GiftGroupT::find()
            ->where('is_free=1')
            ->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();
        $new_array = [];

        foreach($insurer_type_items as $k => $v){

            $order_id = $order_info->id;
            if(!$order_id)
                $order_id = 0;
            $tmp_row = PriceT::find()
                ->where('order_id='.$order_id.' and type_id='.$v->id)
                ->one();
            if($tmp_row) {
                if ($tmp_row->val != '' && $tmp_row->val != '0' && $tmp_row->val != '否' && $tmp_row->val != '无') {
                    $new_array[$k]['zl'] = $v->name . '（' . $v->code . '）';
                    $new_array[$k]['neir'] = $tmp_row->val;
                    $new_array[$k]['bjmp'] = $tmp_row->is_nopay == 1 ? '是' : '';
                }
            }
        }

        //银行列表
        $banks = BankT::find()->all();

        //转账状态列表
        $caiwu_status = CaiwuStatusT::find()->all();

        return $this->render('finance-mng-edit',[
            'car_info' => $car_info,
            'new_array' => $new_array,
            'insurer_type_items' => $insurer_type_items,
            'order_info' => $order_info,
            'caiwu_info' => $caiwu_info,
            'ems_items' => $ems_items,
            'gift_group_items' => $gift_group_items,
            'gift_free_group_items' => $gift_free_group_items,
            'sel_gifts' => $sel_gifts,
            'back_params' => $back_params,
            'banks' => $banks,
            'caiwu_status' => $caiwu_status
        ]);
    }

    /**
     * 非车险出纳办结-详情
     * @return string
     */
    public function actionNonFinanceMngEdit()
    {
        $request = Yii::$app->request;
        $id = $request->get('id',0);
        $oid = $request->get('oid',0);
        $back_params = $request->get('back_params');
//        dd($id);
        $order_info = OrderT::findOne(['id'=>$oid]);

        $caiwu_info = $order_info->caiwu1;
        $nonInfo = NonAutoInsurance::findOne(['id'=>$id]);
        if($caiwu_info->lock_id == 0) {
            $tran = OrderCaiwuT1::getDb()->beginTransaction();
            try {
                $caiwu_info->lock_id = $this->my->id;
                $caiwu_info->save();

                $order_user_info = new OrderUserT();
                $order_user_info->user_id = $this->my->id;
                $order_user_info->order_id = $caiwu_info->order_id;
                $order_user_info->type_id = $caiwu_info->status_id;
                $order_user_info->status = 0;
                $order_user_info->save();

                $tran->commit();
            } catch (\Exception $e) {
                $tran->rollBack();
                throw $e;
            }
        } else {
            if($caiwu_info->lock_id != $this->my->id && $this->my->username != 'admin') {
                echo '该记录已经被别人锁定,【<a href="/insurer/finance-mng?'.$back_params.'">返回</a>】';
                exit;
            }
        }
        //快递
//        $ems_items = EmsT::find()
//            ->where(['car_id'=>$car_info->id,'order_id'=>$order_info->id])
//            ->orderBy('id ASC')
//            ->all();
        //礼品
//        $gift_group_items = [];
//        $sel_gifts = [];
//
//        $gift_group_items = GiftGroupT::find()
//            ->where('is_free=0')
//            ->all();
//        $gift_free_group_items = GiftGroupT::find()
//            ->where('is_free=1')
//            ->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();
//        $new_array = [];
//
//        foreach($insurer_type_items as $k => $v){
//
//            $order_id = $order_info->id;
//            if(!$order_id)
//                $order_id = 0;
//            $tmp_row = PriceT::find()
//                ->where('order_id='.$order_id.' and type_id='.$v->id)
//                ->one();
//            if($tmp_row->val != '' && $tmp_row->val != '0' && $tmp_row->val != '否' && $tmp_row->val != '无'){
//                $new_array[$k]['zl'] = $v->name.'（'.$v->code.'）';
//                $new_array[$k]['neir'] = $tmp_row->val;
//                $new_array[$k]['bjmp'] = $tmp_row->is_nopay==1?'是':'';
//            }
//        }

        //银行列表
//        $banks = BankT::find()->all();

        //转账状态列表
//        $caiwu_status = CaiwuStatusT::find()->all();

        return $this->render('non-finance-mng-edit',[
            'info' => $nonInfo,
//            'new_array' => $new_array,
//            'insurer_type_items' => $insurer_type_items,
            'order_info' => $order_info,
            'caiwu_info' => $caiwu_info,

//            'gift_group_items' => $gift_group_items,
//            'gift_free_group_items' => $gift_free_group_items,
//            'sel_gifts' => $sel_gifts,
            'back_params' => $back_params,
//            'banks' => $banks,
//            'caiwu_status' => $caiwu_status
        ]);
    }
    /**
     * 非车险财务办结-详情
     * @return string
     */
    public function actionNonFinancialSettlementDetail()
    {
        $request = Yii::$app->request;
        $id = $request->get('id',0);
        $oid = $request->get('oid',0);
        $back_params = $request->get('back_params');
//        dd($id);
        $order_info = OrderT::findOne(['id'=>$oid]);

        $caiwu_info = $order_info->caiwu1;
        $nonInfo = NonAutoInsurance::findOne(['id'=>$id]);
        if($caiwu_info->lock_id == 0) {
            $tran = OrderCaiwuT1::getDb()->beginTransaction();
            try {
                $caiwu_info->lock_id = $this->my->id;
                $caiwu_info->save();

                $order_user_info = new OrderUserT();
                $order_user_info->user_id = $this->my->id;
                $order_user_info->order_id = $caiwu_info->order_id;
                $order_user_info->type_id = $caiwu_info->status_id;
                $order_user_info->status = 0;
                $order_user_info->save();

                $tran->commit();
            } catch (\Exception $e) {
                $tran->rollBack();
                throw $e;
            }
        } else {
            if($caiwu_info->lock_id != $this->my->id && $this->my->username != 'admin') {
                echo '该记录已经被别人锁定,【<a href="/insurer/finance-mng?'.$back_params.'">返回</a>】';
                exit;
            }
        }


        return $this->render('non-financial-settlement-detail',[
            'info' => $nonInfo,
//            'new_array' => $new_array,
//            'insurer_type_items' => $insurer_type_items,
            'order_info' => $order_info,
            'caiwu_info' => $caiwu_info,

//            'gift_group_items' => $gift_group_items,
//            'gift_free_group_items' => $gift_free_group_items,
//            'sel_gifts' => $sel_gifts,
            'back_params' => $back_params,
//            'banks' => $banks,
//            'caiwu_status' => $caiwu_status
        ]);
    }

    /**
     * 出纳保存
     * @return array
     * @throws \Exception
     */
    public function actionFinanceMngSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        if($request->isPost) {
            $order_id = $request->post('order_id',0);
            $status_id = $request->post('status_id',0);
            $money_man = $request->post('money_man');
            $money_no = $request->post('money_no');
            $money_bank = $request->post('money_bank');
            $transfer_date = $request->post('transfer_date');
            $transfer_money = $request->post('transfer_money');
            $transfer_bank_id = $request->post('transfer_bank_id');
            $transfer_bank_no = $request->post('transfer_bank_no');
            $caiwu_no = $request->post('caiwu_no');
            $caiwu_status_id = $request->post('caiwu_status_id');

            $tran = OrderCaiwuT::getDb()->beginTransaction();
            try {
                $caiwu_info = OrderCaiwuT::findOne(['order_id'=>$order_id]);
                if(empty($caiwu_info)) {
                    $result['msg'] = '保单错误!';
                    return $result;
                }

                $caiwu_info->money_man = $money_man;
                $caiwu_info->money_no = $money_no;
                $caiwu_info->money_bank = $money_bank;
                $caiwu_info->transfer_date = $transfer_date;
                $caiwu_info->transfer_date = $transfer_date;
                $caiwu_info->transfer_money = $transfer_money;
                $caiwu_info->transfer_bank_id = $transfer_bank_id;
                $caiwu_info->transfer_bank_no = $transfer_bank_no;
                $caiwu_info->caiwu_no = $caiwu_no;
                $old_status_id = $caiwu_info->status_id;
                if($status_id == 10) {
                    if($caiwu_status_id == 0){
                        $result['success'] = false;
                        $result['msg'] = '请先确定转账状态后，再点提交按钮！';
                        return $result;
                    }
                    if($caiwu_info->caiwu_status_id != $caiwu_status_id) {
                        $result['success'] = false;
                        $result['msg'] = '请先保存成功后，再点提交按钮！';
                        return $result;
                    }

                    $caiwu_info->lock_id = 0;
                    $this->addLog($caiwu_info->order->car_id,'返现管理完成',1);
                }
                $caiwu_info->caiwu_status_id = $caiwu_status_id;

                $caiwu_info->status_id = $status_id;
                if(!$caiwu_info->save()) {
                    throw new \Exception(print_r($caiwu_info->getErrors(), true));
                }
                $tran->commit();

                $result['success'] = true;
                $result['msg'] = '保存成功';
            } catch(\Throwable $e) {
                $tran->rollBack();
                $result['msg'] = $e->getMessage();
            }
        }
        return $result;
    }

    /**
     * 非车险出纳保存
     * @return array
     * @throws \Exception
     */
    public function actionNonFinanceMngSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        if($request->isPost) {
            $order_id = $request->post('order_id',0);
            $status_id = $request->post('status_id',0);

            $rate1 = $request->post('rate1');
            $money1 = $request->post('money1');

            $rate4 = $request->post('rate4');
            $money4 = $request->post('money4');


            $tran = OrderCaiwuT::getDb()->beginTransaction();
            try {
                $caiwu_info = OrderCaiwuT1::findOne(['order_id'=>$order_id]);


                if(empty($caiwu_info)) {
                    $result['msg'] = '保单错误!';
                    return $result;
                }

                //原来的财务状态
                $old_status_id = $caiwu_info->status_id;



                $caiwu_info->rate1 = $rate1;
                $caiwu_info->money1 = $money1;

                $caiwu_info->rate4 = $rate4;
                $caiwu_info->money4 = $money4;



                $caiwu_info->status_id = $status_id;
                $caiwu_info->save();



                if($status_id > $old_status_id) {
                    //处理新保、跟踪、续保提成
                    $order_info = $caiwu_info->order;

                    //删除相当记录
                    PayOrderUserT::deleteAll('order_id='.$order_info->id);



                    //截取日期来进行判断
                    $year= (int)substr($caiwu_info->pay_date,0,4);

                    if($year>=2018){
                        $op11= substr($order_info->op1->getShowName(),0,strpos($order_info->op1->getShowName(),'('));
//                        dd($op11);
                        $op1_user = UserT::findOne(['username'=>$op11,'is_delete'=>0]);
                        if($op1_user) {
                            $pay_order_user = new PayOrderUserT();
                            $pay_order_user->user_id = $op1_user->id;
                            $pay_order_user->order_id = $order_info->id;
                            $pay_order_user->type = 8;
                            $pay_order_user->is_own = 2;
                            $pay_order_user->pay_date = $caiwu_info->pay_date;
                            $pay_order_user->save();
                            $pay_order_user->calPay1();
                            $pay_info = PayT::findOne(['user_id'=>$pay_order_user->user_id,'pay_date'=>$pay_order_user->pay_date]);
                            if($pay_info) {
                                $pay_info->calPay();
                            }
                        }



                    }


//                    $op_user1_id = substr($car_info->op_user1,0,strpos($car_info->op_user1,'('));
                    $pay1_user = UserT::findOne(['username'=>$order_info->user_id,'is_delete'=>0]);

                    if($pay1_user) {
                        $pay_order_user = new PayOrderUserT();
                        $pay_order_user->user_id = $pay1_user->id;
                        $pay_order_user->order_id = $order_info->id;
                        $pay_order_user->type = 7;
                        $pay_order_user->is_own = 2;
                        $pay_order_user->pay_date = $caiwu_info->pay_date;
                        $pay_order_user->save();
                        $pay_order_user->calPay1();
                        $pay_info = PayT::findOne(['user_id'=>$pay_order_user->user_id,'pay_date'=>$pay_order_user->pay_date]);
                        if($pay_info) {
                            $pay_info->calPay();
                        }
                    }


                    $caiwu_info->lock_id = 0;
                    $this->addNonLog($caiwu_info->order->non_id,'出纳办结完成,提交财务处理',1);

//                    if($year>=2018){
//                        $this->addLog($caiwu_info->order->car_id,'出纳办结完成,提交财务处理',1);
//                    }else{
//                        $this->addLog1($caiwu_info->order->car_id,'出纳办结完成,提交财务处理',1);
//                    }

                    //处理操作人员状态
                    $order_user_info = OrderUserT::findOne(['order_id'=>$caiwu_info->order_id,'user_id'=>$this->my->id,'type_id'=>$old_status_id,'status'=>0]);
                    if($order_user_info) {
                        $order_user_info->status = 1; //操作结束
                        $order_user_info->save();
                    }
                }
                $caiwu_info->save();

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

                $tran->commit();

            } catch(\Throwable $e) {
                $tran->rollBack();
                file_put_contents('log.txt',$e->getMessage());
                throw $e;
            }
        }
        return $result;
    }
    /**
     * 非车险财务保存
     * @return array
     * @throws \Exception
     */
    public function actionNonFinancialSettlementSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        if($request->isPost) {
            $order_id = $request->post('order_id',0);
            $status_id = $request->post('status_id',0);

            $rate1 = $request->post('rate1');
            $money1 = $request->post('money1');

            $rate4 = $request->post('rate4');
            $money4 = $request->post('money4');


            $tran = OrderCaiwuT::getDb()->beginTransaction();
            try {
                $caiwu_info = OrderCaiwuT1::findOne(['order_id'=>$order_id]);


                if(empty($caiwu_info)) {
                    $result['msg'] = '保单错误!';
                    return $result;
                }

                //原来的财务状态
                $old_status_id = $caiwu_info->status_id;



                $caiwu_info->rate1 = $rate1;
                $caiwu_info->money1 = $money1;

                $caiwu_info->rate4 = $rate4;
                $caiwu_info->money4 = $money4;



                $caiwu_info->status_id = $status_id;
                $caiwu_info->save();



                if($status_id == 10) {
                    //处理新保、跟踪、续保提成
                    $order_info = $caiwu_info->order;

                    //删除相当记录
                    PayOrderUserT::deleteAll('order_id='.$order_info->id);



                    //截取日期来进行判断
                    $year= (int)substr($caiwu_info->pay_date,0,4);

                    if($year>=2018){
                        $op11= substr($order_info->op1->getShowName(),0,strpos($order_info->op1->getShowName(),'('));
//                        dd($op11);
                        $op1_user = UserT::findOne(['username'=>$op11,'is_delete'=>0]);
                        if($op1_user) {
                            $pay_order_user = new PayOrderUserT();
                            $pay_order_user->user_id = $op1_user->id;
                            $pay_order_user->order_id = $order_info->id;
                            $pay_order_user->type = 8;
                            $pay_order_user->is_own = 2;
                            $pay_order_user->pay_date = $caiwu_info->pay_date;
                            $pay_order_user->save();
                            $pay_order_user->calPay1();
                            $pay_info = PayT::findOne(['user_id'=>$pay_order_user->user_id,'pay_date'=>$pay_order_user->pay_date]);
                            if($pay_info) {
                                $pay_info->calPay();
                            }
                        }



                    }


//                    $op_user1_id = substr($car_info->op_user1,0,strpos($car_info->op_user1,'('));
                    $pay1_user = UserT::findOne(['username'=>$order_info->user_id,'is_delete'=>0]);

                    if($pay1_user) {
                        $pay_order_user = new PayOrderUserT();
                        $pay_order_user->user_id = $pay1_user->id;
                        $pay_order_user->order_id = $order_info->id;
                        $pay_order_user->type = 7;
                        $pay_order_user->is_own = 2;
                        $pay_order_user->pay_date = $caiwu_info->pay_date;
                        $pay_order_user->save();
                        $pay_order_user->calPay1();
                        $pay_info = PayT::findOne(['user_id'=>$pay_order_user->user_id,'pay_date'=>$pay_order_user->pay_date]);
                        if($pay_info) {
                            $pay_info->calPay();
                        }
                    }


                    $caiwu_info->lock_id = 0;
//                    $this->addLog($caiwu_info->order->car_id,'出纳办结完成,提交财务处理',1);
                    $this->addNonLog($caiwu_info->order->non_id,'财务办结完成,财务流程结束',1);
//                    if($year>=2018){
//                        $this->addLog($caiwu_info->order->car_id,'出纳办结完成,提交财务处理',1);
//                    }else{
//                        $this->addLog1($caiwu_info->order->car_id,'出纳办结完成,提交财务处理',1);
//                    }

                    //处理操作人员状态
                    $order_user_info = OrderUserT::findOne(['order_id'=>$caiwu_info->order_id,'user_id'=>$this->my->id,'type_id'=>$old_status_id,'status'=>0]);
                    if($order_user_info) {
                        $order_user_info->status = 1; //操作结束
                        $order_user_info->save();
                    }
                }
                $caiwu_info->save();

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

                $tran->commit();

            } catch(\Throwable $e) {
                $tran->rollBack();
                file_put_contents('log.txt',$e->getMessage());
                throw $e;
            }
        }
        return $result;
    }

    /**
     * 退回操作
     * @return array
     * @throws \Exception
     */
    public function actionReturnOp()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '退回失败';

        if($request->isPost) {
            $order_id = $request->post('order_id',0);
            $return_status_id = $request->post('return_status_id',2);
            $return_remark = $request->post('return_remark');

            $tran = OrderT::getDb()->beginTransaction();
            try {
                $row = OrderT::findOne(['id'=>$order_id]);
                if(empty($row)) {
                    $result['msg'] = '保单错误!';
                    return $result;
                }

                $row->status_id = 1;
                $row->return_status_id = $row->status_id;
                if($row->return_status_id == 0) $row->return_status_id = 2;
                $row->return_remark = $return_remark;
                $row->return_time = time();
//                if($return_status_id == 2) {
//                    $row->op1_id = 0;
//                } else {
//                    $row->op2_id = 0;
//                }
                if(!$row->save()) {
                    throw new \Exception(print_r($row->getErrors(), true));
                }

                $this->addLog($row->car_id,'退回业务员,理由是:'.$return_remark,1);

                $tran->commit();

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

            $result['success'] = true;
            $result['msg'] = '退回成功';
        }
        return $result;
    }
    public function actionNonReturnOp()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '退回失败';

        if($request->isPost) {
            $order_id = $request->post('order_id',0);
            $return_status_id = $request->post('return_status_id',0);
            $return_remark = $request->post('return_remark');

            $tran = OrderT::getDb()->beginTransaction();
            try {
                $row = OrderT::findOne(['id'=>$order_id]);
                if(empty($row)) {
                    $result['msg'] = '保单错误!';
                    return $result;
                }

                $row->status_id = 14;
                $row->return_status_id = $return_status_id;
                $row->return_remark = $return_remark;
                $row->return_time = time();
                $row->lock_id = 0;
                $row->save();

                //处理操作人员状态
                $order_user_info = OrderUserT::findOne(['order_id'=>$row->id,'user_id'=>$this->my->id,'status'=>0]);
                if($order_user_info) {
                    $order_user_info->status = 2; //退回
                    $order_user_info->save();

                    $order_user_info2 = new OrderUserT();
                    $order_user_info2->user_id = $row->user_id;
                    $order_user_info2->order_id = $row->id;
                    $order_user_info2->type_id = 1;
                    $order_user_info2->status = 0;
                    $order_user_info2->save();
                }
                //
                //处理礼品数量
                $sel_gifts = OrderGiftT::find()
                    ->where('order_id='.$order_id)
                    ->all();
                foreach($sel_gifts as $sel_gift) {
                    $gift_info = $sel_gift->gift;
                    if($gift_info && $gift_info->total > -1) {
                        $gift_info->total = $gift_info->total + 1;
                        $gift_info->save();
                    }
                }
                $this->addNonLog($row->non_id, '退回业务员,理由是:'.$return_remark, 1);


                $tran->commit();

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

            $result['success'] = true;
            $result['msg'] = '退回成功';
        }
        return $result;
    }
    public function actionNonMyReturnList()
    {
        $request = Yii::$app->request;

        $car_no = $request->get('car_no');
        $date_begin = $request->get('date_begin');
        $date_end = $request->get('date_end');
        $date2_begin = $request->get('date2_begin');
        $date2_end = $request->get('date2_end');
        $page = $request->get('page',1);
        if($page < 1) $page = 1;

        $query = OrderT::find()
            ->where('status_id=14 and return_status_id>0')
            ->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','user_id',$user_ids]);

        if($car_no != '') {
            $query = $query->andWhere('car_no="'.$car_no.'"');
        }
        if($date_begin != '') {
            $query = $query->andWhere('submit_date>="'.$date_begin.'"');
        }
        if($date_end != '') {
            $query = $query->andWhere('submit_date<="'.$date_end.'"');
        }
        if($date2_begin != '') {
            $time_begin = strtotime($date2_begin.' 00:00:00');
            $query = $query->andWhere('return_time>='.$time_begin);
        }
        if($date2_end != '') {
            $time_end = strtotime($date2_end.' 23:59:59');
            $query = $query->andWhere('return_time<='.$time_end);
        }
//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('non-my-return-list',[
            'items' => $items,
            'car_no' => $car_no,
            'page' => $page,
            'page_info' => $page_info,
            'date_begin'=>$date_begin,
            'date_end'=>$date_end,
            'date2_begin'=>$date2_begin,
            'date2_end'=>$date2_end
        ]);
    }

    public function actionMyReturnList() {
        return $this->render('my-return-list');
    }

    public function actionMyReturnListJson()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $car_man = $request->get('car_man');
        $phone = $request->get('phone');
        $car_no = $request->get('car_no');
        $date_begin = $request->get('date_begin');
        $date_end = $request->get('date_end');
        $date2_begin = $request->get('date2_begin');
        $date2_end = $request->get('date2_end');
        $offset = $request->get('offset',0);
        $limit = $request->get('limit',10);

        $query = OrderT::find()
            ->where('status_id=1 and return_status_id>0')
            ->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','user_id',$user_ids]);
        if($car_man != '') {
            $query = $query->andWhere('car_man="'.$car_man.'"');
        }
        if($phone != '') {
            $query = $query->andWhere('link_phone="'.$phone.'"');
        }
        if($car_no != '') {
            $query = $query->andWhere('car_no="'.$car_no.'"');
        }
        if($date_begin != '') {
            $query = $query->andWhere('submit_date>="'.$date_begin.'"');
        }
        if($date_end != '') {
            $query = $query->andWhere('submit_date<="'.$date_end.'"');
        }
        if($date2_begin != '') {
            $time_begin = strtotime($date2_begin.' 00:00:00');
            $query = $query->andWhere('return_time>='.$time_begin);
        }
        if($date2_end != '') {
            $time_end = strtotime($date2_end.' 23:59:59');
            $query = $query->andWhere('return_time<='.$time_end);
        }
//echo $query->createCommand()->rawSql;
        $total = $query->count();

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

        $data = [];
        $data['total'] = $total;
        $data['rows'] = [];
        foreach($items as $item) {
            $row = $item->toArray();
            $row['return_time'] = date('Y-m-d H:i:s', $item->return_time);
            $data['rows'][] = $row;
        }

        return $data;
    }

    public function actionMyReturnListInfo()
    {
        $request = Yii::$app->request;
        $id = $request->get('id',0);

        $car_info = CarT::findOne(['id'=>$id]);
        $order_info = $car_info->getOrders()->one();
        $insurer_type_items = InsurerTypeT::find()
            ->all();
        $insurer_company_items = InsurerCompanyT::find()
            ->all();
        $pay_type_items = PayTypeT::find()
            ->all();
        $car_use_items = CarUseT::find()->all();
        $car_type_items = CarTypeT::find()->all();
        $brand_items = BrandT::find()->all();
        $series_items = SeriesT::find()
            ->where('brand_id='.intval($car_info->brand_id))
            ->all();
        $displacement_items = DisplacementT::find()
            ->where('series_id='.intval($car_info->series_id))
            ->all();
        $direction_items = DirectionT::find()
            ->all();
        $range_items = RangeT::find()
            ->all();
        $city_items = CityT::find()
            ->all();
        $district_items = DistrictT::find()
            ->orderBy('order_id ASC')
            ->all();
        $gift_items = GiftT::find()->all();
        $success_items = InvalidT::getTree(1);
        $failure_items = InvalidT::getTree(2);

        return $this->render('my-return-list-info',[
            'car_info' => $car_info,
            'insurer_type_items' => $insurer_type_items,
            'order_info' => $order_info,
            'insurer_company_items' => $insurer_company_items,
            'pay_type_items' => $pay_type_items,
            'car_use_items' => $car_use_items,
            'car_type_items' => $car_type_items,
            'brand_items' => $brand_items,
            'series_items' => $series_items,
            'displacement_items' => $displacement_items,
            'direction_items' => $direction_items,
            'range_items' => $range_items,
            'city_items' => $city_items,
            'district_items' => $district_items,
            'gift_items' => $gift_items,
            'success_items' => $success_items,
            'failure_items' => $failure_items
        ]);
    }

    /**
     * EMS打印
     * @return string
     */
    public function actionOriginalEmsEdit()
    {
        $request = Yii::$app->request;
        $id = $request->get('id',0);
        $back_params = $request->get('back_params');
        $order_info = OrderT::findOne(['id'=>$id]);
        $car_info = $order_info->car;

        return $this->render('original-ems-edit',[
            'car_info' => $car_info,
            'order_info' => $order_info,
            'back_params' => $back_params
        ]);
    }

    public function actionOriginalEmsEdit1()
    {
        return $this->render('original-ems-edit1',[]);
    }

    public function actionSearch() {
        return $this->render('search');
    }
    public function actionSearchJson()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $car_man = $request->get('car_man');
        $id_man = $request->get('id_man');
        $phone = $request->get('phone');
        $car_no = $request->get('car_no');
        $date_begin = $request->get('date_begin');
        $date_end = $request->get('date_end');
        $date2_begin = $request->get('date2_begin');
        $date2_end = $request->get('date2_end');
        $date3_begin = $request->get('date3_begin');
        $date3_end = $request->get('date3_end');
        $status = $request->get('status');
        $offset = $request->get('offset',0);
        $limit = $request->get('limit', 10);

        $query = OrderT::find()
            ->andWhere('status_id>1')
            ->orderBy('status_id desc,car_no desc,submit_date asc');
        if($id_man != '') {
            $query->andWhere(['like','id_man',$id_man]);
        }
        if($car_man != '') {
            $query->andWhere(['like','car_man',$car_man]);
        }
        if($phone != '') {
            $query->andWhere('car_man_phone like :phone or id_man_phone like :phone or link_man_phone like :phone', [':phone'=>$phone]);
        }
        if($car_no != '') {
            $query->andWhere(['like','car_no',$car_no]);
        }
        if($date_begin != '') {
            $query->andWhere('submit_date>="'.$date_begin.'"');
        }
        if($date_end != '') {
            $query->andWhere('submit_date<="'.$date_end.'"');
        }
        if($date2_begin != '') {
            $query->andWhere('print_date>="'.$date2_begin.'"');
        }
        if($date2_end != '') {
            $query->andWhere('print_date<="'.$date2_end.'"');
        }
        if($date3_begin != '') {
            $query->andWhere('insurer1_begin_date>=:begin_date or insurer2_begin_date>=:begin_date', [':begin_date'=>$date3_begin]);
        }
        if($date3_end != '') {
            $query->andWhere('insurer1_begin_date<=:end_date or insurer2_begin_date<=:end_date', [':end_date'=>$date3_end]);
        }
        if($status == 1) {
            $query->andWhere('status_id>1 and status_id<10');
        }
        if($status == 2) {
            $query->andWhere('status_id=10');
        }
        $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['lock_name'] = $item->lock?$item->lock->getShowName():'';
            $row['status'] = $item->status->name;
            $row['username'] = $item->user->getShowName();
            $row['company_name'] = $item->company->name;
            $row['file_status'] = '未上传';
            if($item->shangye_src || $item->jiaoqiang_src) {
                $row['file_status'] = '保单已上传';
            }
            $data['rows'][] = $row;
        }
        return $data;
    }
    public function actionSearch1()
    {
        $request = Yii::$app->request;
        $car_man = $request->get('car_man');
        $id_man = $request->get('id_man');
        $phone = $request->get('phone');
        $car_no = $request->get('car_no');
        $page = $request->get('page',1);
        $date_begin = $request->get('date_begin');
        $date_end = $request->get('date_end');
        $date2_begin = $request->get('date2_begin');
        $date2_end = $request->get('date2_end');
        $date3_begin = $request->get('date3_begin');
        $date3_end = $request->get('date3_end');
        $group_id = $request->get('group_id');
        $company_id = $request->get('company_id');
        $insurance_status= $request->get('insurance_status');

        if($page < 1) $page = 1;

        $group_items = GroupT::getTree();
        $group_ids[] = $group_id;
        if($group_id > 0) {
            $items = GroupT::getTree($group_id);
            foreach($items as $group_info) {
                $group_ids[] = $group_info->id;
            }
        }
//        $submit_date='2018-10-14';
//        $near_info= OrderT::find()->where(['car_no'=>$car_no])
//            ->orderBy('created_at desc')->select('car_man,created_at,user_id')->one();
//        $near_info= OrderT::find()->where(['car_no'=>$car_no])
//            ->asArray()->select('created_at,submit_date,id,car_man')
//            ->andWhere(['status_id'=>10])
//            ->andWhere(['<', 'submit_date', $submit_date])
//            ->orderBy('created_at desc')->one();
//
//        $car_info->op_user1 = $near_info->user->getShowName();
//        dd($near_info);
        $query = OrderT::find()
            ->where('status_id>1')
//            ->orderBy('submit_date DESC, id DESC');
        ->orderBy('car_no desc,submit_date asc');
        if($id_man != '') {
            $query = $query->andWhere(['like','id_man',$id_man]);
        }
        if($car_man != '') {
            $query = $query->andWhere(['like','car_man',$car_man]);
        }
        if($phone != '') {
            $query = $query->andWhere(['like','link_phone',$phone]);
        }
        if($car_no != '') {
            $query = $query->andWhere(['like','car_no',$car_no]);
        }
        if($date_begin != '') {
            $query = $query->andWhere('submit_date>="'.$date_begin.'"');
        }
        if($date_end != '') {
            $query = $query->andWhere('submit_date<="'.$date_end.'"');
        }
        if($date2_begin != '') {
            $query = $query->andWhere('print_date>="'.$date2_begin.'"');
        }
        if($date2_end != '') {
            $query = $query->andWhere('print_date<="'.$date2_end.'"');
        }
        if($date3_begin != '') {
            $query = $query->andWhere('insurer1_begin_date>="'.$date3_begin.'"');
        }
        if($date3_end != '') {
            $query = $query->andWhere('insurer1_begin_date<="'.$date3_end.'"');
        }

        if($company_id != '') {
            $query = $query->andWhere('company_id ="'.$company_id.'"');
        }
        if($insurance_status != '') {
            $query = $query->andWhere('insurance_status ="'.$insurance_status.'"');
        }
        $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();

//        echo $query->createCommand()->rawSql;

        foreach($items as $vs){

            $order_weizhi_info = OrderWeizhi::findOne(['car_id'=>$vs->car_id]);
            if($order_weizhi_info){
                $order_weizhi_info->num=$order_weizhi_info->num+1;
                $order_weizhi_info->order_text=$order_weizhi_info->order_text.','.$vs->user_id;
                $order_weizhi_info->save();
            }else{
                $order_weizhi_info= new OrderWeizhi();
                $order_weizhi_info->order_id=$vs->id;
                $order_weizhi_info->car_no=$vs->car_no;
                $order_weizhi_info->car_id=$vs->car_id;
                $order_weizhi_info->order_text= $vs->user_id;
                $order_weizhi_info->num=1;
                $order_weizhi_info->save();
            }




        }

        $sum = $query->sum('total1_clear');
        $sum1 = $query->sum('total2_clear');
//        var_dump($sum1) ;

        $page_info = MyLib::getPageInfo($pagination);
        $company_items = InsurerCompanyT::find()->all();
        return $this->render('search',[
            'items' => $items,
            'company_items' => $company_items,
            'insurance_status' => $insurance_status,
            'company_id' => $company_id,
            'car_man' => $car_man,
            'id_man' => $id_man,
            'phone' => $phone,
            'car_no' => $car_no,
            'date_begin' => $date_begin,
            'date_end' => $date_end,
            'date2_begin' => $date2_begin,
            'date2_end' => $date2_end,
            'date3_begin' => $date3_begin,
            'date3_end' => $date3_end,
            'page' => $page,
            'page_info' => $page_info,
            'group_items'=>$group_items,
            'group_id'=>$group_id,
            'sum' => $sum
        ]);
    }

    /**
     * 财务放弃处理
     * @return array
     * @throws \Exception
     */
    public function actionFinanceCancelSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $order_id = $request->post('order_id',0);
        $result = array();
        $result['success'] = false;
        $result['msg'] = '无法放弃';
        $order_info = OrderT::findOne(['id'=>$order_id]);
        if($order_info) {
            $tran = OrderCaiwuT::getDb()->beginTransaction();
            try {
                $caiwu_info = $order_info->caiwu;

                $caiwu_info->lock_id = 0;
                $caiwu_info->save();
                $result['success'] = true;

                $order_user_info = OrderUserT::findOne(['order_id'=>$order_info->id,'status'=>0]);
                if($order_user_info) {
                    $order_user_info->status = 4; //放弃操作
                    $order_user_info->save();
                }

                $tran->commit();

                $result['success'] = true;
                $result['msg'] = '放弃成功';
            } catch (\Exception $e) {
                $tran->rollBack();
                throw $e;
            }
        }
        return $result;
    }

    /**
     * 财务放弃处理
     * @return array
     * @throws \Exception
     */
    public function actionNonFinanceCancelSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $order_id = $request->post('order_id',0);
        $result = array();
        $result['success'] = false;
        $result['msg'] = '无法放弃';
        $order_info = OrderT::findOne(['id'=>$order_id]);
        if($order_info) {
            $tran = OrderCaiwuT1::getDb()->beginTransaction();
            try {
                $caiwu_info = $order_info->caiwu1;

                $caiwu_info->lock_id = 0;
                $caiwu_info->save();
                $result['success'] = true;

                $order_user_info = OrderUserT::findOne(['order_id'=>$order_info->id,'status'=>0]);
                if($order_user_info) {
                    $order_user_info->status = 4; //放弃操作
                    $order_user_info->save();
                }

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

    /**
     * 财务办结-列表
     * @return string
     */

    /**
     * 财务办结-列表
     * @return string
     */

    public function actionFinancialSettlementList()
    {
        $request = Yii::$app->request;
        $begin_date = $request->get('begin_date');
        $end_date = $request->get('end_date');
        $tbegin_date = $request->get('tbegin_date');
        $tend_date = $request->get('tend_date');
        $car_man = $request->get('car_man');
        $phone = $request->get('phone');
        $car_no = $request->get('car_no');
        $insurer_no = $request->get('insurer_no');
        $status = $request->get('status');
        $caiwu_status_id = $request->get('caiwu_status_id');
        $page = $request->get('page',1);
        $username = $request->get('username');
        //级别
        $group_id = $request->get('group_id');
        $group_items = GroupT::getTree((int)$this->my->group_id);
        if($this->my->id == 1 || $this->my->username=='6002')
            $group_items = GroupT::getTree();
        $group_ids[] = $group_id;

        if($group_id > 0) {
            $items = GroupT::getTree($group_id);

            foreach($items as $group_info) {
                $group_ids[] = $group_info->id;
            }
        }
//        die;
        if($page < 1) $page = 1;


        $query = OrderT::find()
            ->leftJoin('order_caiwu_t','order_caiwu_t.order_id=order_t.id')
            ->where('order_t.status_id>5');
        if($car_man != '') {
            $query = $query->andWhere('id_man="'.$car_man.'"');
        }
        if($phone != '') {
            $query = $query->andWhere('link_phone="'.$phone.'"');
        }
        if($car_no != '') {
            $query = $query->andWhere('car_no like "%'.$car_no.'%"');
        }
        if($begin_date != '') {
            $query = $query->andWhere('print_date>="'.$begin_date.'"');
        }
        if($end_date != '') {
            $query = $query->andWhere('print_date<="'.$end_date.'"');
        }
        if($tbegin_date != '') {
            $query = $query->andWhere('order_caiwu_t.transfer_date>="'.$tbegin_date.'"');
        }
        if($tend_date != '') {
            $query = $query->andWhere('order_caiwu_t.transfer_date<="'.$tend_date.'"');
        }
        if($username != '') {
            $user_info = UserT::findOne(['username'=>$username]);
            if($user_info) {
                $query = $query->andWhere('user_id='.$user_info->id);
            }
        }

        if($insurer_no != '') {
            $query = $query->andWhere('(insurer1_no="'.$insurer_no.'" or insurer2_no="'.$insurer_no.'")');
        }
        if($status == 2) {
            $query = $query->andWhere('order_caiwu_t.status_id=10');
        } else if($status == 1) {
            $query = $query->andWhere('order_caiwu_t.status_id=13');
        } else {
            $query = $query->andWhere('order_caiwu_t.status_id=13 or order_caiwu_t.status_id=10 ');
        }
        //转账状态
        if($caiwu_status_id > 0){
            switch($caiwu_status_id){
                case 1:
                    $query = $query->andWhere('order_caiwu_t.caiwu_status_id=1');
                    break;
                case 2:
                    $query = $query->andWhere('order_caiwu_t.caiwu_status_id=2');
                    break;
                case 3:
                    $query = $query->andWhere('order_caiwu_t.caiwu_status_id=3');
                    break;
                case 4:
                    $query = $query->andWhere('order_caiwu_t.caiwu_status_id=4');
                    break;
                default:
                    break;
            }
        }
        //找出$group_id 有多少在职的user_ids
        //      现在的搜索条件
        $userSql = '';
        $user_items = $this->my->getChildren($userSql);
        if($this->my->username == '6002')
            $user_items = $this->my->getChildren($userSql,1);
        $user_items[] = $this->my;

        $row = array();
        foreach($user_items as $user_info) {
//            if ($user_info->is_leave == 1) continue;
            if ($group_id > 0) {
                if (!in_array($user_info->group_id, $group_ids)) {
                    continue;
                }
            }

            $row[] = $user_info->id;

        }

        //加上级别筛选
        if($group_id > 0){
            $query = $query->andWhere(['in','order_t.user_id',$row]);
        }
        $query = $query->orderBy('order_caiwu_t.created_at ASC');
        $total = $query->count();

        $total1_dis = $query->sum('total1_dis');

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

        $query = $query->offset($pagination->offset)->limit($pagination->limit);
        $items = $query->all();
//                echo $query->createCommand()->rawSql;

//die;

        $page_info = MyLib::getPageInfo($pagination);

        return $this->render('financial-settlement-list',[
            'items' => $items,
            'car_man' => $car_man,
            'username' => $username,
            'phone' => $phone,
            'car_no' => $car_no,
            'page' => $page,
            'page_info' => $page_info,
            'insurer_no' => $insurer_no,
            'status' => $status,
            'caiwu_status_id' => $caiwu_status_id,
            'begin_date' => $begin_date,
            'end_date' => $end_date,
            'tbegin_date' => $tbegin_date,
            'tend_date' => $tend_date,
            'group_id' => $group_id,
            'group_items' => $group_items,
            'total1_dis' => $total1_dis
        ]);
    }
    /**
     * 财务办结-详情
     * @return string
     */
    public function actionFinancialSettlementDetail()
    {
        $request = Yii::$app->request;
        $id = $request->get('id',0);
        $back_params = $request->get('back_params');
        $order_info = OrderT::findOne(['id'=>$id]);
        $car_info = $order_info->car;
        $caiwu_info = $order_info->caiwu;

        if($caiwu_info->lock_id == 0) {
            if( $caiwu_info->status_id != 10) {
                $tran = OrderCaiwuT::getDb()->beginTransaction();
                try {
                    $caiwu_info->lock_id = $this->my->id;
                    $caiwu_info->save();

                    $order_user_info = new OrderUserT();
                    $order_user_info->user_id = $this->my->id;
                    $order_user_info->order_id = $caiwu_info->order_id;
                    $order_user_info->type_id = $caiwu_info->status_id;
                    $order_user_info->status = 0;
                    $order_user_info->save();

                    $tran->commit();
                } catch (\Exception $e) {
                    $tran->rollBack();
                    throw $e;
                }
            }
        } else {
            if($caiwu_info->lock_id != $this->my->id && $this->my->username != 'admin') {
                echo '该记录已经被别人锁定,【<a href="/insurer/financial-settlement-list?'.$back_params.'">返回</a>】';
                exit;
            }
        }
        //快递
        $ems_items = EmsT::find()
            ->where(['car_id'=>$car_info->id,'order_id'=>$order_info->id])
            ->orderBy('id ASC')
            ->all();
        //礼品
        $gift_group_items = [];
        $sel_gifts = [];

        $gift_group_items = GiftGroupT::find()
            ->where('is_free=0')
            ->all();
        $gift_free_group_items = GiftGroupT::find()
            ->where('is_free=1')
            ->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();
        $new_array = [];

        foreach($insurer_type_items as $k => $v){

            $order_id = $order_info->id;
            if(!$order_id)
                $order_id = 0;
            $tmp_row = PriceT::find()
                ->where('order_id='.$order_id.' and type_id='.$v->id)
                ->one();
            if($tmp_row->val != '' && $tmp_row->val != '0' && $tmp_row->val != '否' && $tmp_row->val != '无'){
                $new_array[$k]['zl'] = $v->name.'（'.$v->code.'）';
                $new_array[$k]['neir'] = $tmp_row->val;
                $new_array[$k]['bjmp'] = $tmp_row->is_nopay==1?'是':'';
            }
        }

        //银行列表
        $banks = BankT::find()->all();

        //转账信息
        $caiwu_status = CaiwuStatusT::find()->all();

        return $this->render('financial-settlement-detail',[
            'car_info' => $car_info,
            'new_array' => $new_array,
            'insurer_type_items' => $insurer_type_items,
            'order_info' => $order_info,
            'caiwu_info' => $caiwu_info,
            'ems_items' => $ems_items,
            'gift_group_items' => $gift_group_items,
            'gift_free_group_items' => $gift_free_group_items,
            'sel_gifts' => $sel_gifts,
            'back_params' => $back_params,
            'banks' => $banks,
            'caiwu_status' => $caiwu_status
        ]);
    }

    /**
     * 财务保存
     * @return array
     * @throws \Exception
     */
    public function actionFinancialSettlementSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        if($request->isPost) {
            $order_id = $request->post('order_id',0);
            $status_id = $request->post('status_id',0);
            $money_man = $request->post('money_man');
            $money_no = $request->post('money_no');
            $money_bank = $request->post('money_bank');
            $transfer_date = $request->post('transfer_date');
            $transfer_money = $request->post('transfer_money');
            $transfer_bank_id = $request->post('transfer_bank_id');
            $transfer_bank_no = $request->post('transfer_bank_no');
            $budian_rate = $request->post('budian_rate');
            $budian_money = $request->post('budian_money');
            $business_back_money = $request->post('business_back_money');
            $business_back_rate = $request->post('business_back_rate');
            $business_back_routine = $request->post('business_back_routine');
            $business_back_date = $request->post('business_back_date');
            $force_back_money = $request->post('force_back_money');
            $force_back_rate = $request->post('force_back_rate');
            $force_back_routine = $request->post('force_back_routine');
            $force_back_date = $request->post('force_back_date');
            $caiwu_no = $request->post('caiwu_no');
            $rate1 = $request->post('rate1');
            $money1 = $request->post('money1');
            $rate2 = $request->post('rate2');
            $money2 = $request->post('money2');
            $rate3 = $request->post('rate3');
            $money3 = $request->post('money3');
            $rate4 = $request->post('rate4');
            $money4 = $request->post('money4');
            $rate5 = $request->post('rate5');
            $money5 = $request->post('money5');
            $send_rate = $request->post('send_rate');
            $send_money = $request->post('send_money');
            $caiwu_status_id = $request->post('caiwu_status_id');
            $gift_ids = $request->post('gift_ids',array());
            $gift_prices = $request->post('gift_prices',array());
            $gift_rates = $request->post('gift_rates',array());

            $tran = OrderCaiwuT::getDb()->beginTransaction();
            try {
                $caiwu_info = OrderCaiwuT::findOne(['order_id'=>$order_id]);
                if(empty($caiwu_info)) {
                    $result['msg'] = '保单错误!';
                    return $result;
                }

                $caiwu_info->money_man = $money_man;
                $caiwu_info->money_no = $money_no;
                $caiwu_info->money_bank = $money_bank;
                $caiwu_info->transfer_date = $transfer_date;
                $caiwu_info->transfer_date = $transfer_date;
                $caiwu_info->transfer_money = $transfer_money;
                $caiwu_info->transfer_bank_id = $transfer_bank_id;
                $caiwu_info->transfer_bank_no = $transfer_bank_no;
                $caiwu_info->budian_rate = $budian_rate;
                $caiwu_info->budian_money = $budian_money;
                $caiwu_info->business_back_money = $business_back_money;
                $caiwu_info->business_back_rate = $business_back_rate;
                $caiwu_info->business_back_routine = $business_back_routine;
                $caiwu_info->business_back_date = $business_back_date;
                $caiwu_info->force_back_money = $force_back_money;
                $caiwu_info->force_back_rate = $force_back_rate;
                $caiwu_info->force_back_routine = $force_back_routine;
                $caiwu_info->force_back_date = $force_back_date;
                $caiwu_info->caiwu_no = $caiwu_no;
                $old_status_id = $caiwu_info->status_id;
                if($status_id != $old_status_id) {
                    if($caiwu_info->caiwu_status_id != $caiwu_status_id) {
                        $result['success'] = false;
                        $result['msg'] = '请先保存成功后，再点提交按钮！';
                        return $result;
                    }
                }
                $caiwu_info->caiwu_status_id = $caiwu_status_id;

                $caiwu_info->rate1 = $rate1;
                $caiwu_info->money1 = $money1;
                $caiwu_info->rate2 = $rate2;
                $caiwu_info->money2 = $money2;
                $caiwu_info->rate3 = $rate3;
                $caiwu_info->money3 = $money3;
                $caiwu_info->rate4 = $rate4;
                $caiwu_info->money4 = $money4;
                $caiwu_info->rate5 = $rate5;
                $caiwu_info->money5 = $money5;
                $caiwu_info->send_rate = $send_rate;
                $caiwu_info->send_money = $send_money;
//                $caiwu_info->send_price = $send_price;

                $old_status_id = $caiwu_info->status_id;
                $caiwu_info->status_id = $status_id;
                $caiwu_info->save();
//                echo $caiwu_info->lock_id."\r\n";
//                echo $status_id;
//                exit;

                //保存礼品价格
                foreach($gift_ids as $index => $id) {
                    $rate = $gift_rates[$index];
                    $price = $gift_prices[$index];
                    $order_gift = OrderGiftT::findOne(['id'=>$id]);
                    if($order_gift) {
                        $order_gift->rate = $rate;
                        $order_gift->price = $price;
                        $order_gift->save();
                    }
                }

                if($status_id == 10) {
                    //处理新保、跟踪、续保提成
                    $order_info = $caiwu_info->order;
                    $car_info = $order_info->car;
                    //删除相当记录
                    PayOrderUserT::deleteAll('order_id='.$order_info->id);

                    
//                    echo $op_user1_id;
//                    die;
                    //截取日期来进行判断
                    $year= (int)substr($caiwu_info->pay_date,0,4);

                    if($year>=2018){
                        if($order_info->op1){
                            $op11= substr($order_info->op1->getShowName(),0,strpos($order_info->op1->getShowName(),'('));
                            $op1_user = UserT::findOne(['username'=>$op11,'is_delete'=>0]);
                            if($op1_user) {
                                $pay_order_user = new PayOrderUserT();
                                $pay_order_user->user_id = $op1_user->id;
                                $pay_order_user->order_id = $order_info->id;
                                $pay_order_user->type = 5;
                                $pay_order_user->is_own = 0;
                                $pay_order_user->pay_date = $caiwu_info->pay_date;
                                $pay_order_user->save();
                                $pay_order_user->calPay();
                                $pay_info = PayT::findOne(['user_id'=>$pay_order_user->user_id,'pay_date'=>$pay_order_user->pay_date]);
                                if($pay_info) {
                                    $pay_info->calPay();
                                }
                            }
                        }

                        if($order_info->op2){
                            $op22= substr($order_info->op2->getShowName(),0,strpos($order_info->op2->getShowName(),'('));
                            $op2_user = UserT::findOne(['username'=>$op22,'is_delete'=>0]);
                            if($op2_user) {
                                $pay_order_user = new PayOrderUserT();
                                $pay_order_user->user_id = $op2_user->id;
                                $pay_order_user->order_id = $order_info->id;
                                $pay_order_user->type = 6;
                                $pay_order_user->is_own = 0;
                                $pay_order_user->pay_date = $caiwu_info->pay_date;
                                $pay_order_user->save();
                                $pay_order_user->calPay();
                                $pay_info = PayT::findOne(['user_id'=>$pay_order_user->user_id,'pay_date'=>$pay_order_user->pay_date]);
                                if($pay_info) {
                                    $pay_info->calPay();
                                }
                            }
                        }

                    }




                    $op_user1_id = substr($car_info->op_user1,0,strpos($car_info->op_user1,'('));
                    $pay1_user = UserT::findOne(['username'=>$op_user1_id,'is_delete'=>0]);
                    if($pay1_user) {
                        $pay_order_user = new PayOrderUserT();
                        $pay_order_user->user_id = $pay1_user->id;
                        $pay_order_user->order_id = $order_info->id;
                        $pay_order_user->type = 1;
                        $pay_order_user->is_own = $car_info->op_user3 != '' ? 0:1;
                        $pay_order_user->pay_date = $caiwu_info->pay_date;
                        $pay_order_user->save();
                        $pay_order_user->calPay();
                        $pay_info = PayT::findOne(['user_id'=>$pay_order_user->user_id,'pay_date'=>$pay_order_user->pay_date]);
                        if($pay_info) {
                            $pay_info->calPay();
                        }
                    }
                    $op_user2_id = substr($car_info->op_user2,0,strpos($car_info->op_user2,'('));
                    $pay2_user = UserT::findOne(['username'=>$op_user2_id,'is_delete'=>0]);
                    if($pay2_user) {
                        $pay_order_user = new PayOrderUserT();
                        $pay_order_user->user_id = $pay2_user->id;
                        $pay_order_user->order_id = $order_info->id;
                        $pay_order_user->type = 2;
                        $pay_order_user->is_own = 0;
                        $pay_order_user->pay_date = $caiwu_info->pay_date;
                        $pay_order_user->save();
                        $pay_order_user->calPay();
                        $pay_info = PayT::findOne(['user_id'=>$pay_order_user->user_id,'pay_date'=>$pay_order_user->pay_date]);
                        if($pay_info) {
                            $pay_info->calPay();
                        }
                    }
                    $op_user3_id = substr($car_info->op_user3,0,strpos($car_info->op_user3,'('));
                    $pay3_user = UserT::findOne(['username'=>$op_user3_id,'is_delete'=>0]);
                    if($pay3_user) {
                        $pay_order_user = new PayOrderUserT();
                        $pay_order_user->user_id = $pay3_user->id;
                        $pay_order_user->order_id = $order_info->id;
                        $pay_order_user->type = 3;
                        $pay_order_user->is_own = 1;
                        $pay_order_user->pay_date = $caiwu_info->pay_date;
                        $pay_order_user->save();
                        $pay_order_user->calPay();
                        $pay_info = PayT::findOne(['user_id'=>$pay_order_user->user_id,'pay_date'=>$pay_order_user->pay_date]);
                        if($pay_info) {
                            $pay_info->calPay();
                        }
                    }
                    $send_info = $order_info->sendLog;
                    if($send_info) {
                        $pay_order_user = new PayOrderUserT();
                        $pay_order_user->user_id = $send_info->user_id;
                        $pay_order_user->order_id = $order_info->id;
                        $pay_order_user->type = 4;
                        $pay_order_user->is_own = 0;
                        $pay_order_user->pay_date = $caiwu_info->pay_date;
                        $pay_order_user->save();
                        $pay_order_user->calPay();
                        $pay_info = PayT::findOne(['user_id'=>$send_info->user_id,'pay_date'=>$pay_order_user->pay_date]);
                        if($pay_info) {
                            $pay_info->calPay();
                        }
                    }

                    $caiwu_info->lock_id = 0;
                    $caiwu_info->save();

//                    $this->addLog($caiwu_info->order->car_id,'财务办结完成,财务流程结束',1);
                    if($year>=2018){
                        $this->addLog($caiwu_info->order->car_id,'财务办结完成,财务流程结束',1);
                    }else{
                        $this->addLog1($caiwu_info->order->car_id,'财务办结完成,财务流程结束',1);
//                        die;

                    }

                    //处理操作人员状态
                    $order_user_info = OrderUserT::findOne(['order_id'=>$caiwu_info->order_id,'user_id'=>$this->my->id,'type_id'=>$old_status_id,'status'=>0]);
                    if($order_user_info) {
                        $order_user_info->status = 1; //操作结束
                        $order_user_info->save();
                    }
                }

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

                $tran->commit();

            } catch(\Throwable $e) {
                $tran->rollBack();
                file_put_contents('log2.txt',$e->getMessage());
                throw $e;
            }
        }
        return $result;
    }
    /**
     * 财务退回操作
     * @return array
     * @throws \Exception
     */
    public function actionFinanceReturnOp()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '退回失败';

        if($request->isPost) {
            $order_id = $request->post('order_id',0);
            $return_remark = $request->post('return_remark');

            $tran = OrderCaiwuT::getDb()->beginTransaction();
            try {
                $row = OrderCaiwuT::findOne(['order_id'=>$order_id]);
                if(empty($row)) {
                    $result['msg'] = '保单错误!';
                    return $result;
                }

                $row->status_id = 12;
                $row->lock_id = 0;
                $row->save();

                //处理操作人员状态
                $order_user_info = OrderUserT::findOne(['order_id'=>$order_id,'user_id'=>$this->my->id,'status'=>0]);
                if($order_user_info) {
                    $order_user_info->status = 2; //退回
                    $order_user_info->save();
                }

                $this->addLog($row->order->car_id,'退回出纳处理原因：'.$return_remark,1);

                $tran->commit();

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

            $result['success'] = true;
            $result['msg'] = '退回成功';
        }
        return $result;
    }
    public function actionTuidanSave(){
        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);
            $order_info = OrderT::findOne($id);
            $order_info->status_id=5;
            $re=$order_info->save();
            $odc=OrderCaiwuT::find()->where('order_id='.$id)->one();
            $res=$odc->delete();
            $this->addLog($order_info->car_id,'退单成功',1);
            if($re && $res){
                $result['success'] = true;
                $result['msg'] = '保存成功';
            }
        }
        return $result;
    }
    public function actionUnlocked()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '解锁失败';

        if($request->isPost){

            $order_info = OrderCaiwuT::findOne(['order_id'=>$request->post('id')]);
            $order_info->lock_id=0;
            if($order_info->save()){
                $result['success'] = true;
                $result['msg'] = '解锁成功';
            }

        }
        return $result;
    }
    public function actionNonUnlocked()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '解锁失败';

        if($request->isPost){

            $order_info = OrderCaiwuT1::findOne(['order_id'=>$request->post('id')]);
            $order_info->lock_id=0;
            if($order_info->save()){
                $result['success'] = true;
                $result['msg'] = '解锁成功';
            }

        }
        return $result;
    }
    public function actionPdfSave(){
        Yii::$app->response->format = Response::FORMAT_JSON;

        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        if($request->isPost){
            $id = $request->post('order_id',0);
            //上传商业和交强文件
            $urlfile= $request->post('urlfile');
            $urlfile1= $request->post('urlfile1');

            if(substr($urlfile,-3)!='pdf' && substr($urlfile1,-3)!='pdf'){
                $result['msg'] = '请上传正确的商业或交强pdf文件';
                return $result;
            }
            $urlfile= trim($urlfile);
            $urlfile1= trim($urlfile1);
            $order_info = OrderT::findOne($id);
            $order_info->shangye_src = $urlfile;
            $order_info->jiaoqiang_src = $urlfile1;
            $order_info->upload_status = 2;
            $re=$order_info->save();
            $this->addLog($order_info->car_id,'正本保单上传',1);
            if($re){
                $result['success'] = true;
                $result['msg'] = '保存成功';
            }
        }
        return $result;
    }
    public function actionGiftUnSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '取消失败';

        if ($request->isPost) {
            $id = $request->post('order_id', 0);

            $order_info = OrderT::findOne($id);

            $tran = OrderT::getDb()->beginTransaction();
            try {
                $order_info->gift_status = 0;
                if(!$order_info->save()) {
                    throw new \Exception(print_r($order_info->getErrors(), true));
                }
                $result['success'] = true;
                $result['msg'] = '取消成功';

                $tran->commit();
            } catch (\Exception $e) {
                $tran->rollBack();
                $result['msg'] = $e->getMessage();
            }
        }
        return $result;
    }
    public function actionGiftSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        if ($request->isPost) {
            $id = $request->post('order_id', 0);
            $gift_ids = $request->post('gift_ids', []);
            $quan_ids = $request->post('quan_ids', []);

            $order_info = OrderT::findOne($id);
            if ($order_info->gift_status > 0) {
                $result['msg'] = '礼品不能修改';
                return $result;
            }

            if (!isset($order_info->print_date)) {
                $result['msg'] = '正本还没有生成，不能确认礼品';
                return $result;
            }
            $gift_counts = [];
            $tran = OrderT::getDb()->beginTransaction();
            try {
//            OrderGiftT::deleteAll('order_id=' . $order_info->id . ' and gift_src is null');
                OrderGiftT::deleteAll('order_id=' . $order_info->id);
                //礼品
                foreach($gift_ids as $gift_str) {
                    $tmp = explode('-', $gift_str);
                    $zhongjigift_item = ZhongjiGiftT::findOne(['id'=>$tmp[0]]);
                    $gift_id = $tmp[1];
                    $gift_item = GiftT::findOne(['id'=>$gift_id]);
                    $order_gift_id = 0;
                    if($zhongjigift_item && $gift_item) {
                        $row = new OrderGiftT();
                        $row->order_id = $order_info->id;
                        $row->group_id = 0;
                        $row->gift_id = $gift_id;
                        $row->is_free = $zhongjigift_item->free_type;
                        $row->gift_type = $zhongjigift_item->gift_type;
                        $row->send_id = 0;
                        $row->send_time = 0;
                        $row->price = $gift_item->price;
                        $row->status = 0;
                        if (!$row->save()) {
                            throw new \Exception(print_r($row->getErrors(), true));
                        }
                        $order_gift_id = $row->id;
                        if(!isset($gift_counts[$zhongjigift_item->id])) {
                            $gift_counts[$zhongjigift_item->id] = 1;
                        } else {
                            $gift_counts[$zhongjigift_item->id] += 1;
                        }
                        if($gift_counts[$zhongjigift_item->id] > $zhongjigift_item->n) {
                            $result['msg'] = '礼品数量超限，请重新选择';
                            return $result;
                        }
                    }
                    //生成礼品图片
                    if($gift_item) {
                        $this->getGift(0, $gift_id, $order_info->car_no, $order_info, $order_gift_id);
                    }
                }
                //礼券
                foreach($quan_ids as $gift_str) {
                    $tmp = explode('-', $gift_str);
                    $zhongjigift_item = ZhongjiGiftT::findOne(['id'=>$tmp[0]]);
                    $gift_id = $tmp[1];
                    $gift_item = GiftT::findOne(['id'=>$gift_id]);
                    $order_gift_id = 0;
                    if($zhongjigift_item && $gift_item) {
                        $row = new OrderGiftT();
                        $row->order_id = $order_info->id;
                        $row->group_id = 0;
                        $row->gift_id = $gift_id;
                        $row->is_free = $zhongjigift_item->free_type;
                        $row->gift_type = $zhongjigift_item->gift_type;
                        $row->send_id = 0;
                        $row->send_time = 0;
                        $row->price = $gift_item->price;
                        $row->status = 0;
                        if (!$row->save()) {
                            throw new \Exception(print_r($row->getErrors(), true));
                        }
                        $order_gift_id = $row->id;
                        if(!isset($gift_counts[$zhongjigift_item->id])) {
                            $gift_counts[$zhongjigift_item->id] = 1;
                        } else {
                            $gift_counts[$zhongjigift_item->id] += 1;
                        }
                        if($gift_counts[$zhongjigift_item->id] > $zhongjigift_item->n) {
                            $result['msg'] = '礼券数量超限，请重新选择';
                            return $result;
                        }
                    }
                    //生成礼券图片
                    if($gift_item) {
                        $this->getGift(0, $gift_id, $order_info->car_no, $order_info, $order_gift_id);
                    }
                }
                $order_info->gift_status = 1;
                if(!$order_info->save()) {
                    throw new \Exception(print_r($order_info->getErrors(), true));
                }
                $result['success'] = true;
                $result['msg'] = '保存成功';

                $tran->commit();
            } catch (\Exception $e) {
//                var_dump($e->getTrace());
                $tran->rollBack();
                $result['msg'] = $e->getMessage();
            }
        }
        return $result;
    }

    /**
     * 礼品状态回退
     * @return array
     */
    public function actionGiftCancel()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $id = $request->post('order_id');
        $msg= $request->post('return_msg');
        $result = array('success'=>false,'msg'=>'操作成功');
        if(!$request->isPost){
            $result['msg'] = '请求方式错误';
            return $result;
        }
        if(!$this->my->id == 1){
            $result['msg'] = '无此操作权限';
            return $result;
        }
        if ($id < 0) {
            $result['msg'] = '订单ID无效';
            return $result;
        }
        if ($msg == '') {
            $result['msg'] = '退单理由必须';
            return $result;
        }

        $order_info = OrderT::findOne($id);
        if (!$order_info) {
            $result['msg'] = '订单不存在';
            return $result;
        }

        $tran = OrderT::getDb()->beginTransaction();
        try {
            // 删除礼品/券库信息
            GiftTicketTUse::deleteAll('order_id=' . $order_info->id);
            // 修改订单礼品/券信息
            OrderGiftT::updateAll(['gift_src' => ''], ['order_id' => $order_info->id]);
            // 修改订单状态
            $order_info->gift_status = 0;
            $order_info->save();
            $this->addLog($order_info->car_id, '回退礼品状态,理由：' . $msg, 1);
            $tran->commit();
        } catch (\Exception $e) {
            $tran->rollBack();
            $result['msg'] = '订单不存在';
            $result['msg'] = $e->getMessage();
            return $result;
        }
        $result['success'] = true;
        return $result;
    }

    public function getGift($k, $v, $car_no, $order_info, $order_gift_id)
    {
        $result = array();
        $result['tishi'] = true;
        $result['teshu'] = false;
        $gift_info = GiftT::findOne(['id' => $v]);
        if($order_gift_id  == 0) {
            return;
        }
        $bianhao = '';
        $endDate = '';
        //礼券
        if ($gift_info && $gift_info->type_id == 2) {
            $pinyin_arr = explode(' ', $gift_info->pinyin_name);
            $liquan_str = 'wf';
            //获取礼券拼音首字母
            foreach ($pinyin_arr as $first) {
                $liquan_str .= substr($first, 0, 1);
            }
            $liquan_str = strtolower($liquan_str);
            //获取提单日期
            $liquan_str .= date('Ymd', strtotime($order_info->print_date));

            //获取该礼券下的最后一条记录
            $gift_use = GiftTicketTUse::find()->where(['type_id' => $v, 'status' => 1])->orderBy('created_at desc')->one();

            //礼券的使用
            $new_gift_use = new GiftTicketTUse();
            if ($gift_use) {
                $liquan_str .= sprintf("%04d", $gift_use->gift_shuzi + 1);
                $new_gift_use->gift_shuzi = $gift_use->gift_shuzi + 1;

            } else {
                $liquan_str .= sprintf("%04d", 1);
                $new_gift_use->gift_shuzi = 1;
            }
            $new_gift_use->code = strtoupper($liquan_str);
            $new_gift_use->op_id = $this->my->id;
            $new_gift_use->type_id = $v; //礼券ID
            $new_gift_use->input_date = date('Y-m-d H:i:s');
            $new_gift_use->car_no = $car_no;
            $new_gift_use->order_id = $order_info->id;
            $new_gift_use->status = 1;
            $new_gift_use->end_date = $order_info->insurer1_end_date;

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

            //表头
            $bianhao = strtoupper($liquan_str); //转换成大写编号
            $endDate = '有效期' . $order_info->insurer1_end_date;
        }
        //礼品的使用
        if ($gift_info && $gift_info->type_id == 1) {
            $shiwu_use = GiftTicketTUse::find()->where(['type_id' => $v, 'status' => 1])->orderBy('created_at desc')->one();

            $new_shiwu = new GiftTicketTUse();

            if ($shiwu_use) {
                $new_shiwu->gift_shuzi = $shiwu_use->gift_shuzi + 1;
                $new_shiwu->code = sprintf("%04d", $shiwu_use->gift_shuzi + 1);
            } else {
                $new_shiwu->gift_shuzi = 1;
                $new_shiwu->code = sprintf("%04d", 1);
            }
            $new_shiwu->op_id = $this->my->id;
            $new_shiwu->type_id = $v;
            $new_shiwu->input_date = date('Y-m-d H:i:s');
            $new_shiwu->car_no = $car_no;
            $new_shiwu->status = 1;
            $new_shiwu->order_id = $order_info->id;
            $new_shiwu->end_date = $order_info->insurer1_end_date;
            if(!$new_shiwu->save()) {
                throw new \Exception(print_r($new_shiwu->getErrors(), true));
            }
            //表头
            $bianhao = '';
            $endDate = '';
        }

        $gift_name = $gift_info->name;

        //生成png文件
        $gift_src = '';
        $panduan = (object)array();
        $datetime = date('YmdHis');
        $name = md5(rand(100, 200));
        $imgstr = '@frontend/web/upload/images/'.date('Ym');
        $imgstr .= '/gift' . $name . '' . $datetime . '.png';
        FileHelper::createDirectory(dirname(str_replace('@frontend/web/', '',$imgstr)));
        //生成新的图片
        if ($gift_info && $gift_info->type_id == 1) {   // 实物
            \yii\imagine\Image::thumbnail('@frontend/web/images/gift.png', 400, 252)
                ->save(Yii::getAlias($imgstr),
                    ['quality' => 100]);//生成缩略图的质量
            //图片打水印
            \yii\imagine\Image::text('@frontend/web/images/gift.png', $bianhao, Yii::getAlias('@frontend/web/fonts/msyh.ttc'), [15, 15], ['color' => '000000', 'size' => 12])
                ->save(Yii::getAlias($imgstr));
            \yii\imagine\Image::text($imgstr, $gift_name, Yii::getAlias('@frontend/web/fonts/msyh.ttc'), [20, 50], ['color' => '000000', 'size' => 20])
                ->save(Yii::getAlias($imgstr));

            \yii\imagine\Image::text($imgstr, $car_no, Yii::getAlias('@frontend/web/fonts/msyh.ttc'), [20, 120], ['color' => '000000', 'size' => 20])
                ->save(Yii::getAlias($imgstr));

            $panduan = \yii\imagine\Image::text($imgstr, $endDate, Yii::getAlias('@frontend/web/fonts/msyh.ttc'), [20, 200], ['color' => '000000', 'size' => 20])
                ->save(Yii::getAlias($imgstr));

        } elseif ($gift_info && $gift_info->type_id == 2) {
            if($gift_info->original_img == '') {
                throw new \Exception('礼券文件不存在');
            }
            $liquanSrc = '@frontend/web' . $gift_info->original_img;
            \yii\imagine\Image::thumbnail($liquanSrc, 1097, 979)
                ->save(Yii::getAlias($imgstr),
                    ['quality' => 100]);//生成缩略图的质量
            //图片打水印
            $bianhao = '券号：' . $bianhao;
            \yii\imagine\Image::text($liquanSrc, $bianhao, Yii::getAlias('@frontend/web/fonts/msyh.ttc'), [20, 20], ['color' => '000000', 'size' => 14])
                ->save(Yii::getAlias($imgstr));

            \yii\imagine\Image::text($imgstr, $car_no, Yii::getAlias('@frontend/web/fonts/msyh.ttc'), [425, 200], ['color' => '000000', 'size' => 16])
                ->save(Yii::getAlias($imgstr));

            $panduan = \yii\imagine\Image::text($imgstr, $endDate, Yii::getAlias('@frontend/web/fonts/msyh.ttc'), [425, 223], ['color' => '000000', 'size' => 16])
                ->save(Yii::getAlias($imgstr));
        }

        $gift_src = str_replace('@frontend/web', '', $imgstr);
        //保存order_gift_t表里png文件地址

        $order_gift_info = OrderGiftT::findOne(['id' => $order_gift_id]);
        $order_gift_info->gift_src = $gift_src;
        if(!$order_gift_info->save()) {
            throw new \Exception(print_r($order_gift_info->getErrors(), true));
        }
    }

    /**
     * 退单操作（超管权限任意状态退单）
     * @return array
     * @throws \Exception
     */
    public function actionSupperReturn()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '操作失败';
        if($request->isPost) {
            $order_id = $request->post('order_id',0);
            $return_remark = $request->post('return_remark');
            if ($order_id < 0) {
                $result['msg'] = '订单ID无效';
                return $result;
            }
            if($return_remark == ''){
                $result['msg'] = '请填写退单理由!';
                return $result;
            }

            $order_info = OrderT::findOne(['id'=>$order_id]);
            if(empty($order_info)) {
                $result['msg'] = '保单信息不存在!';
                return $result;
            }

            // 订单信息更新
            $order_info->return_status_id = $order_info->status_id;
            if($order_info->return_status_id == 0) $order_info->return_status_id = 2;
            $order_info->lock_id = 0;
            $order_info->status_id = 1;
            $order_info->return_remark = $return_remark;
            $order_info->return_time = time();
            $order_info->gift_status = 0;
            // 车辆信息处理
            $car_info = $order_info->car;
            if ($car_info->op2_id > 0) { //续保
                $car_info->location = 4;
            }else {
                $car_info->location = 2;
                $car_info->is_xubao = 0;
            }
//            $car_info->user_id = $order_info->user_id;

            $tran = OrderT::getDb()->beginTransaction();
            try {
                if(!$car_info->save()) {
                    throw new \Exception(print_r($car_info->getErrors(), true));
                }
                // 财务处理
                CaiwuT::deleteAll(['order_id'=>$order_info->id]);
                OrderCaiwuT::deleteAll(['order_id'=>$order_info->id]);
                OrderUserT::deleteAll(['order_id'=>$order_info->id]);

                // 车辆信息
                CarCT::deleteAll(['id' => $order_info->car_id]);
                // 检测车辆是否移库
                if($car_info->op2_id > 0 && $car_info->location != 4){
                    $car_db_info = new CarDT(false);
                    $car_db_info->id = $order_info->car_id;
                    $car_db_info->user_id = $order_info->user_id;
                    if(!$car_db_info->save()) {
                        throw new \Exception(print_r($car_db_info->getErrors(), true));
                    }
                }
                if(!$order_info->car->op2_id && $order_info->car->location != 2){
                    $car_db_info = new CarBT(false);
                    $car_db_info->id = $order_info->car_id;
                    $car_db_info->user_id = $order_info->user_id;
                    if(!$car_db_info->save()) {
                        throw new \Exception(print_r($car_db_info->getErrors(), true));
                    }
                }

                // 礼品状态回退
                GiftTicketTUse::deleteAll('order_id=' . $order_info->id);
                OrderGiftT::updateAll(['gift_src' => ''], ['order_id' => $order_info->id]);

                $this->addLog($order_info->car_id,'超管退单,理由是:'.$return_remark,1);
                if(!$order_info->save()) {
                    throw new \Exception(print_r($order_info->getErrors(), true));
                }
                $tran->commit();
                $result['success'] = true;
                $result['msg'] = '操作成功';
            } catch (\Exception $e) {
                $tran->rollBack();
                $result['msg'] = '操作失败,' . $e->getMessage();
            }
        }
        return $result;
    }
}