<?php
namespace app\admin\controller;

use app\hander\HelpHander;
use think\App;
use think\Db;
use think\Exception;

class PhOrders extends Auth
{
    protected $status = [
        0=>'待分配',
        1=>'进行中',
        2=>'已完成',
        3=>'已作废',
        4=>'已结算'
    ];
    public function index(){
        if(request()->isAjax()){
            //分页参数
            $length = input('rows',10,'intval');   //每页条数
            $page = input('page',1,'intval');      //第几页
            $start = ($page - 1) * $length;     //分页开始位置
            //排序
            $sortRow = input('sidx','u.id','trim');      //排序列
            $sort = input('sord','desc','trim');        //排序方式
            $order = 'a.id desc';
            $title = input('title','','trim');//用户
            if($title){
                $user = Db::name('user')
                    ->alias('u')
                    ->join('user_org uo','uo.user_id = u.id')
                    ->where('u.real_name','like','%'.$title.'%')
                    ->where('uo.org_id',$this->orgId)
                    ->column('u.id');
                if(!empty($user)){
                    $map[] = ['a.user_id','in',$user];
                }else{
                    $map[] = ['a.user_id','=',0];
                }
            }

            $sn = input('sn','','trim');
            if($sn){
                $map[] = ['a.sn','=',$sn];
            }

            $cateId = input('cateId','','trim');
            if($cateId){
                $map[] = ['a.cate_id','=',$cateId];
            }

            $depId = input('depId','','trim');
            if($depId){
                $map[] = ['a.dep_id','=',$depId];
            }

            $status = input('status','','trim');
            if($status != ''){
                $map[] = ['a.status','=',$status];
            }

            $b = input('begin','','trim');
            $e = input('end','','trim');
            if($b){
                $b = date('Y-m-d 00:00:00',strtotime($b));
                $map[] = ['a.create_time','>=',$b];
            }
            if($e){
                $e = date('Y-m-d 23:59:59',strtotime($e));
                $map[] = ['a.create_time','<=',$e];
            }
            $map[] = ['a.org_id','=',$this->orgId];
            $map= empty($map) ? true: $map;
            //数据查询
            $lists = Db::name('ph_orders')
                ->alias('a')
                ->where($map)
                ->field('a.*')
                ->limit($start,$length)
                ->order($order)
                ->select();
            foreach ($lists as $k=>$v){
                $lists[$k]['userName'] = Db::name('user')
                    ->where('id',$v['user_id'])
                    ->value('real_name');
                $lists[$k]['depName'] = '';
                $lists[$k]['cateName'] = '';
                if($v['cate_id'] > 0){
                    $lists[$k]['cateName'] = Db::name('cate')
                        ->where('id',$v['cate_id'])
                        ->value('title');
                }
                if($v['dep_id'] > 0){
                    $lists[$k]['depName'] = Db::name('dep')
                        ->where('id',$v['dep_id'])
                        ->value('title');
                }
                $lists[$k]['is_zf'] = 0;
                $off = model('Config')->getConfig('ph_order_cancel_time',cur_org_id());
                if($off){
                    $start = strtotime($v['create_time']) + $off*60*60;
                    $end = strtotime(date('Y-m-d H:i:s'));
                    if($start < $end){
                        $lists[$k]['is_zf'] = 1;
                    }
                }
            }
            int_to_string($lists,['status' => $this->status]);
            //数据返回
            $totalCount = Db::name('ph_orders')->alias('a')
                ->where($map)->count();
            $totalPage = ceil($totalCount/$length);
            $totalMoney = Db::name('ph_orders')->alias('a')
                ->where($map)->sum('a.amount');
            $result['totalMoney'] = $totalMoney;
            $result['page'] = $page;
            $result['total'] = $totalPage;
            $result['records'] = $totalCount;
            $result['rows'] = $lists;
            return json($result);
        }else{
            $cate =(new \app\common\model\Cate())->getAllByOrg($this->orgId);
            $this->assign('cate',$cate);

            $dep =(new \app\common\model\Dep())->getList($this->orgId);
            $this->assign('dep',$dep);

            $this->assign('status',$this->status);
            $this->assign('cur_status',input('status'));
            return $this->fetch();
        }
    }

