<?php

namespace frontend\controllers;

use common\libs\MyLib;
use common\models\CaiwuClassT;
use common\models\CaiwuErrorT;
use common\models\CaiwuExcelT;
use common\models\CaiwuGiftT;
use common\models\CaiwuImportT;
use common\models\CaiwuT;
use common\models\CaiwuT1;
use common\models\CaiwuT2;
use common\models\CaiwuZcT;
use common\models\CarGiftT;
use common\models\CarT;

use common\models\Car2T;
use common\models\CarBT;
use common\models\CarCT;
use common\models\CarDT;
use common\models\CarET;
use common\models\CarInvalidT;
use common\models\GiftT;
use common\models\ImportLogT;
use common\models\CompanyT;
use common\models\EmsT;
use common\models\ExpressT;
use common\models\GiftType3T;
use common\models\GroupT;
use common\models\Gz2T;
use common\models\GzT;
use common\models\InsurerCompany2T;
use common\models\InsurerCompanyT;
use common\models\InsurerTypeT;
use common\models\LinkmanT;
use common\models\OrderCaiwuT;
use common\models\OrderGiftT;
use common\models\OrderT;
use common\models\OrderUserT;
use common\models\PayOrderUserT;
use common\models\PayT;
use common\models\PayeeT;
use common\models\Payment;
use common\models\GiftType2T;
use common\models\SendLogT;
use common\models\UserT;
use common\models\WorkDayT;
use common\models\ZhongjiYingxiao;
use Yii;
use yii\data\Pagination;
use yii\web\Response;
use yii\web\UploadedFile;

class FinanceController extends \frontend\controllers\UserBaseController
{
    public $enableCsrfValidation = false;
    public $layout = 'blue-main';

    public function actionReceipt() {
        $insurer_company_items = InsurerCompany2T::find()->all();

        return $this->render('receipt',[
            'insurer_company_items' => $insurer_company_items
        ]);
    }
    public function actionReceiptJson()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $begin_date = $request->get('begin_date');
        $end_date = $request->get('end_date');
        $r_begin_date = $request->get('r_begin_date');
        $r_end_date = $request->get('r_end_date');
        $car_no = trim($request->get('car_no'));
        $insurer_no = trim($request->get('insurer_no'));
        $status = $request->get('status',1);
        $sort_key = $request->get('sort_key');
        $sort_value = $request->get('sort_value');
        $company_id = $request->get('company_id');
        $username = $request->get('username');
        $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)
            $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 = CaiwuT::find()
            ->leftJoin(OrderT::tableName(), "order_t.id=caiwu_t.order_id");

        switch ($sort_key) {
            case 'total':
                $sort = 'caiwu_t.total ';
                break;
            case 'total_clear':
                $sort = 'caiwu_t.total_clear ';
                break;
            case 'total_rate':
                $sort = 'caiwu_t.total_rate ';
                break;
            case 'print_date'://默认按照print_date排序
            default:
                $sort = 'order_t.print_date ';
                break;
        }

        switch ($sort_value) {
            case 'ASC':
                $sort .= 'ASC';
                break;
            case 'DESC':
            default:
                $sort .= 'DESC';
                break;
        }

        $query = $query->orderBy($sort);

        if( $company_id > 0) {
            $query->andWhere('order_t.company2_id='.$company_id);
        }
        if ($username != "") {
            $userdata = UserT::findOne(['username'=>$username]);
            if($userdata){
                $query->andWhere('caiwu_t.user_id = ' . $userdata->id . '');
            }
        }
        if ($car_no != "") {
            $query->andWhere('caiwu_t.car_no like "%' . $car_no . '%"');
        }
        if ($car_no != "") {
            $query->andWhere('caiwu_t.car_no like "%' . $car_no . '%"');
        }
        if ($insurer_no != "") {
            $query->andWhere('caiwu_t.insurer_no like "' . $insurer_no . '%"');
        }
        if ($status > 0) {
            if ($status == 1) {
                $query->andWhere('r_date="" or r_date is null');
            }
            if ($status == 2) {
                $query->andWhere('r_date<>"" and total_dis=0');
            }
            if($status == 3) {
                $query->andWhere('r_date<>"" and total_dis<>0');
            }
        }
        if ($begin_date != "") {
            $query->andWhere('order_t.print_date>="' . $begin_date . '"');
        }
        if ($end_date != "") {
            $query->andWhere('order_t.print_date<="' . $end_date . '"');
        }
        if ($r_begin_date != "") {
            $query->andWhere('caiwu_t.r_date>="' . $r_begin_date . '"');
        }
        if ($r_end_date != "") {
            $query->andWhere('caiwu_t.r_date<="' . $r_end_date . '"');
        }
        //找出$group_id 有多少在职的user_ids
        //      现在的搜索条件
        $userSql = '';

        $user_items = $this->my->getChildren($userSql);
        if($this->my->username == '6002' || $this->my->username == '7053')
            $user_items = $this->my->getChildren($userSql,1);
        $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->andWhere(['in','caiwu_t.user_id',$row]);
        }


        $total = $query->count();

        $sum_r_total = $query->sum('r_total');
        //商业净保费综合
        $sum_total_clear = $query->sum('total_clear'); //是错误的

        //商业总保费
        $sum_total = $query->sum('total');

        $sum_total_dis = $query->sum('total_dis');

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

        $data = [];
        $data['total'] = $total;
        $data['rows'] = [];
        foreach($items as $item) {
            $row = $item->toArray();
            $row['group'] = $item->user && $item->user->group ? $item->user->group->name : '';
            $row['company_name'] = $item->order && $item->order->company2 ? $item->order->company2->name : 0;
            $row['username'] = $item->user ? $item->user->getShowName() : 0;
            $row['submit_date'] = $item->order ? $item->order->submit_date : '';
            $row['print_date'] = $item->order ? $item->order->print_date : '';
            $row['total_real'] = round($item->total_clear_real + $item->total_tax_real,2);
            $data['rows'][] = $row;
        }

        $data['rows'][] = array(
            ['商业保总额', $sum_total],
            ['商业净保总额', $sum_total_clear],
            ['回款总额', $sum_r_total],
            ['回款差额', $sum_total_dis]
        );

        return $data;
    }
    public function actionReceiptImport() {
        return $this->render('receipt-import');
    }
    public function actionReceipt2Import() {
        return $this->render('receipt2-import');
    }

    public function actionEmsReceipt()
    {
        $request = Yii::$app->request;
        $page = $request->get('page', 1);
        $begin_date = $request->get('r_begin_date');
        $end_date = $request->get('r_end_date');
        $z_begin_date = $request->get('z_begin_date');
        $z_end_date = $request->get('z_end_date');
        $id_man = trim($request->get('link_name'));
        $insurer_no = trim($request->get('insurer_no'));
        $car_no = trim($request->get('car_no'));
        $status = $request->get('status',1);
        $is_express = $request->get('is_express',1);


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

//    var_dump($group_ids);

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

        $query = ExpressT::find()
            ->leftJoin(OrderT::tableName(), "order_t.id=express_t.order_id");
//            ->orderBy('order_t.print_date DESC');





        if ($id_man != "") {
            $query = $query->andWhere('express_t.link_name like "%' . $id_man . '%"');
        }
        if ($insurer_no != "") {
            $query = $query->andWhere('express_t.ems_no = "' . $insurer_no . '"');
        }

//        dd($car_no);
        if ($car_no != "") {
//            $car_row=CarT::find()->where(['car_no'=>$car_no])->select('id')->asArray()->all();
////            dd($car_row);
//            $arr2 = array();
//            foreach($car_row as $key => $val){
//                $arr2[] = $val['id'];
//            }
//            dd($arr2);
            $query = $query->andWhere('express_t.car_no = "' . $car_no . '"');
//            $query = $query->andWhere('caiwu_t2.insurer_no like "' . $insurer_no . '%"');
        }
        if($is_express!=""){
            $query=$query->andWhere(['is_express'=>$is_express]);
        }
        if ($status > 0) {
            if ($status == 1) {
                $query = $query->andWhere('r_date="" or r_date is null');
            }
            if ($status == 2) {
                $query = $query->andWhere('r_date<>"" and return_slip=0');
            }
            if($status == 3) {
                $query = $query->andWhere('r_date<>"" and return_slip<>0');
            }
        }
        if ($z_begin_date != "") {
            $query = $query->andWhere('express_t.original_date>="' . $z_begin_date . '"');
        }
        if ($z_end_date != "") {
            $query = $query->andWhere('express_t.original_date<="' . $z_end_date . '"');
        }
        if ($begin_date != "") {
            $query = $query->andWhere('express_t.send_date>="' . $begin_date . '"');
        }
        if ($end_date != "") {
            $query = $query->andWhere('express_t.send_date<="' . $end_date . '"');
        }
//        aa($query);
        $total = $query->count();
        //快递金额
        $sum_ems_price = $query->sum('ems_price');
        //回款金额
        $sum_r_price = $query->sum('r_price');
        //回款差额
        $sum_return_slip = $query->sum('return_slip');


//        $items = $query->all();
//        foreach($items as $value){
//           $car_data= CarT::findOne(['id'=>$value->car_id]);
//           $value->ems_company=0;
//            $value->save();
//        }
//        dd($items);
//        die;

        $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('ems-receipt', [
            'items' => $items,
            'page' => $page,
            'id_man' => $id_man,
            'insurer_no' => $insurer_no,
            'status' => $status,
            'begin_date' => $begin_date,
            'end_date' => $end_date,
            'z_begin_date' => $z_begin_date,
            'z_end_date' => $z_end_date,
            'page_info' => $page_info,
            'sum_ems_price' => $sum_ems_price,
            'sum_r_price' => $sum_r_price,
            'sum_return_slip' => $sum_return_slip,
            'car_no' => $car_no,
            'is_express' => $is_express,



        ]);
    }
    public function actionEmsReceiptOutput()
    {
        $request = Yii::$app->request;
        $page = $request->get('page', 1);
        $begin_date = $request->get('begin_date');
        $end_date = $request->get('end_date');
        $z_begin_date = $request->get('z_begin_date');
        $z_end_date = $request->get('z_end_date');
        $id_man = trim($request->get('link_name'));
        $insurer_no = trim($request->get('insurer_no'));
        $car_no = trim($request->get('car_no'));
        $status = $request->get('status',1);
        $is_express = $request->get('is_express',1);


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

//    var_dump($group_ids);

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

        $query = ExpressT::find()
            ->leftJoin(OrderT::tableName(), "order_t.id=express_t.order_id");
//            ->orderBy('order_t.print_date DESC');





        if ($id_man != "") {
            $query = $query->andWhere('express_t.link_name like "%' . $id_man . '%"');
        }
        if ($insurer_no != "") {
            $query = $query->andWhere('express_t.ems_no = "' . $insurer_no . '"');
        }

//        dd($car_no);
        if ($car_no != "") {
//            $car_row=CarT::find()->where(['car_no'=>$car_no])->select('id')->asArray()->all();
////            dd($car_row);
//            $arr2 = array();
//            foreach($car_row as $key => $val){
//                $arr2[] = $val['id'];
//            }
//            dd($arr2);
            $query = $query->andWhere('express_t.car_no = "' . $car_no . '"');
//            $query = $query->andWhere('caiwu_t2.insurer_no like "' . $insurer_no . '%"');
        }
        if($is_express!=""){
            $query=$query->andWhere(['is_express'=>$is_express]);
        }
        if ($status > 0) {
            if ($status == 1) {
                $query = $query->andWhere('r_date="" or r_date is null');
            }
            if ($status == 2) {
                $query = $query->andWhere('r_date<>"" and return_slip=0');
            }
            if($status == 3) {
                $query = $query->andWhere('r_date<>"" and return_slip<>0');
            }
        }
        if ($z_begin_date != "") {
            $query = $query->andWhere('express_t.original_date>="' . $z_begin_date . '"');
        }
        if ($z_end_date != "") {
            $query = $query->andWhere('express_t.original_date<="' . $z_end_date . '"');
        }
        if ($begin_date != "") {
            $query = $query->andWhere('express_t.send_date>="' . $begin_date . '"');
        }
        if ($end_date != "") {
            $query = $query->andWhere('express_t.send_date<="' . $end_date . '"');
        }
//        aa($query);
        $total = $query->count();
        //快递金额
        $sum_ems_price = $query->sum('ems_price');
        //回款金额
        $sum_r_price = $query->sum('r_price');
        //回款差额
        $sum_return_slip = $query->sum('return_slip');


//        foreach($items as $value){
//           $car_data= CarT::findOne(['id'=>$value->car_id]);
//           $value->car_no=$car_data->car_no;
//            $value->save();
//        }
//        dd($items);
//        die;


        $items = $query->all();

        $objectPHPExcel = new \PHPExcel();
        $index = 1;
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.$index,'车牌号');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('B'.$index,'收件人');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('C'.$index,'快递单号');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('D'.$index,'快递金额');




        foreach($query->each() as $item) {
            $index++;

//            $users=$item->user->group;
//            $username=$item->user;
//            $uname=$username['name'];
//            $nams=$users['name'];



            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.$index,$item->car_no);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('B'.$index,$item->link_name);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('C'.$index,$item->ems_no);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('D'.$index,$item->ems_price);

        }

        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition:attachment;filename="'.date("YmjHis").'.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objectPHPExcel, 'Excel5');
        $objWriter->save('php://output');



    }
    //地址修改
    public function actionEmsEditList()
    {
        $request = Yii::$app->request;
        $page = $request->get('page', 1);

        $id_man = trim($request->get('link_name'));
        $insurer_no = trim($request->get('insurer_no'));
        $car_no = trim($request->get('car_no'));
        $begin_date = $request->get('begin_date');
        $end_date = $request->get('end_date');
        $z_begin_date = $request->get('z_begin_date');
        $z_end_date = $request->get('z_end_date');



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

        $query = ExpressT::find()
            ->leftJoin(OrderT::tableName(), "order_t.id=express_t.order_id");
//            ->orderBy('order_t.print_date DESC');





        if ($id_man != "") {
            $query = $query->andWhere('express_t.link_name like "%' . $id_man . '%"');
        }
        if ($insurer_no != "") {
            $query = $query->andWhere('express_t.ems_no = "' . $insurer_no . '"');
        }

//        dd($car_no);
        if ($car_no != "") {

            $query = $query->andWhere('express_t.car_no = "' . $car_no . '"');
//            $query = $query->andWhere('caiwu_t2.insurer_no like "' . $insurer_no . '%"');
        }



//        aa($query);
        $total = $query->count();


//        foreach($items as $value){
//           $car_data= CarT::findOne(['id'=>$value->car_id]);
//           $value->car_no=$car_data->car_no;
//            $value->save();
//        }
//        dd($items);
//        die;

        $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('ems-receipt1', [
            'items' => $items,
            'page' => $page,
            'id_man' => $id_man,
            'insurer_no' => $insurer_no,
            'page_info' => $page_info,
            'car_no' => $car_no,
            'begin_date' => $begin_date,
            'end_date' => $end_date,
            'z_begin_date' => $z_begin_date,
            'z_end_date' => $z_end_date,

        ]);
    }

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

        $caiwu_info = ExpressT::findOne(['id' => $id]);


        return $this->render('ems-edit-info', [
            'caiwu_info' => $caiwu_info,
            'back_params' => $back_params,
        ]);
    }
    public function actionEmsEditSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '操作失败';

        $id = $request->post('id', 0);
        $ems_no = $request->post('ems_no');
        $physical_no = $request->post('physical_no');

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


        $caiwu_info = ExpressT::findOne(['id' => $id]);
        if ($caiwu_info) {
            $order_info = $caiwu_info->order;

            $caiwu_info->ems_no = $ems_no;
            $caiwu_info->physical_no = $physical_no;
            $caiwu_info->link_address = $link_address;
            $caiwu_info->send_date = date('Y-m-d');
//            $caiwu_info->total_clear_real = sprintf("%.2f",($caiwu_info->total_clear * $caiwu_info->total_rate/100));

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

    }
    public function actionNonReceipt()
    {
        $request = Yii::$app->request;
        $page = $request->get('page', 1);
        $begin_date = $request->get('begin_date');
        $end_date = $request->get('end_date');
        $r_begin_date = $request->get('r_begin_date');
        $r_end_date = $request->get('r_end_date');
        $id_man = trim($request->get('id_man'));
        $insurer_no = trim($request->get('insurer_no'));
        $status = $request->get('status',1);
        $sort_key = $request->get('sort_key');
        $sort_value = $request->get('sort_value');
        $company_id = $request->get('company_id');
        $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;
            }
        }
//    var_dump($group_ids);

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

        $query = CaiwuT2::find()
            ->leftJoin(OrderT::tableName(), "order_t.id=caiwu_t2.order_id");
//            ->orderBy('order_t.print_date DESC');

        switch ($sort_key) {
            case 'total':
                $sort = 'caiwu_t2.total ';
                break;
            case 'total_clear':
                $sort = 'caiwu_t2.total_clear ';
                break;
            case 'total_rate':
                $sort = 'caiwu_t.total_rate ';
                break;
            case 'print_date'://默认按照print_date排序
            default:
                $sort = 'order_t.print_date ';
                break;
        }

        switch ($sort_value) {
            case 'ASC':
                $sort .= 'ASC';
                break;
            case 'DESC':
            default:
                $sort .= 'DESC';
                break;
        }

        $query = $query->orderBy($sort);

        if( $company_id > 0) {
            $query = $query->andWhere('order_t.company_id='.$company_id);
        }

        if ($id_man != "") {
            $query = $query->andWhere('caiwu_t2.id_man like "%' . $id_man . '%"');
        }
        if ($insurer_no != "") {
            $query = $query->andWhere('caiwu_t2.insurer_no like "' . $insurer_no . '%"');
        }
        if ($status > 0) {
            if ($status == 1) {
                $query = $query->andWhere('r_date="" or r_date is null');
            }
            if ($status == 2) {
                $query = $query->andWhere('r_date<>"" and total_dis=0');
            }
            if($status == 3) {
                $query = $query->andWhere('r_date<>"" and total_dis<>0');
            }
        }
        if ($begin_date != "") {
            $query = $query->andWhere('order_t.print_date>="' . $begin_date . '"');
        }
        if ($end_date != "") {
            $query = $query->andWhere('order_t.print_date<="' . $end_date . '"');
        }
        if ($r_begin_date != "") {
            $query = $query->andWhere('caiwu_t2.r_date>="' . $r_begin_date . '"');
        }
        if ($r_end_date != "") {
            $query = $query->andWhere('caiwu_t2.r_date<="' . $r_end_date . '"');
        }

        //找出$group_id 有多少在职的user_ids
        //      现在的搜索条件
        $userSql = '';
//        if($username != '') {
//            $userSql = ' username like "'.$username.'" and ';
//        }
        //$userSql .= 'is_locked=0 and is_login=1';

        $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;
//            var_dump($user_info);
            if ($group_id > 0) {
                if (!in_array($user_info->group_id, $group_ids)) {
                    continue;
                }
            }

            $row[] = $user_info->id;

        }

//        var_dump($row);
        //加上级别筛选
        if($group_id > 0){
//            $query = $query->andWhere('order_t.company_id='.$company_id);
            $query = $query->andWhere(['in','caiwu_t2.user_id',$row]);
//            $query = $query->andWhere('caiwu_t.user_id ="' . $group_id . '"');
        }


//        echo $query->createCommand()->rawSql;
        $total = $query->count();

        $sum_r_total = $query->sum('r_total');
        //商业净保费综合


        //商业总保费
        $sum_total = $query->sum('total');

        $sum_total_dis = $query->sum('total_dis');

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

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

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


        return $this->render('non-receipt', [
            'items' => $items,
            'page' => $page,
            'id_man' => $id_man,
            'insurer_no' => $insurer_no,
            'status' => $status,
            'begin_date' => $begin_date,
            'end_date' => $end_date,
            'r_begin_date' => $r_begin_date,
            'r_end_date' => $r_end_date,
            'page_info' => $page_info,
            'sort_key' => $sort_key,
            'sort_value' => $sort_value,
            'sum_r_total' => $sum_r_total,
            'sum_total' => $sum_total,
            'sum_total_dis' => $sum_total_dis,

            'group_id' => $group_id,
            'group_items' => $group_items,
            'company_id' => $company_id
        ]);
    }
    public function actionReceiptDif()
    {
        $request = Yii::$app->request;
        $page = $request->get('page', 1);
        $begin_date = $request->get('begin_date');
        $end_date = $request->get('end_date');
        $r_begin_date = $request->get('r_begin_date');
        $r_end_date = $request->get('r_end_date');
        $car_no = trim($request->get('car_no'));
        $insurer_no = trim($request->get('insurer_no'));
        $status = $request->get('status',1);
        $sort_key = $request->get('sort_key');
        $sort_value = $request->get('sort_value');
        $company_id = $request->get('company_id');
        $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;
            }
        }
//    var_dump($group_ids);

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

        $query = CaiwuT1::find()
            ->leftJoin(OrderT::tableName(), "order_t.id=caiwu_t1.order_id");

//            ->orderBy('order_t.print_date DESC');

        switch ($sort_key) {
            case 'total':
                $sort = 'caiwu_t1.total ';
                break;
            case 'total_clear':
                $sort = 'caiwu_t1.total_clear ';
                break;
            case 'total_rate':
                $sort = 'caiwu_t1.total_rate ';
                break;
            case 'print_date'://默认按照print_date排序
            default:
                $sort = 'order_t.print_date ';
                break;
        }

        switch ($sort_value) {
            case 'ASC':
                $sort .= 'ASC';
                break;
            case 'DESC':
            default:
                $sort .= 'DESC';
                break;
        }

        $query = $query->orderBy($sort);
        if ($username != "") {
            $userdata = UserT::findOne(['username'=>$username]);
            if($userdata){
                $query = $query->andWhere('caiwu_t1.user_id = ' . $userdata->id . '');
            }
        }
        if( $company_id > 0) {
            $query = $query->andWhere('order_t.company_id='.$company_id);
        }
        if ($car_no != "") {
            $query = $query->andWhere('caiwu_t1.car_no like "%' . $car_no . '%"');
        }
        if ($insurer_no != "") {
            $query = $query->andWhere('caiwu_t1.insurer_no like "' . $insurer_no . '%"');
        }
        if ($status > 0) {
            if ($status == 1) {
                $query = $query->andWhere('r_date="" or r_date is null');
            }
            if ($status == 2) {
                $query = $query->andWhere('r_date<>"" and total_dis=0');
            }
            if($status == 3) {
                $query = $query->andWhere('r_date<>"" and total_dis<>0');
            }
        }
        if ($begin_date != "") {
            $query = $query->andWhere('order_t.print_date>="' . $begin_date . '"');
        }
        if ($end_date != "") {
            $query = $query->andWhere('order_t.print_date<="' . $end_date . '"');
        }
        if ($r_begin_date != "") {
            $query = $query->andWhere('caiwu_t1.r_date>="' . $r_begin_date . '"');
        }
        if ($r_end_date != "") {
            $query = $query->andWhere('caiwu_t1.r_date<="' . $r_end_date . '"');
        }
        //找出$group_id 有多少在职的user_ids
        //      现在的搜索条件
        $userSql = '';
//        if($username != '') {
//            $userSql = ' username like "'.$username.'" and ';
//        }
        //$userSql .= 'is_locked=0 and is_login=1';

        $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;
//            var_dump($user_info);
            if ($group_id > 0) {
                if (!in_array($user_info->group_id, $group_ids)) {
                    continue;
                }
            }

            $row[] = $user_info->id;

        }

//        var_dump($row);
        //加上级别筛选
        if($group_id > 0){
//            $query = $query->andWhere('order_t.company_id='.$company_id);
            $query = $query->andWhere(['in','caiwu_t1.user_id',$row]);
//            $query = $query->andWhere('caiwu_t.user_id ="' . $group_id . '"');
        }


//        echo $query->createCommand()->rawSql;
        $total = $query->count();

        $sum_r_total = $query->sum('r_total');
        //商业净保费综合
        $sum_total_clear = $query->sum('total_clear');

        //商业总保费
        $sum_total = $query->sum('total');

        $sum_total_dis = $query->sum('total_dis');

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

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

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

        $company_items = InsurerCompanyT::find()->all();

        return $this->render('receipt-dif', [
            'items' => $items,
            'username' => $username,
            'page' => $page,
            'car_no' => $car_no,
            'insurer_no' => $insurer_no,
            'status' => $status,
            'begin_date' => $begin_date,
            'end_date' => $end_date,
            'r_begin_date' => $r_begin_date,
            'r_end_date' => $r_end_date,
            'page_info' => $page_info,
            'sort_key' => $sort_key,
            'sort_value' => $sort_value,
            'sum_r_total' => $sum_r_total,
            'sum_total_clear' => $sum_total_clear,
            'sum_total' => $sum_total,
            'sum_total_dis' => $sum_total_dis,
            'company_items' => $company_items,
            'group_id' => $group_id,
            'group_items' => $group_items,
            'company_id' => $company_id
        ]);
    }
    public function actionReceiptAd()
    {
        $request = Yii::$app->request;
        $page = $request->get('page', 1);
        $begin_date = $request->get('begin_date');
        $end_date = $request->get('end_date');
        $status_id = $request->get('status_id');
        $payee_id = $request->get('payee_id');
        $payment_id = $request->get('payment_id');

        $car_no = trim($request->get('car_no'));
        $insurer_no = trim($request->get('insurer_no'));

        $sort_key = $request->get('sort_key');
        $sort_value = $request->get('sort_value');
        $company_id = $request->get('company_id');
        $account_status= $request->get('account_status');
        $hk_status= $request->get('hk_status');
        $sort_value = $request->get('sort_value');
        //级别
        $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;
            }
        }

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

        $query = OrderT::find()

//            ->orderBy('order_t.print_date DESC')
            ->leftJoin(InsurerCompanyT::tableName(), "insurer_company_t.id=order_t.company_id")
            ->Where('insurer_company_t.difc=2');

        switch ($sort_value) {
            case 'ASC':
                $sort = 'order_t.print_date ASC';
                break;
            case 'DESC':
            default:
                $sort = 'order_t.print_date DESC';
                break;
        }
        $query = $query->orderBy($sort);
        $query = $query->andWhere('status_id= 5');
//        if($status_id!=""){
//            $query = $query->andWhere('status_id='.$status_id);
//        }else{
//            $query = $query->andWhere('status_id= 5 or status_id= 10');
//        }
        //收款人是诚合的
        $query = $query->andWhere('payee_id=9');
//        if($payee_id != '') {
//            $query = $query->andWhere('payee_id="'.$payee_id.'"');
//        }
        if($payment_id != '') {
            $query = $query->andWhere('payment_id="'.$payment_id.'"');
        }
        if($account_status != '') {
            $query = $query->andWhere('account_status="'.$account_status.'"');
        }
        if($hk_status != '') {
            $query = $query->andWhere('hk_status="'.$hk_status.'"');
        }
        if( $company_id > 0) {
            $query = $query->andWhere('order_t.company_id='.$company_id);
        }
        if ($car_no != "") {
            $query = $query->andWhere('order_t.car_no like "%' . $car_no . '%"');
        }
        if ($insurer_no != "") {
            $query = $query->andWhere('order_t.insurer_no like "' . $insurer_no . '%"');
        }

        if ($begin_date != "") {
            $query = $query->andWhere('order_t.print_date>="' . $begin_date . '"');
        }
        if ($end_date != "") {
            $query = $query->andWhere('order_t.print_date<="' . $end_date . '"');
        }

        //找出$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('order_t.company_id='.$company_id);
            $query = $query->andWhere(['in','order_t.user_id',$row]);
//            $query = $query->andWhere('caiwu_t.user_id ="' . $group_id . '"');
        }

//        aa($query);
        $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);

        $company_items = InsurerCompanyT::find()
            ->where('difc=2')
            ->all();
        $payee_items=PayeeT::find()->all();
        $payment_items=Payment::find()->all();
        $sum_total2='';
        $sum_total3='';
//        round($item->total_clear * $caiwu->budian_rate/100,2)
        foreach($items as $item){
            $sum_total2+=$item->total1 * $item->total1_rate/100;
            $sum_total3+= $item->total2 * $item->total2_rate/100;
        }
        $sum_total = $query->sum('total1');
        $sum_total1 = $query->sum('total2');
        $sum_total6 = $query->sum('total1_clear');
        $sum_total7 = $query->sum('total2_clear');
//       var_dump($sum_total6);
//       var_dump($sum_total7);
        return $this->render('receipt-ad', [
            'items' => $items,
            'page' => $page,
            'car_no' => $car_no,
            'insurer_no' => $insurer_no,
            'status_id' => $status_id,
            'payee_items' => $payee_items,
            'payment_items' => $payment_items,
            'account_status' => $account_status,
            'hk_status' => $hk_status,
            'payee_id' => $payee_id,
            'payment_id' => $payment_id,
            'begin_date' => $begin_date,
            'end_date' => $end_date,
            'page_info' => $page_info,
            'sort_key' => $sort_key,
            'sort_value' => $sort_value,
            'company_items' => $company_items,
            'group_id' => $group_id,
            'group_items' => $group_items,
            'sum_total' => $sum_total,
            'sum_total1' => $sum_total1,
            'sum_total2' => $sum_total2,
            'sum_total3' => $sum_total3,
            'company_id' => $company_id
        ]);
    }
    public function actionReceiptAdOutput()
    {
        $request = Yii::$app->request;
        $page = $request->get('page', 1);
        $begin_date = $request->get('begin_date');
        $end_date = $request->get('end_date');
        $status_id = $request->get('status_id');
        $payee_id = $request->get('payee_id');
        $payment_id = $request->get('payment_id');

        $car_no = trim($request->get('car_no'));
        $insurer_no = trim($request->get('insurer_no'));

//        $sort_key = $request->get('sort_key');
        $sort_value = $request->get('sort_value');
        $company_id = $request->get('company_id');
        $account_status= $request->get('account_status');
        //级别
        $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;
            }
        }

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

        $query = OrderT::find()

//            ->orderBy('order_t.print_date DESC')
            ->leftJoin(InsurerCompanyT::tableName(), "insurer_company_t.id=order_t.company_id")
            ->Where('insurer_company_t.difc=2');
        switch ($sort_value) {
            case 'ASC':
                $sort = 'order_t.print_date ASC';
                break;
            case 'DESC':
            default:
                $sort = 'order_t.print_date DESC';
                break;
        }
        $query = $query->orderBy($sort);
        if($status_id!=""){
            $query = $query->andWhere('status_id='.$status_id);
        }else{
            $query = $query->andWhere('status_id= 5 or status_id= 10');
        }
        if($payee_id != '') {
            $query = $query->andWhere('payee_id="'.$payee_id.'"');
        }
        if($payment_id != '') {
            $query = $query->andWhere('payment_id="'.$payment_id.'"');
        }
        if($account_status != '') {
            $query = $query->andWhere('account_status="'.$account_status.'"');
        }
        if( $company_id > 0) {
            $query = $query->andWhere('order_t.company_id='.$company_id);
        }
        if ($car_no != "") {
            $query = $query->andWhere('order_t.car_no like "%' . $car_no . '%"');
        }
        if ($insurer_no != "") {
            $query = $query->andWhere('order_t.insurer_no like "' . $insurer_no . '%"');
        }

        if ($begin_date != "") {
            $query = $query->andWhere('order_t.print_date>="' . $begin_date . '"');
        }
        if ($end_date != "") {
            $query = $query->andWhere('order_t.print_date<="' . $end_date . '"');
        }

        //找出$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('order_t.company_id='.$company_id);
            $query = $query->andWhere(['in','order_t.user_id',$row]);
//            $query = $query->andWhere('caiwu_t.user_id ="' . $group_id . '"');
        }

