| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981 | <?phpnamespace app\admin\controller;use app\hander\HelpHander;use PhpOffice\PhpWord\Shared\Html;use think\Db;use PhpOffice\PhpWord\PhpWord;use PhpOffice\PhpWord\IOFactory;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');                $orderId = Db::name('ph_todo')                    ->alias('p')                    ->join('worker w','w.id=p.worker_id')                    ->where('w.user_id','in',$user)                    ->column('p.order_id');                if(!empty($orderId)){                    $map[] = ['a.id','in',$orderId];                }else{                    $map[] = ['a.id','=',0];                }            }            $sn = input('sn','','trim');            if($sn){                $map[] = ['a.sn','=',$sn];            }            $name = input('name','','trim');            if($name){                $map[] = ['a.name','like','%'.$name.'%'];            }            $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){                $map[] = ['a.create_time','>=',$b];            }            if($e){                $map[] = ['a.create_time','<=',$e];            }            $map[] = ['a.org_id','=',$this->orgId];            $map[] = ['a.is_service','=',1];            $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'] = '';                $lists[$k]['workerName'] = '';                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');                }                $workerId  =                    $v['status'] == 3 ?                    Db::name('ph_todo')->where('order_id',$v['id'])->column('worker_id')                    :                    Db::name('ph_todo')->where('order_id',$v['id'])->whereIn('status',[1,2])->column('worker_id');                if (!empty($workerId)) {                    foreach ($workerId as $k2=>$v2){                        $userId = Db::name('worker')->where('id',$v2)->value('user_id');                        $workerId[$k2]= Db::name('user')->where('id',$userId)->value('real_name');                    }                    $lists[$k]['workerName'] = implode(',',$workerId);                }                $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;                    }                }                if ($v['status'] == 2){                    $lists[$k]['days'] = $this->getWorkerDay($v['start'],$v['end']);                }            }            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');            $totalService = Db::name('ph_orders')->alias('a')                ->where($map)->sum('a.service_money');            $result['totalMoney'] = $totalMoney+$totalService;            $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);            foreach ($cate as $k => $v){                $cate[$k]['deps'] = $v['deps'] ? explode(',',$v['deps']):[];            }            $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 editDept($id = 0){        if(request()->isPost()){            $res = Db::name('ph_orders')->where('id',$id)->update(['dep_id'=>input('dep_id',0)]);            if($res){                $this->success('操作成功',url('index'));            }else{                $this->error('操作失败');            }        }else{            $depId= Db::name('ph_orders')                ->where('id',$id)                ->value('dep_id');            $this->assign('depId',$depId);            $dep =(new \app\common\model\Dep())->getList($this->orgId);            $this->assign('deps',$dep);            $this->assign('id',$id);            return $this->fetch();        }    }    public function detail($id=0){        $model = new \app\common\model\PhOrders();        $info = $model->getInfo($id);        if(!$info){            $this->error('订单不存在');        }        $serviceMoney = model("Config")->getConfig("web_service_money",$this->orgId);        $serviceMoney = floatval($serviceMoney) > 0? floatval($serviceMoney) : 0;        $this->assign('service_money',$serviceMoney);        $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,$busType=0){        if(request()->isPost()){            $remark = input('remark','','trim');            $money = input('money/f',0);            $busType = input('busType/d',0);            if($money <= 0){                HelpHander::error('输入金额错误');            }            $res = model('PhOrderPay')->addSaveDispatch($this->orgId,$this->userId,$id,$money,$remark,$busType);            if($res){                $this->success('操作成功',url('index'));            }else{                $this->error(model('PhOrderPay')->getError());            }        }else{            $serviceMoney = model("Config")->getConfig("web_service_money",$this->orgId);            $serviceMoney = floatval($serviceMoney) > 0? floatval($serviceMoney) : 0;            $this->assign('service_money',$serviceMoney);            $this->assign('id',$id);            $this->assign('busType',$busType);            return $this->fetch();        }    }    /**     * 退款     */    public function refund($id = 0){        if(request()->isPost()){            $res = model('PhOrderPay')->refundOrder($this->userId,$this->orgId);            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');                $orderId = Db::name('ph_todo')                    ->alias('p')                    ->join('worker w','w.id=p.worker_id')                    ->where('w.user_id','in',$user)                    ->column('p.order_id');                if(!empty($orderId)){                    $map[] = ['a.id','in',$orderId];                }else{                    $map[] = ['a.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){                $map[] = ['a.create_time','>=',$b];            }            if($e){                $map[] = ['a.create_time','<=',$e];            }            $map[] = ['a.org_id','=',$this->orgId];            $map[] = ['a.is_service','=',1];            $map= empty($map) ? true: $map;            //数据查询            $lists = Db::name('ph_orders')->alias('a')                ->where($map)                ->field('a.*')                ->distinct(true)                ->order($order)                ->select();            foreach ($lists as $k=>$v){                $lists[$k]['name'] =preg_replace('/[^\x{4E00}-\x{9FFF}]/u', '', $v['name']);                $lists[$k]['userName'] = Db::name('user')                    ->where('id',$v['user_id'])                    ->value('real_name');                $lists[$k]['depName'] = '';                $lists[$k]['cateName'] = '';                $lists[$k]['price'] = '';                $lists[$k]['workerName'] = '';                $workerId  = Db::name('ph_todo')                    ->where('order_id',$v['id'])                    ->whereIn('status',[1,2])                    ->column('worker_id');                if (!empty($workerId)) {                    foreach ($workerId as $k2=>$v2){                        $userId = Db::name('worker')->where('id',$v2)->value('user_id');                        $workerId[$k2]= Db::name('user')->where('id',$userId)->value('real_name');                    }                    $lists[$k]['workerName'] = implode(',',$workerId);                }                if($v['cate_id'] > 0){                    $cate = Db::name('cate')                        ->where('id',$v['cate_id'])                        ->field('price,title')                        ->find();                    $lists[$k]['cateName'] =$cate['title'];                    $lists[$k]['price'] =$cate['price'];                }                if($v['dep_id'] > 0){                    $lists[$k]['depName'] = Db::name('dep')                        ->where('id',$v['dep_id'])                        ->value('title');                }                $lists[$k]['days'] = $v['status'] == 2 ? $this->getWorkerDay($v['start'],$v['end']) : '';            }            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', '开始日期')                ->setCellValue('K1', '结束日期')                ->setCellValue('L1', '服务天数')                ->setCellValue('M1', '订单金额')                ->setCellValue('N1', '服务费')                ->setCellValue('O1', '状态')                ->setCellValue('P1', '下单日期')                ->setCellValue('Q1', '完成日期');            $arrs = ['A','B','C','D','E','F','G','H','I','J','H','I','J','K','L','M','N','O','P','Q'];            foreach ($arrs as $arr){                // 设置表格头水平居中                $objPHPExcel->setActiveSheetIndex(0)->getStyle($arr.'1')->getAlignment()                    ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);                //设置列水平居中                $objPHPExcel->setActiveSheetIndex(0)->getStyle($arr)->getAlignment()                    ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);                //设置单元格宽度                if ($arr == 'E'){                    $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension($arr)->setWidth(50);                }else{                    $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension($arr)->setWidth(20);                }            }            //循环刚取出来的数组,将数据逐一添加到excel表格。            for ($i = 0; $i < count($lists); $i++) {                $objPHPExcel->getActiveSheet()->setCellValueExplicit('A' . ($i + 2), $lists[$i]['sn']);                $objPHPExcel->getActiveSheet()->setCellValue('B' . ($i + 2), $lists[$i]['name']);                $objPHPExcel->getActiveSheet()->setCellValue('C' . ($i + 2), $lists[$i]['bed']);                $objPHPExcel->getActiveSheet()->setCellValue('D' . ($i + 2), $lists[$i]['contact']);                $objPHPExcel->getActiveSheet()->setCellValue('E' . ($i + 2), $lists[$i]['phone']);                $objPHPExcel->getActiveSheet()->setCellValue('F' . ($i + 2), $lists[$i]['depName']);                $objPHPExcel->getActiveSheet()->setCellValue('G' . ($i + 2), $lists[$i]['cateName']);                $objPHPExcel->getActiveSheet()->setCellValue('H' . ($i + 2), $lists[$i]['price']);                $objPHPExcel->getActiveSheet()->setCellValue('I' . ($i + 2), $lists[$i]['workerName']);                $objPHPExcel->getActiveSheet()->setCellValue('J' . ($i + 2), $lists[$i]['start']);                $objPHPExcel->getActiveSheet()->setCellValue('K' . ($i + 2), $lists[$i]['end']);                $objPHPExcel->getActiveSheet()->setCellValue('L' . ($i + 2), $lists[$i]['days']);                $objPHPExcel->getActiveSheet()->setCellValue('M' . ($i + 2), $lists[$i]['amount']);                $objPHPExcel->getActiveSheet()->setCellValue('N' . ($i + 2), $lists[$i]['service_money']);                $objPHPExcel->getActiveSheet()->setCellValue('O' . ($i + 2), $lists[$i]['status_text']);                $objPHPExcel->getActiveSheet()->setCellValue('P' . ($i + 2), $lists[$i]['create_time']);                $objPHPExcel->getActiveSheet()->setCellValue('Q' . ($i + 2), $lists[$i]['update_time']);            }            //设置保存的Excel表格名称            $filename = '订单列表' . date('YmdHis', time()) . '.xlsx';            //设置当前激活的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, 'Excel2007');            //下载文件在浏览器窗口            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);    }    /**     * 计算工期(不满一天按0.5天计算)     * @param string $startDate 开始时间(格式:Y-m-d H:i:s)     * @param string $endDate 结束时间(格式:Y-m-d H:i:s)     * @return float 计算后的天数     */    function getWorkerDay($startDate, $endDate)    {        // 将日期字符串转换为时间戳        $startTimestamp = strtotime($startDate);        $endTimestamp = strtotime($endDate);        // 计算时间差(秒)        $diffSeconds = $endTimestamp - $startTimestamp;        // 计算完整的天数        $fullDays = intval($diffSeconds / (24 * 3600)); // 完整的天数        $remainingSeconds = $diffSeconds % (24 * 3600); // 剩余的秒数        // 如果剩余时间大于0,则按0.5天计算        $partialDay = ($remainingSeconds > 0) ? 0.5 : 0;        $totalDays = $fullDays + $partialDay;        return $totalDays;    }    public function exportWord()    {        $id = input('id',0);        $orders = Db::name('ph_orders')            ->where('id',$id)            ->field('sign,sn,name,gender,age,contact,phone')            ->find();        $todos = Db::name('ph_todo')            ->where('order_id',$id)            ->whereIn('status',[1,2])            ->field('sign,worker_id')            ->select();        $protocol = Db::name("ph_protocol")->where('org_id',$this->orgId)->value('content');        $phpWord = new PhpWord();        $section = $phpWord->addSection();        Html::addHtml($section, $protocol);        $style = ['name' => '宋体', 'size' => 10.5];        $gender = $orders['gender'] == 1 ? '男' : '女';        $section->addText('甲方姓名:'.$orders['name'].'  性别:'.$gender.'  年龄:'.$orders['age'].'  联系人:'.$orders['contact'].'  电话:'.$orders['phone'],$style);        foreach ($todos as $todo){            $worker = Db::name('worker')                ->alias('a')                ->join('user b','a.user_id = b.id')                ->where('a.id',$todo['worker_id'])                ->field('a.gender,a.card,b.real_name,b.mobile')                ->find();            $gender = $worker['gender'] == 1 ? '男' : '女';            $age = $this->getAgeByIdCard($worker['card']);            $section->addText('乙方姓名:'.$worker['real_name'].'  性别:'.$gender.'  年龄:'.$age.'  电话:'.$worker['mobile'],$style);        }        $section->addText('丙方:'.getCompany($this->orgId),$style);        $section->addTextBreak(1);        $section->addText('客户签名:', ['name' => '宋体', 'size' => 26, 'bold' => true]);        if ($orders['sign']){            $section->addImage($orders['sign'], ['width' => 120, 'height' => 110]);        }        $section->addText('护工签名:', ['name' => '宋体', 'size' => 26, 'bold' => true]);        $table = $section->addTable();        $length = count($todos) > 4 ? ceil(count($todos) / 4) : 1;        for ($i = 0; $i < $length; $i++) {            $table->addRow(1, 4); // 添加1行4列            $imgs = array_slice($todos, $i * 4, 4);            foreach ($imgs as $v2) {                if ($v2['sign'] != '') {                    $cell = $table->addCell(1000); // 单元格宽度,单位为EMU                    $cell->addImage($v2['sign'], [                        'width' => 120,                        'height' => 110                    ]);                }            }        }        $objWriter = IOFactory::createWriter($phpWord, 'Word2007');        $fileName = '陪护协议-'.$orders['sn'].'.docx';        header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');        header('Content-Disposition: attachment;filename="'.$fileName);        header('Cache-Control: max-age=0');        $objWriter->save('php://output');        exit;    }    public function getAgeByIdCard($idCard) {        if (strlen($idCard) != 18) {            return '身份证号错误';        }        // 提取出生年月日        $birthDate = substr($idCard, 6, 8);        $birthYear = substr($birthDate, 0, 4);        $birthMonth = substr($birthDate, 4, 2);        $birthDay = substr($birthDate, 6, 2);        // 创建日期对象        $birthday = new \DateTime("$birthYear-$birthMonth-$birthDay");        $today = new \DateTime();        // 计算年龄        $age = $today->diff($birthday)->y;        return $age;    }}
 |