    /**
     * 新增
     */
    public function add(){
        $model = new \app\common\model\PhOrders();
        if(request()->isPost()){
            $res = $model->addSave($this->userId,$this->orgId);
            if($res){
                $this->success('操作成功',url('index'));
            }else{
                $this->error($model->getError());
            }
        }else{
            $cate =(new \app\common\model\Cate())->getAllByOrg($this->orgId);
            $this->assign('cate',$cate);

            $dep =(new \app\common\model\Dep())->getList($this->orgId);
            $this->assign('dep',$dep);

            $workers =(new \app\common\model\Worker())->getAllByOrg($this->orgId);
            $this->assign('workers',$workers);

            $this->assign('meta_title','创建订单');
            return $this->fetch();
        }
    }

    /**
     * 新增
     */
    public function edit($id = 0){
        $model = new \app\common\model\PhOrders();
        if(request()->isPost()){
            $res = $model->editSave($this->userId,$this->orgId);
            if($res){
                $this->success('操作成功',url('index'));
            }else{
                $this->error($model->getError());
            }
        }else{
            $info = Db::name('ph_orders')
                ->where('id',$id)->find();
            $this->assign('info',$info);

            $cate =(new \app\common\model\Cate())->getAllByOrg($this->orgId);
            $this->assign('cate',$cate);

            $dep =(new \app\common\model\Dep())->getList($this->orgId);
            $this->assign('dep',$dep);

            $this->assign('meta_title','编辑订单');
            return $this->fetch();
        }
    }

    public function detail($id=0){
        $model = new \app\common\model\PhOrders();
        $info = $model->getInfo($id);
        if(!$info){
            $this->error('订单不存在');
        }
        $this->assign('info',$info);
        return $this->fetch();
    }

    /**
     * 派单
     */
    public function send($id = 0){
        $model = new \app\common\model\PhOrders();
        if(request()->isPost()){
            $res = $model->sendSave($this->userId,$this->orgId);
            if($res){
                $this->success('操作成功',url('index'));
            }else{
                $this->error($model->getError());
            }
        }else{
            $this->assign('id',$id);
            $workers =(new \app\common\model\Worker())->getAllByOrg($this->orgId);
            $this->assign('workers',$workers);

            return $this->fetch();
        }
    }

    /**
     * 预收金
     */
    public function payOrder($id = 0){
        if(request()->isPost()){
            $remark = input('remark','','trim');
            $money = input('money/f',0);
            if($money <= 0){
                HelpHander::error('输入金额错误');
            }

            $res = model('PhOrderPay')->addSaveDispatch($this->orgId,$id,$money,$remark);
            if($res){
                $this->success('操作成功',url('index'));
            }else{
                $this->error(model('PhOrderPay')->getError());
            }
        }else{
            $this->assign('id',$id);
            return $this->fetch();
        }
    }

    /**
     * 退款
     */
    public function refund($id = 0){
        if(request()->isPost()){
            $res = model('PhOrderPay')->refundOrder($this->userId);
            if($res){
                $this->success('操作成功',url('index'));
            }else{
                $this->error(model('PhOrderPay')->getError());
            }
        }else{
            $pay = Db::name('ph_order_pay')->where('id',$id)->find();
            $money = round($pay['money'] - $pay['money2'],2);
            $this->assign('money',$money);
            $this->assign('pay',$pay);
            $this->assign('id',$id);
            return $this->fetch();
        }
    }

    /**
     * 完成订单
     */
    public function finish($id = 0){
        $model = new \app\common\model\PhOrders();
        if(request()->isPost()){
            $res = $model->finishSave($this->userId,$this->orgId);
            if($res){
                $this->success('操作成功',url('index'));
            }else{
                $this->error($model->getError());
            }
        }else{
            $info = Db::name('ph_orders')
                ->where('id',$id)->find();
            $info['end'] = $info['end']?$info['end']:date('Y-m-d H:i:s');

            $price = Db::name('cate')->where('id',$info['cate_id'])->value('price');
            $time = strtotime($info['end']) - strtotime($info['start']);
            $day =  round($time/(60*60*24),1);
            $sfMoney = round($price * $day,2);
            $info['amount'] = $info['amount']>0?$info['amount']:$sfMoney;
            $bjMoney = $tkMoney = 0.00;
            if($sfMoney > $info['pre_money']){
                $bjMoney = $sfMoney - $info['pre_money'];
            }else{
                $tkMoney =  $info['pre_money'] - $sfMoney;
            }

            $this->assign('bjMoney',$bjMoney);
            $this->assign('tkMoney',$tkMoney);

            $this->assign('info',$info);
            return $this->fetch();
        }
    }