//        aa($query);
        $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();

        $objectPHPExcel = new \PHPExcel();
        $index = 1;
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.$index,'车牌号');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('B'.$index,'被保险人');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('C'.$index,'保险公司');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('D'.$index,'级别');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('E'.$index,'生成状态');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('F'.$index,'支付方式');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('G'.$index,'收款人');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('H'.$index,'收款方式');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('I'.$index,'付款人');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('J'.$index,'商业保单号');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('K'.$index,'交强保单号');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('L'.$index,'收费时间');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('M'.$index,'出单日期');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('N'.$index,'商业总保费');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('O'.$index,'交强总保费');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('P'.$index,'商业手续费比例');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('Q'.$index,'交强手续费比例');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('R'.$index,'商业应得金额');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('S'.$index,'交强应得金额');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('T'.$index,'对账状态');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('U'.$index,'回款状态');



        foreach($query->each() as $item) {
            $index++;

            $users=$item->user->group;
            $username=$item->user;
            $uname=$username['name'];
            $nams=$users['name'];

            $total_real1 = $item->total1 * $item->total1_rate/100;
            $total_real2 = $item->total2 * $item->total2_rate/100;

            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.$index,$item->car_no);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('B'.$index,$item->id_man);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('C'.$index,$item && $item->company ? $item->company->name:'');
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('D'.$index,$uname.'-'.$nams);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('E'.$index,$item->status->name);

            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('F'.$index,$item->shoufei_id?MyLib::zhifufs($item->shoufei_id):''-$item->payType?$item->payType->name:'');
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('G'.$index,$item->payee_id?$item->payee->name:'');
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('H'.$index,$item->payment_id?$item->payment->name:'');
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('I'.$index,$item && $item->payer? MyLib::payers($item->payer):'');
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('J'.$index,$item->insurer1_no?$item->insurer1_no:'');
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('K'.$index,$item->insurer2_no?$item->insurer2_no:'');
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('L'.$index,$item ? $item->zhifu_date : '');
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('M'.$index,$item ? $item->print_date : '');
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('N'.$index,$item->total1);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('O'.$index,$item->total2);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('P'.$index,$item->total1_rate);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('Q'.$index,$item->total2_rate);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('R'.$index,sprintf("%.2f",$total_real1));
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('S'.$index,sprintf("%.2f",$total_real2));
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('T'.$index,$item->account_status?MyLib::duizhang($item->account_status):'');
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('U'.$index,$item->hk_status?MyLib::hkstatus($item->hk_status):'');
        }

        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition:attachment;filename="'.date("YmjHis").'.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objectPHPExcel, 'Excel5');
        $objWriter->save('php://output');

    }
    /**
     * 回单管理-详情
     * @return string
     */
    public function actionReceiptAdEdit()
    {
        $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;



        //礼品
        $gift_group_items = array();
        $gift_free_group_items = array();
        //获取礼品数据
        $sel_gifts = array();
        $tmp_items = OrderGiftT::find()
            ->where('order_id='.$order_info->id)
            ->all();
        foreach($tmp_items as $item) {
            $gift_info = $item->gift;
            if($gift_info->type == 1) {
                $gift_free_group_items[] = $gift_info;
            } else {
                $gift_group_items[] = $gift_info;
            }
            $sel_gifts[$item->group_id] = $item;
        }

        $gift_items = CarGiftT::find()
            ->where('order_id='.$order_info->id)
            ->orderBy('strategy_id DESC')
            ->all();

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

        $type_items = GiftType2T::find()->all();
        $payee_items=PayeeT::find()->all();
        return $this->render('receipt-ad-edit',[
            'car_info' => $car_info,
            'insurer_type_items' => $insurer_type_items,
            'payee_items' => $payee_items,
            'order_info' => $order_info,
            'insurer_company_items' => $insurer_company_items,
            'gift_items' => $gift_items,
            'back_params' => $back_params,
            'gift_group_items' => $gift_group_items,
            'gift_free_group_items' => $gift_free_group_items,
            'sel_gifts' => $sel_gifts,
            'type_items' => $type_items
        ]);
    }
    //针对保单号输入错误的 receipt-baodan.php
    public function actionReceiptAdEdit1()
    {
        $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;



        //礼品
        $gift_group_items = array();
        $gift_free_group_items = array();
        //获取礼品数据
        $sel_gifts = array();
        $tmp_items = OrderGiftT::find()
            ->where('order_id='.$order_info->id)
            ->all();
        foreach($tmp_items as $item) {
            $gift_info = $item->gift;
            if($gift_info->type == 1) {
                $gift_free_group_items[] = $gift_info;
            } else {
                $gift_group_items[] = $gift_info;
            }
            $sel_gifts[$item->group_id] = $item;
        }

        $gift_items = CarGiftT::find()
            ->where('order_id='.$order_info->id)
            ->orderBy('strategy_id DESC')
            ->all();

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

        $type_items = GiftType2T::find()->all();
        $payee_items=PayeeT::find()->all();
        return $this->render('receipt-baodan',[
            'car_info' => $car_info,
            'insurer_type_items' => $insurer_type_items,
            'payee_items' => $payee_items,
            'order_info' => $order_info,
            'insurer_company_items' => $insurer_company_items,
            'gift_items' => $gift_items,
//            'back_params' => $back_params,
            'gift_group_items' => $gift_group_items,
            'gift_free_group_items' => $gift_free_group_items,
            'sel_gifts' => $sel_gifts,
            'type_items' => $type_items
        ]);
    }
    /**
     * 回单管理-保存
     * @return array
     * @throws \Exception
     */
    public function actionReceiptAdBaocun()
    {
        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);
            $payee_id = $request->post('payee_id',0);
//            $huikuan= $request->post('huikuan');
            $account_status= $request->post('account_status');
//            dd($huikuan);

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

//                if($status_id == 10) {
//                    $order_info->hk_status=$huikuan;
//                }


                $order_info->payee_id = $payee_id;
                $order_info->account_status = $account_status;
//                dd($status_id);
                $this->addLog($order_info->car_id,'回单管理保存',1);

                $order_info->save();

                $result['success'] = true;
                $result['msg'] = '保存成功';
                $tran->commit();

            } catch(\Exception $e) {
                $tran->rollBack();
                throw $e;
            }
        }
        return $result;
    }
    /**
     * 回单管理-提交
     * @return array
     * @throws \Exception
     */
    public function actionReceiptAdSaveEd()
    {
       $data= CaiwuT1::find()->where('total_dis!=0')->all();
        foreach($data as $v){
            $v->total_dis=$v->total*$v->total_rate/100;
//            var_dump($v->total_dis);
            $v->save();
        }
//        var_dump($data);
    }
    public function actionReceiptAdSave()
    {
        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);
            $payee_id = $request->post('payee_id',0);
            $huikuan= $request->post('huikuan');
            $account_status= $request->post('account_status');
//            dd($huikuan);


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

                if($status_id != 10) {
                    if ($insurer1_no == '' && $insurer2_no == '') {
                        $result['msg'] = '没有商业或交强保单号不能提交';
                        return $result;
                    }
                }
                if($status_id !=10){
                    $result['msg'] = '正本未办结不能提交';
                    return $result;
                }
//                $old_status_id = $order_info->status_id;

                $order_info->payee_id = $payee_id;
                $order_info->account_status = $account_status;
//                dd($status_id);
                if($status_id == 10) {
//                    $order_info->op2_id = $this->my->id;
//                    $order_info->lock_id = 0;
//                    $order_info->print_date = date('Y-m-d');
                    if($huikuan ==''){
                        $result['msg'] = '手续费回款状态不能为空';
                        return $result;
                    }
                    $order_info->hk_status=$huikuan;
                    //财务处理
                    CaiwuT1::deleteAll(['order_id'=>$order_info->id]);

                    //商业
                    if($order_info->insurer1_no != '' && $order_info->total1_clear > 0) {
                        $row = null;
                        CaiwuT1::deleteAll('insurer_no="'.$order_info->insurer1_no.'"');
                        $row = new CaiwuT1();
                        $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->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->user_id = $order_info->user_id;
                        $row->status = 0;
                        $row->insurer_type = 1;
                        $row->order_id = $order_info->id;
                        if($huikuan==1){
                            $row->r_date ='';
                            $row->total_dis = sprintf("%.2f",($order_info->total1 * $order_info->total1_rate/100));
                        }else{
                            $row->r_date =date('Y-m-d');
                            $row->total_dis=0;
                            $row->r_total=sprintf("%.2f",($order_info->total1 * $order_info->total1_rate/100));
                        }

                        if(!$row->save()) {
                            var_dump($row->errors);
                            exit;
                        }
                    }

                    //交强
                    if($order_info->insurer2_no != '' && $order_info->total2_clear > 0) {
                        $row = null;
                        CaiwuT1::deleteAll('insurer_no="'.$order_info->insurer2_no.'"');
                        $row = new CaiwuT1();
                        $row->insurer_no = $order_info->insurer2_no;
                        $row->car_no = $order_info->car_no;
                        $row->factory_model = $order_info->car->factory_model;
                        $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->user_id = $order_info->user_id;
                        $row->status = 0;
                        $row->insurer_type = 2;
                        $row->order_id = $order_info->id;
                        if($huikuan==1){
                            $row->r_date ='';
                            $row->total_dis = sprintf("%.2f",($order_info->total2 * $order_info->total2_rate/100));
                        }else{
                            $row->r_date =date('Y-m-d');
                            $row->total_dis=0;
                            $row->r_total=sprintf("%.2f",($order_info->total2 * $order_info->total2_rate/100));
                        }
                        $row->save();
                    }
                    $this->addLog($order_info->car_id,'回单管理提交到回单匹配',1);

                }
                $order_info->save();

                $result['success'] = true;
                $result['msg'] = '提交成功';
                $tran->commit();

            } catch(\Exception $e) {
                $tran->rollBack();
                throw $e;
            }
        }
        return $result;
    }
    public function actionReceipt1()
    {
        return $this->render('receipt1', []);
    }
    public function actionWashData()
    {
        return $this->render('wash', []);
    }
    public function actionWashDataChejia()
    {
        return $this->render('wash-che', []);
    }
    //批量导入新车辆数据
    public function actionCarinfos()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '操作失败';
//        $company = $request->post('company', '');

        $web_path = Yii::$app->getBasePath() . '/../frontend/web';
        $filename = $web_path . $request->post('urlfile');
        $base_filename=$request->post('urlfile');

//        $file_path = \Yii::getAlias('@console').'/controllers/';
//
//        $base_filename=$this->mname;
//        $filename = $file_path.$base_filename;
//        if(file_exists($filename)) {
//            echo 'OK'."\r\n";
//        }
        $reader = new \PHPExcel_Reader_Excel2007();
        if(!$reader->canRead($filename)) {
            $reader = new \PHPExcel_Reader_Excel5();
            if(!$reader->canRead($filename)) {
                $errorMessage = "Can not read file.";
                echo $errorMessage;
                return;
            }
        }
        $excel = $reader->load($filename);
        $sheet = $excel->getSheet(0);
        $data = $sheet->toArray('', true, true);
        $total = count($data);

//        exit;
        $j = 0;
        $insert_total = 0;
        foreach($data as $index => $item) {
            $j++;
            if($j == 1) continue;

            flush();

            $car_no = sprintf("%s",$item[0]);
            $car_man = sprintf("%s",$item[1]);
            $factory_model = sprintf("%s",$item[2]);
            $engine_no = sprintf("%s",$item[3]);
            $car_frame_no = sprintf("%s",$item[4]);
            $register_date = sprintf("%s",$item[5]);
            $company = sprintf("%s",$item[6]);
            $insurer1_date = sprintf("%s",$item[7]);
            $insurer2_date = sprintf("%s",$item[7]);
            $id_man = sprintf("%s",$item[9]);
            $id_number = sprintf("%s",$item[10]);
            $car_no= trim($car_no);

//            if($car_no == '') {
////                echo "\r\n";
//                $car_no = '京xxxxxx';
////                continue;
//            }


//            $tmp_date = explode('-',$register_date);
//            $register_date = date('Y-m-d',strtotime('20'.$tmp_date[2].'-'.$tmp_date[0].'-'.$tmp_date[1].' 00:00:00'));
//            echo $register_date.'...';
//            echo $new_date.'...';
//            exit;
            //排除京牌xxx
//            CarT::find()->where('car_no= $car_no')
            $car_info = CarT::findOne(['car_no'=>$car_no]);
//            $car_c_info = CarCT::findOne(['id'=>$car_info->id]);
//            $car_d_info = CarDT::findOne(['id'=>$car_info->id]);
//            $car_w_info = CarInvalidT::findOne(['id'=>$car_info->id]);
//
//            if($car_c_info || $car_d_info || $car_w_info ){
//                continue;
//            }
            if(isset($car_info)) {

                $car_c_info = CarCT::findOne(['id'=>$car_info->id]);
                $car_d_info = CarDT::findOne(['id'=>$car_info->id]);
                $car_e_info = CarET::findOne(['id'=>$car_info->id]);
                if($car_c_info || $car_d_info || $car_e_info){
                    continue;
                }
                //原车牌更新
                $car_info->car_man = $car_man;
                $car_info->factory_model = $factory_model;
                $car_info->engine_no = $engine_no;
                $car_info->car_frame_no = $car_frame_no;
                $car_info->register_date = $register_date;
                $car_info->company = $company;
                $car_info->insurer1_date = $insurer1_date;
                $car_info->insurer2_date = $insurer2_date;
                $car_info->id_man = $id_man;
                $car_info->id_man_number = $id_number;
                $car_info->save();

                //为空的车牌新增
//                if($car_info->car_no!='京xxxxxx'){
//                    continue;
//                }
//                $car_info = new CarT();
//                $car_info->user_id = 0;
//                $car_info->car_use_id = 0;
//                $car_info->car_type_id = 0;
//                $car_info->car_no = $car_no;
//                $car_info->car_man = $car_man;
//                $car_info->factory_model = $factory_model;
//                $car_info->engine_no = $engine_no;
//                $car_info->car_frame_no = $car_frame_no;
//                $car_info->register_date = $register_date;
//                $car_info->company = $company;
//                $car_info->insurer1_date = $insurer1_date;
//                $car_info->insurer2_date = $insurer2_date;
//                $car_info->id_man = $id_man;
//                $car_info->id_number = $id_number;
//                $car_info->location = 1;
//                $car_info->is_track = 0;
//                $car_info->times = 1;
//                $car_info->invalid_flag = 0;
//                $car_info->invalid_id = 0;
//                if(!$car_info->save()) {
//                    var_dump($car_info->errors);
//                    exit;
//                }

            }else {
                //车架号查询
                $car_infos = CarT::findOne(['car_frame_no'=>$car_frame_no]);
                if($car_infos){
                    if($car_no == '') {
                        $car_no = '京xxxxxx';
                    }
                    $car_infos->car_no=$car_no;
                    $car_infos->car_man = $car_man;
                    $car_infos->factory_model = $factory_model;
                    $car_infos->engine_no = $engine_no;
                    $car_infos->car_frame_no = $car_frame_no;
                    $car_infos->register_date = $register_date;
                    $car_infos->company = $company;
                    $car_infos->insurer1_date = $insurer1_date;
                    $car_infos->insurer2_date = $insurer2_date;
                    $car_infos->id_man = $id_man;
                    $car_infos->id_man_number = $id_number;
                    $car_infos->save();
                }else{
                    $car_info = new CarT();
                    $car_info->user_id = 0;
                    $car_info->car_use_id = 0;
                    $car_info->car_type_id = 0;
                    if($car_no == '') {
                        $car_no = '京xxxxxx';
                    }
                    $car_info->car_no = $car_no;
                    $car_info->car_man = $car_man;
                    $car_info->factory_model = $factory_model;
                    $car_info->engine_no = $engine_no;
                    $car_info->car_frame_no = $car_frame_no;
                    $car_info->register_date = $register_date;
                    $car_info->company = $company;
                    $car_info->insurer1_date = $insurer1_date;
                    $car_info->insurer2_date = $insurer2_date;
                    $car_info->id_man = $id_man;
                    $car_info->id_man_number = $id_number;
                    $car_info->location = 1;
                    $car_info->is_track = 0;
                    $car_info->times = 1;
                    $car_info->invalid_flag = 0;
                    $car_info->invalid_id = 0;
                    if(!$car_info->save()) {
                        var_dump($car_info->errors);
                        exit;
                    }
                }

//                echo 'insert...'.$car_info->id.'...';
            }

            $insert_total++;
            echo "\r\n";
        }

        $total1=$total-1;
        $log = new ImportLogT();
        $log->filename = $base_filename;
        $log->total = $total1;
        $log->success = $insert_total;
        $log->success_rate = ($insert_total/$total1) * 100;
        $log->save();
        $result['success'] = true;
        $result['msg'] = '操作成功';


        return $result;
//        $end_time = time();
//        $total_time = $end_time - $begin_time;
//        $h = floor($total_time/3600);
//        $m = floor(($total_time - $h * 3600)/60);
//        $s = $total_time - $h * 3600 - $m * 60;
//        echo '花费时间: '.$h.'小时'.$m.'分钟'.$s.'秒';
//        echo "OK\r\n";



    }

    public function actionChuliPhone()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '操作失败';
//        $company = $request->post('company', '');

        $web_path = Yii::$app->getBasePath() . '/../frontend/web';
        $filename = $web_path . $request->post('urlfile1');
        $base_filename=$request->post('urlfile1');
//
//        $file_path = \Yii::getAlias('@console').'/controllers/';
//        $yearname='wash12.xlsx';
//        $filename = $file_path.$yearname;
//        $basename=$yearname;
//        $company = $request->post('company', '');
//
//        $web_path = Yii::$app->getBasePath() . '/../frontend/web';
//
//        $urlfile = $web_path . $request->post('urlfile');
//        if(file_exists($filename)) {
//            echo 'OK'."\r\n";
//        }
        //读取Excel 2007
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filename)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filename)) {
                $errorMessage = "Can not read file.";
                echo $errorMessage;
                return;
            }
        }
        $PHPExcel = $PHPReader->load($filename);
        $currentSheet = $PHPExcel->getSheet(0);

        $rowCount = $currentSheet->getHighestRow();
        //$data = $currentSheet->toArray('', true, true);
        //创建新的xlsx表
//        $objectPHPExcel = new \PHPExcel();
//        $index = 1;
        $insert_total = 0;
//        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.$index,'车牌号');
//        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('B'.$index,'车架号');
//        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('C'.$index,'发动机号');
//        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('D'.$index,'品牌车型');
//        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('E'.$index,'车主');
//        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('F'.$index,'证件号');
//        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('G'.$index,'联系方式');
//        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('H'.$index,'保险到期日');
//        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('I'.$index,'初登日期');
//        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('J'.$index,'标准初登日期');
//        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('K'.$index,'车牌号不匹配');

        for ($i = 1; $i <= $rowCount; $i++) {
//            echo $i.'/'.$rowCount."...";
            $cell = $currentSheet->getCellByColumnAndRow(0, $i);
            $cars= $cell->getValue();
//            var_dump($cars);
            $cell = $currentSheet->getCellByColumnAndRow(1, $i);
            $car_frame_no = $cell->getValue();//$data[$i][1];
//            var_dump($car_frame_no);
            $cell = $currentSheet->getCellByColumnAndRow(2, $i);
            $engine_no = $cell->getValue();//$data[$i][2];

            $cell = $currentSheet->getCellByColumnAndRow(3, $i);
            $factory_model = $cell->getValue();//$data[$i][3];
            $cell = $currentSheet->getCellByColumnAndRow(4, $i);
            $car_man = $cell->getValue();//$data[$i][4];
            $cell = $currentSheet->getCellByColumnAndRow(5, $i);
            $car_man_number = $cell->getValue();//$data[$i][5];
            $cell = $currentSheet->getCellByColumnAndRow(6, $i);
            $phone = $cell->getValue();//$data[$i][6];





            $cell = $currentSheet->getCellByColumnAndRow(7, $i);
            $insurer_date = $cell->getFormattedValue();
//            var_dump($insurer_date);


//            $insurer_date = \PHPExcel_Shared_Date::ExcelToPHP($cell->getValue());//$data[$i][7];
            $cell = $currentSheet->getCellByColumnAndRow(8, $i);
            $resgt='';
            $resgt1='';
            $register_date = $cell->getValue();//$data[$i][8];
            $car_info = CarT::findOne(['car_no'=>$cars]);

//            if($car_info){
//                $resgt=$car_info->register_date?$car_info->register_date:'';
//                $resgt1=$car_info->car_no?$car_info->car_no:'';
//                $insert_total++;
//            }
            if($car_info){

                if($car_info->phone!=''&& $phone!=$car_info->phone){
                    $car_info->phone1 =(string) $phone;
                }else{
                    $car_info->phone=(string)$phone;
                }



                $car_c_info = CarCT::findOne(['id'=>$car_info->id]);
                $car_d_info = CarDT::findOne(['id'=>$car_info->id]);
                $car_e_info = CarET::findOne(['id'=>$car_info->id]);

                if($car_c_info || $car_d_info || $car_e_info){
                    continue;
                }
                $car_info->save();
                $insert_total++;
            }

            if(!$car_info){
                $car_infos = CarT::findOne(['car_frame_no'=>$car_frame_no]);

                if($car_infos){
                    if($car_infos->phone!=''&& $phone!=$car_infos->phone){
                        $car_infos->phone1 =(string) $phone;
                    }else{
                        $car_infos->phone=$phone;
                    }
                    $car_infos->save();
                    $insert_total++;
                }
            }



//            var_dump($car_infos);
//            die;


//            $index++;
//            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.$index,$cars);
//            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('B'.$index,$car_frame_no);
//            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('C'.$index,$engine_no);
//            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('D'.$index,$factory_model);
//            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('E'.$index,$car_man);
//            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('F'.$index,$car_man_number);
//            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('G'.$index,$phone);
//            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('H'.$index,$insurer_date);
//            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('I'.$index,$register_date);
//            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('J'.$index,$resgt?$resgt:'');
//            if(!$car_info){
//                $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('K'.$index,$resgt1?$resgt1:'');
//            }
//    die;


//            if($insurer_no == 'PDAA201811010000089441') {
//            echo $insurer_no.'='.$policy_man.'='.$total_real.'='.$total_rate.'=';
//            echo $pay_total.'='.$insurer_total.'='.date('Y-m-d',$insurer_date).'='.$car_no."\r\n";
//            exit;
//            }
//            $row = CaiwuT::findOne(['car_no' => $car_no, 'insurer_no' => $insurer_no]);
//            die;
//            $row = CaiwuT::findOne(['insurer_no' => $insurer_no]);
//            var_dump($row);
//            die;
//            if ($row) {
//                CaiwuErrorT::deleteAll(['insurer_no' => $insurer_no]);

//            echo $insurer_no.'='.$policy_man.'='.$total_real.'='.$total_rate.'=';
//            echo $pay_total.'='.$insurer_total.'='.date('Y-m-d',$insurer_date).'='.$car_no."\r\n";

//                $row->r_total = $insurer_total;
//                $row->r_date = $insurer_date;
//                $row->company = $company;
//                $row->total_dis = round((($row->total_clear * $row->total_rate / 100) - $insurer_total), 2);
//                if (!$row->save()) {
//                    var_dump($row->errors);
//                    exit;
//                }
//            } else {
//                CaiwuErrorT::deleteAll(['insurer_no' => $insurer_no]);
//                $tmp_row = new CaiwuErrorT();
//                $tmp_row->car_no = $car_no;
//                $tmp_row->insurer_no = $insurer_no;
//                $tmp_row->policy_man = $policy_man;
//                $tmp_row->total_real = $total_real;
//                $tmp_row->total_rate = $total_rate;
//                $tmp_row->pay_total = $pay_total;
//                $tmp_row->finish_total = $insurer_total;
//                $tmp_row->pay_date = $insurer_date;
//                $tmp_row->company = $company;
//                $tmp_row->save();
//            }
        }
//        die;
//        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
//        die;
//        header('Content-Disposition:attachment;filename="'.date("YmjHis").'.xls"');
//        header('Cache-Control: max-age=0');
//        $objWriter = \PHPExcel_IOFactory::createWriter($objectPHPExcel, 'Excel2007');
//        $objWriter->save('simple6.xlsx');
//        $result['success'] = true;
//        $result['msg'] = '操作成功';
        $log = new ImportLogT();
        $datacount=$rowCount;
        $log->filename = $base_filename;
        $log->total = $datacount;
        $log->success = $insert_total;
        $log->success_rate = ($insert_total/$datacount) * 100;
        $log->save();

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

        return $result;
//        $end_time = time();
//        $total_time = $end_time - $begin_time;
//        $h = floor($total_time/3600);
//        $m = floor(($total_time - $h * 3600)/60);
//        $s = $total_time - $h * 3600 - $m * 60;
//        echo '花费时间: '.$h.'小时'.$m.'分钟'.$s.'秒';
//        echo "OK\r\n";
//        return $result;
    }

    public function actionChuliChejiaPhone()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '操作失败';
//        $company = $request->post('company', '');

        $web_path = Yii::$app->getBasePath() . '/../frontend/web';
        $filename = $web_path . $request->post('urlfile1');
        $base_filename=$request->post('urlfile1');
//

        //读取Excel 2007
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filename)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filename)) {
                $errorMessage = "Can not read file.";
                echo $errorMessage;
                return;
            }
        }
        $PHPExcel = $PHPReader->load($filename);
        $currentSheet = $PHPExcel->getSheet(0);

        $rowCount = $currentSheet->getHighestRow();
        //$data = $currentSheet->toArray('', true, true);
        //创建新的xlsx表
//        $objectPHPExcel = new \PHPExcel();
//        $index = 1;
        $insert_total = 0;

        for ($i = 2; $i <= $rowCount; $i++) {
//            echo $i.'/'.$rowCount."...";
//            if($i=1) continue;
            $cell = $currentSheet->getCellByColumnAndRow(0, $i);
//            $cars= $cell->getValue();
            $car_frame_no = $cell->getValue();//$data[$i][2];
//            dd($car_frame_no);
            $car_frame_no=$car_frame_no;
//            var_dump($cars);
            $cell = $currentSheet->getCellByColumnAndRow(1, $i);
            $phone = $cell->getValue();
//            $car_frame_no = $cell->getValue();//$data[$i][1];
//            var_dump($car_frame_no);
            $cell = $currentSheet->getCellByColumnAndRow(2, $i);
//            $car_frame_no = $cell->getValue();//$data[$i][2];

            $cell = $currentSheet->getCellByColumnAndRow(3, $i);
//            $phone = $cell->getValue();//$data[$i][3];







            $resgt='';
            $resgt1='';
            $register_date = $cell->getValue();//$data[$i][8];




            $car_infos = CarT::findOne(['car_frame_no'=>$car_frame_no]);


            if($car_infos){
                if($car_infos->phone!=''&& $phone!=$car_infos->phone){
                    $car_infos->phone1 =(string) $phone;
                }else{
                    $car_infos->phone=(string)$phone;
//                        echo 23;
                }
//                    die;
                $car_infos->save();
                $insert_total++;
            }



        }

        $log = new ImportLogT();
        $datacount=$rowCount;
        $log->filename = $base_filename;
        $log->total = $datacount;
        $log->success = $insert_total;
        $log->success_rate = ($insert_total/$datacount) * 100;
        $log->save();

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

        return $result;
//        $end_time = time();
//        $total_time = $end_time - $begin_time;
//        $h = floor($total_time/3600);
//        $m = floor(($total_time - $h * 3600)/60);
//        $s = $total_time - $h * 3600 - $m * 60;
//        echo '花费时间: '.$h.'小时'.$m.'分钟'.$s.'秒';
//        echo "OK\r\n";
//        return $result;
    }
    public function actionReceipt3()
    {
        $request = Yii::$app->request;
        $page = $request->get('page', 1);
        $year = $request->get('year');
        $month = $request->get('month');
        if ($page < 1) $page = 1;

        $query = CarT::find()->where("insurer1_date is null or insurer1_date='0000-00-00' or insurer1_date='1970-01-01'")
            ->andWhere('car_no like "京%"')
            ->select('id,register_date,insurer1_date,car_no');
        if($year != '') {
            $query = $query->andWhere('year(register_date)="'.$year.'"');
        }
        if($month != '') {
            $query = $query->andWhere('month(register_date)="'.$month.'"');
        }
        $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;
        $page_info = MyLib::getPageInfo($pagination);
        return $this->render('receipt3', [
            'items' => $items,
            'page' => $page,
            'total' => $total,
            'page_info' => $page_info,
            'year' => $year,
            'month' => $month,
        ]);
    }
    public function actionReceipt4()
    {
        $request = Yii::$app->request;
        $page = $request->get('page', 1);
        $year = $request->get('year');
        $month = $request->get('month');
        if ($page < 1) $page = 1;
//        where (`car_no` REGEXP '[^0-9.]')=0 and (register_date>="2016-01-01") AND (register_date<="2016-12-31") and length(car_frame_no)=17
        $query = CarT::find()->where("register_date>='2016-01-01' and register_date<='2016-4-28'")
//            ->andWhere(['REGEXP', 'car_no', $this->title_name])
//            ->andWhere('(car_no REGEXP "[^0-9.]")=0 ')
            ->andWhere('length(car_frame_no)=17 ')

            ->select('id,register_date,car_frame_no,engine_no,car_no')->groupBy('car_frame_no HAVING COUNT(*) > 1')
            ->orderBy('car_frame_no desc');

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

        $query = $query->offset($pagination->offset)->limit($pagination->limit);
        $items = $query->all();
//        aa($query);
//        foreach($items as $value){
//            if(is_numeric($value->car_no)){
//                if($value->location==3 || $value->location==4 || $value->location==6){
//                    continue;
//                }
////                $value->delete();
////                echo $value->car_no;
//
//
//            }
//        }


//        echo $query->createCommand()->rawSql;
        $page_info = MyLib::getPageInfo($pagination);
        return $this->render('receipt4', [
            'items' => $items,
            'page' => $page,
            'total' => $total,
            'page_info' => $page_info,
            'year' => $year,
            'month' => $month,
        ]);
    }
    public function actionReceiptOutput()
    {
        $request = Yii::$app->request;
        $page = $request->get('page', 1);
        $begin_date = $request->get('begin_date');
        $end_date = $request->get('end_date');
        $r_begin_date = $request->get('r_begin_date');
        $r_end_date = $request->get('r_end_date');
        $car_no = trim($request->get('car_no'));
        $insurer_no = trim($request->get('insurer_no'));
        $status = $request->get('status');
        $sort_key = $request->get('sort_key');
        $sort_value = $request->get('sort_value');
        $company_id = $request->get('company_id');
        //级别
        $group_id = $request->get('group_id');
        $group_items = GroupT::getTree((int)$this->my->group_id);

        if($this->my->id == 1 || $this->my->username=='6002'|| $this->my->username == '7053')
            $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;
            }
        }
        if ($page < 1) $page = 1;

        $query = CaiwuT::find()
            ->leftJoin(OrderT::tableName(), "order_t.id=caiwu_t.order_id");
//            ->orderBy('order_t.print_date DESC');

        switch ($sort_key) {
            case 'total':
                $sort = 'caiwu_t.total ';
                break;
            case 'total_clear':
                $sort = 'caiwu_t.total_clear ';
                break;
            case 'total_rate':
                $sort = 'caiwu_t.total_rate ';
                break;
            case 'print_date'://默认按照print_date排序
            default:
                $sort = 'order_t.print_date ';
                break;
        }

        switch ($sort_value) {
            case 'ASC':
                $sort .= 'ASC';
                break;
            case 'DESC':
            default:
                $sort .= 'DESC';
                break;
        }

        $query = $query->orderBy($sort);

        if( $company_id > 0) {
            $query = $query->andWhere('order_t.company_id='.$company_id);
        }
        if ($car_no != "") {
            $query = $query->andWhere('caiwu_t.car_no like "' . $car_no . '%"');
        }
        if ($insurer_no != "") {
            $query = $query->andWhere('caiwu_t.insurer_no like "' . $insurer_no . '%"');
        }
        if ($status > 0) {
            if ($status == 1) {
                $query = $query->andWhere('r_date="" or r_date is null');
            }
            if ($status == 2) {
                $query = $query->andWhere('r_date<>"" and total_dis=0');
            }
            if($status == 3) {
                $query = $query->andWhere('r_date<>"" and total_dis<>0');
            }
        }
        if ($begin_date != "") {
            $query = $query->andWhere('order_t.print_date>="' . $begin_date . '"');
        }
        if ($end_date != "") {
            $query = $query->andWhere('order_t.print_date<="' . $end_date . '"');
        }
        if ($r_begin_date != "") {
            $query = $query->andWhere('caiwu_t.r_date>="' . $r_begin_date . '"');
        }
        if ($r_end_date != "") {
            $query = $query->andWhere('caiwu_t.r_date<="' . $r_end_date . '"');
        }
        $userSql = '';


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

        if($this->my->username == '6002'|| $this->my->username == '7053')
            $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;

        }

//        var_dump($row);
        //加上级别筛选
        if($group_id > 0){

            $query = $query->andWhere(['in','caiwu_t.user_id',$row]);
//            $query = $query->andWhere('caiwu_t.user_id ="' . $group_id . '"');
        }
        $total = $query->count();

        $sum_r_total = $query->sum('r_total');
        //商业净保费综合
        $sum_total_clear = $query->sum('total_clear');

        //商业总保费
        $sum_total = $query->sum('total');

        $sum_total_dis = $query->sum('total_dis');

        $items = $query->all();

        $objectPHPExcel = new \PHPExcel();
        $index = 1;
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.$index,'车牌号');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('B'.$index,'被保险人');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('C'.$index,'保险公司');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('D'.$index,'级别');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('E'.$index,'付款人');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('F'.$index,'保单号');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('G'.$index,'提单日期');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('H'.$index,'出单日期');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('I'.$index,'商业总保费');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('J'.$index,'商业净保费');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('K'.$index,'手续费比例');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('L'.$index,'应得金额');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('M'.$index,'实得金额');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('N'.$index,'税差');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('O'.$index,'回款金额');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('P'.$index,'回款差额');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('Q'.$index,'回款日期');

        foreach($query->each() as $item) {
            $index++;
            $order = $item->order;
            $total_real = $item->total * $item->total_rate/100;
            $total_clear_real = $item->total_clear * $item->total_rate/100;
            $users=$item->user?$item->user->group:'';
            $username=$item->user?$item->user:'';
            $uname=$username?$username['name']:'';
            $nams=$username?$users['name']:'';

            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.$index,$item->car_no);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('B'.$index,$item->id_man);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('C'.$index,$order && $order->company ? $order->company->name:'');
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('D'.$index,$uname.'-'.$nams);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('E'.$index,$order && $order->payer? MyLib::payers($order->payer):'');
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('F'.$index,$item->insurer_no);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('G'.$index,($order ? $order->submit_date : ''));
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('H'.$index,($order ? $order->print_date : ''));
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('I'.$index,$item->total);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('J'.$index,$item->total_clear);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('K'.$index,$item->total_rate);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('L'.$index,sprintf("%.2f",$total_real));
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('M'.$index,sprintf("%.2f",$total_clear_real));
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('N'.$index,sprintf("%.2f",$total_real - $total_clear_real));
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('O'.$index,$item->r_total);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('P'.$index,$item->total_dis);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('Q'.$index,$item->r_date);
        }

        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition:attachment;filename="'.date("YmjHis").'.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objectPHPExcel, 'Excel5');
        $objWriter->save('php://output');
    }
    public function actionNonReceiptOutput()
    {
        $request = Yii::$app->request;
        $page = $request->get('page', 1);
        $begin_date = $request->get('begin_date');
        $end_date = $request->get('end_date');
        $r_begin_date = $request->get('r_begin_date');
        $r_end_date = $request->get('r_end_date');
        $id_man = trim($request->get('id_man'));
        $insurer_no = trim($request->get('insurer_no'));
        $status = $request->get('status',1);
        $sort_key = $request->get('sort_key');
        $sort_value = $request->get('sort_value');
        $company_id = $request->get('company_id');
        $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;
            }
        }
//    var_dump($group_ids);

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

        $query = CaiwuT2::find()
            ->leftJoin(OrderT::tableName(), "order_t.id=caiwu_t2.order_id");
//            ->orderBy('order_t.print_date DESC');

        switch ($sort_key) {
            case 'total':
                $sort = 'caiwu_t2.total ';
                break;
            case 'total_clear':
                $sort = 'caiwu_t2.total_clear ';
                break;
            case 'total_rate':
                $sort = 'caiwu_t.total_rate ';
                break;
            case 'print_date'://默认按照print_date排序
            default:
                $sort = 'order_t.print_date ';
                break;
        }

        switch ($sort_value) {
            case 'ASC':
                $sort .= 'ASC';
                break;
            case 'DESC':
            default:
                $sort .= 'DESC';
                break;
        }

        $query = $query->orderBy($sort);

        if( $company_id > 0) {
            $query = $query->andWhere('order_t.company_id='.$company_id);
        }

        if ($id_man != "") {
            $query = $query->andWhere('caiwu_t2.id_man like "%' . $id_man . '%"');
        }
        if ($insurer_no != "") {
            $query = $query->andWhere('caiwu_t2.insurer_no like "' . $insurer_no . '%"');
        }
        if ($status > 0) {
            if ($status == 1) {
                $query = $query->andWhere('r_date="" or r_date is null');
            }
            if ($status == 2) {
                $query = $query->andWhere('r_date<>"" and total_dis=0');
            }
            if($status == 3) {
                $query = $query->andWhere('r_date<>"" and total_dis<>0');
            }
        }
        if ($begin_date != "") {
            $query = $query->andWhere('order_t.print_date>="' . $begin_date . '"');
        }
        if ($end_date != "") {
            $query = $query->andWhere('order_t.print_date<="' . $end_date . '"');
        }
        if ($r_begin_date != "") {
            $query = $query->andWhere('caiwu_t2.r_date>="' . $r_begin_date . '"');
        }
        if ($r_end_date != "") {
            $query = $query->andWhere('caiwu_t2.r_date<="' . $r_end_date . '"');
        }

        //找出$group_id 有多少在职的user_ids
        //      现在的搜索条件
        $userSql = '';
//        if($username != '') {
//            $userSql = ' username like "'.$username.'" and ';
//        }
        //$userSql .= 'is_locked=0 and is_login=1';

        $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;
//            var_dump($user_info);
            if ($group_id > 0) {
                if (!in_array($user_info->group_id, $group_ids)) {
                    continue;
                }
            }

            $row[] = $user_info->id;

        }

//        var_dump($row);
        //加上级别筛选
        if($group_id > 0){
//            $query = $query->andWhere('order_t.company_id='.$company_id);
            $query = $query->andWhere(['in','caiwu_t2.user_id',$row]);
//            $query = $query->andWhere('caiwu_t.user_id ="' . $group_id . '"');
        }


//        echo $query->createCommand()->rawSql;
        $total = $query->count();

        $sum_r_total = $query->sum('r_total');
        //商业净保费综合


        //商业总保费
        $sum_total = $query->sum('total');

        $sum_total_dis = $query->sum('total_dis');


        $items = $query->all();
        $objectPHPExcel = new \PHPExcel();
        $index = 1;
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.$index,'被保险人');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('B'.$index,'保单号');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('C'.$index,'保险公司');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('D'.$index,'级别');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('E'.$index,'提单日期');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('F'.$index,'出单日期');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('G'.$index,'起保日期');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('H'.$index,'终保日期');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('I'.$index,'总保费');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('J'.$index,'手续费比例');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('K'.$index,'应得金额');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('L'.$index,'回款金额');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('M'.$index,'回款差额');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('N'.$index,'回款日期');

        foreach($query->each() as $item) {
            $index++;
            $order = $item->order;
            $users=$item->user->group;
            $username=$item->user;
            $uname=$username['name'];
            $nams=$users['name'];

            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.$index,$item->id_man);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('B'.$index,$item->insurer_no);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('C'.$index,'人保');
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('D'.$index,$uname.'-'.$nams);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('E'.$index,$order ? $order->submit_date : '');
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('F'.$index,$order ? $order->print_date : '');
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('G'.$index,($order ? $order->insurer_date_start : ''));
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('H'.$index,($order ? $order->insurer_date_end : ''));
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('I'.$index,$item->total);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('J'.$index,$item->total_rate);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('K'.$index,$item->total_real);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('L'.$index,$item->r_total);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('M'.$index,$item->total_dis);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('N'.$index,$item->r_date);

        }

        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition:attachment;filename="'.date("YmjHis").'.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objectPHPExcel, 'Excel5');
        $objWriter->save('php://output');


    }
    public function actionReceiptOutput1()
    {
        $request = Yii::$app->request;
        $page = $request->get('page', 1);
        $begin_date = $request->get('begin_date');
        $end_date = $request->get('end_date');
        $r_begin_date = $request->get('r_begin_date');
        $r_end_date = $request->get('r_end_date');
        $car_no = trim($request->get('car_no'));
        $insurer_no = trim($request->get('insurer_no'));
        $status = $request->get('status');
        $sort_key = $request->get('sort_key');
        $sort_value = $request->get('sort_value');
        $company_id = $request->get('company_id');
        //级别
        $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;
            }
        }
        if ($page < 1) $page = 1;

        $query = CaiwuT1::find()
            ->leftJoin(OrderT::tableName(), "order_t.id=caiwu_t1.order_id");
//            ->orderBy('order_t.print_date DESC');

        switch ($sort_key) {
            case 'total':
                $sort = 'caiwu_t1.total ';
                break;
            case 'total_clear':
                $sort = 'caiwu_t1.total_clear ';
                break;
            case 'total_rate':
                $sort = 'caiwu_t1.total_rate ';
                break;
            case 'print_date'://默认按照print_date排序
            default:
                $sort = 'order_t.print_date ';
                break;
        }

        switch ($sort_value) {
            case 'ASC':
                $sort .= 'ASC';
                break;
            case 'DESC':
            default:
                $sort .= 'DESC';
                break;
        }

        $query = $query->orderBy($sort);

        if( $company_id > 0) {
            $query = $query->andWhere('order_t.company_id='.$company_id);
        }
        if ($car_no != "") {
            $query = $query->andWhere('caiwu_t1.car_no like "' . $car_no . '%"');
        }
        if ($insurer_no != "") {
            $query = $query->andWhere('caiwu_t1.insurer_no like "' . $insurer_no . '%"');
        }
        if ($status > 0) {
            if ($status == 1) {
                $query = $query->andWhere('r_date="" or r_date is null');
            }
            if ($status == 2) {
                $query = $query->andWhere('r_date<>"" and total_dis=0');
            }
            if($status == 3) {
                $query = $query->andWhere('r_date<>"" and total_dis<>0');
            }
        }
        if ($begin_date != "") {
            $query = $query->andWhere('order_t.print_date>="' . $begin_date . '"');
        }
        if ($end_date != "") {
            $query = $query->andWhere('order_t.print_date<="' . $end_date . '"');
        }
        if ($r_begin_date != "") {
            $query = $query->andWhere('caiwu_t1.r_date>="' . $r_begin_date . '"');
        }
        if ($r_end_date != "") {
            $query = $query->andWhere('caiwu_t1.r_date<="' . $r_end_date . '"');
        }
        $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;

        }

//        var_dump($row);
        //加上级别筛选
        if($group_id > 0){

            $query = $query->andWhere(['in','caiwu_t1.user_id',$row]);
//            $query = $query->andWhere('caiwu_t.user_id ="' . $group_id . '"');
        }
        $total = $query->count();

        $sum_r_total = $query->sum('r_total');
        //商业净保费综合
        $sum_total_clear = $query->sum('total_clear');

        //商业总保费
        $sum_total = $query->sum('total');

        $sum_total_dis = $query->sum('total_dis');

        $items = $query->all();

        $objectPHPExcel = new \PHPExcel();
        $index = 1;
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.$index,'车牌号');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('B'.$index,'被保险人');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('C'.$index,'保险公司');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('D'.$index,'级别');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('E'.$index,'付款人');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('F'.$index,'保单号');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('G'.$index,'提单日期');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('H'.$index,'出单日期');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('I'.$index,'商业总保费');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('J'.$index,'商业净保费');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('K'.$index,'手续费比例');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('L'.$index,'应得金额');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('M'.$index,'实得金额');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('N'.$index,'税差');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('O'.$index,'回款金额');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('P'.$index,'回款差额');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('Q'.$index,'回款日期');

        foreach($query->each() as $item) {
            $index++;
            $order = $item->order;
            $total_real = $item->total * $item->total_rate/100;
            $total_clear_real = $item->total_clear * $item->total_rate/100;
            $users=$item->user->group;
            $username=$item->user;
            $uname=$username['name'];
            $nams=$users['name'];

            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.$index,$item->car_no);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('B'.$index,$item->id_man);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('C'.$index,$order && $order->company ? $order->company->name:'');
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('D'.$index,$uname.'-'.$nams);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('E'.$index,$order && $order->payer? MyLib::payers($order->payer):'');
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('F'.$index,$item->insurer_no);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('G'.$index,($order ? $order->submit_date : ''));
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('H'.$index,($order ? $order->print_date : ''));
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('I'.$index,$item->total);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('J'.$index,$item->total_clear);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('K'.$index,$item->total_rate);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('L'.$index,sprintf("%.2f",$total_real));
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('M'.$index,sprintf("%.2f",$total_clear_real));
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('N'.$index,sprintf("%.2f",$total_real - $total_clear_real));
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('O'.$index,$item->r_total);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('P'.$index,$item->total_dis);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('Q'.$index,$item->r_date);
        }

        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition:attachment;filename="'.date("YmjHis").'.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objectPHPExcel, 'Excel5');
        $objWriter->save('php://output');
    }
    public function actionReceipt3Output()
    {
        $request = Yii::$app->request;
        $page = $request->get('page', 1);
        $year = $request->get('year');
        $month = $request->get('month');
        if ($page < 1) $page = 1;

        $query = CarT::find()->where("insurer1_date is null or insurer1_date='0000-00-00' or insurer1_date='1970-01-01'")
            ->andWhere('car_no like "京%"')
            ->select('id,register_date,insurer1_date,car_no');
        if($year != '') {
            $query = $query->andWhere('year(register_date)="'.$year.'"');
        }
        if($month != '') {
            $query = $query->andWhere('month(register_date)="'.$month.'"');
        }
        $total = $query->count();


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


        $items = $query->all();
        $objectPHPExcel = new \PHPExcel();
        $index = 1;
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.$index,'车牌号');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('B'.$index,'初登日期');



        foreach($query->each() as $item) {
            $index++;

            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.$index,$item->car_no);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('B'.$index,$item->register_date);


        }

        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition:attachment;filename="'.date("YmjHis").'.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objectPHPExcel, 'Excel5');
        $objWriter->save('php://output');


    }

    public function actionUploadPdf()
    {
        Yii::$app->response->format = Response::FORMAT_RAW;
        $result = array();
        $result['success'] = false;

        $file = UploadedFile::getInstanceByName('file');
        if (!empty($file) ) {
            $name = md5(rand(100, 200));
//            dd($name);
            $ext = $file->extension;
//            dd($ext);
            if($ext!='pdf'){
                $result['files'][0]['error'] = '上传格式文件不是pdf文件';
                return json_encode($result);
            }
            $filename = $name.date('Ymdhis') . '.' . $ext;
//            dd($filename);
            $destination = '/upload';
            $web_path = Yii::$app->getBasePath() . '/../frontend/web';
            if (!is_dir($web_path . $destination)) {
                mkdir($web_path . $destination);
            }
            $destination .= '/files';
            if (!is_dir($web_path . $destination))
                mkdir($web_path . $destination);
            $destination .= '/' . date('Ym');
            if (!is_dir($web_path . $destination))
                mkdir($web_path . $destination);
            $destination .= '/sy';
            if (!is_dir($web_path . $destination))
                mkdir($web_path . $destination);
            $destination .= '/' . $filename;

            $src='/' . date('Ym').'/sy'.'/' . $filename;
            $file->saveAs($web_path . $destination);

            $row['name'] = $file->baseName;
            $row['size'] = $file->size;
            $row['url'] = $destination;
            $row['src'] = $src;
            $row['thumbnailUrl'] = $destination;
            $row['deleteUrl'] = '';
            $row['deleteType'] = 'DELETE';
            $result['success'] = true;
            $result['files'][] = $row;
            return json_encode($result);
        }
        $result['files'][0]['error'] = '上传文件失败';

        return json_encode($result);
    }
    public function actionUploadPdf1()
    {
        Yii::$app->response->format = Response::FORMAT_RAW;
        $result = array();
        $result['success'] = false;
        $file = UploadedFile::getInstanceByName('file1');
        if (!empty($file) ) {
            $name = md5(rand(100, 200));
//            dd($name);
            $ext = $file->extension;
//            dd($ext);
            if($ext!='pdf'){
                $result['files'][0]['error'] = '上传格式文件不是pdf文件';
                return json_encode($result);
            }
            $filename =$name.date('Ymdhis') . '.' . $ext;
            $destination = '/upload';
            $web_path = Yii::$app->getBasePath() . '/../frontend/web';
            if (!is_dir($web_path . $destination)) {
                mkdir($web_path . $destination);
            }
            $destination .= '/files';
            if (!is_dir($web_path . $destination))
                mkdir($web_path . $destination);
            $destination .= '/' . date('Ym');
            if (!is_dir($web_path . $destination))
                mkdir($web_path . $destination);
            $destination .= '/jq';
            if (!is_dir($web_path . $destination))
                mkdir($web_path . $destination);
            $destination .= '/' . $filename;

            $src='/' . date('Ym').'/jq'.'/' . $filename;
            $file->saveAs($web_path . $destination);

            $row['name'] = $file->baseName;
            $row['size'] = $file->size;
            $row['url'] = $destination;
            $row['src'] = $src;
            $row['thumbnailUrl'] = $destination;
            $row['deleteUrl'] = '';
            $row['deleteType'] = 'DELETE';
            $result['success'] = true;
            $result['files'][] = $row;
            return json_encode($result);
        }
        $result['files'][0]['error'] = '上传文件失败';

        return json_encode($result);
    }
    public function actionReceiptUpload()
    {
        Yii::$app->response->format = Response::FORMAT_RAW;
        $result = array();
        $result['success'] = false;

        $file = UploadedFile::getInstanceByName('file');
        if (!empty($file)) {
            $name = md5(rand(100, 200));
            $ext = $file->extension;
            $filename = $name . '.' . $ext;
            $destination = '/upload';
            $web_path = Yii::$app->getBasePath() . '/../frontend/web';
            if (!is_dir($web_path . $destination)) {
                mkdir($web_path . $destination);
            }
            $destination .= '/files';
            if (!is_dir($web_path . $destination))
                mkdir($web_path . $destination);
            $destination .= '/' . date('Ym');
            if (!is_dir($web_path . $destination))
                mkdir($web_path . $destination);
            $destination .= '/' . $filename;
            $file->saveAs($web_path . $destination);

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

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

        return json_encode($result);
    }
    public function actionReceiptUpload1()
    {
        Yii::$app->response->format = Response::FORMAT_RAW;
        $result = array();
        $result['success'] = false;

        $file = UploadedFile::getInstanceByName('file1');
        if (!empty($file)) {
            $name = md5(rand(100, 200));
            $ext = $file->extension;
            $filename = $name . '.' . $ext;
            $destination = '/upload';
            $web_path = Yii::$app->getBasePath() . '/../frontend/web';
            if (!is_dir($web_path . $destination)) {
                mkdir($web_path . $destination);
            }
            $destination .= '/files';
            if (!is_dir($web_path . $destination))
                mkdir($web_path . $destination);
            $destination .= '/' . date('Ym');
            if (!is_dir($web_path . $destination))
                mkdir($web_path . $destination);
            $destination .= '/' . $filename;
            $file->saveAs($web_path . $destination);

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

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

        return json_encode($result);
    }
    public function actionEmsReceiptProcess()
    {
        set_time_limit(0);
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '操作失败';
        $company = $request->post('company', '');

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

        $urlfile = $web_path . $request->post('urlfile');

        //读取Excel 2007
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($urlfile)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($urlfile)) {
                $result['success'] = false;
                $result['msg'] = '无法读取文件';
                return $result;
            }
        }
        $PHPExcel = $PHPReader->load($urlfile);
        $currentSheet = $PHPExcel->getSheet(0);

        $rowCount = $currentSheet->getHighestRow();
        //$data = $currentSheet->toArray('', true, true);
//        $objectPHPExcel = new \PHPExcel();
//        $index = 1;
//        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.$index,'业务日期');
//        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('B'.$index,'快递单号');
//        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('C'.$index,'收货人');
//        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('D'.$index,'快递金额');

        for ($i = 3; $i <= $rowCount; $i++) {
            $cell = $currentSheet->getCellByColumnAndRow(0, $i);
            $yewu_date = $cell->getValue();
//            dd($yewu_date);
            $cell = $currentSheet->getCellByColumnAndRow(1, $i);
            $ems_no = $cell->getValue();//$data[$i][1];
//dd($ems_no);
//            $cell = $currentSheet->getCellByColumnAndRow(2, $i);
//            $policy_man = $cell->getValue();//$data[$i][2];
//            $cell = $currentSheet->getCellByColumnAndRow(3, $i);
//            $total_real = $cell->getValue();//$data[$i][3];
//            $cell = $currentSheet->getCellByColumnAndRow(4, $i);
//            $total_rate = $cell->getValue();//$data[$i][4];
//            $cell = $currentSheet->getCellByColumnAndRow(5, $i);
//            $pay_total = $cell->getValue();//$data[$i][5];
            $cell = $currentSheet->getCellByColumnAndRow(7, $i);
            $recieve_man = $cell->getValue();//$data[$i][6];
            $cell = $currentSheet->getCellByColumnAndRow(17, $i);
            $ems_price = $cell->getFormattedValue();
//            dd(date('Y-m-d'));
//            var_dump($insurer_date);
//            die;



//            $insurer_date = \PHPExcel_Shared_Date::ExcelToPHP($cell->getValue());//$data[$i][7];
//            $cell = $currentSheet->getCellByColumnAndRow(8, $i);
//            $car_no = $cell->getValue();//$data[$i][8];

//            if($insurer_no == 'PDAA201811010000089441') {
//            echo $insurer_no.'='.$policy_man.'='.$total_real.'='.$total_rate.'=';
//            echo $pay_total.'='.$insurer_total.'='.date('Y-m-d',$insurer_date).'='.$car_no."\r\n";
//            exit;
//            }
//            $row = CaiwuT::findOne(['car_no' => $car_no, 'insurer_no' => $insurer_no]);
//            echo $insurer_no;

//            $query = ExpressT::find()
//                ->leftJoin(OrderT::tableName(), "order_t.id=express_t.order_id");
            $row=ExpressT::find()->where(['ems_no' => $ems_no])->andWhere('is_express!=3')->one();
//            $row = CaiwuT::findOne(['ems_no' => $ems_no]);
//            var_dump($row);
//            die;
            if ($row) {
//                CaiwuErrorT::deleteAll(['insurer_no' => $insurer_no]);

//            echo $insurer_no.'='.$policy_man.'='.$total_real.'='.$total_rate.'=';
//            echo $pay_total.'='.$insurer_total.'='.date('Y-m-d',$insurer_date).'='.$car_no."\r\n";
//                dd($row->ems_price);
                $row->return_slip = round(($ems_price - $row->ems_price), 2);
//                dd($row->return_slip);
                $row->r_price = $ems_price;
//                var_dump($insurer_no);
                $row->r_date = date('Y-m-d');
                if (!$row->save()) {
                    var_dump($row->errors);
                    exit;
                }
//                die;
            } else {

                $new_express=new ExpressT();
                $new_express->is_express=3;
                $new_express->ems_no=$ems_no;
                $new_express->user_id=1;
                $new_express->link_name=$recieve_man;
                $new_express->ems_price=$ems_price;
                $new_express->save();

//                    $index++;
//
//                    $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.$index,$yewu_date);
//                    $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('B'.$index,$ems_no);
//                    $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('C'.$index,$recieve_man);
//                    $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('D'.$index,$ems_price);




            }
        }
//        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
//        header('Content-Disposition:attachment;filename="'.date("YmjHis").'.xls"');
//        header('Cache-Control: max-age=0');
//        $objWriter = \PHPExcel_IOFactory::createWriter($objectPHPExcel, 'Excel5');
//        $objWriter->save('php://output');

        $result['success'] = true;

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

        return $result;
    }
    public function actionReceiptProcess()
    {
        set_time_limit(0);
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '操作失败';
        $company = $request->post('company', '');

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

        $urlfile = $web_path . $request->post('urlfile');

        //读取Excel 2007
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($urlfile)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($urlfile)) {
                $result['success'] = false;
                $result['msg'] = '无法读取文件';
                return $result;
            }
        }
        $PHPExcel = $PHPReader->load($urlfile);
        $currentSheet = $PHPExcel->getSheet(0);

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

        for ($i = 7; $i <= $rowCount; $i++) {
            $cell = $currentSheet->getCellByColumnAndRow(1, $i);
            $insurer_no = $cell->getFormattedValue();//$data[$i][1];
//            var_dump($insurer_no);
            $cell = $currentSheet->getCellByColumnAndRow(2, $i);
            $policy_man = $cell->getFormattedValue();//$data[$i][2];
            $cell = $currentSheet->getCellByColumnAndRow(3, $i);
            $total_real = $cell->getFormattedValue();//$data[$i][3];
            $cell = $currentSheet->getCellByColumnAndRow(4, $i);
            $total_rate = $cell->getFormattedValue();//$data[$i][4];
            $cell = $currentSheet->getCellByColumnAndRow(5, $i);
            $pay_total = $cell->getFormattedValue();//$data[$i][5];
            $cell = $currentSheet->getCellByColumnAndRow(6, $i);
            $insurer_total = $cell->getFormattedValue();//$data[$i][6];
            $cell = $currentSheet->getCellByColumnAndRow(7, $i);
            $insurer_date = $cell->getFormattedValue();
//            var_dump($insurer_date);
//            die;



//            $insurer_date = \PHPExcel_Shared_Date::ExcelToPHP($cell->getValue());//$data[$i][7];
            $cell = $currentSheet->getCellByColumnAndRow(8, $i);
            $car_no = $cell->getValue();//$data[$i][8];

//            if($insurer_no == 'PDAA201811010000089441') {
//            echo $insurer_no.'='.$policy_man.'='.$total_real.'='.$total_rate.'=';
//            echo $pay_total.'='.$insurer_total.'='.date('Y-m-d',$insurer_date).'='.$car_no."\r\n";
//            exit;
//            }
//            $row = CaiwuT::findOne(['car_no' => $car_no, 'insurer_no' => $insurer_no]);
//            echo $insurer_no;
            $row = CaiwuT::findOne(['insurer_no' => $insurer_no]);
//            var_dump($row);
//            die;
            if ($row) {
                CaiwuErrorT::deleteAll(['insurer_no' => $insurer_no]);

//            echo $insurer_no.'='.$policy_man.'='.$total_real.'='.$total_rate.'=';
//            echo $pay_total.'='.$insurer_total.'='.date('Y-m-d',$insurer_date).'='.$car_no."\r\n";

                $row->r_total = $insurer_total;
//                var_dump($insurer_no);
                $row->r_date = $insurer_date;
                $row->company = $company;
                $row->total_dis = round((($row->total_clear * $row->total_rate / 100) - $insurer_total), 2);
                if (!$row->save()) {
                    var_dump($row->errors);
                    exit;
                }
//                die;
            } else {
                CaiwuErrorT::deleteAll(['insurer_no' => $insurer_no]);
                $tmp_row = new CaiwuErrorT();
                $tmp_row->car_no = $car_no;
                $tmp_row->insurer_no = $insurer_no;
                $tmp_row->policy_man = $policy_man;
                $tmp_row->total_real = $total_real;
                $tmp_row->total_rate = $total_rate;
                $tmp_row->pay_total = $pay_total;
                $tmp_row->finish_total = $insurer_total;
                $tmp_row->pay_date = $insurer_date;
                $tmp_row->company = $company;
                $tmp_row->save();
            }
        }

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

        return $result;
    }
    public function actionReceiptProcess1()
    {
        set_time_limit(0);
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '操作失败';
        $company = $request->post('company', '');

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

        $urlfile = $web_path . $request->post('urlfile');

        //读取Excel 2007
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($urlfile)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($urlfile)) {
                $result['success'] = false;
                $result['msg'] = '无法读取文件';
                return $result;
            }
        }
        $PHPExcel = $PHPReader->load($urlfile);
        $currentSheet = $PHPExcel->getSheet(0);

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

        for ($i = 7; $i <= $rowCount; $i++) {
            $cell = $currentSheet->getCellByColumnAndRow(1, $i);
            $insurer_no = $cell->getValue();//$data[$i][1];
//            var_dump($insurer_no);
            $cell = $currentSheet->getCellByColumnAndRow(2, $i);
            $policy_man = $cell->getValue();//$data[$i][2];
            $cell = $currentSheet->getCellByColumnAndRow(3, $i);
            $total_real = $cell->getValue();//$data[$i][3];
            $cell = $currentSheet->getCellByColumnAndRow(4, $i);
            $total_rate = $cell->getValue();//$data[$i][4];
            $cell = $currentSheet->getCellByColumnAndRow(5, $i);
            $pay_total = $cell->getValue();//$data[$i][5];
            $cell = $currentSheet->getCellByColumnAndRow(6, $i);
            $insurer_total = $cell->getValue();//$data[$i][6];
            $cell = $currentSheet->getCellByColumnAndRow(7, $i);
            $insurer_date = $cell->getFormattedValue();
//            var_dump($insurer_date);
//            die;



//            $insurer_date = \PHPExcel_Shared_Date::ExcelToPHP($cell->getValue());//$data[$i][7];
            $cell = $currentSheet->getCellByColumnAndRow(8, $i);
            $car_no = $cell->getValue();//$data[$i][8];

//            if($insurer_no == 'PDAA201811010000089441') {
//            echo $insurer_no.'='.$policy_man.'='.$total_real.'='.$total_rate.'=';
//            echo $pay_total.'='.$insurer_total.'='.date('Y-m-d',$insurer_date).'='.$car_no."\r\n";
//            exit;
//            }
//            $row = CaiwuT::findOne(['car_no' => $car_no, 'insurer_no' => $insurer_no]);
//            echo $insurer_no;
            $row = CaiwuT1::findOne(['insurer_no' => $insurer_no]);
//            var_dump($row);
//            die;
            if ($row) {
                CaiwuErrorT::deleteAll(['insurer_no' => $insurer_no]);

//            echo $insurer_no.'='.$policy_man.'='.$total_real.'='.$total_rate.'=';
//            echo $pay_total.'='.$insurer_total.'='.date('Y-m-d',$insurer_date).'='.$car_no."\r\n";

                $row->r_total = $insurer_total;
//                var_dump($insurer_no);
                $row->r_date = $insurer_date;
                $row->company = $company;
                $row->total_dis = round((($row->total * $row->total_rate / 100) - $insurer_total), 2);
                if (!$row->save()) {
                    var_dump($row->errors);
                    exit;
                }
//                die;
            } else {
                CaiwuErrorT::deleteAll(['insurer_no' => $insurer_no]);
                $tmp_row = new CaiwuErrorT();
                $tmp_row->car_no = $car_no;
                $tmp_row->insurer_no = $insurer_no;
                $tmp_row->policy_man = $policy_man;
                $tmp_row->total_real = $total_real;
                $tmp_row->total_rate = $total_rate;
                $tmp_row->pay_total = $pay_total;
                $tmp_row->finish_total = $insurer_total;
                $tmp_row->pay_date = $insurer_date;
                $tmp_row->company = $company;
                $tmp_row->save();
            }
        }

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

        return $result;
    }

    public function actionImports1()
    {
//        set_time_limit(0);
//        $begin_time = time();
//        $file_path = \Yii::getAlias('@console').'/controllers/';
//        $filename = $file_path.'2015-11-7-7.xlsx';
//        $base_filename = '2015-11-7-7.xlsx';

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

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

        $filename = $web_path . $request->post('urlfile');
        $base_filename=$request->post('urlfile');
//        var_dump($base_filename);
//        die;


//        var_dump($filename);
//        die;

//        if(file_exists($filename)) {
//            echo 'OK'."\r\n";
//        }
//        var_dump($filename);
//        die;
        $reader = new \PHPExcel_Reader_Excel2007();
        if(!$reader->canRead($filename)) {
            $reader = new \PHPExcel_Reader_Excel5();
            if(!$reader->canRead($filename)) {
                $errorMessage = "Can not read file.";
                echo $errorMessage;
                return;
            }
        }
        $excel = $reader->load($filename);
        $sheet = $excel->getSheet(0);
//        $rowCount = $sheet->getHighestRow();
        $data = $sheet->toArray('', true, true);
        $total = count($data);
        $total1 = $total-1;
//        echo 'num:'.$total."\r\n";
        $j = 0;
        $insert_total = 0;
        foreach($data as $index => $item) {

            $j++;
            if($j == 1) continue;
//            echo $j.'/'.$total."...";
            flush();
            $car_no = sprintf("%s",$item[0]);
            $car_man = sprintf("%s",$item[1]);
            $factory_model = sprintf("%s",$item[2]);




            $car_no = sprintf("%s",$item[0]);
            $car_man = sprintf("%s",$item[1]);
            $factory_model = sprintf("%s",$item[2]);
            //发动机号
            $engine_no = sprintf("%s",$item[3]);
            //车架号
            $car_frame_no = sprintf("%s",$item[4]);
            $register_date = sprintf("%s",$item[5]);
            $company = $item[6];
            $insurer1_date = sprintf("%s",$item[7]);
            $insurer2_date = sprintf("%s",$item[8]);
            $id_man = sprintf("%s",$item[9]);
            $id_number = sprintf("%s",$item[10]);



//            if($insurer1_date != '')
//                $insurer1_date = date('Y-m-d',strtotime(date('Y-m-d',strtotime($insurer1_date."-1 year")).'+1 day'));
//            if($insurer2_date != '')
//                $insurer2_date = date('Y-m-d',strtotime(date('Y-m-d',strtotime($insurer2_date."-1 year")).'+1 day'));
//            echo $car_no."...";
//            echo $car_man."...";
//            echo $factory_model."...";
//            echo $engine_no."...";
//            echo $car_frame_no."...";
//            echo $register_date."...";
//            echo $insurer1_no."...";
//            echo $insurer2_no."...";
//            echo $id_man."...";
//            echo $id_number."\r\n";
//            exit;
            $car_info = CarT::findOne(['car_no'=>$car_no]);
            if(isset($car_info)) {

                $car_info->car_man = $car_man;
                $car_info->car_no = $car_no;
                $car_info->factory_model = $factory_model;
                $car_info->engine_no = $engine_no;
                $car_info->car_frame_no = $car_frame_no;
                $car_info->register_date = $register_date;
                $car_info->company = $company;
                $car_info->insurer1_date = $insurer1_date;
                $car_info->insurer2_date = $insurer2_date;
                $car_info->id_man = $id_man;
                $car_info->id_man_number = $id_number;
//                $car_info->location = 1;
//                $car_info->is_track = 0;

//                $car_info->location = 1;
//                $car_info->is_track = 0;

                $car_c_info = CarCT::findOne(['id'=>$car_info->id]);
                $car_d_info = CarDT::findOne(['id'=>$car_info->id]);
                $car_w_info = CarInvalidT::findOne(['id'=>$car_info->id]);

                if($car_c_info || $car_d_info || $car_w_info){
                    continue;
                }
                $car_info->save();

//                if($company == '人保') {
//                    $car_info->location = 3;
//                    $car_info->save();
//
//                    $car_c_info = CarCT::findOne(['id'=>$car_info->id]);
//                    if(!$car_c_info) {
//                        $car_c_info = new CarCT();
//                        $car_c_info->id = $car_info->id;
//                        $car_c_info->user_id = 0;
//                        $car_c_info->save();
//                    }
//                }
//                echo "ok";
                $insert_total++;

            }
            echo "\r\n";
        }
//        var_dump($insert_total);
        //记录导入Log
        $log = new ImportLogT();
        $log->filename = $base_filename;
        $log->total = $total1;
        $log->success = $insert_total;
        $log->success_rate = ($insert_total/$total1) * 100;
        $log->save();

//        $end_time = time();
//        $total_time = $end_time - $begin_time;
//        $h = floor($total_time/3600);
//        $m = floor(($total_time - $h * 3600)/60);
//        $s = $total_time - $h * 3600 - $m * 60;
//        echo '花费时间: '.$h.'小时'.$m.'分钟'.$s.'秒';
//        echo "OK\r\n";
//        echo '总添加新车辆：'.$insert_total."\r\n";
        $result['success'] = true;
        $result['msg'] = '操作成功';

        return $result;

    }

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

        $caiwu_info = CaiwuT::findOne(['id' => $id]);


        return $this->render('receipt-info', [
            'caiwu_info' => $caiwu_info
        ]);
    }
    public function actionEmsReceiptInfo()
    {
        $request = Yii::$app->request;
        $id = $request->get('id', 0);
        $back_params = $request->get('back_params');

        $caiwu_info = ExpressT::findOne(['id' => $id]);


        return $this->render('ems-receipt-info', [
            'caiwu_info' => $caiwu_info,
            'back_params' => $back_params,
        ]);
    }
    public function actionNonReceiptInfo()
    {
        $request = Yii::$app->request;
        $id = $request->get('id', 0);
        $back_params = $request->get('back_params');

        $caiwu_info = CaiwuT2::findOne(['id' => $id]);


        return $this->render('non-receipt-info', [
            'caiwu_info' => $caiwu_info,
            'back_params' => $back_params,
        ]);
    }
    public function actionReceiptInfoDif()
    {
        $request = Yii::$app->request;
        $id = $request->get('id', 0);
        $back_params = $request->get('back_params');

        $caiwu_info = CaiwuT1::findOne(['id' => $id]);


        return $this->render('receipt-info-dif', [
            'caiwu_info' => $caiwu_info,
            'back_params' => $back_params,
        ]);
    }


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

        $query = CaiwuErrorT::find()
            ->orderBy('pay_date desc');
        if($car_no != '') {
            $query = $query->andWhere('car_no="'.$car_no.'"');
        }
        if($insurer_no != '') {
            $query = $query->andWhere('insurer_no="'.$insurer_no.'"');
        }