    // 编辑
    public function editTodo($id = 0){
        $model = new \app\common\model\PhOrders();
        if(request()->isPost()){
            $res = $model->edit_todo($this->userId,$this->orgId);
            if($res){
                $this->success('操作成功',url('index'));
            }else{
                $this->error($model->getError());
            }
        }else{
            $info = Db::name('ph_todo')->where('id',$id)->find();
            $this->assign('info',$info);
            return $this->fetch();
        }
    }

    /**
     * 作废订单
     */
    public function cancel($id=0){
        if(request()->isPost()){
            $note = input('cancel_reason','','trim');
            $id = input('id/d',0);
            $model = new \app\common\model\PhOrders();
            $ret = $model->cancelOrder($id,$note,$this->userId);
            if(!$ret){
                $this->error($model->getError());
            }else{
                $this->success('操作成功');
            }
        }else{
            $this->assign('id',$id);
            return $this->fetch();
        }
    }

    //excel导出
    public function export(){

        if(request()->isGet()){
            $order = 'a.id desc';
            $title = input('title','','trim');//用户
            if($title){
                $user = Db::name('user')
                    ->alias('u')
                    ->join('user_org uo','uo.user_id = u.id')
                    ->where('u.real_name','like','%'.$title.'%')
                    ->where('uo.org_id',$this->orgId)
                    ->column('u.id');
                if(!empty($user)){
                    $map[] = ['a.user_id','in',$user];
                }else{
                    $map[] = ['a.user_id','=',0];
                }
            }

            $sn = input('sn','','trim');
            if($sn){
                $map[] = ['a.sn','=',$sn];
            }

            $cateId = input('cateId','','trim');
            if($cateId){
                $map[] = ['a.cate_id','=',$cateId];
            }

            $depId = input('depId','','trim');
            if($depId){
                $map[] = ['a.dep_id','=',$depId];
            }

            $status = input('status','','trim');
            if($status != ''){
                $map[] = ['a.status','=',$status];
            }

            $b = input('begin','','trim');
            $e = input('end','','trim');
            if($b){
                $b = date('Y-m-d 00:00:00',strtotime($b));
                $map[] = ['a.create_time','>=',$b];
            }
            if($e){
                $e = date('Y-m-d 23:59:59',strtotime($e));
                $map[] = ['a.create_time','<=',$e];
            }
            $map[] = ['a.org_id','=',$this->orgId];
            $map= empty($map) ? true: $map;
            //数据查询
            $lists = Db::name('ph_orders')->alias('a')
                ->where($map)
                ->field('a.*')
                ->order($order)
                ->select();

            foreach ($lists as $k=>$v){
                $lists[$k]['userName'] = Db::name('user')
                    ->where('id',$v['user_id'])
                    ->value('real_name');
                $lists[$k]['depName'] = '';
                $lists[$k]['cateName'] = '';
                if($v['cate_id'] > 0){
                    $lists[$k]['cateName'] = Db::name('cate')
                        ->where('id',$v['cate_id'])
                        ->value('title');
                }
                if($v['dep_id'] > 0){
                    $lists[$k]['depName'] = Db::name('dep')
                        ->where('id',$v['dep_id'])
                        ->value('title');
                }
            }
            int_to_string($lists,['status' => $this->status]);
            //实例化PHPExcel类
            include_once env('root_path') . '/extend/phpexcel/Classes/PHPExcel.php';
            $objPHPExcel = new \PHPExcel();
            //激活当前的sheet表
            $objPHPExcel->setActiveSheetIndex(0);
            //设置表格头(即excel表格的第一行)
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A1', '订单编号')
                ->setCellValue('B1', '联系人')
                ->setCellValue('C1', '联系电话')
                ->setCellValue('D1', '科室')
                ->setCellValue('E1', '陪护服务')
                ->setCellValue('F1', '开始日期')
                ->setCellValue('G1', '结束日期')
                ->setCellValue('H1', '订单金额')
                ->setCellValue('I1', '状态')
                ->setCellValue('J1', '下单日期');


            // 设置表格头水平居中
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('A1')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('B1')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('C1')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('D1')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('E1')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('F1')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('G1')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('H1')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('I1')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('J1')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('K1')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

            //设置列水平居中
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('A')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('B')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('C')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('D')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('E')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('F')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('G')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('H')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('I')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('J')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('K')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);


            //设置单元格宽度
            $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('A')->setWidth(10);
            $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('B')->setWidth(20);
            $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('C')->setWidth(20);
            $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('D')->setWidth(20);
            $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('E')->setWidth(20);
            $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('F')->setWidth(50);
            $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('G')->setWidth(20);
            $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('H')->setWidth(20);
            $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('I')->setWidth(20);
            $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('J')->setWidth(20);
            $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('K')->setWidth(20);


            //循环刚取出来的数组,将数据逐一添加到excel表格。
            for ($i = 0; $i < count($lists); $i++) {
                $objPHPExcel->getActiveSheet()->setCellValue('A' . ($i + 2), $lists[$i]['sn']);
                $objPHPExcel->getActiveSheet()->setCellValue('B' . ($i + 2), $lists[$i]['contact']);
                $objPHPExcel->getActiveSheet()->setCellValue('C' . ($i + 2), $lists[$i]['phone']);
                $objPHPExcel->getActiveSheet()->setCellValue('D' . ($i + 2), $lists[$i]['depName']);
                $objPHPExcel->getActiveSheet()->setCellValue('E' . ($i + 2), $lists[$i]['cateName']);
                $objPHPExcel->getActiveSheet()->setCellValue('F' . ($i + 2), $lists[$i]['start']);
                $objPHPExcel->getActiveSheet()->setCellValue('G' . ($i + 2), $lists[$i]['end']);
                $objPHPExcel->getActiveSheet()->setCellValue('H' . ($i + 2), $lists[$i]['amount']);
                $objPHPExcel->getActiveSheet()->setCellValue('I' . ($i + 2), $lists[$i]['status_text']);
                $objPHPExcel->getActiveSheet()->setCellValue('J' . ($i + 2), $lists[$i]['create_time']);
            }
            //设置保存的Excel表格名称
            $filename = '订单列表' . date('YmdHis', time()) . '.xls';

            //设置当前激活的sheet表格名称
            $objPHPExcel->getActiveSheet()->setTitle('订单列表');

            //设置浏览器窗口下载表格
            ob_end_clean();
            header("Content-Type: application/force-download");
            header("Content-Type: application/octet-stream");
            header("Content-Type: application/download");
            header('Content-Disposition:inline;filename="' . $filename);

            //生成excel文件
            $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
            //下载文件在浏览器窗口
            return  $objWriter->save('php://output');
        }

    }
    //陪护总览
    public function view(){

        $url = 'xxxxxxx';
        $downcode = think_encrypt($url);

        $url1= 'xxxxxxx';
        $this->assign('code',$downcode);
        $downcode1 = think_encrypt($url1);
        $this->assign('code1',$downcode1);
        $time=array();
        $currentTime = time();
        $cyear = floor(date("Y",$currentTime));
        $cMonth = floor(date("m",$currentTime));
        for($i=0;$i<12;$i++){
            $nMonth = $cMonth-$i;
            $cyear = $nMonth == 0 ? ($cyear-1) : $cyear;
            $nMonth = $nMonth <= 0 ? 12+$nMonth : $nMonth;
            if(strlen($nMonth)==1){
                $nMonth = '0'.$nMonth;
            }
            $time[]=$cyear.'-'.$nMonth;
        }
        //订单金额
        $m = input('month','');
        $type = input('type','');
        if(request()->isPost()){
            $begin=date('Y-m-d H:i:s',mktime(0,0,0,date('m',strtotime($m)),1,date('Y',strtotime($m))));
            $end=date('Y-m-d H:i:s',mktime(23,59,59,date('m',strtotime($begin)),date('t',strtotime($begin)),date('Y',strtotime($begin))));
        }else{
            $begin=date('Y-m-d H:i:s',mktime(0,0,0,date('m'),1,date('Y')));
            $end=date('Y-m-d H:i:s',mktime(23,59,59,date('m',strtotime($begin)),date('t',strtotime($begin)),date('Y',strtotime($begin))));
        }

        $map[] = ['create_time','>=',$begin];
        $map[] = ['create_time','<=',$end];
        $map[] = ['org_id','=',$this->orgId];

        $total =  Db::name('ph_orders')
            ->where($map)
            ->where('status','<>',3)
            ->sum('amount');
        $order['total'] =$total?'¥'.number_format($total,2):'¥0.00';
        $pre_money = Db::name('ph_orders')
            ->where($map)
            ->where('status','<>',3)
            ->sum('pre_money');
        $order['pre_money'] =$pre_money?'¥'.number_format($pre_money,2):'¥0.00';
        $pay = Db::name('ph_orders')
            ->where($map)
            ->where('status','in',[2,4])
            ->sum('amount');
        $order['pay'] =$pay?'¥'.number_format($pay,2):'¥0.00';
        $yjsTotal = Db::name('ph_orders')
            ->where($map)
            ->where('status','=',4)
            ->sum('amount');
        $order['yjs'] =$yjsTotal?'¥'.number_format($yjsTotal,2):'¥0.00';

        if($type==1){
           HelpHander::success($order);
        }

        //科室订单
        $typeList = Db::name('cate')
            ->where('enable',1)
            ->where('del',0)
            ->where('org_id',$this->orgId)
            ->select();
        $typeName = array_column($typeList,'title');
        $depIds = Db::name('ph_orders')
            ->where('org_id',$this->orgId)
            ->group('dep_id')
            ->column('dep_id');
        $viewData = [];
        if(empty($depIds)){
            $depName = [];
        }else{
            $depList = Db::name('dep')
                ->where('id','in',$depIds)
                ->select();
            $depName = array_column($depList,'title');
            foreach ($typeList as $k=>$v){
                $a = [
                    'name'=>$v['title'],
                    'type'=>'line',
                    'stack'=>'Total',
                ];
                $t = [];
                foreach ($depList as $k1=>$v1){
                    $sum = Db::name('ph_orders')
                        ->where($map)
                        ->where('cate_id',$v['id'])
                        ->where('dep_id',$v1['id'])
                        ->count();
                    $t[] = $sum?$sum:0;
                }
                $a['data'] = $t;
                $viewData[] = $a;
            }

        }
        $viewDataList = [
            'data1'=>$typeName,
            'data2'=>$depName,
            'data3'=>$viewData,
        ];
        if($type==2){
            HelpHander::success($viewDataList);
        }

        $count = Db::name('ph_orders')
            ->where('org_id',$this->orgId)
            ->count();
        $dfp['count1'] = Db::name('ph_orders')
            ->where('org_id',$this->orgId)
            ->where('status','=',0)
            ->count();
        $dfp['count2'] = $count-$dfp['count1'];
        if($count >0 && $dfp['count1']>0){
            $dfp['bl'] =round($dfp['count1']/$count*100,2).'%';
        }else{
            $dfp['bl'] = '0%';
        }

        $jxz['count1'] = Db::name('ph_orders')
            ->where('org_id',$this->orgId)
            ->where('status','=',1)
            ->count();
        $jxz['count2'] = $count-$jxz['count1'];
        if($count >0 && $jxz['count1']>0){
            $jxz['bl'] =round($jxz['count1']/$count*100,2).'%';
        }else{
            $jxz['bl'] = '0%';
        }


        $ywc['count1'] = Db::name('ph_orders')
            ->where('org_id',$this->orgId)
            ->where('status','=',2)
            ->count();
        $ywc['count2'] = $count-$ywc['count1'];
        if($count >0 && $ywc['count1']>0){
            $ywc['bl'] =round($ywc['count1']/$count*100,2).'%';
        }else{
            $ywc['bl'] = '0%';
        }

        $yzf['count1'] = Db::name('ph_orders')
            ->where('org_id',$this->orgId)
            ->where('status','=',3)
            ->count();
        $yzf['count2'] = $count-$yzf['count1'];
        if($count >0 && $yzf['count1']>0){
            $yzf['bl'] =round($yzf['count1']/$count*100,2).'%';
        }else{
            $yzf['bl'] = '0%';
        }


        $yjs['count1'] = Db::name('ph_orders')
            ->where('org_id',$this->orgId)
            ->where('status',4)
            ->count();
        $yjs['count2'] = $count-$yjs['count1'];
        if($count >0 && $yjs['count1']>0){
            $yjs['bl'] =round($yjs['count1']/$count*100,2).'%';
        }else{
            $yjs['bl'] = '0%';
        }

        $standardTime = date('Y-m-1');
        $_lastMonthStart = date('Y-m-1 00:00:00', strtotime("-1 month", strtotime($standardTime)));
        $_lastMonthEnd = date('Y-m-d H:i:s', strtotime('-1 sec', strtotime($standardTime)));

        $lastOrder = Db::name('ph_orders')
            ->where('org_id',$this->orgId)
            ->where('create_time','>=',$_lastMonthStart)
            ->where('create_time','<=',$_lastMonthEnd)
            ->count();
        $curOrder = Db::name('ph_orders')
            ->where('org_id',$this->orgId)
            ->where('create_time','>=',$begin)
            ->where('create_time','<=',$end)
            ->count();
        if($count >0 && $lastOrder >0){
            $lastBl = round($lastOrder/$count*100,2).'%';
        }else{
            $lastBl = '0%';
        }
        if($count >0 && $curOrder >0){
            $curBl = round($curOrder/$count*100,2).'%';
        }else{
            $curBl = '0%';
        }
        $bl = 0;
        if($lastOrder==0 && $curOrder==0){
            $bl = 0;
        }
        if($lastOrder==0 && $curOrder>0){
            $bl = 100;
        }
        if($lastOrder>0){
            $bl = round(($curOrder-$lastOrder)/$lastOrder*100,2);
        }

        $phCount = (new \app\common\model\Worker())->getAllByOrgCount($this->orgId);
        $zgIds = Db::name('ph_todo')
            ->where('status',1)
            ->group('worker_id')
            ->column('worker_id');
        if(empty($zgIds)){
            $zgCount = 0;
        }else{
            $p[] = ['a.id','in',$zgIds];
            $zgCount = (new \app\common\model\Worker())->getAllByOrgCount($this->orgId,$p);
        }

        $kxCount = abs($phCount-$zgCount);
        $userCount = [
            'count1'=>$phCount,
            'count2'=>$zgCount,
            'count3'=>$kxCount,
        ];

        $workerList  =(new \app\common\model\Worker())->getAllByOrg($this->orgId);
        foreach ($workerList as $k=>$v){
            $ywcTotal = Db::name('ph_todo')
                ->where('worker_id',$v['id'])
                ->where('org_id',$this->orgId)
                ->where('status',2)
                ->count();
            $workerList[$k]['ywc'] = $ywcTotal?$ywcTotal:0;
            $workerList[$k]['day'] = Db::name('ph_todo')
                ->where('worker_id',$v['id'])
                ->where('org_id',$this->orgId)
                ->where('status',2)
                ->sum('day');
        }
        $this->assign('workerList',$workerList);
        $this->assign('userCount',$userCount);
        $this->assign('viewDataList',$viewDataList);
        $this->assign('lastOrder',$lastOrder);
        $this->assign('curOrder',$curOrder);
        $this->assign('bl',$bl);
        $this->assign('curBl',$curBl);
        $this->assign('lastBl',$lastBl);
        $this->assign('dfp',$dfp);
        $this->assign('jxz',$jxz);
        $this->assign('ywc',$ywc);
        $this->assign('yzf',$yzf);
        $this->assign('yjs',$yjs);
        $this->assign('orderData',$order);
        $this->assign('month',$time);
        $this->assign('curMonth',date('Y-m'));
        return $this->fetch();
    }

    public function calculateMoney(){
        $orderId= input('orderId');
        $end = input('end');
        if(empty($end)){
            $this->error('参数错误');
        }
        $info = Db::name('ph_orders')
            ->where('id',$orderId)->find();

        $price = Db::name('cate')->where('id',$info['cate_id'])->value('price');

//        $day = model('PhOrders')->getWorkerDay($info['start'],$end);

        $time = strtotime($end) - strtotime($info['start']);
        $day =  round($time/(60*60*24),1);
        $sfMoney = round($price * $day,2);

        $bjMoney =$tkMoney = 0.00;
        if($sfMoney > $info['pre_money']){
            $bjMoney = $sfMoney - $info['pre_money'];
        }else{
            $tkMoney =  $info['pre_money'] - $sfMoney;
        }

        $data = [
            'sfMoney' =>$sfMoney,
            'bjMoney' =>$bjMoney,
            'tkMoney' =>$tkMoney,
        ];

        $this->success('操作成功','',$data);

    }

}