//        echo $query->createCommand()->rawSql;
        $total = $query->count();

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

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

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

        return $this->render('receipt-error', [
            'items' => $items,
            'page' => $page,
            'page_info' => $page_info,
            'car_no' => $car_no,
            'insurer_no' => $insurer_no
        ]);
    }

    public function actionReceiptErrorDel()
    {
        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);

            if($id > 0) {
                $row = CaiwuErrorT::findOne(['id'=>$id]);
                $row->delete();

                $result['success'] = true;
                $result['msg'] = '删除成功';
            }
        }
        return $result;
    }

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

        $id = $request->post('id', 0);
        $insurer_no = $request->post('insurer_no','');
        $total_rate = $request->post('total_rate', 0);
        $r_total = $request->post('r_total');
        $r_date = $request->post('r_date');

        $caiwu_info = CaiwuT::findOne(['id' => $id]);
        if ($caiwu_info) {
            $order_info = $caiwu_info->order;
            if ($order_info) {
                if ($caiwu_info->insurer_type == 1) {
                    $order_info->insurer1_no = $insurer_no;
                    $order_info->total1_rate = $total_rate;
                    $order_info->save();
                } else {
                    $order_info->insurer2_no = $insurer_no;
                    $order_info->total2_rate = $total_rate;
                    $order_info->save();
                }
            }
            $caiwu_info->insurer_no = $insurer_no;
            $caiwu_info->total_rate = $total_rate;
            $caiwu_info->total_clear_real = sprintf("%.2f",($caiwu_info->total_clear * $caiwu_info->total_rate/100));
            $caiwu_info->total_dis = $caiwu_info->total_clear_real - floatval($r_total);
            $caiwu_info->r_date = $r_date;
            $caiwu_info->r_total = $r_total;
            $caiwu_info->save();
            $result['success'] = true;
            $result['msg'] = '操作成功';
        }
        return $result;

    }

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

        $id = $request->post('id', 0);
        $ems_no = $request->post('ems_no','');
        $link_address = $request->post('link_address');
        $ems_price = $request->post('ems_price');
        $r_total = $request->post('r_total');
        $r_date = $request->post('r_date');

        $caiwu_info = ExpressT::findOne(['id' => $id]);
        if ($caiwu_info) {
            $order_info = $caiwu_info->order;

            $caiwu_info->ems_no = $ems_no;
            $caiwu_info->link_address = $link_address;
            $caiwu_info->ems_price = $ems_price;
//            $caiwu_info->total_clear_real = sprintf("%.2f",($caiwu_info->total_clear * $caiwu_info->total_rate/100));
            $caiwu_info->return_slip = $ems_price - floatval($r_total);
            $caiwu_info->r_date = $r_date;
            $caiwu_info->r_price = $r_total;
            $caiwu_info->save();
            $result['success'] = true;
            $result['msg'] = '操作成功';
        }
        return $result;

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

        $id = $request->post('id', 0);
        $insurer_no = $request->post('insurer_no','');
        $total_rate = $request->post('total_rate', 0);
        $r_total = $request->post('r_total');
        $r_date = $request->post('r_date');

        $caiwu_info = CaiwuT2::findOne(['id' => $id]);
        if ($caiwu_info) {
            $order_info = $caiwu_info->order;
            if ($order_info) {
                $order_info->insurer_non_no = $insurer_no;
                $order_info->non_rate = $total_rate;
                $order_info->save();
            }
            $caiwu_info->insurer_no = $insurer_no;
            $caiwu_info->total_rate = $total_rate;
//            $caiwu_info->total_clear_real = sprintf("%.2f",($caiwu_info->total_clear * $caiwu_info->total_rate/100));
            $caiwu_info->total_dis = $caiwu_info->total_real - floatval($r_total);
            $caiwu_info->r_date = $r_date;
            $caiwu_info->r_total = $r_total;
            $caiwu_info->save();
            $result['success'] = true;
            $result['msg'] = '操作成功';
        }
        return $result;

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

        $id = $request->post('id', 0);
        $insurer_no = $request->post('insurer_no','');
        $total_rate = $request->post('total_rate', 0);
        $r_total = $request->post('r_total');
        $r_date = $request->post('r_date');

        $caiwu_info = CaiwuT1::findOne(['id' => $id]);
        if ($caiwu_info) {
            $order_info = $caiwu_info->order;
            if ($order_info) {
                if ($caiwu_info->insurer_type == 1) {
                    $order_info->insurer1_no = $insurer_no;
                    $order_info->total1_rate = $total_rate;
                    $order_info->save();
                } else {
                    $order_info->insurer2_no = $insurer_no;
                    $order_info->total2_rate = $total_rate;
                    $order_info->save();
                }
            }
            $caiwu_info->insurer_no = $insurer_no;
            $caiwu_info->total_rate = $total_rate;
            $caiwu_info->total_clear_real = sprintf("%.2f",($caiwu_info->total * $caiwu_info->total_rate/100));
            $caiwu_info->total_dis = $caiwu_info->total_clear_real - floatval($r_total);
            $caiwu_info->r_date = $r_date;
            $caiwu_info->r_total = $r_total;
            $caiwu_info->save();
            $result['success'] = true;
            $result['msg'] = '操作成功';
        }
        return $result;

    }
    public function actionReceipt2() {
        $insurer_company_items = InsurerCompany2T::find()->all();

        return $this->render('receipt2', [
            'insurer_company_items' => $insurer_company_items
        ]);
    }
    public function actionReceipt2Json()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $begin_date = $request->get('begin_date');
        $end_date = $request->get('end_date');
        $r_begin_date = $request->get('r_begin_date');
        $r_end_date = $request->get('r_end_date');
        $car_no = $request->get('car_no');
        $insurer_no = $request->get('insurer_no');
        $status = $request->get('status');
        $sort_key = $request->get('sort_key');
        $sort_value = $request->get('sort_value');
        $company_id = $request->get('company_id');
        $insurer_type = $request->get('insurer_type');
        $offset = $request->get('offset', 0);
        $limit = $request->get('limit', 10);

        $query = CaiwuT::find()
            ->leftJoin(OrderCaiwuT::tableName(), "order_caiwu_t.order_id=caiwu_t.order_id")
            ->leftJoin(OrderT::tableName(), "order_caiwu_t.order_id=order_t.id")
            ->where('caiwu_t.budian_rate > 0');
        if( $company_id > 0) {
            $query = $query->andWhere('order_t.company_id='.$company_id);
        }
        if ($car_no != "") {
            $query = $query->andWhere('caiwu_t.car_no like "' . $car_no . '%"');
        }
        if ($insurer_no != "") {
            $query = $query->andWhere('caiwu_t.insurer_no like "' . $insurer_no . '%"');
        }
        if ($status > 0) {
            if ($status == 1) {
                $query = $query->andWhere('b1_date is null');
            }
            if ($status == 2) {
                $query = $query->andWhere('b1_date is not null');
            }
        }
        if ($begin_date != "") {
            $query = $query->andWhere('order_t.print_date>="' . $begin_date . '"');
        }
        if ($end_date != "") {
            $query = $query->andWhere('order_t.print_date<="' . $end_date . '"');
        }
        if ($r_begin_date != "") {
            $query = $query->andWhere('caiwu_t.r_date>="' . $r_begin_date . '"');
        }
        if ($r_end_date != "") {
            $query = $query->andWhere('caiwu_t.r_date<="' . $r_end_date . '"');
        }

        if($insurer_type != 0){
            $query = $query->andWhere('caiwu_t.insurer_type =' . $insurer_type);
        }
//        echo $query->createCommand()->rawSql;
        $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->order->company2->name;
            $row['print_date'] = $item->order->print_date;
            $row['total_real'] = round($item->total_clear,2);
            $row['budian_rate'] = $item->budian_rate;
            $row['budian_money'] = $item->budian_money;
            $row['b1_total'] = $item->b1_total;
            $row['b1_date'] = $item->b1_date;
            $row['b2_total'] = $item->b2_total;
            $row['b2_date'] = $item->b2_date;
            $row['b3_total'] = $item->b3_total;
            $row['b3_date'] = $item->b3_date;
            $row['b_total'] = round($row['b1_total']+$row['b2_total']+$row['b3_total'],2);
            $row['un_b_total'] = round($row['budian_money'] - $row['b_total'],2);
            $data['rows'][] = $row;
        }

        return $data;
    }
    public function actionReceipt2Output()
    {
        $request = Yii::$app->request;
        $page = $request->get('page', 1);
        $begin_date = $request->get('begin_date');
        $end_date = $request->get('end_date');
        $r_begin_date = $request->get('r_begin_date');
        $r_end_date = $request->get('r_end_date');
        $car_no = $request->get('car_no');
        $insurer_no = $request->get('insurer_no');
        $status = $request->get('status');
        $sort_key = $request->get('sort_key');
        $sort_value = $request->get('sort_value');
        $company_id = $request->get('company_id');
        if ($page < 1) $page = 1;


        $query = CaiwuT::find()
            ->leftJoin(OrderCaiwuT::tableName(), "order_caiwu_t.order_id=caiwu_t.order_id")
            ->leftJoin(OrderT::tableName(), "order_caiwu_t.order_id=order_t.id")
            ->where('order_caiwu_t.budian_rate > 0');
        if( $company_id > 0) {
            $query = $query->andWhere('order_t.company_id='.$company_id);
        }
        if ($car_no != "") {
            $query = $query->andWhere('caiwu_t.car_no like "' . $car_no . '%"');
        }
        if ($insurer_no != "") {
            $query = $query->andWhere('caiwu_t.insurer_no like "' . $insurer_no . '%"');
        }
        if ($status > 0) {
            if ($status == 1) {
                $query = $query->andWhere('r_date=""');
            }
            if ($status == 2) {
                $query = $query->andWhere('r_date<>""');
            }
        }
        if ($begin_date != "") {
            $query = $query->andWhere('order_t.print_date>="' . $begin_date . '"');
        }
        if ($end_date != "") {
            $query = $query->andWhere('order_t.print_date<="' . $end_date . '"');
        }
        if ($r_begin_date != "") {
            $query = $query->andWhere('caiwu_t.r_date>="' . $r_begin_date . '"');
        }
        if ($r_end_date != "") {
            $query = $query->andWhere('caiwu_t.r_date<="' . $r_end_date . '"');
        }
//        echo $query->createCommand()->rawSql;
        $total = $query->count();

        $items = $query->all();
        $objectPHPExcel = new \PHPExcel();
        $index = 1;
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.$index,'车牌号');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('B'.$index,'保险公司');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('C'.$index,'保单号');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('D'.$index,'出单日期	');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('E'.$index,'商业净保费');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('F'.$index,'补点比例');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('G'.$index,'应得金额');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('H'.$index,'补点1回款');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('I'.$index,'补点1日期');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('J'.$index,'补点2回款');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('K'.$index,'补点2日期');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('L'.$index,'补点3回款');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('M'.$index,'补点3日期');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('N'.$index,'已回金额');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('O'.$index,'未回金额');


        foreach($query->each() as $item) {
            $index++;
            $order = $item->order;
            $caiwu = $order->caiwu;

            if($item->insurer_type==2){
                $caiwu->budian_rate=0;
            }
            $total_clear = round($item->total_clear * $caiwu->budian_rate/100,2);
            $b_total = $item->b1_total+$item->b2_total+$item->b3_total;

            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.$index,$order->car_no);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('B'.$index,$order && $order->company ? $order->company->name:'');
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('C'.$index,$item->insurer_no);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('D'.$index,$order->print_date);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('E'.$index,$item->total_clear);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('F'.$index,$caiwu->budian_rate);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('G'.$index,$total_clear);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('H'.$index,$item->b1_total);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('I'.$index,$item->b1_date);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('J'.$index,$item->b2_total);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('K'.$index,$item->b2_date);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('L'.$index,$item->b3_total);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('M'.$index,$item->b3_date);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('N'.$index,$b_total);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('O'.$index,$total_clear-$b_total);

        }

        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition:attachment;filename="'.date("YmjHis").'.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objectPHPExcel, 'Excel5');
        $objWriter->save('php://output');


    }
    public function actionReceipt2Process()
    {
        set_time_limit(0);
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '操作失败';
        $bdlx = $request->post('bdlx', '');

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

        $urlfile = $web_path . $request->post('urlfile');
//        var_dump($request->post('urlfile'));
//        die;

        //读取Excel 2007
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($urlfile)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($urlfile)) {
                $result['success'] = false;
                $result['msg'] = '无法读取文件';
                return $result;
            }
        }
        $PHPExcel = $PHPReader->load($urlfile);
        $currentSheet = $PHPExcel->getSheet(0);

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

        for ($i = 7; $i <= $rowCount; $i++) {
            $cell = $currentSheet->getCellByColumnAndRow(1, $i);
            $insurer_no = $cell->getValue();//$data[$i][1];
            $cell = $currentSheet->getCellByColumnAndRow(2, $i);
            $policy_man = $cell->getValue();//$data[$i][2];
            $cell = $currentSheet->getCellByColumnAndRow(3, $i);
            $total_real = $cell->getValue();//$data[$i][3];
            $cell = $currentSheet->getCellByColumnAndRow(4, $i);
            $total_rate = $cell->getValue();//$data[$i][4];
            $cell = $currentSheet->getCellByColumnAndRow(5, $i);
            $pay_total = $cell->getValue();//$data[$i][5];
            $cell = $currentSheet->getCellByColumnAndRow(6, $i);
            $insurer_total = $cell->getValue();//$data[$i][6];
            $cell = $currentSheet->getCellByColumnAndRow(7, $i);
            $insurer_date = $cell->getFormattedValue();
            $cell = $currentSheet->getCellByColumnAndRow(8, $i);
            $car_no = $cell->getValue();//$data[$i][8];

            $row = CaiwuT::findOne(['insurer_no' => $insurer_no]);
            if ($row) {
                CaiwuErrorT::deleteAll(['insurer_no' => $insurer_no]);

                if($bdlx == 1) {
                    $row->b1_total = $insurer_total;
                    $row->b1_date = $insurer_date;
                }
                if($bdlx == 2) {
                    $row->b2_total = $insurer_total;
                    $row->b2_date = $insurer_date;
                }
                if($bdlx == 3) {
                    $row->b3_total = $insurer_total;
                    $row->b3_date = $insurer_date;
                }
                if (!$row->save()) {
                    var_dump($row->errors);
                    exit;
                }
            } else {
                CaiwuErrorT::deleteAll(['insurer_no' => $insurer_no]);
                $tmp_row = new CaiwuErrorT();
                $tmp_row->car_no = $car_no;
                $tmp_row->insurer_no = $insurer_no;
                $tmp_row->policy_man = $policy_man;
                $tmp_row->total_real = $total_real;
                $tmp_row->total_rate = $total_rate;
                $tmp_row->pay_total = $pay_total;
                $tmp_row->finish_total = $insurer_total;
                $tmp_row->pay_date = $insurer_date;
                $tmp_row->company = $bdlx;
                $tmp_row->save();
            }
        }

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

        return $result;
    }

    public function actionPayList()
    {
        $request = Yii::$app->request;
        $year = $request->get('year', date('Y'));
        $month = $request->get('month', date('m'));
        $group_id = $request->get('group_id');
        $name = $request->get('name');

        //读取礼品价格
        $price_items = CaiwuGiftT::find()
            ->where('year=' . $year . ' and month=' . $month)
            ->all();
        $gift_price = array();
        foreach ($price_items as $item) {
            $gift_price[$item->gift_id] = $item->price;
        }

        //获取员工
        $query = UserT::find()
            ->where('is_login=1 and is_delete=0 and group_id > 0')
            ->orderBy('username ASC,id asc');
        if ($name != '') {
            $query = $query->andWhere('username="' . $name . '"');
        }
        if ($group_id > 0) {
            $group_ids = array();
            $items = GroupT::getTree($group_id);
            foreach ($items as $group_info) {
                $group_ids[] = $group_info->id;
            }
            $group_ids[] = $group_id;
            $query = $query->andWhere(['in', 'group_id', $group_ids]);
        }
        $items = array();

        foreach ($query->each() as $index => $item) {
            $items[$index] = $item->toArray();

            $gz_info = GzT::findOne(['sale_id' => $item->id, 'year' => $year, 'month' => $month]);
            if (!isset($gz_info)) {
                $gz_info = new GzT();
                $gz_info->sale_id = $item->id;
                $gz_info->year = $year;
                $gz_info->month = $month;
                $gz_info->hb = 0;
                $gz_info->other = 0;
                $gz_info->tx = 0;
                $gz_info->cd = 0;
                $gz_info->tb = 0;
                $gz_info->sb = 0;
                $gz_info->bd = 0;
                if (!$gz_info->save()) {
                    var_dump($gz_info->errors);
                    exit;
                }
                $assign_query = OrderT::find()
                    ->where('user_id=' . $item->id . ' and status_id>5');
                $printdate_begin = $year . '-' . $month . '-01';
                if ($printdate_begin != '') {
                    $assign_query = $assign_query->andWhere('print_date>="' . $printdate_begin . '"');
                }
                $printdate_end = date('Y-m-d', strtotime('+1 months', strtotime($printdate_begin)));
                if ($printdate_end != '') {
                    $assign_query = $assign_query->andWhere('print_date<"' . $printdate_end . '"');
                }
                $order_count = 0;
                $total1_clear = 0;
                $total1_rate = 0;
                $total1_dis = 0;
                $gift1_count = 0;
                $gift1_total = 0;
                $gift2_count = 0;
                $gift2_total = 0;
                $tj = 0;
                foreach ($assign_query->each() as $assign_info) {
                    $order_count++;
                    $total1_clear += $assign_info->total1_clear;
                    $total1_rate += $assign_info->total1_clear * $assign_info->total1_rate / 100;
                    $tj += $assign_info->total1_clear * $assign_info->tijiang / 100;
                    $total1_dis += $assign_info->total1_dis;

                    $gift_query = OrderGiftT::find()
                        ->where('order_id=' . $assign_info->id);
//                    echo $gift_query->createCommand()->rawSql."<br>";
                    $gift_items = $gift_query->all();
//                    $gift_items = CarGiftT::find()
//                        ->where('order_id='.$assign_info->id)
//                        ->orderBy('strategy_id DESC')
//                        ->all();
                    foreach ($gift_items as $gift_item) {
                        $gift_info = $gift_item->gift;
                        $group_info = $gift_item->group;
                        if (!$group_info) continue;
                        if (!$gift_info) continue;
                        if ($group_info->is_free == 1) {
                            $gift1_count++;
                            if (isset($gift_price[$gift_info->id]))
                                $gift1_total += $gift_price[$gift_info->id];//0;//$gift_info->price;
                        } else {
                            $gift2_count++;
                            if (isset($gift_price[$gift_info->id]))
                                $gift2_total += $gift_price[$gift_info->id];//0;//$gift_info->price;

                        }
                    }
                }
                $items[$index]['order_count'] = $order_count;
                $items[$index]['total1_clear'] = round($total1_clear, 2);
                $items[$index]['total1_rate'] = round($total1_rate, 2);
                $items[$index]['total1_dis'] = round($total1_dis, 2);
                $items[$index]['gift1_count'] = $gift1_count;
                $items[$index]['gift1_total'] = $gift1_total;
                $items[$index]['gift2_count'] = $gift2_count;
                $items[$index]['gift2_total'] = $gift2_total;

                $items[$index]['tj'] = round($tj, 2);
                $items[$index]['tc'] = round($tj + $gz_info->hb + $gz_info->other + $gz_info->tx + $gz_info->bd
                    - $total1_dis - $gz_info->cd - $gz_info->tb - $gz_info->sb - $gz_info->lp, 2);
                $tmp_yf = 0;
                if ($gz_info->ycq > $gz_info->scq) {
                    $tmp_yf += $items[$index]['tc'] * 0.2;
                }
                if ($gz_info->yts > $gz_info->sts) {
                    $tmp_yf += $items[$index]['tc'] * 0.2;
                }
                $items[$index]['yf'] = $items[$index]['tc'] - $tmp_yf;

                $gz_info->order_count = $order_count;
                $gz_info->total1_clear = round($total1_clear, 2);
                $gz_info->total1_rate = round($total1_rate, 2);
                $gz_info->total1_dis = round($total1_dis, 2);
                $gz_info->gift1_count = $gift1_count;
                $gz_info->gift1_total = $gift1_total;
                $gz_info->gift2_count = $gift2_count;
                $gz_info->gift2_total = $gift2_total;
                $gz_info->tj = $items[$index]['tj'];
                $gz_info->tc = $items[$index]['tc'];
                $gz_info->yf = $items[$index]['yf'];
                $gz_info->save();
            } else {
                $items[$index]['order_count'] = $gz_info->order_count;
                $items[$index]['total1_clear'] = $gz_info->total1_clear;
                $items[$index]['total1_rate'] = $gz_info->total1_rate;
                $items[$index]['total1_dis'] = $gz_info->total1_dis;
                $items[$index]['gift1_count'] = $gz_info->gift1_count;
                $items[$index]['gift1_total'] = $gz_info->gift1_total;
                $items[$index]['gift2_count'] = $gz_info->gift2_count;
                $items[$index]['gift2_total'] = $gz_info->gift2_total;

                $items[$index]['tj'] = $gz_info->tj;
                $items[$index]['tc'] = $gz_info->tc;
                $items[$index]['yf'] = $gz_info->yf;
            }
        }

        $group_items = GroupT::getTree();

        return $this->render('pay-list', [
            'items' => $items,
            'year' => $year,
            'month' => $month,
            'group_id' => $group_id,
            'name' => $name,
            'group_items' => $group_items
        ]);
    }

    public function actionGzCal()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $year = $request->post('year', date('Y'));
        $month = $request->post('month', date('m'));
        $area_id = $request->post('area_id');
        $name = $request->post('name');

        //读取礼品价格
        $price_items = CaiwuGiftT::find()
            ->where('year=' . $year . ' and month=' . $month)
            ->all();
        $gift_price = array();
        foreach ($price_items as $item) {
            $gift_price[$item->gift_id] = $item->price;
        }

        //获取员工
        $query = UserT::find()
            ->where('is_login=1 and is_delete=0 and group_id>0')
            ->orderBy('id asc');
        if ($name != '') {
            $query = $query->andWhere('username="' . $name . '"');
        }
        if ($area_id > 0) {
            $query = $query->andWhere('area_id=' . $area_id);
        }
        $items = array();

        foreach ($query->each() as $index => $item) {
            $items[$index] = $item->toArray();

            $gz_info = GzT::findOne(['sale_id' => $item->id, 'year' => $year, 'month' => $month]);
            if (!isset($gz_info)) {
                $gz_info = new GzT();
                $gz_info->sale_id = $item->id;
                $gz_info->year = $year;
                $gz_info->month = $month;
                $gz_info->hb = 0;
                $gz_info->other = 0;
                $gz_info->tx = 0;
                $gz_info->cd = 0;
                $gz_info->tb = 0;
                $gz_info->sb = 0;
                $gz_info->bd = 0;
                if (!$gz_info->save()) {
                    var_dump($gz_info->errors);
                    exit;
                }
            }
            $assign_query = OrderT::find()
                ->where('user_id=' . $item->id . ' and status_id>5');
            $printdate_begin = $year . '-' . $month . '-01';
            if ($printdate_begin != '') {
                $assign_query = $assign_query->andWhere('print_date>="' . $printdate_begin . '"');
            }
            $printdate_end = date('Y-m-d', strtotime('+1 months', strtotime($printdate_begin)));
            if ($printdate_end != '') {
                $assign_query = $assign_query->andWhere('print_date<"' . $printdate_end . '"');
            }
            $order_count = 0;
            $total1_clear = 0;
            $total1_rate = 0;
            $total1_dis = 0;
            $gift1_count = 0;
            $gift1_total = 0;
            $gift2_count = 0;
            $gift2_total = 0;
            $tj = 0;
            foreach ($assign_query->each() as $assign_info) {
                $order_count++;
                $total1_clear += $assign_info->total1_clear;
                $total1_rate += $assign_info->total1_clear * $assign_info->total1_rate / 100;
                $tj += $assign_info->total1_clear * $assign_info->tijiang / 100;
                $total1_dis += $assign_info->total1_dis;

                $gift_query = OrderGiftT::find()
                    ->where('order_id=' . $assign_info->id);
//                    echo $gift_query->createCommand()->rawSql."<br>";
                $gift_items = $gift_query->all();
//                $gift_items = CarGiftT::find()
//                    ->where('order_id='.$assign_info->id)
//                    ->orderBy('strategy_id DESC')
//                    ->all();
                foreach ($gift_items as $gift_item) {
                    $gift_info = $gift_item->gift;
                    $group_info = $gift_item->group;
                    if (!$group_info) continue;
                    if (!$gift_info) continue;
                    if ($group_info->is_free == 1) {
                        $gift1_count++;
                        $gift1_total += $gift_price[$gift_info->id];//0;//$gift_info->price;
                    } else {
                        $gift2_count++;
                        $gift2_total += $gift_price[$gift_info->id];//0;//$gift_info->price;
                    }
                }
//                foreach($gift_items as $gift_item) {
//                    $gift_info = $gift_item->gift;
//                    if(!$gift_info) continue;
//                    if($gift_info->type_id != 1) continue;
//                    if($gift_item->strategy_id > 0) {
//                        $gift1_count++;
//                        $gift1_total += $gift_info->price;
//                    } else {
//                        $gift2_count++;
//                        $gift2_total += $gift_info->price;
//                    }
//                }
            }
            $items[$index]['order_count'] = $order_count;
            $items[$index]['total1_clear'] = round($total1_clear, 2);
            $items[$index]['total1_rate'] = round($total1_rate, 2);
            $items[$index]['total1_dis'] = round($total1_dis, 2);
            $items[$index]['gift1_count'] = $gift1_count;
            $items[$index]['gift1_total'] = $gift1_total;
            $items[$index]['gift2_count'] = $gift2_count;
            $items[$index]['gift2_total'] = $gift2_total;

            $items[$index]['tj'] = round($tj, 2);
            $items[$index]['tc'] = round($tj + $gz_info->hb + $gz_info->other + $gz_info->tx + $gz_info->bd
                - $total1_dis - $gz_info->cd - $gz_info->tb - $gz_info->sb - $gz_info->lp, 2);
            $tmp_yf = 0;
            if ($gz_info->ycq > $gz_info->scq) {
                $tmp_yf += $items[$index]['tc'] * 0.2;
            }
            if ($gz_info->yts > $gz_info->sts) {
                $tmp_yf += $items[$index]['tc'] * 0.2;
            }
            $items[$index]['yf'] = $items[$index]['tc'] - $tmp_yf;

            $gz_info->order_count = $order_count;
            $gz_info->total1_clear = round($total1_clear, 2);
            $gz_info->total1_rate = round($total1_rate, 2);
            $gz_info->total1_dis = round($total1_dis, 2);
            $gz_info->gift1_count = $gift1_count;
            $gz_info->gift1_total = $gift1_total;
            $gz_info->gift2_count = $gift2_count;
            $gz_info->gift2_total = $gift2_total;
            $gz_info->tj = $items[$index]['tj'];
            $gz_info->tc = $items[$index]['tc'];
            $gz_info->yf = $items[$index]['yf'];
            $gz_info->save();
        }

        $result['success'] = true;
        $result['msg'] = '计算成功';

        return $result;
    }

    public function actionPayListInfo()
    {
        $request = Yii::$app->request;
        $id = $request->get('id', 0);
        $year = $request->get('year', date('Y'));
        $month = $request->get('month', date('m'));
        $area_id = $request->get('area_id');
        $name = $request->get('name');
        $total1_rate = $request->get('total1_rate');

        $info = UserT::findOne(['id' => $id]);
        $gz_info = GzT::findOne(['sale_id' => $info->id, 'year' => $year, 'month' => $month]);

        $assign_query = OrderT::find()
            ->where('user_id=' . $info->id . ' and status_id>5');
        $printdate_begin = $year . '-' . $month . '-01';
        if ($printdate_begin != '') {
            $assign_query = $assign_query->andWhere('print_date>="' . $printdate_begin . '"');
        }
        $printdate_end = date('Y-m-d', strtotime('+1 months', strtotime($printdate_begin)));
        if ($printdate_end != '') {
            $assign_query = $assign_query->andWhere('print_date<"' . $printdate_end . '"');
        }
        $items = $assign_query->all();

        return $this->render('pay-list-info', [
            'info' => $info,
            'gz_info' => $gz_info,
            'items' => $items,
            'year' => $year,
            'month' => $month,
            'area_id' => $area_id,
            'name' => $name,
            'total1_rate' => $total1_rate,
        ]);
    }

    public function actionGzSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        $sale_id = $request->post('sale_id', 0);
        $year = $request->post('year', date('Y'));
        $month = $request->post('month', date('m'));
        $ycq = $request->post('ycq');
        $scq = $request->post('scq');
        $yts = $request->post('yts');
        $sts = $request->post('sts');
        $hb = $request->post('hb');
        $other = $request->post('other');
        $tx = $request->post('tx');
        $cd = $request->post('cd');
        $tb = $request->post('tb');
        $sb = $request->post('sb');
        $bd = $request->post('bd');
        $tj = $request->post('tj');
        $lp = $request->post('lp');

        $gz_info = GzT::findOne(['sale_id' => $sale_id, 'year' => $year, 'month' => $month]);
        if (isset($gz_info)) {
            $gz_info->ycq = $ycq;
            $gz_info->scq = $scq;
            $gz_info->yts = $yts;
            $gz_info->sts = $sts;
            $gz_info->hb = $hb;
            $gz_info->other = $other;
            $gz_info->tx = $tx;
            $gz_info->cd = $cd;
            $gz_info->tb = $tb;
            $gz_info->sb = $sb;
            $gz_info->bd = $bd;
            $gz_info->lp = $lp;
            if (!$gz_info->save()) {
                var_dump($gz_info->errors);
                exit;
            }
            $result['success'] = true;
            $result['msg'] = '保存成功';
        }
        foreach ($tj as $id => $tijiang) {
            $row = OrderT::findOne(['id' => $id]);
            $row->tijiang = $tijiang;
            $row->save();
        }
        return $result;
    }

    public function actionEmsList()
    {
        $request = Yii::$app->request;
        $year = $request->get('year');
        $month = $request->get('month');
        $page = $request->get('page', 1);
        if ($page < 1) $page = 1;

        $query = EmsT::find();
        if ($year != '') {
            $date = $year . '-' . $month;
            $query = $query->andWhere('created_at like "' . $date . '%"');
        }
        $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('ems-list', [
            'items' => $items,
            'page' => $page,
            'page_info' => $page_info,
            'year' => $year,
            'month' => $month
        ]);
    }

    public function actionEmsListSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        $request = Yii::$app->request;
        $prices = $request->post('prices');
        foreach ($prices as $id => $price) {
            $row = EmsT::findOne(['id' => $id]);
            if ($row) {
                $row->ems_price = $price;
                $row->save();
            }
        }
        $result['success'] = true;
        $result['msg'] = '保存成功';

        return $result;
    }

    public function actionEmsExport()
    {
        Yii::$app->response->format = Response::FORMAT_RAW;
        $request = Yii::$app->request;

        $objectPHPExcel = new \PHPExcel();

        $objectPHPExcel->getProperties()->setCreator("华信互动")
            ->setLastModifiedBy("华信互动")
            ->setTitle("Office 2007 XLSX Test Document")
            ->setSubject("Office 2007 XLSX Test Document")
            ->setDescription("自动生成");

        $objectPHPExcel->setActiveSheetIndex(0);

        $year = $request->get('year');
        $month = $request->get('month');

        $query = EmsT::find();
        if ($year != '') {
            $date = $year . '-' . $month;
            $query = $query->andWhere('created_at like "' . $date . '%"');
        }

        $items = $query->all();

        $index = 1;
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('A' . $index, '快递公司');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('B' . $index, '快递单号');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('C' . $index, '快递电话');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('D' . $index, '快递价格');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('E' . $index, '备注');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('F' . $index, '发送时间');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('G' . $index, '车牌号');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('H' . $index, '业务员');

        foreach ($items as $item) {
            $index++;
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('A' . $index, $item->ems_company);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('B' . $index, $item->ems_no);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('C' . $index, $item->ems_phone);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('D' . $index, $item->ems_price);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('E' . $index, $item->ems_remark);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('F' . $index, $item->created_at);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('G' . $index, $item->car->car_no);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('H' . $index, $item->user->getShowName());
        }

        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition:attachment;filename="' . date("YmjHis") . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objectPHPExcel, 'Excel5');
        $objWriter->save('php://output');
    }

    public function actionPayList3()
    {
        $request = Yii::$app->request;
        $year = $request->get('year', date('Y'));
        $month = $request->get('month', date('m'));
        $name = $request->get('name');

        //获取员工
        $user_items = SendLogT::find()
            ->groupBy('user_id')
            ->all();

        $items = array();
        foreach ($user_items as $index => $item) {
            $row = array();
            $row['id'] = $item->user ? $item->user->id : '';
            $row['showname'] = $item->user ? $item->user->getShowName() : '';
            $gz_info = Gz2T::findOne(['sale_id' => $item->user_id, 'year' => $year, 'month' => $month]);
            if (!isset($gz_info)) {
                $gz_info = new Gz2T();
                $gz_info->sale_id = $item->id;
                $gz_info->year = $year;
                $gz_info->month = $month;
                $gz_info->send_count = 0;
                $gz_info->send_count2 = 0;
                $gz_info->price = 0;
                $gz_info->base_money = 0;
                $gz_info->phone_money = 0;
                $gz_info->other_money = 0;
                $gz_info->pay_money = 0;
                if (!$gz_info->save()) {
                    var_dump($gz_info->errors);
                    exit;
                }
            }
            $assign_query = SendLogT::find()
                ->where('user_id=' . $item->user_id);
            $printdate_begin = $year . '-' . $month . '-01 00:00:00';
            if ($printdate_begin != '') {
                $assign_query = $assign_query->andWhere('send_time>=' . strtotime($printdate_begin));
            }
            $printdate_end = date('Y-m-d 00:00:00', strtotime('+1 months', strtotime($printdate_begin)));
            if ($printdate_end != '') {
                $assign_query = $assign_query->andWhere('send_time<=' . strtotime($printdate_end));
            }
            $send_count = $assign_query->count();
            $row['send_count'] = $send_count;

            $gz_info->send_count = $send_count;
            $gz_info->send_count2 = 0;
            $gz_info->pay_money = round(($gz_info->send_count + $gz_info->send_count2) * $gz_info->price
                + $gz_info->base_money + $gz_info->phone_money + $gz_info->other_money, 2);
            $gz_info->save();

            $row['price'] = $gz_info->price;
            $row['base_money'] = $gz_info->base_money;
            $row['phone_money'] = $gz_info->phone_money;
            $row['other_money'] = $gz_info->other_money;
            $row['pay_money'] = $gz_info->pay_money;
            $items[$index] = $row;
        }

        return $this->render('pay-list3', [
            'items' => $items,
            'year' => $year,
            'month' => $month,
            'name' => $name
        ]);
    }

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

        $prices = $request->post('prices');
        $year = $request->post('year');
        $month = $request->post('month');
        $base_moneys = $request->post('base_moneys');
        $phone_moneys = $request->post('phone_moneys');
        $other_moneys = $request->post('other_moneys');

        foreach ($prices as $id => $price) {
            $gz_info = Gz2T::findOne(['sale_id' => $id, 'year' => $year, 'month' => $month]);
            if (!isset($gz_info)) {
                $gz_info = new Gz2T();
                $gz_info->sale_id = $id;
                $gz_info->year = $year;
                $gz_info->month = $month;
                $gz_info->send_count = 0;
                $gz_info->send_count2 = 0;
                $gz_info->price = 0;
                $gz_info->base_money = 0;
                $gz_info->phone_money = 0;
                $gz_info->other_money = 0;
                $gz_info->pay_money = 0;
                if (!$gz_info->save()) {
                    var_dump($gz_info->errors);
                    exit;
                }
            }
            $gz_info->price = $price;
            $gz_info->base_money = $base_moneys[$id];
            $gz_info->phone_money = $phone_moneys[$id];
            $gz_info->other_money = $other_moneys[$id];
            $gz_info->pay_money = round(($gz_info->send_count + $gz_info->send_count2) * $gz_info->price
                + $gz_info->base_money + $gz_info->phone_money + $gz_info->other_money, 2);
            if (!$gz_info->save()) {
                var_dump($gz_info->errors);
                exit;
            }
        }

        $result['success'] = true;
        $result['msg'] = '计算成功';

        return $result;
    }

    public function actionPayList3Info()
    {
        $request = Yii::$app->request;
        $id = $request->get('id', 0);
        $year = $request->get('year', date('Y'));
        $month = $request->get('month', date('m'));
        $name = $request->get('name');

        $info = UserT::findOne(['id' => $id]);
        $gz_info = Gz2T::findOne(['sale_id' => $info->id, 'year' => $year, 'month' => $month]);

        $assign_query = SendLogT::find()
            ->where('user_id=' . $info->id);
        $printdate_begin = $year . '-' . $month . '-01 00:00:00';
        if ($printdate_begin != '') {
            $assign_query = $assign_query->andWhere('send_time>=' . strtotime($printdate_begin));
        }
        $printdate_end = date('Y-m-d 00:00:00', strtotime('+1 months', strtotime($printdate_begin)));
        if ($printdate_end != '') {
            $assign_query = $assign_query->andWhere('send_time<=' . strtotime($printdate_end));
        }
//        echo $assign_query->createCommand()->getRawSql();
        $items = $assign_query->all();

        return $this->render('pay-list3-info', [
            'info' => $info,
            'gz_info' => $gz_info,
            'items' => $items,
            'year' => $year,
            'month' => $month,
            'name' => $name
        ]);
    }

    public function actionPayList3InfoExport()
    {
        Yii::$app->response->format = Response::FORMAT_RAW;
        $request = Yii::$app->request;
        $id = $request->get('sale_id', 0);
        $year = $request->get('year', date('Y'));
        $month = $request->get('month', date('m'));

        $info = UserT::findOne(['id' => $id]);
        $gz_info = Gz2T::findOne(['sale_id' => $info->id, 'year' => $year, 'month' => $month]);

        $assign_query = SendLogT::find()
            ->where('user_id=' . $info->id);
        $printdate_begin = $year . '-' . $month . '-01 00:00:00';
        if ($printdate_begin != '') {
            $assign_query = $assign_query->andWhere('send_time>=' . strtotime($printdate_begin));
        }
        $printdate_end = date('Y-m-d 00:00:00', strtotime('+1 months', strtotime($printdate_begin)));
        if ($printdate_end != '') {
            $assign_query = $assign_query->andWhere('send_time<=' . strtotime($printdate_end));
        }
//        echo $assign_query->createCommand()->getRawSql();
        $items = $assign_query->all();

        $objectPHPExcel = new \PHPExcel();

        $objectPHPExcel->getProperties()->setCreator("华信互动")
            ->setLastModifiedBy("华信互动")
            ->setTitle("Office 2007 XLSX Test Document")
            ->setSubject("Office 2007 XLSX Test Document")
            ->setDescription("自动生成");

        $objectPHPExcel->setActiveSheetIndex(0);

        $index = 1;
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('A' . $index, '车牌号码');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('B' . $index, '被保险人');

        foreach ($items as $item) {
            $index++;
            $order_info = $item->order;
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('A' . $index, $order_info->car_no);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('B' . $index, $order_info->id_man);
        }

        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition:attachment;filename="' . date("YmjHis") . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objectPHPExcel, 'Excel5');
        $objWriter->save('php://output');
    }

    public function actionFeeList()
    {
        $request = Yii::$app->request;
        $page = $request->get('page', 1);
        $printdate_begin = $request->get('printdate_begin', date('Y-m-d'));
        $printdate_end = $request->get('printdate_end', date('Y-m-d'));
        $return_flag = $request->get('return_flag', 0);
        $company_id = $request->get('company_id', 0);

        $query = CaiwuT::find()
            ->leftJoin('order_t', 'order_t.id=caiwu_t.order_id')
            ->where('order_t.print_date>="' . $printdate_begin . '" and order_t.print_date<="' . $printdate_end . '"');

        if ($company_id > 0) {
            $query = $query->andWhere('order_t.company_id=' . $company_id);
        }
        if ($return_flag > 0) {
            if ($return_flag == 1) {
                $query = $query->andWhere('process_date is not null');
            }
            if ($return_flag == 2) {
                $query = $query->andWhere('process_date is null');
            }
        }
//        echo $query->createCommand()->rawSql;
//        exit;
        $total = $query->count();

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

        $price_totals = array();
        $price_totals['total'] = round($query->sum('total'), 2);
        $price_totals['price3'] = round($query->sum('total_clear_real'), 2);
        $price_totals['price4'] = round($query->sum('total_tax_real'), 2);
        if ($return_flag == 0 || $return_flag == 1) {
            $tmp_query = clone $query;
            $tmp_query2 = CaiwuExcelT::find()
                ->where(['in', 'field1', $tmp_query->select('insurer_no')->andWhere('process_date is not null')]);
            $price_totals['price5'] = round($tmp_query2->sum('field8'), 2);
        } else {
            $price_totals['price5'] = '0.00';
        }

        $query = $query->offset($pagination->offset)->limit($pagination->limit)
            ->orderBy('id desc');
        $items = $query->all();

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

        $company_items = InsurerCompanyT::find()
            ->all();

        return $this->render('fee-list', [
            'printdate_begin' => $printdate_begin,
            'printdate_end' => $printdate_end,
            'items' => $items,
            'return_flag' => $return_flag,
            'page_info' => $page_info,
            'price_totals' => $price_totals,
            'company_items' => $company_items,
            'company_id' => $company_id
        ]);
    }

    public function actionGiftPrice()
    {
        $request = Yii::$app->request;
        $year = $request->get('year', date('Y'));
        $month = $request->get('month', date('m'));

        $items = CaiwuGiftT::find()
            ->where('year=' . $year . ' and month=' . $month)
            ->all();
        if (!$items) {
            $gift_items = GiftType3T::find()->all();
            foreach ($gift_items as $item) {
                $row = new CaiwuGiftT();
                $row->year = $year;
                $row->month = $month;
                $row->gift_id = $item->id;
                $row->price = 0;
                $row->save();
            }
            $items = CaiwuGiftT::find()
                ->where('year=' . $year . ' and month=' . $month)
                ->all();
        }

        return $this->render('gift-price', [
            'year' => $year,
            'month' => $month,
            'items' => $items
        ]);
    }

    public function actionGiftPriceSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '提交失败';

        $request = Yii::$app->request;
        $prices = $request->post('prices');

        $tran = OrderT::getDb()->beginTransaction();
        try {
            foreach ($prices as $id => $price) {
                $row = CaiwuGiftT::findOne(['id' => $id]);
                if ($row) {
                    $row->price = $price;
                    $row->save();
                }
            }

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

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

        return $result;
    }

    public function actionPayGiftList()
    {
        $request = Yii::$app->request;
        $year = $request->get('year', date('Y'));
        $month = $request->get('month', date('m'));
        $user_id = $request->get('user_id');
        $is_free = $request->get('is_free', 1);

        //读取礼品价格
        $price_items = CaiwuGiftT::find()
            ->where('year=' . $year . ' and month=' . $month)
            ->all();
        $gift_price = array();
        foreach ($price_items as $item) {
            $gift_price[$item->gift_id] = $item->price;
        }

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

        $order_query = OrderT::find()
            ->where('user_id=' . $user_info->id . ' and status_id>5')
            ->orderBy('print_date ASC');
        $printdate_begin = $year . '-' . $month . '-01';
        if ($printdate_begin != '') {
            $order_query = $order_query->andWhere('print_date>="' . $printdate_begin . '"');
        }
        $printdate_end = date('Y-m-d', strtotime('+1 months', strtotime($printdate_begin)));
        if ($printdate_end != '') {
            $order_query = $order_query->andWhere('print_date<"' . $printdate_end . '"');
        }
        $gift_list = array();
        foreach ($order_query->each() as $order_info) {
            $gift_query = OrderGiftT::find()
                ->where('order_id=' . $order_info->id);
            $gift_items = $gift_query->all();
            foreach ($gift_items as $gift_item) {
                $gift_info = $gift_item->gift;
                $group_info = $gift_item->group;
                if (!$group_info) continue;
                if (!$gift_info) continue;
                if ($is_free && $group_info->is_free == 1) {
                    $row = array();
                    $row['price'] = 0;
                    $row['count'] = 0;
                    $row['total'] = 0;
                    $row['print_date'] = $order_info->print_date;
//                    if(isset($gift_list[$gift_info->id]))
//                        $row = $gift_list[$gift_info->id];
                    $row['name'] = $gift_info->name;
                    $row['price'] = $gift_price[$gift_info->id];
                    $row['count'] += 1;
                    $row['total'] += $gift_price[$gift_info->id];
//                    $gift_list[$gift_info->id] = $row;
                    $gift_list[] = $row;
                }
                if ($is_free == 0 && $group_info->is_free == 0) {
                    $row = array();
                    $row['price'] = 0;
                    $row['count'] = 0;
                    $row['total'] = 0;
                    $row['print_date'] = $order_info->print_date;
//                    if(isset($gift_list[$gift_info->id]))
//                        $row = $gift_list[$gift_info->id];
                    $row['name'] = $gift_info->name;
                    $row['price'] = $gift_price[$gift_info->id];
                    $row['count'] += 1;
                    $row['total'] += $gift_price[$gift_info->id];
//                    $gift_list[$gift_info->id] = $row;
                    $gift_list[] = $row;
                }
            }
        }


        return $this->render('pay-gift-list', [
            'year' => $year,
            'month' => $month,
            'gift_list' => $gift_list
        ]);
    }

    /**
     * 财务工资列表
     * @return string
     */
    public function actionPay2List() {
        $group_items = GroupT::getTree();
        return $this->render('pay2-list',[
            'group_items' => $group_items
        ]);
    }
    public function actionPay2ListJson()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $username = $request->get('username');
        $name = $request->get('name');
        $pay_date = $request->get('pay_date', date('Y-m'));
        $group_id = $request->get('group_id', 0);
        $is_leave = $request->get('is_leave');
        $offset = $request->get('offset', 0);
        $limit = $request->get('limit', 10);

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

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

        $data = [];
        $data['total'] = $total;
        $data['rows'] = [];
        foreach($items as $item) {
            $row = $item->toArray();
            $row['pay_date'] = $pay_date;
            $row['group_name'] = $item->group ? $item->group->path : '';
            $row['is_leave'] = $item->is_leave ? '已离职':'';
            $pay_info = $item->getPay($pay_date);
            $row['status_name'] = $pay_info ? $pay_info->getStatus($pay_info->status_id) : '';
            $row['real_pay'] = $pay_info ? $pay_info->base_real_pay : '';
            $row['should_pay'] = $pay_info ? $pay_info->ticheng_real_pay : '';
            $row['is_show'] = $pay_info && ($pay_info->renshi_status_id > 0 && $pay_info->chuna_status_id > 0 && $pay_info->status_id != 7 && $pay_info->status_id != 8) ? 1 : 0;
            $data['rows'][] = $row;
        }

        $pay_chexian = PayT::find()
            ->where("pay_date='{$pay_date}'")
            ->sum('ticheng_real_pay');

        $data['rows'][] = array(
            ['提成工资总额', number_format($pay_chexian,2)],
        );

        return $data;
    }

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

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

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

        if (!$work_day) {
            echo $pay_date . '还没有开始统计';
            echo "[<a href='/finance/pay2-list?$back_params'>返回</a>]";
            die;
        }

        $pay_info = PayT::findOne(['user_id' => $user_id, 'pay_date' => $pay_date]);
        if (!$pay_info) {
            $pay_info = new PayT();
            $pay_info->user_id = $user_id;
            $pay_info->pay_date = $pay_date;
            if ($group_info) {
                $pay_info->should_pay = $group_info->base_pay + $group_info->job_pay + $group_info->station_pay + $user_info->ext_pay;
            } else {
                $pay_info->should_pay = $user_info->ext_pay;
            }
            if (!$pay_info->save()) {
                var_dump($pay_info->errors);
                exit;
            }
        }
        //内勤
        //核保
        $my_type5_query = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and is_own=0 and type=5  and user_id=' . $user_id)
            ->orderBy('created_at asc');
//                echo $my_type5_query->createCommand()->rawSql;
        //正本
        $my_type6_query = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and is_own=0 and type=6 and user_id=' . $user_id)
            ->orderBy('created_at asc');


        $my_type1_query = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and is_own=1 and type=1 and user_id=' . $user_id)
            ->orderBy('created_at asc');
        $my_type1_query_non = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and is_own=2 and type=7 and user_id=' . $user_id)
            ->orderBy('created_at asc');
        $my_type1_query_hebao = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and is_own=2 and type=8 and user_id=' . $user_id)
            ->orderBy('created_at asc');

//原新保
        $my_type0_query = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '"  and type=1 and user_id=' . $user_id.' and is_own =0')
            ->orderBy('created_at asc');



//        echo $my_type1_query->createCommand()->rawSql;
        $my_type3_query = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and is_own=1 and type=3 and user_id=' . $user_id)
            ->orderBy('created_at asc');
//        echo $my_type3_query->createCommand()->rawSql;
        $type_query = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and type<>4 and type<>5 and type<>6 and is_own=0 and user_id=' . $user_id)
            ->andWhere('should_pay>0')
            ->orderBy('created_at asc');
//        echo $type_query->createCommand()->rawSql;
        $type3_query = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and type=4 and user_id=' . $user_id)
            ->orderBy('created_at asc');
        $pay_order_users = OrderT::find()
            ->where('print_date like "' . $pay_date . '-%"')
            ->andWhere('user_id=' . $this->my->id)
            ->orderBy('updated_at ASC');

        return $this->render('pay2-info', [
            'pay_date' => $pay_date,
            'user_info' => $user_info,
            'group_info' => $group_info,
            'pay_info' => $pay_info,
            'my_type0_query' => $my_type0_query,
            'my_type1_query' => $my_type1_query,
            'my_type3_query' => $my_type3_query,
            'my_type5_query' => $my_type5_query,
            'my_type6_query' => $my_type6_query,
            'my_type1_query_non' => $my_type1_query_non,
            'my_type1_query_hebao' => $my_type1_query_hebao,
            'type_query' => $type_query,
            'type3_query' => $type3_query,
            'back_params' => $back_params,
            'pay_order_users' => $pay_order_users
        ]);
    }
    public function actionPay2ReturnSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        $id = $request->post('id',0);
        $status_id = $request->post('status_id',0);
        $remark = $request->post('remark','');

        $pay_info = PayT::findOne($id);

        $pay_info->status_id = $status_id + 6;


        $content = '财务：'.$this->my->showName.'退回'.$pay_info->pay_date.'工资';
        $this->addUserLog($pay_info->id, $content,$remark);

        if($pay_info->save()){
            $result['success'] = true;
            $result['msg'] = '保存成功';
        }
        return $result;
    }

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

        $pay_id = $request->post('id', 0);
        $my_rate1 = $request->post('my_rate1', array());
        $my_rate2 = $request->post('my_rate2', array());
        $tc_my_payids_1 = $request->post('tc_my_payids_1', array());
        $tc_my_payids_2 = $request->post('tc_my_payids_2', array());
        $my_should_pays1 = $request->post('my_should_pays1', array());
        $my_should_pays2 = $request->post('my_should_pays2', array());
        $my_real_pays1 = $request->post('my_real_pays1', array());
        $my_real_pays2 = $request->post('my_real_pays2', array());
        $tc_payids_1 = $request->post('tc_payids_1', array());
        $tc_payids_2 = $request->post('tc_payids_2', array());
        $rate1 = $request->post('rate1', array());
        $rate2 = $request->post('rate2', array());
        $should_pays1 = $request->post('should_pays1', array());
        $should_pays2 = $request->post('should_pays2', array());
        $real_pays1 = $request->post('real_pays1', array());
        $real_pays2 = $request->post('real_pays2', array());
        $tc_send_payids = $request->post('tc_send_payids', array());
        $send_moneys = $request->post('send_moneys', array());

        //内勤核保
        $neqi_payids = $request->post('neqi_payids', array());
        $should_pays5 = $request->post('should_pays5', array());
        $rate5 = $request->post('rate5', array());
        //内勤正本
        $zhengben = $request->post('zhengben', array());
        $should_pays6 = $request->post('should_pays6', array());
        $rate6 = $request->post('rate6', array());



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

        $pay_info = PayT::findOne(['id' => $pay_id]);
        if ($pay_info) {
            $tran = PayT::getDb()->beginTransaction();
            try {
                //保存我的新保
                foreach ($tc_my_payids_1 as $index => $id) {
                    $rate = $my_rate1[$index];
                    $pay_order = PayOrderUserT::findOne(['id' => $id]);
                    if (!$pay_order) {
                        $result['msg'] = '我的新保错误：' . $id . '=>' . $rate;
                        return $result;
                    }
                    $order_info = $pay_order->order;
                    $caiwu_info = $order_info->caiwu;
                    if ($caiwu_info) {
                        $caiwu_info->rate1 = $rate;
                        $caiwu_info->money1 = $my_should_pays1[$index];
                        if(!$caiwu_info->save()) {
                            throw new \Exception(print_r($caiwu_info->getErrors(), true));
                        }
                    }
                    $pay_order->should_pay = $my_should_pays1[$index];
                    $pay_order->real_pay = $my_real_pays1[$index];
                    if(!$pay_order->save()) {
                        throw new \Exception(print_r($pay_order->getErrors(), true));
                    }
                }
                //我的续保
                foreach ($tc_my_payids_2 as $index => $id) {
                    $rate = $my_rate2[$index];
                    $pay_order = PayOrderUserT::findOne(['id' => $id]);
                    if (!$pay_order) {
                        $result['msg'] = '我的续保错误：' . $id . '=>' . $rate;
                        return $result;
                    }
                    $order_info = $pay_order->order;
                    $caiwu_info = $order_info->caiwu;
                    if ($caiwu_info) {
                        $caiwu_info->rate3 = $rate;
                        $caiwu_info->money3 = $my_should_pays2[$index];
                        if(!$caiwu_info->save()) {
                            throw new \Exception(print_r($caiwu_info->getErrors(), true));
                        }
                    }
                    $pay_order->should_pay = $my_should_pays2[$index];
                    $pay_order->real_pay = $my_real_pays2[$index];
                    if(!$pay_order->save()) {
                        throw new \Exception(print_r($pay_order->getErrors(), true));
                    }
                }
                //我的提成
                foreach ($tc_payids_1 as $index => $id) {
                    $pay_order = PayOrderUserT::findOne(['id' => $id]);
                    if (!$pay_order) {
                        $result['msg'] = '我的提成错误1：' . $id . '=>' . $rate1[$index];
                        return $result;
                    }
                    $order_info = $pay_order->order;
                    $caiwu_info = $order_info->caiwu;
                    if ($caiwu_info) {
                        $caiwu_info->rate1 = $rate1[$index];
                        $caiwu_info->money1 = $should_pays1[$index];
                        if(!$caiwu_info->save()) {
                            throw new \Exception(print_r($caiwu_info->getErrors(), true));
                        }
                    }
                    $pay_order->should_pay = $should_pays1[$index];
                    $pay_order->real_pay = $real_pays1[$index];
                    if(!$pay_order->save()) {
                        throw new \Exception(print_r($pay_order->getErrors(), true));
                    }
                }
                foreach ($tc_payids_2 as $index => $id) {
                    $pay_order = PayOrderUserT::findOne(['id' => $id]);
                    if (!$pay_order) {
                        $result['msg'] = '我的提成错误2：' . $id . '=>' . $rate2[$index];
                        return $result;
                    }
                    $order_info = $pay_order->order;
                    $caiwu_info = $order_info->caiwu;
                    if ($caiwu_info) {
                        $caiwu_info->rate2 = $rate2[$index];
                        $caiwu_info->money2 = $should_pays2[$index];
                        if(!$caiwu_info->save()) {
                            throw new \Exception(print_r($caiwu_info->getErrors(), true));
                        }
                    }
                    $pay_order->should_pay = $should_pays2[$index];
                    $pay_order->real_pay = $real_pays2[$index];
                    if(!$pay_order->save()) {
                        throw new \Exception(print_r($pay_order->getErrors(), true));
                    }
                }
                //核保
                foreach ($neqi_payids as $index => $id) {
                    $pay_order = PayOrderUserT::findOne(['id' => $id]);
                    if (!$pay_order) {
                        $result['msg'] = '我的提成错误2：' . $id . '=>' . $rate5[$index];
                        return $result;
                    }
                    $order_info = $pay_order->order;
                    $caiwu_info = $order_info->caiwu;
                    if ($caiwu_info) {
                        if(!isset($rate5[$index])) continue;
                        $caiwu_info->rate4 = $rate5[$index];
                        $caiwu_info->money4 = $should_pays5[$index];
                        if(!$caiwu_info->save()) {
                            throw new \Exception(print_r($caiwu_info->getErrors(), true));
                        }
                    }
                    $pay_order->should_pay = $should_pays5[$index];
                    $pay_order->real_pay = $should_pays5[$index];
                    if(!$pay_order->save()) {
                        throw new \Exception(print_r($pay_order->getErrors(), true));
                    }
                }
                //正本$neqi_payids1
                foreach ($zhengben as $index => $id) {
                    $pay_order = PayOrderUserT::findOne(['id' => $id]);
                    if (!$pay_order) {
                        $result['msg'] = '我的提成错误2：' . $id . '=>' . $rate6[$index];
                        return $result;
                    }
                    $order_info = $pay_order->order;
                    $caiwu_info = $order_info->caiwu;
                    if ($caiwu_info) {
                        if(!isset($rate6[$index])) continue;
                        $caiwu_info->rate5 = $rate6[$index];
                        $caiwu_info->money5 = $should_pays6[$index];
                        if(!$caiwu_info->save()) {
                            throw new \Exception(print_r($caiwu_info->getErrors(), true));
                        }
                    }
                    $pay_order->should_pay = $should_pays6[$index];
                    $pay_order->real_pay = $should_pays6[$index];
                    if(!$pay_order->save()) {
                        throw new \Exception(print_r($pay_order->getErrors(), true));
                    }
                }

                $pay_info->calls = $calls;
                $pay_info->bus = $bus;
                $pay_info->bonus = $bonus;
                $pay_info->turnover = $turnover;
                $pay_info->driver_num = $driver_num;
                $pay_info->driver_price = $driver_price;
                $pay_info->fix_total = $fix_total;
                $pay_info->fix_rate = $fix_rate;
                $pay_info->tax = $tax;
                $pay_info->caiwu_status_id = 1;
                $pay_info->status_id = $pay_info->renshi_status_id + $pay_info->chuna_status_id + $pay_info->caiwu_status_id;
                if(!$pay_info->save()) {
                    throw new \Exception(print_r($pay_info->getErrors(), true));
                }
                $pay_info->calPay();
//                $pay_info->save();

                $content = $this->my->showName . '修改' . $pay_info->pay_date . '工资';
                $this->addUserLog($pay_info->user_id, $content);

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

            $result['success'] = true;
            $result['msg'] = '保存成功';
        }
        return $result;
    }
    /**
     * 重新计算指定月份工资
     * @return array
     * @throws \Exception
     * @throws \yii\db\Exception
     */
    public function actionPay2Reset()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '计算失败';

        $pay_date = $request->post('pay_date');
        if ($pay_date) {
            $orders = OrderT::find()
                ->where('print_date like "' . $pay_date . '%"')
                ->with('caiwu')
                ->with('car')
                ->with('sendLog');
            foreach ($orders->each() as $order) {
                $order_caiwu = $order->caiwu;
                $car = $order->car;
                if (!$order_caiwu) {
                    continue;
                }
                if (!$order_caiwu->pay_date) {
                    $order_caiwu->pay_date = $pay_date;
                    $order_caiwu->save();
                }

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

                    $op_user1_id = substr($car->op_user1, 0, strpos($car->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->id;
                        $pay_order_user->type = 1;
                        $pay_order_user->is_own = $car->op_user3 != '' ? 0 : 1;
                        $pay_order_user->pay_date = $pay_date;
                        $pay_order_user->save();
                        $pay_order_user->calPay();
                        $pay_info = PayT::findOne(['user_id' => $pay1_user->id, 'pay_date' => $pay_date]);
                        if ($pay_info) {
                            $pay_info->calPay();
                        }
                    }
                    $op_user2_id = substr($car->op_user2, 0, strpos($car->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->id;
                        $pay_order_user->type = 2;
                        $pay_order_user->is_own = 0;
                        $pay_order_user->pay_date = $pay_date;
                        $pay_order_user->save();
                        $pay_order_user->calPay();
                        $pay_info = PayT::findOne(['user_id' => $pay2_user->id, 'pay_date' => $pay_date]);
                        if ($pay_info) {
                            $pay_info->calPay();
                        }
                    }
                    $op_user3_id = substr($car->op_user3, 0, strpos($car->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->id;
                        $pay_order_user->type = 3;
                        $pay_order_user->is_own = 1;
                        $pay_order_user->pay_date = $pay_date;
                        $pay_order_user->save();
                        $pay_order_user->calPay();
                        $pay_info = PayT::findOne(['user_id' => $pay3_user->id, 'pay_date' => $pay_date]);
                        if ($pay_info) {
                            $pay_info->calPay();
                        }
                    }
                    $send_info = $order->sendLog;
                    if ($send_info) {
                        $pay_order_user = new PayOrderUserT();
                        $pay_order_user->user_id = $send_info->user_id;
                        $pay_order_user->order_id = $order->id;
                        $pay_order_user->type = 4;
                        $pay_order_user->is_own = 0;
                        $pay_order_user->pay_date = $pay_date;
                        $pay_order_user->save();
                        $pay_order_user->calPay();
                        $pay_info = PayT::findOne(['user_id' => $send_info->user_id, 'pay_date' => $pay_date]);
                        if ($pay_info) {
                            $pay_info->calPay();
                        }
                    }
                }

            }
            $result['success'] = true;
            $result['msg'] = '计算成功';
        }
        return $result;
    }

    public function actionPay2GiftInfo()
    {
        $request = Yii::$app->request;
        $order_id = $request->get('order_id', 0);
        $is_free = $request->get('is_free', 0);
        $type = $request->get('type', 0);
        $user_id = $request->get('user_id');
        $pay_date = $request->get('pay_date');

        $order_info = OrderT::findOne(['id' => $order_id]);

        $order_gifts = OrderGiftT::find()
            ->where(['order_id' => $order_id, 'is_free' => $is_free, 'gift_type' => $type])
            ->all();

        return $this->render('pay2-gift-info', [
            'order_info' => $order_info,
            'is_free' => $is_free,
            'type' => $type,
            'order_gifts' => $order_gifts,
            'user_id' => $user_id,
            'pay_date' => $pay_date
        ]);
    }

    public function actionPay2GiftSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        $user_id = $request->post('user_id');
        $pay_date = $request->post('pay_date');
        $order_id = $request->post('order_id');
        $gift_ids = $request->post('gift_ids', array());
        $gift_rates = $request->post('gift_rates', array());
        $gift_prices = $request->post('gift_prices', array());

        $tran = OrderGiftT::getDb()->beginTransaction();
        try {
            //保存礼品
            foreach ($gift_ids as $index => $id) {
                $rate = isset($gift_rates[$index]) ? $gift_rates[$index] : 0;
                $order_gift = OrderGiftT::findOne(['id' => $id]);
                if ($order_gift) {
                    $order_gift->rate = $rate;
                    $order_gift->price = $gift_prices[$index];
                    $order_gift->save();
                }
            }
            $pay_order = PayOrderUserT::findOne(['user_id' => $user_id, 'pay_date' => $pay_date, 'order_id' => $order_id]);
            if ($pay_order) {
                $pay_order->calPay();
            }
            $pay = PayT::findOne(['user_id' => $user_id, 'pay_date' => $pay_date]);
            if ($pay) {
                $pay->calPay();
            }

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

            //保存礼品
            $tran->commit();

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

        return $result;
    }

    //工资统计
    public function actionPay3List()
    {
        $request = Yii::$app->request;
        $user_id = $this->my->id;
//        var_dump($user_id );
        $ids = $this->my->getChildrenUserIDs();
//        var_dump($ids);
        $username = $request->get('username');
        $name = $request->get('name');
        $pay_date = $request->get('pay_date', date('Y-m'));
        $group_id = $request->get('group_id', 0);
        $page = $request->get('page', 1);

        $query = UserT::find()
            ->where('group_id>0 and is_leave=0')
            ->andWhere('id = ' . $user_id)
            ->orWhere(['in', 'id', $ids]);

        if ($username != '') {
            $query = $query->andWhere('username like "' . $username . '"');
        }
        if ($name != '') {
            $query = $query->andWhere('name like "' . $name . '"');
        }
        if ($group_id > 0) {
            $query = $query->andWhere('group_id=' . $group_id);
        }
        $query = $query->orderBy('username ASC,id ASC');
        $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);

        $group_items = GroupT::getTree($user_id);

        return $this->render('pay3-list', [
            'group_items' => $group_items,
            'items' => $items,
            'page_info' => $page_info,
            'page' => $page,
            'username' => $username,
            'name' => $name,
            'pay_date' => $pay_date,
            'group_id' => $group_id
        ]);
    }

    //工资统计详情
    public function actionPay3Info()
    {
        $request = Yii::$app->request;

        $user_id = $request->get('id', 0);
        $pay_date = $request->get('pay_date');
        $back_params = $request->get('back_params');

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

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

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

        if ($day_num == '0') {
            echo $pay_date . ' 还没有进行工资统计，无法查看!';
            echo '[<a href="/finance/pay3-list">返回</a>]';
            die;
        }

        $pay_info = PayT::findOne(['user_id' => $user_id, 'pay_date' => $pay_date]);
        if (!$pay_info) {
            $pay_info = new PayT();
            $pay_info->user_id = $user_id;
            $pay_info->pay_date = $pay_date;
            if ($group_info) {
                $pay_info->should_pay = $group_info->base_pay + $group_info->job_pay + $group_info->station_pay + $user_info->ext_pay;
            } else {
                $pay_info->should_pay = $user_info->ext_pay;
            }
            if (!$pay_info->save()) {
                var_dump($pay_info->errors);
                exit;
            }
        }

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


        $my_type1_query = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and is_own=1 and type=1 and user_id=' . $user_id);
        $my_type3_query = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and is_own=1 and type=3 and user_id=' . $user_id);
//        echo $my_type3_query->createCommand()->rawSql;
        $type_query = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and type<>4 and is_own=0 and user_id=' . $user_id);
//        echo $type_query->createCommand()->rawSql;
        $type3_query = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and type=4 and user_id=' . $user_id);
        $pay_order_users = OrderT::find()
            ->where('print_date like "' . $pay_date . '-%"')
            ->andWhere('user_id=' . $this->my->id)
            ->orderBy('updated_at ASC');

        return $this->render('pay3-info', [
            'pay_date' => $pay_date,
            'user_info' => $user_info,
            'group_info' => $group_info,
            'pay_info' => $pay_info,
            'my_type1_query' => $my_type1_query,
            'my_type3_query' => $my_type3_query,
            'type_query' => $type_query,
            'type3_query' => $type3_query,
            'back_params' => $back_params,
            'pay_order_users' => $pay_order_users,
            'try_pay' => $try_pay,
            'true_pay' => $true_pay
        ]);
    }

    //退保统计
    public function actionReturnInsurer()
    {
        $request = Yii::$app->request;
        $page = $request->get('page', 1);
        $begin_date = $request->get('begin_date');
        $end_date = $request->get('end_date');
        $p_begin_date = $request->get('p_begin_date');
        $p_end_date = $request->get('p_end_date');
        $car_no = $request->get('car_no');
        $insurer_no = $request->get('insurer_no');
        if ($page < 1) $page = 1;

        $query = OrderCaiwuT::find()
            ->leftJoin('order_t', 'order_t.id=order_caiwu_t.order_id')
            ->where('order_caiwu_t.business_back_money>0 or order_caiwu_t.force_back_money>0')
            ->orderBy('order_caiwu_t.id DESC');

        if ($car_no != "") {
            $query = $query->andWhere('order_t.car_no like "' . $car_no . '%"');
        }
        if ($insurer_no != "") {
            $query = $query->andWhere('order_t.insurer1_no like "' . $insurer_no . '%" or order_t.insurer2_no like "' . $insurer_no . '%"');
        }
        if ($begin_date != "") {
            $query = $query->andWhere('order_t.submit_date>="' . $begin_date . '"');
        }
        if ($end_date != "") {
            $query = $query->andWhere('order_t.submit_date<="' . $end_date . '"');
        }
        if ($p_begin_date != "") {
            $query = $query->andWhere('order_t.print_date>="' . $p_begin_date . '"');
        }
        if ($p_end_date != "") {
            $query = $query->andWhere('order_t.print_date<="' . $p_end_date . '"');
        }
//        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('return-insurer', [
            'items' => $items,
            'page' => $page,
            'car_no' => $car_no,
            'insurer_no' => $insurer_no,
            'begin_date' => $begin_date,
            'end_date' => $end_date,
            'p_begin_date' => $p_begin_date,
            'p_end_date' => $p_end_date,
            'page_info' => $page_info
        ]);
    }

    public function actionCaiwuZcList()
    {
        $request = Yii::$app->request;
        $record_s_date = $request->get('record_s_date',date('Y-m-d'));
        $record_e_date = $request->get('record_e_date',date('Y-m-d'));
        $class_id = $request->get('class_id',0);
        $title = $request->get('title','');
        $page = $request->get('page', 1);

        $query = CaiwuZcT::find()
            ->where('1=1');
        if ($record_s_date != '') {
            $query = $query->andWhere('record_date>="' . $record_s_date . '"');
        }
        if ($record_e_date != '') {
            $query = $query->andWhere('record_date<="' . $record_e_date . '"');
        }
        if($class_id != '') {
            $query = $query->andWhere('class_id<="' . $class_id . '"');
        }
        if($title != '') {
            $query = $query->andWhere('title like "%' . $title . '%"');
        }

        $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);

        $class_list = CaiwuClassT::find()->all();

        return $this->render('caiwu-zc-list', [
            'items' => $items,
            'page_info' => $page_info,
            'page' => $page,
            'record_s_date' => $record_s_date,
            'record_e_date' => $record_e_date,
            'class_id' => $class_id,
            'title' => $title,
            'class_list' => $class_list
        ]);
    }

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

        $caiwu_info = CaiwuZcT::findOne(['id' => $id]);
        if($id == 0) {
            $caiwu_info = new CaiwuZcT();
            $caiwu_info->record_date = date('Y-m-d');
            $caiwu_info->class_id = 0;
        }

        $class_list = CaiwuClassT::find()->all();

        return $this->render('caiwu-zc-info', [
            'info' => $caiwu_info,
            'class_list' => $class_list,
            'back_params' => $back_params
        ]);
    }

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

        $id = $request->post('id', 0);
        $record_date = $request->post('record_date');
        $class_id = $request->post('class_id');
        $title = $request->post('title');
        $price = floatval($request->post('price'));
        $num = intval($request->post('num'));
        $note = $request->post('note');

        $total = $price * $num;

        $caiwu_info = CaiwuZcT::findOne(['id' => $id]);
        if (!$caiwu_info) {
            $caiwu_info = new CaiwuZcT();
        }

        $caiwu_info->record_date = $record_date;
        $caiwu_info->title = $title;
        $caiwu_info->class_id = $class_id;
        $caiwu_info->price = $price;
        $caiwu_info->num = $num;
        $caiwu_info->total = $total;
        $caiwu_info->note = $note;

        $caiwu_info->save();
        $result['success'] = true;
        $result['msg'] = '操作成功';

        return $result;
    }

    public function actionCaiwuZcDelete()
    {
        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);

            $tran = CaiwuZcT::getDb()->beginTransaction();
            try {
                if($id > 0) {
                    $caiwu_info = CaiwuZcT::findOne(['id'=>$id]);
                    $caiwu_info->delete();
                }

                $tran->commit();
                $result['success'] = true;
                $result['msg'] = '删除成功';

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

    public function actionCaiwuTjList()
    {
        $request = Yii::$app->request;
        $data_type = $request->get('data_type',1);
        $type = $request->get('type',0);
        $record_s_date = $request->get('record_s_date',date('Y-m-d'));
        $record_e_date = $request->get('record_e_date',date('Y-m-d'));
        $company_id = $request->get('company_id');
        $car_no = $request->get('car_no');
        $insurer_no = $request->get('insurer_no');
        $userid = $request->get('userid');
        $zc_rate = $request->get('zc_rate',0);
        $page = $request->get('page', 1);

        // 回单匹配
        $query = CaiwuT::find()
            ->leftJoin(OrderT::tableName(), "order_t.id=caiwu_t.order_id")
            ->leftJoin(OrderCaiwuT::tableName(), "caiwu_t.order_id=order_caiwu_t.order_id");

        if($data_type == 1) { // 正本日期
            if($record_s_date != '') {
                $query = $query->andWhere('order_t.print_date>="'.$record_s_date.'"');
            }
            if($record_e_date != '') {
                $query = $query->andWhere('order_t.print_date<="'.$record_e_date.'"');
            }
        } else if($data_type == 2) { // 回款日期
            if($record_s_date != '') {
                $query = $query->andWhere('caiwu_t.r_date>="'.$record_s_date.'"');
            }
            if($record_e_date != '') {
                $query = $query->andWhere('caiwu_t.r_date<="'.$record_e_date.'"');
            }
        }
        if($type > 0) {
            if($type == 1) { // 商业
                $query = $query->andWhere('caiwu_t.insurer_type=1');
            }
            if($type == 2) { // 交强
                $query = $query->andWhere('caiwu_t.insurer_type=2');
            }
            if($type == 3) { // 退保
                $query = $query->andWhere('order_caiwu_t.business_back_date<>"" or order_caiwu_t.force_back_date<>""');
            }
        }
        if($company_id > 0) { // 保险公司
            $query = $query->andWhere('order_t.company_id='.$company_id);
        }
        if($car_no != '') {
            $query = $query->andWhere('order_t.car_no="'.$car_no.'"');
        }
        if($insurer_no != '') {
            $query = $query->andWhere('caiwu_t.insurer_no="'.$insurer_no.'"');
        }
        if($userid != '') {
            $tmp_query = UserT::find()->select('id')->where('username like "'.$userid.'%"');
            $query = $query->andWhere(['in','order_t.user_id',$tmp_query]);
        }
//echo $query->createCommand()->rawSql;

        $total = $query->count();

        $all_items = $query->all();

        $totals = array();
        $totals['total_zbf'] = $query->sum('total');
        $totals['total_jbf'] = $query->sum('total_clear');
        $totals['total_yd'] = 0;
        $totals['total_sd'] = 0;
        $totals['total_yhje'] = 0;
        $totals['total_hkce'] = 0;
        $totals['total_yhk'] = 0;
        $totals['total_ywtc'] = 0;
        $totals['total_jl'] = 0;
//        foreach($all_items as $item) {
//            $order_info = $item->order;
//            $order_caiwu_info = $order_info->caiwu;
//
//            $totals['total_zbf'] += $item->total;
//            $totals['total_jbf'] += $item->total_clear;
//            $totals['total_yd'] += round($item->total * $item->total_rate / 100,2);
//            $totals['total_sd'] += round($item->total_clear * $item->total_rate / 100, 2);
//            $totals['total_yhje'] += $item->r_total;
//            $totals['total_hkce'] += $item->total_dis;
//            $totals['total_yhk'] += $order_info->total1_dis;
//            if($order_caiwu_info)
//                $totals['total_ywtc'] += round($order_caiwu_info->money1 + $order_caiwu_info->money2 + $order_caiwu_info->money3 + $order_caiwu_info->money4 + $order_caiwu_info->money5 + $order_caiwu_info->send_money - $order_info->total1_dis,2);
//        }
//        $totals['total_jl'] = round($totals['total_yhje'] - $totals['total_yhk'] - $totals['total_ywtc'],2);
//        if($zc_rate > 0) {
//            $totals['total_jl'] -= round($totals['total_jbf'] * $zc_rate / 100,2);
//        }
        $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);

        $company_items = InsurerCompanyT::find()->all();

        return $this->render('caiwu-tj-list',[
            'items' => $items,
            'page' => $page,
            'page_info' => $page_info,
            'zc_rate' => $zc_rate,
            'data_type' => $data_type,
            'record_s_date' => $record_s_date,
            'record_e_date' => $record_e_date,
            'data_type' => $data_type,
            'company_id' => $company_id,
            'car_no' => $car_no,
            'insurer_no' => $insurer_no,
            'type' => $type,
            'userid' => $userid,
            'company_items' => $company_items,
            'totals' => $totals,
            'zc_rate' => $zc_rate
        ]);
    }
    public function actionWashDataDian()
    {
        return $this->render('wash-che-dian', []);
    }
    public function actionCarinfosDian()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '操作失败';
//        $company = $request->post('company', '');

        $web_path = Yii::$app->getBasePath() . '/../frontend/web';
        $filename = $web_path . $request->post('urlfile');
        $base_filename=$request->post('urlfile');

//        $file_path = \Yii::getAlias('@console').'/controllers/';
//
//        $base_filename=$this->mname;
//        $filename = $file_path.$base_filename;
//        if(file_exists($filename)) {
//            echo 'OK'."\r\n";
//        }
        $reader = new \PHPExcel_Reader_Excel2007();
        if(!$reader->canRead($filename)) {
            $reader = new \PHPExcel_Reader_Excel5();
            if(!$reader->canRead($filename)) {
                $errorMessage = "Can not read file.";
                echo $errorMessage;
                return;
            }
        }
        $excel = $reader->load($filename);
        $sheet = $excel->getSheet(0);
        $data = $sheet->toArray('', true, true);
        $total = count($data);

//        exit;
        $j = 0;
        $insert_total = 0;
        foreach($data as $index => $item) {
            $j++;
            if($j == 1) continue;

            flush();

            $car_no = sprintf("%s",$item[0]);
            $car_man = sprintf("%s",$item[1]);
            $factory_model = sprintf("%s",$item[2]);
            $engine_no = sprintf("%s",$item[3]);
            $car_frame_no = sprintf("%s",$item[4]);
            $register_date = sprintf("%s",$item[5]);
            $company = sprintf("%s",$item[6]);
            $insurer1_date = sprintf("%s",$item[8]);
            $insurer2_date = sprintf("%s",$item[8]);
            $id_man = sprintf("%s",$item[9]);
            $id_number = sprintf("%s",$item[10]);
            $car_no= trim($car_no);

//            if($car_no == '') {
////                echo "\r\n";
//                $car_no = '京xxxxxx';
////                continue;
//            }


//            $tmp_date = explode('-',$register_date);
//            $register_date = date('Y-m-d',strtotime('20'.$tmp_date[2].'-'.$tmp_date[0].'-'.$tmp_date[1].' 00:00:00'));
//            echo $register_date.'...';
//            echo $new_date.'...';
//            exit;
            //排除京牌xxx
//            CarT::find()->where('car_no= $car_no')
//            $car_info = CarT::findOne(['car_no'=>$car_no]);
//            $car_c_info = CarCT::findOne(['id'=>$car_info->id]);
//            $car_d_info = CarDT::findOne(['id'=>$car_info->id]);
//            $car_w_info = CarInvalidT::findOne(['id'=>$car_info->id]);
//
//            if($car_c_info || $car_d_info || $car_w_info ){
//                continue;
//            }

            $car_info = new CarT();
            $car_info->user_id = 0;
            $car_info->car_use_id = 0;
            $car_info->car_type_id = 0;
            if($car_no == '') {
                $car_no = '宣xxxxxx';
            }
            $car_info->car_no = '宣'.$car_no;
//            dd($car_info->car_no);
            $car_info->car_man = $car_man;
            $car_info->factory_model = $factory_model;
            $car_info->engine_no = $engine_no;
            $car_info->car_frame_no = '宣'.$car_frame_no;
            $car_info->register_date = $register_date;
            $car_info->company = $company;
            $car_info->insurer1_date = $insurer1_date;
            $car_info->insurer2_date = $insurer2_date;
            $car_info->id_man = $id_man;
            $car_info->id_man_number = $id_number;
            $car_info->location = 1;
            $car_info->is_track = 0;
            $car_info->times = 1;
            $car_info->invalid_flag = 0;
            $car_info->invalid_id = 0;
            $car_info->save();
//                if(!$car_info->save()) {
//                    var_dump($car_info->errors);
//                    exit;
//                }

//                echo 'insert...'.$car_info->id.'...';

            $insert_total++;
            echo "\r\n";
        }

        $total1=$total-1;
        $log = new ImportLogT();
        $log->filename = $base_filename;
        $log->total = $total1;
        $log->success = $insert_total;
        $log->success_rate = ($insert_total/$total1) * 100;
        $log->save();
        $result['success'] = true;
        $result['msg'] = '操作成功';


        return $result;
//        $end_time = time();
//        $total_time = $end_time - $begin_time;
//        $h = floor($total_time/3600);
//        $m = floor(($total_time - $h * 3600)/60);
//        $s = $total_time - $h * 3600 - $m * 60;
//        echo '花费时间: '.$h.'小时'.$m.'分钟'.$s.'秒';
//        echo "OK\r\n";



    }

    public function actionCarUpdateFrame()
    {
        return $this->render('car-update-frame');
    }

    public function actionCarUpdateFrameInfo()
    {
        set_time_limit(0);
        ini_set('memory_limit', '3072M');
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '操作失败';

        $web_path = Yii::$app->getBasePath() . '/../frontend/web';
        $filename = $web_path . $request->post('file');
        $base_filename=$request->post('file');

        //读取Excel 2007
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filename)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filename)) {
                $errorMessage = "Can not read file.";
                $result['msg'] = $errorMessage;
                return $result;
            }
        }
        $tran = CarT::getDb()->beginTransaction();
        try {
            $PHPExcel = $PHPReader->load($filename);
            $currentSheet = $PHPExcel->getSheet(0);

            $rowCount = $currentSheet->getHighestRow();
            //创建新的xlsx表
            $insert_total = 0;

            for ($i = 2; $i <= $rowCount; $i++) {
//            echo $i.'/'.$rowCount."...";
                $cell = $currentSheet->getCellByColumnAndRow(0, $i);
                $car_no = $cell->getFormattedValue();
//            $cell = $currentSheet->getCellByColumnAndRow(1, $i);
//            $car_man = $cell->getValue();
                $cell = $currentSheet->getCellByColumnAndRow(1, $i);
                $factory_model = $cell->getFormattedValue();//$data[$i][3];
                $cell = $currentSheet->getCellByColumnAndRow(2, $i);
                $engine_no = $cell->getFormattedValue();//$data[$i][2];
//            var_dump($cars);
                $cell = $currentSheet->getCellByColumnAndRow(3, $i);
                $car_frame_no = $cell->getFormattedValue();//$data[$i][1];
//            var_dump($car_frame_no);
                $cell = $currentSheet->getCellByColumnAndRow(4, $i);
                $register_date = $cell->getFormattedValue();
                $cell = $currentSheet->getCellByColumnAndRow(5, $i);
                $company = $cell->getValue();//$data[$i][8];
                $cell = $currentSheet->getCellByColumnAndRow(6, $i);
                $insurer1_date = $cell->getFormattedValue();
                $cell = $currentSheet->getCellByColumnAndRow(7, $i);
                $insurer2_date = $cell->getFormattedValue();
                $cell = $currentSheet->getCellByColumnAndRow(8, $i);
                $seats = $cell->getFormattedValue();
                $cell = $currentSheet->getCellByColumnAndRow(9, $i);
                $car_man = $cell->getFormattedValue();
                $cell = $currentSheet->getCellByColumnAndRow(10, $i);
                $car_man_number = $cell->getFormattedValue();
                $cell = $currentSheet->getCellByColumnAndRow(11, $i);
                $car_man_phone = $cell->getFormattedValue();
                $cell = $currentSheet->getCellByColumnAndRow(12, $i);
                $id_man = $cell->getFormattedValue();
                $cell = $currentSheet->getCellByColumnAndRow(13, $i);
                $id_number = $cell->getFormattedValue();
                $cell = $currentSheet->getCellByColumnAndRow(14, $i);
                $id_phone = $cell->getFormattedValue();

                if($car_no == '' && $engine_no == '' && $car_frame_no == '') continue;

                $car_info = CarT::findOne(['car_frame_no' => $car_frame_no]);

                if ($car_info) {
                    if($car_no != ''){
                        $car_info->car_no = $car_no;
                    }

                    if($car_man != ''){
                        $car_info->car_man = $car_man;
                    }
                    if($factory_model != ''){
                        $car_info->factory_model = $factory_model;
                    }
                    if($engine_no != ''){
                        $car_info->engine_no = $engine_no;
                    }
//                if($car_frame_no != ''){
//                    $car_info->car_frame_no = $car_frame_no;
//                }
                    if($register_date != ''){
                        $car_info->register_date = $register_date;
                    }
                    if($company != ''){
                        $car_info->company = $company;
                    }
                    if($insurer1_date != ''){
                        $car_info->insurer1_date = $insurer1_date;
                    }
                    if($insurer2_date != ''){
                        $car_info->insurer2_date = $insurer2_date;
                    }
                    if($id_man != ''){
                        $car_info->id_man = $id_man;
                    }
                    if($id_number != ''){
                        $car_info->id_man_number = $id_number;
                    }
                    if($id_phone != ''){
                        $car_info->id_man_phone = $id_phone;
                    }
                    if($seats != ''){
                        $car_info->seats = $seats;
                    }
                    if($car_man_number != ''){
                        $car_info->car_man_number = $car_man_number;
                    }
                    if($car_man_phone != ''){
                        $car_info->car_man_phone = $car_man_phone;
                    }
                    if(!$car_info->save(false)) {
                        throw new \Exception(print_r($car_info->getErrors(), true));
                    }

                    $insert_total++;
                }

                if (!$car_info) {

                    $car_info = new CarT();

                    if($car_no != ''){
                        $car_info->car_no = $car_no;
                    }

                    if($car_man != ''){
                        $car_info->car_man = $car_man;
                    }
                    if($factory_model != ''){
                        $car_info->factory_model = $factory_model;
                    }
                    if($engine_no != ''){
                        $car_info->engine_no = $engine_no;
                    }
                    if($car_frame_no != ''){
                        $car_info->car_frame_no = $car_frame_no;
                    }
                    if($register_date != ''){
                        $car_info->register_date = $register_date;
                    }
                    if($company != ''){
                        $car_info->company = $company;
                    }
                    if($insurer1_date != ''){
                        $car_info->insurer1_date = $insurer1_date;
                    }
                    if($insurer2_date != ''){
                        $car_info->insurer2_date = $insurer2_date;
                    }
                    if($id_man != ''){
                        $car_info->id_man = $id_man;
                    }
                    if($id_number != ''){
                        $car_info->id_man_number = $id_number;
                    }
                    if($id_phone != ''){
                        $car_info->id_man_phone = $id_phone;
                    }
                    if($seats != ''){
                        $car_info->seats = $seats;
                    }
                    if($car_man_number != ''){
                        $car_info->car_man_number = $car_man_number;
                    }
                    if($car_man_phone != ''){
                        $car_info->car_man_phone = $car_man_phone;
                    }
                    if(!$car_info->save(false)) {
                        throw new \Exception(print_r($car_info->getErrors(), true));
                    }
                    $insert_total++;
                }

            }

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

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

        return $result;

    }

    public function actionBudianList() {
        $company_items = InsurerCompany2T::find()->all();
        return $this->render('budian-list',[
            'company_items' => $company_items
        ]);
    }
    public function actionBudianListJson()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $begin_date = $request->get('begin_date',date('Y-m-d'));
        $end_date = $request->get('end_date',date('Y-m-d'));
        $begin_totalclear = $request->get('begin_totalclear');
        $end_totalclear = $request->get('end_totalclear');
        $car_no_type = $request->get('car_no_type');
        $company_id = $request->get('company_id');
        $insurer_type = $request->get('insurer_type');

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

        $query = CaiwuT::find()
            ->leftJoin(OrderT::tableName(), "order_t.id=caiwu_t.order_id")
            ->orderBy('order_t.print_date DESC');
        if( $insurer_type > 0) {
            $query->andWhere('caiwu_t.insurer_type='.$insurer_type);
        }
        if( $company_id > 0) {
            $query->andWhere('order_t.company2_id='.$company_id);
        }
        if($car_no_type == 1){
            $query->andWhere('caiwu_t.car_no like "' . '京' . '%"');
        }elseif($car_no_type == 2){
            $query->andWhere('caiwu_t.car_no not like "' . '京' . '%"');
        }

        if($begin_totalclear != ''){
            $query->andWhere('caiwu_t.total_clear >=' . $begin_totalclear);
        }
        if($end_totalclear != ''){
            $query->andWhere('caiwu_t.total_clear <=' . $end_totalclear);
        }

        if ($begin_date != "") {
            $query->andWhere('order_t.print_date>="' . $begin_date . '"');
        }
        if ($end_date != "") {
            $query->andWhere('order_t.print_date<="' . $end_date . '"');
        }
        $total = $query->count();
        $sum_total1_clear = $query->sum('total1_clear');

        $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->order->company2->name;
            $row['print_date'] = $item->order->print_date;
            $row['insurer_type'] = '商业';
            if($item->insurer_type != 1)
                $row['insurer_type'] = '交强';
            $row['user'] = $item->user?$item->user->getShowName():'';
            $data['rows'][] = $row;
        }

        $data['rows'][] = array(
            ['商业净保总额', number_format($sum_total1_clear,2)],
        );

        return $data;
    }

    public function actionBudianSave()

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

        $begin_date = $request->get('begin_date',date('Y-m-d'));
        $end_date = $request->get('end_date',date('Y-m-d'));
        $begin_totalclear = $request->get('begin_totalclear');
        $end_totalclear = $request->get('end_totalclear');
        $car_no_type = $request->get('car_no_type');
        $company_id = $request->get('company_id');
        $insurer_type = $request->get('insurer_type');

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

        $query = CaiwuT::find()
            ->leftJoin(OrderT::tableName(), "order_t.id=caiwu_t.order_id")
            ->orderBy('order_t.print_date DESC');
        if( $insurer_type > 0) {
            $query->andWhere('caiwu_t.insurer_type='.$insurer_type);
        }
        if( $company_id > 0) {
            $query->andWhere('order_t.company2_id='.$company_id);
        }
        if($car_no_type == 1){
            $query->andWhere('caiwu_t.car_no like "' . '京' . '%"');
        }elseif($car_no_type == 2){
            $query->andWhere('caiwu_t.car_no not like "' . '京' . '%"');
        }

        if($begin_totalclear != ''){
            $query->andWhere('caiwu_t.total_clear >=' . $begin_totalclear);
        }
        if($end_totalclear != ''){
            $query->andWhere('caiwu_t.total_clear <=' . $end_totalclear);
        }

        if ($begin_date != "") {
            $query->andWhere('order_t.print_date>="' . $begin_date . '"');
        }
        if ($end_date != "") {
            $query->andWhere('order_t.print_date<="' . $end_date . '"');
        }

        $items = $query->all();

        $tran = OrderCaiwuT::getDb()->beginTransaction();
        try {
            foreach ($items as $item){
                if($budian_rate != '') {
                    $item->budian_rate = $budian_rate;
                    $item->budian_money = $item->total_clear * $budian_rate / 100;
                }
                if(!$item->save()) {
                    throw new \Exception(print_r($item->getErrors(), true));
                }
            }
            $tran->commit();
            $result['success'] = true;
            $result['msg'] = '保存成功';
        } catch(\Exception $e) {
            $tran->rollBack();
            $result['msg'] = $e->getMessage();
        }
        return $result;
    }

    public function actionSelUserDlg() {
        $request = Yii::$app->request;
        $name = $request->get('name');
        $group_items = GroupT::getTree((int)$this->my->group_id);
        if($this->my->id == 1)
            $group_items = GroupT::getTree();

        return $this->render('sel-user-dlg',[
            'group_items' => $group_items,
            'id_name' => $name
        ]);
    }

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

        $username = $request->get('username');
        $group_id = $request->get('group_id', 0);

        $query = UserT::find()->where('is_delete=0')
            ->orderBy('username', 'asc');
        if($group_id > 0) {
            $group_items = GroupT::getTree($group_id);
            $group_ids = [];
            $group_ids[] = $group_id;
            foreach($group_items as $group_item) {
                $group_ids[] = $group_item->id;
            }
            $query->andWhere('group_id in ('.join(',',$group_ids).')');
        }
        if($username != '') {
            $query->andWhere('username like "'.$username.'%"');
        }
        $items = $query->all();
        foreach($items as $item) {
            $row = [];
            $row['id'] = $item->id;
            $row['username'] = $item->username;
            $row['name'] = $item->getShowName();
            $result['users'][] = $row;
        }
        $result['success'] = true;
        $result['msg'] = '操作成功';

        return $result;
    }

    public function actionTichengJisuan() {
        $group_items = GroupT::getTree((int)$this->my->group_id);
        if($this->my->id == 1)
            $group_items = GroupT::getTree();
        $company_items = InsurerCompany2T::find()->all();

        return $this->render('ticheng-jisuan',[
            'group_items' => $group_items,
            'company_items' => $company_items
        ]);
    }

    public function actionTichengJisuanJson()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $user_names = $request->get('user_names');
        $car_no_type = $request->get('car_no_type');
        $company_id = $request->get('company_id');
        $insurer_type = $request->get('insurer_type',1);
        $car_no = $request->get('car_no');
        $begin_date = $request->get('begin_date',date('Y-m-d'));
        $end_date = $request->get('end_date',date('Y-m-d'));
        $begin_totalclear = $request->get('begin_totalclear');
        $end_totalclear = $request->get('end_totalclear');
        $group_id = $request->get('group_id', 0);
        $offset = $request->get('offset', 0);
        $limit = $request->get('limit', 10);

        $group_ids = [];
        if($group_id > 0) {
            $items = GroupT::getTree($group_id);
            $group_ids[] = $group_id;
            foreach($items as $group_info) {
                $group_ids[] = $group_info->id;
            }
        }
        $query = CaiwuT::find()
            ->leftJoin(OrderT::tableName(), "order_t.id=caiwu_t.order_id")
            ->where('order_t.status_id>1');
        if($user_names != '' && $user_names != 'null'){
            $user_arr = explode(',',$user_names);
            $user_ids = [];
            foreach ($user_arr as $username){
                $user = UserT::find()->where('is_delete=0')->andWhere('username="'.$username.'"')->one();
                if($user)
                    $user_ids[] = $user->id;
            }
            $query->andWhere(['in','caiwu_t.user_id',$user_ids]);
        }
        if( $company_id > 0) {
            $query->andWhere('order_t.company2_id='.$company_id);
        }
        if( $car_no != '') {
            $query->andWhere('order_t.car_no="'.$car_no.'"');
        }
        if($car_no_type == 1){
            $query->andWhere('caiwu_t.car_no like "' . '京' . '%"');
        }elseif($car_no_type == 2){
            $query->andWhere('caiwu_t.car_no not like "' . '京' . '%"');
        }
        if($begin_totalclear != ''){
            $query->andWhere('caiwu_t.total_clear >=' . $begin_totalclear);
        }
        if($end_totalclear != ''){
            $query->andWhere('caiwu_t.total_clear <=' . $end_totalclear);
        }
        if ($begin_date != "") {
            $query->andWhere('order_t.print_date>="' . $begin_date . '"');
        }
        if ($end_date != "") {
            $query->andWhere('order_t.print_date<="' . $end_date . '"');
        }
        $user_items = $this->my->getChildren('');
        $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->andWhere(['in','caiwu_t.user_id',$row]);
        }
        if($insurer_type ==1){
            $query->andWhere('caiwu_t.insurer_type=1');
        }
        $query1 = clone $query;
        $sums = $query1
            ->leftJoin(OrderCaiwuT::tableName(), "order_t.id=order_caiwu_t.order_id")
            ->select([
                'sum_total1_clear' => 'sum(order_t.total1_clear)',
                'sum_total2_clear' => 'sum(order_t.total2_clear)',
                'sum_yeji_ticheng' => 'sum(order_caiwu_t.yeji_ticheng)',
                'sum_ticheng_money' => 'sum(order_caiwu_t.ticheng_money)',
                'sum_yuangong_money' => 'sum(order_caiwu_t.yuangong_money)',
                'sum_yewu_ticheng' => 'sum(order_caiwu_t.yewu_ticheng)',
            ])->asArray()->one();
        $query2 = clone $query;
        $gift_sum = $query2
            ->leftJoin(OrderGiftT::tableName(), "order_gift_t.order_id=caiwu_t.order_id")
            ->leftJoin(GiftT::tableName(), "gift_t.id=order_gift_t.gift_id")
            ->andWhere('order_gift_t.gift_type=1 && order_gift_t.is_free=2')
            ->sum('gift_t.price');
        $query2 = clone $query;
        $voucher_sum = $query2
            ->leftJoin(OrderGiftT::tableName(), "order_gift_t.order_id=caiwu_t.order_id")
            ->leftJoin(GiftT::tableName(), "gift_t.id=order_gift_t.gift_id")
            ->andWhere('order_gift_t.gift_type=2 && order_gift_t.is_free=2')
            ->sum('gift_t.price');
        $total = $query->count();
        $query=$query->offset($offset)->limit($limit);
        $items = $query->orderBy('order_t.print_date DESC')->all();

        $data = [];
        $data['total'] = $total;
        $data['rows'] = [];
        foreach($items as $item) {
            $row = $item->toArray();
            $row['company_name'] = $item->order->company2?$item->order->company2->name:'';
            $row['print_date'] = $item->order->print_date;
            $row['yeji_rate'] = $item->orderCaiwu->yeji_rate;
            $row['yeji_ticheng'] = $item->orderCaiwu->yeji_ticheng;
            $row['ticheng_zong_rate'] = $item->order->ticheng_zong_rate;
            $row['ticheng_money'] = $item->order->ticheng_money;
            $row['gift1_price'] = $item->order->getGiftPrice(1,1);
            $row['gift2_price'] = $item->order->getGiftPrice(1,2);
            $row['yuangong_money'] = $item->order->yuangong_money;
            $row['yewu_ticheng'] = $item->orderCaiwu->yewu_ticheng;
            if($item->order->car->op2_id > 0) {
                $row['op_user'] = $item->order->car->op2?$item->order->car->op2->showName:'';
                $row['op_user1'] = $item->order->car->op1?$item->order->car->op1->showName:'';
            } else {
                $row['op_user'] = $item->order->car->op1?$item->order->car->op1->showName:'';
                $row['op_user1'] = '';
            }
            $row['first_xinbao_ticheng'] = $item->orderCaiwu->first_xinbao_ticheng;
            $row['hebao_ticheng'] = $item->orderCaiwu->hebao_ticheng;
            $row['op1_user'] = $item->order->op1?$item->order->op1->showName:'';
            $row['zhengben_ticheng'] = $item->orderCaiwu->zhengben_ticheng;
            $row['op2_user'] = $item->order->op2?$item->order->op2->showName:'';
            $row['dz_ticheng1'] = $item->orderCaiwu->dz_ticheng1;
            $row['dz_names1'] = $item->orderCaiwu->dz_names1;
            $row['dz_ticheng2'] = $item->orderCaiwu->dz_ticheng2;
            $row['dz_names2'] = $item->orderCaiwu->dz_names2;
            $row['dz_ticheng3'] = $item->orderCaiwu->dz_ticheng3;
            $row['dz_names3'] = $item->orderCaiwu->dz_names3;
            $row['dz_ticheng4'] = $item->orderCaiwu->dz_ticheng4;
            $row['dz_names4'] = $item->orderCaiwu->dz_names4;
            $row['dz_ticheng5'] = $item->orderCaiwu->dz_ticheng5;
            $row['dz_names5'] = $item->orderCaiwu->dz_names5;
            $data['rows'][] = $row;
        }
        $data['rows'][] = array(
            ['保费总额', number_format($sums['sum_total1_clear'] + $sums['sum_total2_clear'],2)],
            ['商业净保总额', number_format($sums['sum_total1_clear'],2)],
            ['基本提成合计', number_format($sums['sum_yeji_ticheng'],2)],
            ['加点提成合计', number_format($sums['sum_ticheng_money'],2)],
            ['自费礼品合计', number_format($gift_sum,2)],
            ['自费礼券合计', number_format($voucher_sum,2)],
            ['自费减免合计', number_format($sums['sum_yuangong_money'],2)],
            ['提成合计', number_format($sums['sum_yewu_ticheng'],2)]
        );
        return $data;
    }

    public function actionTichengJisuanSave()
    {
        set_time_limit(0);
        ini_set('memory_limit', '3072M');
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '操作失败';


        $begin_date = $request->post('begin_date');
        $end_date = $request->post('end_date');
        $user_names = $request->post('user_names');
        $begin_totalclear = $request->post('begin_totalclear');
        $end_totalclear = $request->post('end_totalclear');
        $car_no_type = $request->post('car_no_type');
        $company_id = $request->post('company_id');
        $car_no = $request->post('car_no');
        $insurer_type = $request->post('insurer_type');

        $dz_group = $request->post('dz_group');
        $dz_rate = $request->post('dz_rate');
        $dz_names = $request->post('dz_names');


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

        $zhengben_ticheng = $request->post('zhengben_ticheng');
        $hebao_ticheng = $request->post('hebao_ticheng');
        $songdan_ticheng = $request->post('songdan_ticheng');
        $genzong_ticheng = $request->post('genzong_ticheng');
        $first_xinbao_rate = $request->post('first_xinbao_rate');

        $group_id = $request->post('group_id');
        $group_ids[] = $group_id;

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

            foreach($items as $group_info) {
                $group_ids[] = $group_info->id;
            }
        }


        $query = CaiwuT::find()
            ->leftJoin(OrderT::tableName(), "order_t.id=caiwu_t.order_id")
            ->where('order_t.status_id>1')
            ->orderBy('order_t.print_date DESC');

        if($user_names != '' && $user_names != 'null'){
            $user_arr = explode(',',$user_names);
            $user_ids = [];
            foreach ($user_arr as $username){
                $user = UserT::find()->where('is_delete=0')->andWhere('username="'.$username.'"')->one();
                if($user)
                    $user_ids[] = $user->id;
            }

            $query->andWhere(['in','caiwu_t.user_id',$user_ids]);
        }

        if($company_id > 0) {
            $query->andWhere('order_t.company2_id='.$company_id);
        }
        if( $car_no != '') {
            $query->andWhere('order_t.car_no="'.$car_no.'"');
        }

        if($car_no_type == 1){
            $query->andWhere('caiwu_t.car_no like "' . '京' . '%"');
        }elseif($car_no_type == 2){
            $query->andWhere('caiwu_t.car_no not like "' . '京' . '%"');
        }

        if($begin_totalclear != ''){
            $query->andWhere('caiwu_t.total_clear >=' . $begin_totalclear);
        }
        if($end_totalclear != ''){
            $query->andWhere('caiwu_t.total_clear <=' . $end_totalclear);
        }

        if ($begin_date != "") {
            $query->andWhere('order_t.print_date>="' . $begin_date . '"');
        }
        if ($end_date != "") {
            $query->andWhere('order_t.print_date<="' . $end_date . '"');
        }

        $user_items = $this->my->getChildren('');
        $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->andWhere(['in','caiwu_t.user_id',$row]);
        }

        if($insurer_type == 1){
            $query->andWhere('caiwu_t.insurer_type=1');
        }
//        echo $query->createCommand()->rawSql;exit;
        $query1 = clone $query;
        $items = $query->all();

        $item1s = $query1->all();


        foreach($items as $item) {
            //在计算之前检查数据是否匹配
            $order = $item->order;
            $car = $order->car;
            $count = OrderT::find()->where('car_no="' . $car->car_no . '"')->andWhere('status_id>1')
                ->andWhere('insurance_status <>2')->count();
            $orders = OrderT::find()->where('car_no="' . $car->car_no . '"')->andWhere('status_id>1')
                ->andWhere('insurance_status <>2')->orderBy('print_date ASC')->all();
            if ($car->op2_id == 0 && $car->op1_id != $item->user_id ) {
                $result['msg'] = '数据错误，车牌：' . $car->car_no . '是新保car_t的op1_id:'.$car->op1_id.'--实际order_t的user_id:'.$item->user_id;
                return $result;
            }

            if ($car->op2_id > 0 && $car->op2_id != $item->user_id) {
                $result['msg'] = '数据错误，车牌：' . $car->car_no . '是续保但是car_t的op2_id：'.$car->op2_id.'--实际order_t的user_id:'.$item->user_id;
                return $result;
            }

            if ($count > 1) {
                $ord = $orders[0];
                if (empty($ord->user)) {
                    continue;
                }
                if ($car->op1_id != $orders[0]->user_id) {
                    $result['msg'] = '数据错误，车牌：' . $car->car_no . '是续保但原新保的car_t的op1_id：'.$car->op1_id.'--实际原新保的order_t的user_id:'.$orders[0]->user_id;
                    return $result;
                }

            }
        }

        $dz_ids = [];
        if($dz_names != '' && $dz_names != 'null'){
            $user_arr = explode(',',$dz_names);

            foreach ($user_arr as $user){
                $username = substr($user,0,strpos($user, '('));
                $user = UserT::find()->where('is_delete=0')->andWhere('username="'.$username.'"')->one();
                if($user)
                    $dz_ids[] = $user->id;
            }

        }

        $tran = OrderCaiwuT::getDb()->beginTransaction();
        try {

            foreach ($items as $item){
                $order_caiwu_info = $item->orderCaiwu;
                $order_info = $item->order;

                if($order_caiwu_info){

                    if($yeji_rate != '')
                        $order_caiwu_info->yeji_rate = $yeji_rate;
                    if($dz_rate != ''){
                        if($dz_group == 1) {
                            $order_caiwu_info->dz_rate1 = $dz_rate;
                        }elseif ($dz_group == 2){
                            $order_caiwu_info->dz_rate2 = $dz_rate;
                        }elseif ($dz_group == 3){
                            $order_caiwu_info->dz_rate3 = $dz_rate;
                        }elseif ($dz_group == 4){
                            $order_caiwu_info->dz_rate4 = $dz_rate;
                        }elseif ($dz_group == 5){
                            $order_caiwu_info->dz_rate5 = $dz_rate;
                        }
                    }


                    if($dz_names != ''){
                        if($dz_group == 1) {
                            $order_caiwu_info->dz_names1 = $dz_names != 0 ? $dz_names : '';
                        }elseif ($dz_group == 2){
                            $order_caiwu_info->dz_names2 = $dz_names != 0 ? $dz_names : '';
                        }elseif ($dz_group == 3){
                            $order_caiwu_info->dz_names3 = $dz_names != 0 ? $dz_names : '';
                        }elseif ($dz_group == 4){
                            $order_caiwu_info->dz_names4 = $dz_names != 0 ? $dz_names : '';
                        }elseif ($dz_group == 5){
                            $order_caiwu_info->dz_names5 = $dz_names != 0 ? $dz_names : '';
                        }
                    }


                    if($first_xinbao_rate != '')
                        $order_caiwu_info->first_xinbao_rate = $first_xinbao_rate;

                    //商业净保费
                    $total_clear = $item->total_clear;

                    //业绩提成
                    if($yeji_rate != '')
                        $yeji_ticheng = $total_clear * $yeji_rate /100;

                    if($first_xinbao_rate != '')
                        $first_xinbao_ticheng = $first_xinbao_rate * $total_clear /100;


                    if($yeji_rate != '')
                        $order_caiwu_info->yeji_ticheng = $yeji_ticheng;

                    if($dz_rate != ''){
                        if($dz_group == 1) {
                            $order_caiwu_info->dz_ticheng1 = $total_clear * $dz_rate /100;
                        }elseif ($dz_group == 2){
                            $order_caiwu_info->dz_ticheng2 = $total_clear * $dz_rate /100;
                        }elseif ($dz_group == 3){
                            $order_caiwu_info->dz_ticheng3 = $total_clear * $dz_rate /100;
                        }elseif ($dz_group == 4){
                            $order_caiwu_info->dz_ticheng4 = $total_clear * $dz_rate /100;
                        }elseif ($dz_group == 5){
                            $order_caiwu_info->dz_ticheng5 = $total_clear * $dz_rate /100;
                        }
                    }

                    if($first_xinbao_rate != '')
                        $order_caiwu_info->first_xinbao_ticheng = $first_xinbao_ticheng;


                    $order_caiwu_info->ticheng_zong_rate = $order_info->ticheng_zong_rate;
                    $order_caiwu_info->ticheng_money = $order_info->ticheng_money;
                    $order_caiwu_info->yuangong_money = $order_info->yuangong_money;
                    $order_caiwu_info->celuo_id = $order_info->celuo_id;

                    $yuangong_money = $order_caiwu_info->yuangong_money >0 ? $order_caiwu_info->yuangong_money : 0;
                    $yewu_ticheng = $order_caiwu_info->yeji_ticheng + $order_caiwu_info->ticheng_money - $yuangong_money;
                    $yewu_ticheng -= $order_info->getGiftPrice(1,1);
                    $yewu_ticheng -= $order_info->getGiftPrice(1,2);

                    $order_caiwu_info->yewu_ticheng = $yewu_ticheng;

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

                    //处理新保、跟踪、续保提成
                    $order_info = $order_caiwu_info->order;
                    $car_info = $order_info->car;

                    //新保
                    if($car_info->op1_id > 0 && ($yeji_rate != '' || $first_xinbao_rate != '' || $yeji_rate === '0' || $first_xinbao_rate === '0')) {
                        $pay1_user = $car_info->op1;
                        if ($pay1_user && $pay1_user->is_delete == 0) {
                            $pay_order_user = PayOrderUserT::find()
                                ->where('order_id='.$order_info->id)
                                ->andWhere('user_id='.$pay1_user->id)
                                ->andWhere('pay_date="'.$order_caiwu_info->pay_date.'"')
                                ->andWhere('type=1')
                                ->one();
                            if(!$pay_order_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->op2_id > 0 ? 0 : 1;//现在用判断是原新保
                                $pay_order_user->pay_date = $order_caiwu_info->pay_date;

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

                            if($pay_order_user){

                                $pay_order_user->calPay();

                                if($pay_order_user->is_own == 0 && $first_xinbao_rate === '0'){
                                    $pay_order_user->delete();
                                }elseif($pay_order_user->is_own == 1 && $yeji_rate === '0'){
                                    $pay_order_user->delete();
                                }
                            }
                        }
                    }

                    //续保
                    if($car_info->op2_id > 0 && ($yeji_rate != '' || $yeji_rate === '0') ) {
                        $pay3_user = $car_info->op2;
                        if ($pay3_user && $pay3_user->is_delete==0) {
                            $pay_order_user = PayOrderUserT::find()
                                ->where('order_id='.$order_info->id)
                                ->andWhere('user_id='.$pay3_user->id)
                                ->andWhere('pay_date="'.$order_caiwu_info->pay_date.'"')
                                ->andWhere('type=3')
                                ->one();
                            if(!$pay_order_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 = $order_caiwu_info->pay_date;
                                if(!$pay_order_user->save()) {
                                    throw new \Exception(print_r($pay_order_user->getErrors(), true));
                                }
                            }

                            $pay_order_user->calPay();

                            if($yeji_rate === '0'){
                                $pay_order_user->delete();
                            }
                        }
                    }

                    foreach ($dz_ids as $id){
                        $pay_order_user = PayOrderUserT::find()
                            ->where('order_id='.$order_info->id)
                            ->andWhere('user_id='.$id)
                            ->andWhere('pay_date="'.$order_caiwu_info->pay_date.'"')
                            ->andWhere('type=10')
                            ->one();

                        if(!$pay_order_user){
                            $pay_order_user = new PayOrderUserT();
                            $pay_order_user->user_id = $id;
                            $pay_order_user->order_id = $order_info->id;
                            $pay_order_user->type = 10; //团队长
                            $pay_order_user->is_own = 0;
                            $pay_order_user->pay_date = $order_caiwu_info->pay_date;
                            if(!$pay_order_user->save()) {
                                throw new \Exception(print_r($pay_order_user->getErrors(), true));
                            }
                        }

                        $pay_order_user->calPay($dz_group);
                        if($dz_rate === '0'){
                            $pay_order_user->delete();
                        }
                    }


                }else{
                    $result['success'] = true;
                    $result['msg'] = '保存失败，order_caiwu_t不存在'.$item->id;
                    return $result;
                }
            }

            foreach ($item1s as $item){
                $order_caiwu_info = $item->orderCaiwu;
                $order_info = $item->order;

                if($order_caiwu_info){
                    if($hebao_ticheng != '')
                        $order_caiwu_info->hebao_ticheng = $hebao_ticheng;
                    if($zhengben_ticheng != '')
                        $order_caiwu_info->zhengben_ticheng = $zhengben_ticheng;
                    if($songdan_ticheng != '')
                        $order_caiwu_info->songdan_ticheng = $songdan_ticheng;
                    if($genzong_ticheng != '')
                        $order_caiwu_info->genzong_ticheng = $genzong_ticheng;


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

                    //处理新保、跟踪、续保提成
                    $order_info = $order_caiwu_info->order;
                    $car_info = $order_info->car;

                    //核保
                    if($order_info->op1  && ($hebao_ticheng != '' || $hebao_ticheng === '0') ){
                        $op11= substr($order_info->op1->getShowName(),0,strpos($order_info->op1->getShowName(),'('));
                        $op1_user = $order_info->op1;
                        if($op1_user && $op1_user->is_delete == 0) {
                            $pay_order_user = PayOrderUserT::find()
                                ->where('order_id='.$order_info->id)
                                ->andWhere('user_id='.$op1_user->id)
                                ->andWhere('pay_date="'.$order_caiwu_info->pay_date.'"')
                                ->andWhere('type=5')
                                ->one();

                            if(!$pay_order_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 = $order_caiwu_info->pay_date;
                                if(!$pay_order_user->save()) {
                                    throw new \Exception(print_r($pay_order_user->getErrors(), true));
                                }
                            }

                            $pay_order_user->calPay();
                            if($hebao_ticheng === '0'){
                                $pay_order_user->delete();
                            }
                        }
                    }

                    //正本
                    if($order_info->op2  && ($zhengben_ticheng != '' || $zhengben_ticheng === '0')){
                        $op22= substr($order_info->op2->getShowName(),0,strpos($order_info->op2->getShowName(),'('));
                        $op2_user = $order_info->op2;
                        if($op2_user && $op2_user->is_delete==0) {
                            $pay_order_user = PayOrderUserT::find()
                                ->where('order_id='.$order_info->id)
                                ->andWhere('user_id='.$op2_user->id)
                                ->andWhere('pay_date="'.$order_caiwu_info->pay_date.'"')
                                ->andWhere('type=6')
                                ->one();
                            if(!$pay_order_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 = $order_caiwu_info->pay_date;
                                if(!$pay_order_user->save()) {
                                    throw new \Exception(print_r($pay_order_user->getErrors(), true));
                                }
                            }
                            $pay_order_user->calPay();
                            if($zhengben_ticheng === '0'){
                                $pay_order_user->delete();
                            }
                        }
                    }
                }else{
                    $result['success'] = true;
                    $result['msg'] = '保存失败，order_caiwu_t不存在'.$item->id;
                    return $result;
                }
            }

            $result['success'] = true;
            $result['msg'] = '保存成功';
            $tran->commit();

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

        return $result;

    }

    /**
     * 出纳工资列表
     * @return string
     */
    public function actionChunaGongziList() {
        $group_items = GroupT::getTree();
        return $this->render('chuna-gongzi-list',[
            'group_items' => $group_items
        ]);
    }

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

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

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

        $query = $query->offset($offset)->limit($limit);
        $items = $query->all();
        $pay_chexian = PayOrderUserT::find()
            ->where("pay_date='{$pay_date}'")
            ->sum('real_pay');

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

        $data['rows'][] = array(
            ['提成工资总额', number_format($pay_chexian,2)],
        );

        return $data;
    }
    /**
     * 出纳工资-详情
     * @return string
     */
    public function actionChunaGongziInfo()
    {
        $request = Yii::$app->request;
        $user_id = $request->get('id', 0);
        $pay_date = $request->get('pay_date', date('Y-m'));

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

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

//        if (!$work_day) {
//            echo $pay_date . '还没有开始统计';
//            echo "[<a href='/finance/pay2-list?$back_params'>返回</a>]";
//            die;
//        }

        $pay_info = PayT::findOne(['user_id' => $user_id, 'pay_date' => $pay_date]);
        if (!$pay_info) {
            $pay_info = new PayT();
            $pay_info->user_id = $user_id;
            $pay_info->pay_date = $pay_date;
            if ($group_info) {
                $pay_info->should_pay = $group_info->base_pay + $group_info->job_pay + $group_info->station_pay + $user_info->ext_pay;
            } else {
                $pay_info->should_pay = $user_info->ext_pay;
            }
            if (!$pay_info->save()) {
                var_dump($pay_info->errors);
                exit;
            }
            $pay_info = PayT::findOne(['user_id' => $user_id, 'pay_date' => $pay_date]);
        }
        //内勤
        //核保
        $my_type5_query = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and is_own=0 and type=5  and user_id=' . $user_id)
            ->orderBy('created_at asc');
//                echo $my_type5_query->createCommand()->rawSql;
        //正本
        $my_type6_query = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and is_own=0 and type=6 and user_id=' . $user_id)
            ->orderBy('created_at asc');

        //新保
        $my_type1_query = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '"  and type=1 and user_id=' . $user_id .' and is_own =1')
            ->orderBy('created_at asc');
        //原新保
        $my_type0_query = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '"  and type=1 and user_id=' . $user_id.' and is_own =0')
            ->orderBy('created_at asc');
        //非车险
        $my_type1_query_non = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and is_own=0 and type=7 and user_id=' . $user_id)
            ->orderBy('created_at asc');
        //非车险核保
        $my_type1_query_hebao = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and is_own=0 and type=8 and user_id=' . $user_id)
            ->orderBy('created_at asc');

        //外区
        $my_out_query = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '"  and type=1 and user_id=' . $user_id .' and (is_own=4 or is_own=5)')
            ->orderBy('created_at asc');



//        echo $my_type1_query->createCommand()->rawSql;
        //续保
        $my_type3_query = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and is_own=1 and type=3 and user_id=' . $user_id)
            ->orderBy('created_at asc');
//        echo $my_type3_query->createCommand()->rawSql;
        //不是核保 正本 送单
        $type_query = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and type<>4 and type<>5 and type<>6 and is_own=0 and user_id=' . $user_id)
            ->andWhere('should_pay>0')
            ->orderBy('created_at asc');
//        echo $type_query->createCommand()->rawSql;
        //送单
        $type3_query = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and type=4 and user_id=' . $user_id)
            ->orderBy('created_at asc');
        $pay_order_users = OrderT::find()
            ->where('print_date like "' . $pay_date . '-%"')
            ->andWhere('user_id=' . $this->my->id)
            ->orderBy('updated_at ASC');


        $pay_chexian = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and type<>7 and type<>8 and type<>10 and user_id=' . $user_id)
            ->sum('real_pay');

        $pay_nochexian = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and type=7 and user_id=' . $user_id)
            ->orWhere('pay_date="' . $pay_date . '" and type=8 and user_id=' . $user_id)
            ->sum('real_pay');

        $pay_dz = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and type=10 and user_id=' . $user_id)
            ->sum('real_pay');

        return $this->render('chuna-gongzi-info', [
            'pay_date' => $pay_date,
            'user_info' => $user_info,
            'group_info' => $group_info,
            'pay_info' => $pay_info,
            'my_type0_query' => $my_type0_query,
            'my_type1_query' => $my_type1_query,
            'my_type3_query' => $my_type3_query,
            'my_type5_query' => $my_type5_query,
            'my_type6_query' => $my_type6_query,
            'my_out_query' => $my_out_query,
            'my_type1_query_non' => $my_type1_query_non,
            'my_type1_query_hebao' => $my_type1_query_hebao,
            'type_query' => $type_query,
            'type3_query' => $type3_query,
            'pay_order_users' => $pay_order_users,
            'pay_chexian' => $pay_chexian,
            'pay_nochexian' => $pay_nochexian,
            'pay_dz' => $pay_dz
        ]);
    }

    public function actionChunaGongziSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        $id = $request->post('id',0);
        $pay_chexian = $request->post('pay_chexian',0);
        $pay_nochexian = $request->post('pay_nochexian',0);
        $pay_dz = $request->post('pay_dz',0);

        $pay_info = PayT::findOne($id);
        $pay_dz = $pay_dz?$pay_dz:0;
        $pay_nochexian = $pay_nochexian?$pay_nochexian:0;
        $pay_chexian = $pay_chexian?$pay_chexian:0;

        $pay_info->ticheng_real_pay = $pay_chexian + $pay_nochexian + $pay_dz;
        $pay_info->chuna_status_id = 2;
        $pay_info->status_id = $pay_info->renshi_status_id + 2;

        $content = '出纳：'.$this->my->showName.'提交'.$pay_info->pay_date.'工资';
        $this->addUserLog($pay_info->id, $content);


        if($pay_info->save()){
            $result['success'] = true;
            $result['msg'] = '保存成功';
        }
        return $result;
    }

    /**
     * 财务工资列表
     * @return string
     */
    public function actionGongziAllList() {
        $group_items = GroupT::getTree();
        return $this->render('gongzi-all-list',[
            'group_items' => $group_items
        ]);
    }

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

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

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

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

        $data = [];
        $data['total'] = $total;
        $data['rows'] = [];
        foreach($items as $item) {
            $row = $item->toArray();
            $row['pay_date'] = $pay_date;
            $row['group_name'] = $item->group ? $item->group->path : '';
            $row['is_leave'] = $item->is_leave ? '已离职':'';
            $pay_info = $item->getPay($pay_date);
            $row['status_name'] = $pay_info ? $pay_info->getStatus($pay_info->status_id) : '';
            $row['real_pay'] = $pay_info->base_real_pay;
            $row['should_pay'] = $pay_info->ticheng_real_pay;
            $row['is_show'] = ($pay_info->renshi_status_id > 0 && $pay_info->chuna_status_id > 0 && $pay_info->status_id != 7 && $pay_info->status_id != 8) ? 1 : 0;
            $data['rows'][] = $row;
        }

        $pay_chexian = PayT::find()
            ->where("pay_date='{$pay_date}'")
            ->sum('ticheng_real_pay');

        $data['rows'][] = array(
            ['提成工资总额', number_format($pay_chexian,2)],
        );

        return $data;
    }

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

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

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

        if (!$work_day) {
            echo $pay_date . '还没有开始统计';
            echo "[<a href='/finance/pay2-list?$back_params'>返回</a>]";
            die;
        }

        $pay_info = PayT::findOne(['user_id' => $user_id, 'pay_date' => $pay_date]);
        if (!$pay_info) {
            $pay_info = new PayT();
            $pay_info->user_id = $user_id;
            $pay_info->pay_date = $pay_date;
            if ($group_info) {
                $pay_info->should_pay = $group_info->base_pay + $group_info->job_pay + $group_info->station_pay + $user_info->ext_pay;
            } else {
                $pay_info->should_pay = $user_info->ext_pay;
            }
            if (!$pay_info->save()) {
                var_dump($pay_info->errors);
                exit;
            }
            $pay_info = PayT::findOne(['user_id' => $user_id, 'pay_date' => $pay_date]);
        }
        //内勤
        //核保
        $my_type5_query = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and is_own=0 and type=5  and user_id=' . $user_id)
            ->orderBy('created_at asc');
//                echo $my_type5_query->createCommand()->rawSql;
        //正本
        $my_type6_query = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and is_own=0 and type=6 and user_id=' . $user_id)
            ->orderBy('created_at asc');

        //新保
        $my_type1_query = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '"  and type=1 and user_id=' . $user_id)
            ->orderBy('created_at asc');
        //非车险
        $my_type1_query_non = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and is_own=0 and type=7 and user_id=' . $user_id)
            ->orderBy('created_at asc');
        //非车险核保
        $my_type1_query_hebao = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and is_own=0 and type=8 and user_id=' . $user_id)
            ->orderBy('created_at asc');


//原新保
        $my_type0_query = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '"  and type=1 and user_id=' . $user_id.' and is_own =0')
            ->orderBy('created_at asc');



//        echo $my_type1_query->createCommand()->rawSql;
        //续保
        $my_type3_query = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and is_own=1 and type=3 and user_id=' . $user_id)
            ->orderBy('created_at asc');
//        echo $my_type3_query->createCommand()->rawSql;
        //不是核保 正本 送单
        $type_query = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and type<>4 and type<>5 and type<>6 and is_own=0 and user_id=' . $user_id)
            ->andWhere('should_pay>0')
            ->orderBy('created_at asc');
//        echo $type_query->createCommand()->rawSql;
        //送单
        $type3_query = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and type=4 and user_id=' . $user_id)
            ->orderBy('created_at asc');
        $pay_order_users = OrderT::find()
            ->where('print_date like "' . $pay_date . '-%"')
            ->andWhere('user_id=' . $this->my->id)
            ->orderBy('updated_at ASC');


        $pay_chexian = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and type<>7 and type<>8 and type<>10 and user_id=' . $user_id)
            ->sum('real_pay');

        $pay_nochexian = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and type=7 and type=8 and user_id=' . $user_id)
            ->sum('real_pay');

        $pay_dz = PayOrderUserT::find()
            ->where('pay_date="' . $pay_date . '" and type=10 and user_id=' . $user_id)
            ->sum('real_pay');

        return $this->render('gongzi-all-info', [
            'pay_date' => $pay_date,
            'user_info' => $user_info,
            'group_info' => $group_info,
            'pay_info' => $pay_info,
            'my_type0_query' => $my_type0_query,
            'my_type1_query' => $my_type1_query,
            'my_type3_query' => $my_type3_query,
            'my_type5_query' => $my_type5_query,
            'my_type6_query' => $my_type6_query,
            'my_type1_query_non' => $my_type1_query_non,
            'my_type1_query_hebao' => $my_type1_query_hebao,
            'type_query' => $type_query,
            'type3_query' => $type3_query,
            'back_params' => $back_params,
            'pay_order_users' => $pay_order_users,
            'pay_chexian' => $pay_chexian,
            'pay_nochexian' => $pay_nochexian,
            'pay_dz' => $pay_dz
        ]);
    }

    public function actionReceiptLirun() {
        $company_items = InsurerCompany2T::find()->all();
        $group_items = GroupT::getTree((int)$this->my->group_id);
        if($this->my->id == 1)
            $group_items = GroupT::getTree();

        return $this->render('receipt-lirun',[
            'company_items' => $company_items,
            'group_items' => $group_items
        ]);
    }

    public function actionReceiptLirunJson()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        set_time_limit(0);
        ini_set('memory_limit', '3072M');
        $request = Yii::$app->request;
        $offset = $request->get('offset', 0);
        $limit = $request->get('limit', 10);
        $insurer_type = $request->get('insurer_type', 0);
        $begin_date = $request->get('begin_date',date('Y-m-d'));
        $end_date = $request->get('end_date',date('Y-m-d'));
        $r_begin_date = $request->get('r_begin_date');
        $r_end_date = $request->get('r_end_date');
        $car_no = trim($request->get('car_no'));
        $insurer_no = trim($request->get('insurer_no'));
        $status = $request->get('status',0);
        $sort_key = $request->get('sort_key');
        $sort_value = $request->get('sort_value');
        $company_id = $request->get('company_id');
        $username = $request->get('username');
        $hebaoname = $request->get('hebaoname');
        $zbname = $request->get('zbname');
        //级别
        $group_id = $request->get('group_id');
        $group_ids[] = $group_id;
        if($group_id > 0) {
            $items = GroupT::getTree($group_id);
            foreach($items as $group_info) {
                $group_ids[] = $group_info->id;
            }
        }

        $query = CaiwuT::find()
            ->leftJoin(OrderT::tableName(), "order_t.id=caiwu_t.order_id")
            ->where('order_t.status_id>1');
        if( $insurer_type != 0) {
            $query->andWhere('caiwu_t.insurer_type='.$insurer_type);
        }
        if( $company_id > 0) {
            $query->andWhere('order_t.company2_id='.$company_id);
        }
        if ($username != "") {
            $userdata = UserT::find()->where('username="'.$username.'"')->andwhere('is_leave=0')->one();
            if($userdata){
                $query->andWhere('caiwu_t.user_id = ' . $userdata->id . '');
            }
        }
        if ($hebaoname != "") {
            $userdata = UserT::find()->where('username="'.$hebaoname.'"')->andwhere('is_leave=0')->one();
            if($userdata){
                $query->andWhere('order_t.op1_id = ' . $userdata->id . '');
            }
        }
        if ($zbname != "") {
            $userdata = UserT::find()->where('username="'.$zbname.'"')->andwhere('is_leave=0')->one();
            if($userdata){
                $query->andWhere('order_t.op2_id = ' . $userdata->id . '');
            }
        }
        if ($car_no != "") {
            $query->andWhere('caiwu_t.car_no like "%' . $car_no . '%"');
        }
        if ($insurer_no != "") {
            $query->andWhere('caiwu_t.insurer_no like "' . $insurer_no . '%"');
        }
        if ($status > 0) {
            if ($status == 1) {
                $query->andWhere('r_date="" or r_date is null');
            }
            if ($status == 2) {
                $query->andWhere('r_date<>"" and total_dis=0');
            }
            if($status == 3) {
                $query->andWhere('r_date<>"" and total_dis<>0');
            }
        }
        if ($begin_date != "") {
            $query->andWhere('order_t.print_date>="' . $begin_date . '"');
        }
        if ($end_date != "") {
            $query->andWhere('order_t.print_date<="' . $end_date . '"');
        }
        if ($r_begin_date != "") {
            $query->andWhere('caiwu_t.r_date>="' . $r_begin_date . '"');
        }
        if ($r_end_date != "") {
            $query->andWhere('caiwu_t.r_date<="' . $r_end_date . '"');
        }
        //找出$group_id 有多少在职的user_ids
        //      现在的搜索条件
        $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->andWhere(['in','caiwu_t.user_id',$row]);
        }
        $total = $query->count();

        $query1 = clone $query;
        $sums = $query1->select([
            'sum_total1' => 'sum(order_t.total1)',
            'sum_r_total' => 'sum(caiwu_t.r_total)',
            'sum_total1_clear' => 'sum(order_t.total1_clear)',
            'sum_budian' => 'sum(order_t.yuangong_money)',
            'sum_r_budian' => 'sum(ifnull(caiwu_t.budian_rate,0)*total_clear/100)',
            'sum_total1_dis' => 'sum(order_t.total1_dis)',
        ])->asArray()->one();
        $query2 = clone $query;
        $gift_sum = $query2
            ->leftJoin(OrderGiftT::tableName(), "order_gift_t.order_id=caiwu_t.order_id")
            ->leftJoin(GiftT::tableName(), "gift_t.id=order_gift_t.gift_id")
            ->andWhere('caiwu_t.insurer_type=1')
            ->andWhere('order_gift_t.gift_type=1 && order_gift_t.is_free=2')
            ->sum('gift_t.price');
        $query2 = clone $query;
        $voucher_sum = $query2
            ->leftJoin(OrderGiftT::tableName(), "order_gift_t.order_id=caiwu_t.order_id")
            ->leftJoin(GiftT::tableName(), "gift_t.id=order_gift_t.gift_id")
            ->andWhere('caiwu_t.insurer_type=1')
            ->andWhere('order_gift_t.gift_type=2 && order_gift_t.is_free=2')
            ->sum('gift_t.price');
        $query2 = clone $query;
        $gongzi_sum = $query2
            ->leftJoin(PayOrderUserT::tableName(), "pay_order_user_t.order_id=caiwu_t.order_id")
            ->andWhere('caiwu_t.insurer_type=1')
            ->sum('pay_order_user_t.real_pay');

        switch ($sort_key) {
            case 'total':
                $sort = 'caiwu_t.total ';
                break;
            case 'total_clear':
                $sort = 'caiwu_t.total_clear ';
                break;
            case 'total_rate':
                $sort = 'caiwu_t.total_rate ';
                break;
            case 'print_date'://默认按照print_date排序
            default:
                $sort = 'order_t.print_date ';
                break;
        }
        switch ($sort_value) {
            case 'ASC':
                $sort .= 'ASC';
                break;
            case 'DESC':
            default:
                $sort .= 'DESC';
                break;
        }

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

        $data = [];
        $data['total'] = $total;
        $data['rows'] = [];
        foreach($items as $item) {
            $order_info = $item->order;
            $user_info = $item->user;
            $row = $item->toArray();
            $row['username'] = $user_info->username;
            $row['company_name'] = $order_info ? $order_info->company2->name : '';
            $row['group_name'] = $user_info->group ? $user_info->group->path : '';
            $row['submit_date'] = $order_info ? $order_info->submit_date : '';
            $row['print_date'] = $order_info ? $order_info->print_date : '';
            if($item->insurer_type == 1) {
                $row['insurer_type'] = '商业';
            } else {
                $row['insurer_type'] = '交强';
            }
            $row['total_real'] = round($item->total * $item->total_rate/100,2);
            $row['total_clear_real'] = round($item->total_clear * $item->total_rate/100,2);
            $row['bu_dian'] = $item->budian_rate?round($item->budian_rate * $item->total_clear,2) / 100:0;
            $row['r_bu_dian'] = $item->insurer_type == 1?round($item->b1_total+$item->b2_total+$item->b3_total,2):0;
            $row['total1_dis'] = $item->insurer_type == 1?round($order_info->total1_dis + $order_info->yuangong_money,2):0;

            $ticket = $item->insurer_type == 1?$order_info->getGiftPrice(1,1):0;
            $gift = $item->insurer_type == 1?$order_info->getGiftPrice(1,2):0;

            $row['liwu'] = round($ticket + $gift,2);
            $row['gongzi'] = $item->insurer_type == 1?round($item->getPayOrderUser()->sum('real_pay'),2):0;
            $row['lirun'] = round($row['total_clear_real'] + $row['bu_dian']  - $row['total1_dis'] - $row['gongzi'] - $row['liwu'],2);
            $data['rows'][] = $row;
        }

        $data['rows'][] = array(
            ['商业保总额', number_format($sums['sum_total1'],2)],
            ['商业净保总额', number_format($sums['sum_total1_clear'],2)],
            ['回款总额', number_format($sums['sum_r_total'],2)],
            ['补点总额', number_format($sums['sum_budian'],2)],
            ['回款补点总额', number_format($sums['sum_r_budian'],2)],
            ['减免总额', number_format($sums['sum_total1_dis'],2)],
            ['礼品礼券自费总额', number_format($gift_sum + $voucher_sum,2)],
            ['工资总额', number_format($gongzi_sum,2)],
            ['利润总额', number_format($sums['sum_total1_clear'] + $sums['sum_budian'] - $sums['sum_total1_dis'] - $gongzi_sum - $gift_sum - $voucher_sum,2)],
        );

        return $data;
    }

    public function actionGongziAllReturnSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        $id = $request->post('id',0);
        $remark = $request->post('remark','');
        $status_id = 4;

        $pay_info = PayT::findOne($id);
        $pay_info->status_id = $status_id + 6;

        $content = '老板：'.$this->my->showName.'退回'.$pay_info->pay_date.'工资';
        $this->addUserLog($pay_info->id, $content,$remark);

        if($pay_info->save()){
            $result['success'] = true;
            $result['msg'] = '保存成功';
        }
        return $result;
    }

    public function actionGongziAllSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        $id = $request->post('id',0);

        $pay_info = PayT::findOne($id);
        $pay_info->status_id = 5;

        $content = '老板：'.$this->my->showName.'同意本条记录'.$pay_info->pay_date.'工资';
        $this->addUserLog($pay_info->id, $content);


        if($pay_info->save()){
            $result['success'] = true;
            $result['msg'] = '保存成功';
        }
        return $result;
    }

    public function actionCarInfoImportIndex()
    {
        $request = Yii::$app->request;
        return $this->render('car-info-import-index');
    }

    public function actionCarInfoImport()
    {
        set_time_limit(0);
        ini_set('memory_limit', '3072M');
        $this->pushInfoToHtml('开始处理上传文件...');
        $request = Yii::$app->request;
        $base_filename = $request->get('urlfile');
        $upload_filename = $request->get('filename');
        $this->pushInfoToHtml('文件名：' . $upload_filename);
        $web_path = Yii::$app->getBasePath() . '/../frontend/web';
        $filename = $web_path . $base_filename;
        $this->pushInfoToHtml('开始加载excel文件...');
        $reader = new \PHPExcel_Reader_Excel2007();
        if(!$reader->canRead($filename)) {
            $reader = new \PHPExcel_Reader_Excel5();
            if(!$reader->canRead($filename)) {
                $this->pushInfoToHtml('加载失败，不能读取文件...');
                exit();
            }
        }
        $data = $reader->load($filename)->getSheet(0)->toArray('', true, true);
        $total = count($data);
        $this->pushInfoToHtml('加载完成，预计'. $total .'条数据...');
        $statistical_information = [
            'total_all' => $total - 1,
            'total_skip' => 0,
            'total_insert' => 0,
            'total_update' => 0,
            'total_conflict' => 0,
            'total_handle' => 0,
        ];
        $from_src = 'BMC' . date('Ymd') . strtoupper(substr(md5($filename), 0, 6));
        $file_path = Yii::getAlias('@frontend/web');
        $destination = '/upload/outlier_data/';
        if (!is_dir($file_path . $destination)) {
            @mkdir($file_path . $destination, 0777);
        }
        $filename = md5('outlier_data_' . date('Y-m-d-H-i')) . '.csv';
        $this->pushInfoToHtml('开始处理...');
        for ($i = 1; $i < $total; $i++) {
            $item = $data[$i];
            $this->pushInfoToHtml('第' . ($i) . '条：' . $item[1]);
            $import_info = ['linkmans'=>[], 'linkphones'=>[]];
            $import_info['register_date'] = trim(sprintf("%s",$item[0]));
            $import_info['car_no'] = trim(sprintf("%s",$item[1]));
            $import_info['car_frame_no'] = trim(sprintf("%s",$item[2]));
            $import_info['engine_no'] = trim(sprintf("%s",$item[3]));
            $import_info['factory_model'] = trim(sprintf("%s",$item[4]));
            $import_info['car_year'] = trim(sprintf("%s", $item[5]));
            $import_info['factory_model'] .= ' ' . trim(sprintf("%s", $item[6]));
            $import_info['car_man'] = trim(sprintf("%s",$item[7]));
            $import_info['car_number'] = trim(sprintf("%s",$item[8]));
            $import_info['phone'] = trim(sprintf("%s",$item[9]));
            $import_info['purchase_value'] = trim(sprintf("%s",$item[10]));
            $import_info['id_man'] = trim(sprintf("%s",$item[11]));
            $import_info['id_number'] = trim(sprintf("%s",$item[12]));
            $import_info['id_phone'] = trim(sprintf("%s",$item[13]));
            $import_info['company'] = trim(sprintf("%s",$item[14]));
            $import_info['insurer1_date'] = trim(sprintf("%s",$item[15]));
            $import_info['insurer2_date'] = trim(sprintf("%s",$item[16]));
            $import_info['insurer_type'] = trim(sprintf("%s",$item[17]));
            $import_info['linkmans'][] = trim(sprintf("%s",$item[18]));
            $import_info['linkphones'][] = trim(sprintf("%s",$item[19]));
            $import_info['linkmans'][] = trim(sprintf("%s",$item[20]));
            $import_info['linkphones'][] = trim(sprintf("%s",$item[21]));
            $import_info['linkmans'][] = trim(sprintf("%s",$item[22]));
            $import_info['linkphones'][] = trim(sprintf("%s",$item[23]));
            $import_info['car_no'] = $import_info['car_no'] == '*' ? '' : $import_info['car_no'];
            if ($import_info['car_frame_no'] == '' && $import_info['car_no'] == '' && $import_info['engine_no'] == '') {
                $statistical_information['total_skip']++;
                unset($item,$data[$i]);
                $statistical_information['total_all'] --;
                continue;
            }
            $tran = CarT::getDb()->beginTransaction();
            try {
                $ret = $this->checkCarProject($from_src, $import_info);
                switch($ret['code']){
                    case 1:
                        $this->pushInfoToHtml('项目存在，做更新处理...');
                        $ret = $this->updateCarInfo($ret['id'], $import_info, $from_src, false, true);
                        $statistical_information['total_update']++;
                        break;
                    case 2:
                        $this->pushInfoToHtml('空行或已导入，跳过...');
                        $statistical_information['total_skip']++;
                        break;
                    case 3:
                        $this->pushInfoToHtml('新增数据，做插入处理...');
                        $ret = $this->createCarInfo($import_info, $from_src);
                        $statistical_information['total_insert']++;
                        break;
                }
                $tran->commit();
            }catch(\Exception $e){
                $tran->rollBack();
                $this->pushInfoToHtml('操作失败：' . $e->getMessage());
            }

            if(!$ret['success']){
                $data[$i][] = $ret['msg'];
                $this->outlierDataHandle($data[$i], $file_path . $destination . $filename);
                $statistical_information['total_handle']++;
            }
            unset($item, $data[$i], $ret);
        }
        $this->pushInfoToHtml('操作成功'. "数据总计{$statistical_information['total_all']}条，
            冲突{$statistical_information['total_conflict']}, 
            更新{$statistical_information['total_update']}，
            跳过{$statistical_information['total_skip']}，
            插入{$statistical_information['total_insert']}，
            异常{$statistical_information['total_handle']}");
        echo '<script>parent.window.layer.closeAll();parent.window.onbeforeunload = null;</script>';
        exit();
    }

    public function actionCarInfoBhxUpdate()
    {
        set_time_limit(0);
        ini_set('memory_limit', '3072M');
        $this->pushInfoToHtml('开始处理上传文件...');
        $request = Yii::$app->request;
        $base_filename = $request->get('urlfile');
        $upload_filename = $request->get('filename');
        $this->pushInfoToHtml('文件名：' . $upload_filename);
        $web_path = Yii::$app->getBasePath() . '/../frontend/web';
        $filename = $web_path . $base_filename;
        $this->pushInfoToHtml('开始加载excel文件...');
        $reader = new \PHPExcel_Reader_Excel2007();
        if(!$reader->canRead($filename)) {
            $reader = new \PHPExcel_Reader_Excel5();
            if(!$reader->canRead($filename)) {
                $this->pushInfoToHtml('加载失败，不能读取文件...');
                exit();
            }
        }
        $data = $reader->load($filename)->getSheet(0)->toArray('', true, true);
        $total = count($data);
        $this->pushInfoToHtml('加载完成，预计'. $total .'条数据...');
        $statistical_information = [
            'total_all' => $total - 1,
            'total_skip' => 0,
            'total_insert' => 0,
            'total_update' => 0,
            'total_error' => 0,
            'total_error_arr' => [],
        ];
        $this->pushInfoToHtml('开始处理...');
        for ($i = 1; $i < $total; $i++) {
            $item = $data[$i];
            $this->pushInfoToHtml('第' . ($i + 1) . '条：' . $item[0]);
            $car_no = trim(sprintf("%s", $item[0]));
            $car_man = trim(sprintf("%s", $item[1]));
            $factory_model = trim(sprintf("%s", $item[2]));
            $engine_no = trim(sprintf("%s", $item[3]));
            $car_frame_no = trim(sprintf("%s", $item[4]));
            $register_date = trim(sprintf("%s", $item[5]));
            $company = trim(sprintf("%s", $item[6]));
            $insurer1_date = trim(sprintf("%s", $item[7]));
            $insurer2_date = trim(sprintf("%s", $item[8]));
            $id_man = trim(sprintf("%s", $item[9]));
            $id_number = trim(sprintf("%s", $item[10]));

            $car_info = CarT::findOne(['car_frame_no' => $car_frame_no]);
            if(isset($car_info)) {
                if ($car_info->location > 2 && $car_info->insurer1_date >= $insurer1_date) {
                    $this->pushInfoToHtml('空行或已导入，跳过...');
                    $statistical_information['total_skip'] ++ ;
                    continue;
                }
                $car_info->car_no = $car_no!= '' ? $car_no : $car_info->car_no;
                $car_info->car_man = $car_info->car_man!= '' ? $car_info->car_man : $car_man;
                $car_info->register_date = $register_date;
                $car_info->factory_model = $factory_model;
                //对比原信息是否包含待更新信息(删除星号)
                $car_info->engine_no = $car_info->engine_no != '' && MyLib::StartsWith($car_info->engine_no,rtrim($engine_no,'*')) ? $car_info->engine_no : $engine_no;
                $insurer1_flag = strtotime(date('Y',strtotime($insurer1_date))) > strtotime(date('Y',strtotime($car_info->insurer1_date)));
                if($insurer1_flag){
                    $car_info->insurer1_date = $insurer1_date;
                }
                $insurer2_flag = strtotime(date('Y',strtotime($insurer2_date))) > strtotime(date('Y',strtotime($car_info->insurer2_date)));
                if($insurer2_flag) {
                    $car_info->insurer2_date = $insurer2_date;
                }
                if(($car_info->insurer1_date != '' && $insurer1_flag) || ($car_info->insurer2_date != '' && $insurer2_flag) || $car_info->insurer1_date == '' || $car_info->insurer2_date == ''){
                    $car_info->company = $company != '' ? $company : $car_info->company;
                    $car_info->id_man = $car_info->id_man != '' && MyLib::StartsWith($car_info->id_man,rtrim($id_man,'*')) ? $car_info->id_man : $id_man;
                    $car_info->id_man_number = $car_info->id_man_number != '' && MyLib::StartsWith($car_info->id_man_number,rtrim($id_number,'*')) ? $car_info->id_man_number : $id_number;
                }

                if (!$car_info->save()) {
                    $this->pushInfoToHtml('操作失败：' . json_encode($car_info->getErrorSummary(true)));
                    $statistical_information['total_error'] ++ ;
                    $statistical_information['total_error_arr'][] = $i;
                }else {
                    $this->pushInfoToHtml('更新车辆信息...');
                    $statistical_information['total_update'] ++ ;
                }
            }else {
                $statistical_information['total_skip'] ++ ;
                $this->pushInfoToHtml('空行或不存在，跳过...');
            }
        }
        $this->pushInfoToHtml('操作成功'. "数据总计{$statistical_information['total_all']}条，
            更新{$statistical_information['total_update']}，
            失败{$statistical_information['total_error']}，
            失败数据列：". implode(',',$statistical_information['total_error_arr']) . "，
            跳过{$statistical_information['total_skip']}");
        echo '<script>parent.window.layer.closeAll();parent.window.onbeforeunload = null;</script>';
        exit();
    }

    private function pushInfoToHtml($msg){
        echo "<p style='color: #fff;font-size: 12px;'><span>>>>&nbsp;&nbsp;&nbsp;&nbsp;</span>$msg</p><script>document.body.scrollTop = document.body.offsetHeight;</script>";
        ob_flush();
        flush();
    }

    /**
     * 检查车辆信息
     * @param $from_src
     * @param $import_info
     * @return array
     */
    private function checkCarProject($from_src, $import_info)
    {
        $result = ['success' => true];
        $car_info = CarT::find()->where([
            'car_frame_no' => $import_info['car_frame_no'],
        ])->one();

        //如果当前批次插入信息则跳过
        if ($car_info) { //基础信息冲突调整
            if ($car_info->from_src == $from_src) {
                $result['code'] = 2;
                $result['msg'] = '批次重复，跳过';
                return $result;
            }
            $result['code'] = 1;
            $result['msg'] = '信息更新';
            $result['id'] = $car_info->id;
        } else {
            $result['code'] = 3;
            $result['msg'] = '新增数据';
        }
        unset($car_info);
        return $result;
    }

    /**
     * 新增车辆信息
     * @param $info
     * @param $from_src
     * @param int $lv
     * @param null $old_car_info
     * @return array
     * @throws \Exception
     */
    private function createCarInfo($info, $from_src, $lv = 1, &$old_car_info = null)
    {
        $result = [];
        $car_info = new CarT();
        $car_info->from_src = $from_src;
        $car_info->user_id = $this->my->id;
        $car_info->car_use_id = 0;
        $car_info->car_type_id = 0;
        $car_info->car_no = $info['car_no']?:$car_info->car_no;
        $car_info->location = 1;
        $car_info->car_man = $info['car_man'];
        $car_info->car_man_number = $info['car_number'];
        $car_info->car_man_phone = $info['phone'];
        $car_info->factory_model = $info['factory_model'];
        $car_info->engine_no = $info['engine_no'];
        $car_info->car_frame_no = $info['car_frame_no'];
        $car_info->register_date = $info['register_date'];
        $car_info->company = $info['company'];
        $car_info->insurer1_date = $info['insurer1_date'];
        $car_info->insurer2_date = $info['insurer2_date'];
        $car_info->id_man = $info['id_man'];
        $car_info->id_man_number = $info['id_number'];
        $car_info->id_man_phone = $info['id_phone'];
        $car_info->purchase_value = $info['purchase_value']?:0;;
        if (!$car_info->save()) throw new \Exception("车辆信息保存失败：" . json_encode($car_info->getErrors(),JSON_UNESCAPED_UNICODE));
        $info['linkphones'] = is_array($info['linkphones']) ? $info['linkphones'] : explode(',', $info['linkphones']);
        $info['linkmans'] = is_array($info['linkmans']) ? $info['linkmans'] : explode(',', $info['linkmans']);
        foreach ($info['linkphones'] as $k => $link) {
            if(!$link) continue;
            $linkman_info = LinkmanT::findOne(['car_id' => $car_info->id, 'phone' => $link]);
            if(!$linkman_info){
                $linkman_info = new LinkmanT();
            }
            $linkman_info->car_id = $car_info->id;
            $linkman_info->phone = $link;
            $linkman_info->name = $info['linkmans'][$k];
            $linkman_info->type = '联系人';
            if (!$linkman_info->save()) throw new \Exception("联系人信息保存：" . json_encode($linkman_info->getErrors(),JSON_UNESCAPED_UNICODE));
        }
        unset($car_info,$kehu_info,$linkman_info);
        $result['success'] = true;
        $result['msg'] = '保存成功';
        return $result;
    }

    /**
     * 更新车辆信息
     * 强制更新 以导入信息为主
     * 车主电话冲突处理 原被保险人电话为空时，原车主电话改至更新信息的被保险人电话作更新处理，如果原被保险人电话不为空改至联系人电话作更新处理
     * 车牌、发动机、车主、车主证件 原库不为空使用原库否则更新
     * 保险日期以最新为主
     * 其余项以更新消息为主
     * @param $id
     * @param $info
     * @param $from_src
     * @param bool $is_car_phone_conflict
     * @return array
     * @throws \Exception
     */
    private function updateCarInfo($id, $info, $from_src, $is_car_phone_conflict = false)
    {
        $result = [];
        $car_info = CarT::findOne(['id' => $id]);
        $car_info->car_frame_no = $info['car_frame_no'];
        $car_info->from_src = $from_src;
        $car_info->user_id = $this->my->id;
        $car_info->car_use_id = 0;
        $car_info->car_type_id = 0;
        $car_info->is_track = 0;
        $car_info->times = 1;
        $car_info->invalid_flag = 0;
        $car_info->invalid_id = 0;
        $car_info->car_year = $info['car_year'];
        if (str_replace('-', '', $car_info->car_no) == $info['car_no']) {
            $car_info->car_no = $info['car_no'];
        } else {
            $car_info->car_no = $car_info->car_no != '' ? $car_info->car_no : $info['car_no'];
        }
        $car_info->engine_no = $car_info->engine_no != '' ? $car_info->engine_no : $info['engine_no'];
        $car_info->car_man = $car_info->car_man != '' ? $car_info->car_man : $info['car_man'];
        $car_info->car_man_number = $car_info->car_man_number != '' ? $car_info->car_man_number : $info['car_number'];
        if($is_car_phone_conflict && $car_info->id_man_phone == ''){
            $car_info->id_man_phone = $car_info->car_man_phone;
            $car_info->car_man_phone = $info['phone'];
        }else if($is_car_phone_conflict && $car_info->id_man_phone != ''){
            $info['linkmans'][] = $car_info->car_man;
            $info['linkphones'][] = $car_info->car_man_phone;
            $car_info->car_man_phone = $info['phone'];
        }else {
            $car_info->id_man_phone = $car_info->id_man_phone != '' && $car_info->id_man_phone == $info['id_phone'] ? $car_info->id_man_phone : $info['id_phone'];
            $car_info->car_man_phone = $car_info->car_man_phone != '' ? $car_info->car_man_phone : $info['phone'];
        }
        $car_info->factory_model = $car_info->factory_model != '' && $car_info->factory_model == $info['factory_model'] ? $car_info->factory_model : ($info['factory_model']?:$car_info->factory_model);
        $car_info->register_date = $car_info->register_date != '' && $car_info->register_date == $info['register_date'] ? $car_info->register_date : ($info['register_date'] ?: $car_info->register_date);
        $car_info->company = $car_info->company != '' && $car_info->company == $info['company'] ? $car_info->company : ($info['company'] ?: $car_info->company);
        $car_info->id_man = $car_info->id_man != '' && $car_info->id_man == $info['id_man'] ? $car_info->id_man : ($info['id_man'] ?: $car_info->id_man);
        $car_info->id_man_number = $car_info->id_man_number != '' && $car_info->id_man_number == $info['id_number'] ? $car_info->id_man_number : ($info['id_number']?:$car_info->id_man_number);
        $car_info->purchase_value = $car_info->purchase_value != '' && $car_info->purchase_value == $info['purchase_value'] ? $car_info->purchase_value : ($info['purchase_value'] ?: $car_info->purchase_value);
        $car_info->purchase_value = $car_info->purchase_value > 0 ? $car_info->purchase_value : 0;
        $car_info->insurer1_date = $car_info->insurer1_date != '' && strtotime($car_info->insurer1_date) >= strtotime($info['insurer1_date']) ? $car_info->insurer1_date : $info['insurer1_date'];
        $car_info->insurer2_date = $car_info->insurer2_date != '' && strtotime($car_info->insurer2_date) >= strtotime($info['insurer2_date']) ? $car_info->insurer2_date : $info['insurer2_date'];
        if (!$car_info->save())
            throw new \Exception("车辆信息保存失败：" . json_encode($car_info->getErrors(),JSON_UNESCAPED_UNICODE));
        $info['linkphones'] = is_array($info['linkphones']) ? $info['linkphones'] : explode(',', $info['linkphones']);
        $info['linkmans'] = is_array($info['linkmans']) ? $info['linkmans'] : explode(',', $info['linkmans']);
        foreach ($info['linkphones'] as $k => $link) {
            if(!$link){
                continue;
            }
            $id = $id ?: $car_info->id;
            $linkman_info = LinkmanT::findOne(['car_id' => $id, 'phone' => $link]);
            if(!$linkman_info){
                $linkman_info = new LinkmanT();
            }
            $linkman_info->car_id = $id;
            $linkman_info->phone = $link;
            $linkman_info->name = $info['linkmans'][$k];
            $linkman_info->type = '联系人';
            if (!$linkman_info->save())
                throw new \Exception("联系人信息保存失败：" . json_encode($linkman_info->getErrors(),JSON_UNESCAPED_UNICODE));
        }
        unset($car_info,$kehu_info,$linkman_info);
        $result['success'] = true;
        $result['msg'] = '保存成功';
        return $result;
    }
}
