| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697 | <?phpnamespace app\admin\controller;use app\common\util\ExcelUtil;use think\Db;class Address extends Auth{    public function index(){        if(request()->isAjax()){            //分页参数            $length = input('rows',10,'intval');   //每页条数            $page = input('page',1,'intval');      //第几页            $start = ($page - 1) * $length;     //分页开始位置            //排序            $sortRow = input('sidx','id','trim');      //排序列            $sort = input('sord','desc','trim');        //排序方式            $order = $sortRow.' '.$sort;            $title = input('title','','trim');            if($title){                $map[] = ['title','like','%'.$title.'%'];            }            $enable = input('enable','','trim');            if($enable != ''){                $map[] = ['enable','=',$enable];            }            $type = input('type','','trim');            if($type != ''){                $map[]=['','exp',Db::raw("FIND_IN_SET($type,types)")];            }            $map[] = ['del','=',0];            $map[] = ['org_id','=',$this->orgId];            $map= empty($map) ? true: $map;            //数据查询            $lists = db('address')->where($map)->limit($start,$length)->order($order)->select();            foreach ($lists as $k=>$v){                $ts = $v['types']?explode(',',$v['types']):[];                $lists[$k]['types_text'] = '';                $filteredArray = array_diff($ts, [null, '']);                if(!empty($ts)){                    $lists[$k]['types_text'] = model('Address')->getTypeStr($filteredArray);                }            }            //数据返回            $totalCount = db('address')->where($map)->count();            $totalPage = ceil($totalCount/$length);            $result['page'] = $page;            $result['total'] = $totalPage;            $result['records'] = $totalCount;            $result['rows'] = $lists;            return json($result);        }else{            $types = model('Address')->getTypes();            $this->assign('types',$types);            return $this->fetch();        }    }    /**     * 新增/编辑     */    public function add($id=0){        if(request()->isPost()){            $res = model('Address')->updates();            if($res){                $this->success('操作成功',url('index'));            }else{                $this->error(model('Address')->getError());            }        }else{            if($id){                $info = db('address')->where('id',$id)->find();                if($info){                    $info['types'] = $info['types']?explode(',',$info['types']):[];                }                $this->assign('info',$info);            }            $ts = model('Address')->getTypes();            $types = [];            foreach ($ts as $k=>$v){                $types[] = [                    'id' => $k,                    'title' => $v                ];            }            $bjUserList = model('User')->getWorkTypeModeUser(2,$this->orgId,-1);            $ysUserList = model('User')->getWorkTypeModeUser(3,$this->orgId,-1);            $this->assign('bjUserList',$bjUserList);            $this->assign('ysUserList',$ysUserList);            $dep = model('dep')->getList();            $this->assign('dep',$dep);            $this->assign('types',$types);            return $this->fetch();        }    }    /**     * 删除记录     * @param int $id     */    public function del($id=0){        if(!$id){            $this->error('参数错误');        }        $res = db('address')->where('id',$id)->setField('del',1);        if($res){            $this->success('删除成功');        }else{            $this->error('删除失败');        }    }    /**     * 改变字段值     * @param int $fv     * @param string $fn     * @param int $fv     */    public function changeField($id=0,$fn='',$fv=0){        if(!$fn||!$id){            $this->error('参数错误');        }        $res = db('address')->where('id',$id)->setField($fn,$fv);        if($res){            $this->success('操作成功');        }else{            $this->error('操作失败');        }    }    public function qrcode($id=0){        $info = Db::name('address')->where('id',$id)->find();        $code = get_qrcode_str('address',$id);        //request()->domain().'/h5/repair/index?code='        $config = config('app.addr_url');        $code = $config.$code;        $this->assign('code',$code);        $this->assign('info',$info);        return $this->fetch();    }    // 地址下载    public function addrdown(){        $orgid = $this->orgId;        $map[] = ['del','=',0];        $map[] = ['org_id','=',$this->orgId];        $title = input('title','','trim');        if($title){            $map[] = ['title','like','%'.$title.'%'];        }        $enable = input('enable','','trim');        if($enable != ''){            $map[] = ['enable','=',$enable];        }        $type = input('type','','trim');        if($type != ''){            $map[]=['','exp',Db::raw("FIND_IN_SET($type,types)")];        }        $ids = input('ids','','trim');        if($ids !=''){            $map[] = ['id','in',explode(',',$ids)];        }        $map= empty($map) ? true: $map;        //数据查询        $lists = db('address')->where($map)->select();        $config = config('app.addr_url');        foreach ($lists as $k=>$v){            $lists[$k]['code'] = $config.get_qrcode_str('address',$v['id']);        }        $path = date('Ymd').'_'.$orgid.'_'.time().mt_rand(1000,9999);        $dir = './uploads/qrcodeimg/'.$path.'/';        foreach ($lists as $v1){            $name = str_ireplace('/','_',$v1['title']).'('.$v1['id'].')'.'.jpg';            $filepath = $dir.'/'.$name;            create_qrcode($v1['code'],$filepath);        }        $zippath = './uploads/qrcodeimg/'.$path.'.zip';        $spath = $dir;        @unlink($zippath);        $zip = new \ZipArchive();        if($zip->open($zippath, \ZipArchive::CREATE)=== TRUE){            add_file_to_zip($spath,$zip); //调用方法,对要打包的根目录进行操作,并将ZipArchive的对象传递给方法            $zip->close(); //关闭处理的zip文件            if(!file_exists($zippath)){                $this->error("打包失败"); //即使创建,仍有可能失败。。。。            }            deldir($dir); // 删除生成的目录            $downname = session('orgName').'地点二维码.zip';            header("Cache-Control: public");            header("Content-Description: File Transfer");            header('Content-disposition: attachment; filename='.$downname); //文件名            header("Content-Type: application/zip"); //zip格式的            header("Content-Transfer-Encoding: binary"); //告诉浏览器,这是二进制文件            header('Content-Length: '. filesize($zippath)); //告诉浏览器,文件大小            @readfile($zippath);        }else{            $this->error("打包失败");        }    }    public function import(){        return $this->fetch();    }    /**     * 下载点模板     */    public function downloadtem(){        set_time_limit(0);        ini_set("memory_limit","512M");        include_once env('root_path').'/extend/phpexcel/Classes/PHPExcel.php';        $fileName = '地点模板.xlsx';        $excel = new \PHPExcel();        $sheet = $excel->setActiveSheetIndex(0);        $arr = array('A','B','C','D');        $types = model('Address')->getTypes();        ksort($types);        foreach($arr as $k=>$v){            $excel->getActiveSheet()->getStyle($v)->getAlignment()->setWrapText(true);//换行            $excel->getActiveSheet()->getStyle($v.'1')->getFont()->setBold(true);            if($k==3){                $excel->getActiveSheet()->getColumnDimension($v)->setWidth(100);            }else{                $excel->getActiveSheet()->getColumnDimension($v)->setWidth(18);            }        }        $sheet->setCellValueByColumnAndRow(0,1,'名称');        $sheet->setCellValueByColumnAndRow(1,1,'设备编号');        $sheet->setCellValueByColumnAndRow(2,1,'备注');        $sheet->setCellValueByColumnAndRow(3,1,'类型('.implode(',',$types).') 多个用英文逗号隔开');        $excel->getActiveSheet()->setCellValue('A2', '示例地址');        $excel->getActiveSheet()->setCellValue('B2', 'XXX');        $excel->getActiveSheet()->setCellValue('C2', 'XXX');        $excel->getActiveSheet()->setCellValue('D2', '报修,运送');        ob_end_clean();//清除缓冲区,避免乱码        header('Content-Type: application/vnd.ms-excel');        header('Content-Disposition: attachment;filename="'.$fileName.'"');        header('Cache-Control: max-age=0');        $objWriter = \PHPExcel_IOFactory::createWriter($excel, 'Excel2007');        $objWriter->save('php://output'); //文件通过浏览器下载    }    /**     * 导入     */    public function importexcel_bak(){        set_time_limit(0);        ini_set("memory_limit", -1);        ob_flush();//清空缓存        flush();//刷新缓存        include_once env('root_path').'/extend/phpexcel/Classes/PHPExcel.php';        $orgId = $this->orgId;        if(request()->file()) {            $file = request()->file('file');            //获取文件后缀            $e = explode('.',$_FILES['file']['name']);            $ext = $e[count($e)-1];            if($ext == 'xls'){                \PHPExcel_IOFactory::createReader( 'Excel5');            }else{                \PHPExcel_IOFactory::createReader('Excel2007');            }            $newArr=['xls','xlsx'];            if(!in_array($ext,$newArr)){                exit('文件格式不正确');            }            // 移动到框架应用根目录/uploads/ 目录下            $info = $file->validate([ 'size'=>config('app.max_upload_file_size') ])                ->move(env('root_path') . 'public' . DIRECTORY_SEPARATOR . 'uploads'. DIRECTORY_SEPARATOR . 'files');            if(!$info){                exit('文件上传失败');            }            $img = './uploads/files/' . $info->getSaveName();            $filePath = str_replace('\\', '/', $img);            $newPath = \PHPExcel_IOFactory::load($filePath);            $excelArray = $newPath->getsheet(0)->toArray();   //转换为数组格式            array_shift($excelArray);  //删除第一个数组(标题);            unset($excelArray[0]);            if(empty($excelArray)){                exit('文件内容为空');            }            foreach ($excelArray as $k => $v) {                if(!$v[1]){                    echo "<font color=\"red\" style='margin-left: 20px;font-size: 17px'>第".($k+1)."行,名称为空,未导入</font><br />";                    continue;                }                if(!$v[4]){                    echo "<font color=\"red\" style='margin-left: 20px;font-size: 17px'>第".($k+1)."行,类型为空,未导入</font><br />";                    continue;                }                $check = Db::name('address')                    ->where('org_id',$orgId)                    ->where('del',0)                    ->where('title',$v[1])                    ->find();                if($check){                    echo "<font color=\"red\" style='margin-left: 20px;font-size: 17px'>第".($k+1)."行,名称已存在,未导入</font><br />";                    continue;                }                $typeId = [];                $type = explode(',',$v[4]);                $types = model('Address')->getTypes();                $types =  array_flip($types);                foreach ($type as $k1=>$v1){                    if(isset($types[$v1])){                        $typeId[] = $types[$v1];                    }                }                if(count($type)!=count($typeId) || empty($typeId)){                    echo "<font color=\"red\" style='margin-left: 20px;font-size: 17px'>第".($k+1)."行,类型字段格式错误,未导入</font><br />";                    continue;                }                $rData = [                    'org_id'=>$orgId,                    'title'=>$v[1],                    'sn'=>$v[0],                    'remark'=>'',                    'types'=>implode(',',$typeId),                    'create_time'=>getTime()                ];                $ret=Db::name('address')->insert($rData);                if(!$ret){                    echo "<font color=\"red\" style='margin-left: 20px;font-size: 17px'>第".($k+1)."行,导入失败</font><br />";                }else{                    echo "<font color=\"green\" style='margin-left:20px;font-size: 17px'>第".($k+1)."行,导入成功</font><br />";                }            }        }else{            exit('请上传文件');        }    }    public function importexcel(){        set_time_limit(0);        ini_set("memory_limit", -1);        ob_flush();//清空缓存        flush();//刷新缓存        include_once env('root_path').'/extend/phpexcel/Classes/PHPExcel.php';        $orgId = $this->orgId;        if(request()->file()) {            $file = request()->file('file');            //获取文件后缀            $e = explode('.',$_FILES['file']['name']);            $ext = $e[count($e)-1];            if($ext == 'xls'){                \PHPExcel_IOFactory::createReader( 'Excel5');            }else{                \PHPExcel_IOFactory::createReader('Excel2007');            }            $newArr=['xls','xlsx'];            if(!in_array($ext,$newArr)){                exit('文件格式不正确');            }            // 移动到框架应用根目录/uploads/ 目录下            $info = $file->validate([ 'size'=>config('app.max_upload_file_size') ])                ->move(env('root_path') . 'public' . DIRECTORY_SEPARATOR . 'uploads'. DIRECTORY_SEPARATOR . 'files');            if(!$info){                exit('文件上传失败');            }            $img = './uploads/files/' . $info->getSaveName();            $filePath = str_replace('\\', '/', $img);            $newPath = \PHPExcel_IOFactory::load($filePath);            $excelArray = $newPath->getsheet(0)->toArray();   //转换为数组格式            array_shift($excelArray);  //删除第一个数组(标题);            if(empty($excelArray)){                exit('文件内容为空');            }            foreach ($excelArray as $k => $v) {                if(!$v[0]){                    echo "<font color=\"red\" style='margin-left: 20px;font-size: 17px'>第".($k+1)."行,名称为空,未导入</font><br />";                    continue;                }                if(!$v[3]){                    echo "<font color=\"red\" style='margin-left: 20px;font-size: 17px'>第".($k+1)."行,类型为空,未导入</font><br />";                    continue;                }                $check = Db::name('address')                    ->where('org_id',$orgId)                    ->where('del',0)                    ->where('title',$v[0])                    ->find();                if($check){                    echo "<font color=\"red\" style='margin-left: 20px;font-size: 17px'>第".($k+1)."行,名称已存在,未导入</font><br />";                    continue;                }                $typeId = [];                $type = explode(',',$v[3]);                $types = model('Address')->getTypes();                $types =  array_flip($types);                foreach ($type as $k1=>$v1){                    if(isset($types[$v1])){                        $typeId[] = $types[$v1];                    }                }                if(count($type)!=count($typeId) || empty($typeId)){                    echo "<font color=\"red\" style='margin-left: 20px;font-size: 17px'>第".($k+1)."行,类型字段格式错误,未导入</font><br />";                    continue;                }                $rData = [                    'org_id'=>$orgId,                    'title'=>$v[0],                    'sn'=>$v[1],                    'remark'=>$v[2],                    'types'=>implode(',',$typeId),                    'create_time'=>getTime()                ];                $ret=Db::name('address')->insert($rData);                if(!$ret){                    echo "<font color=\"red\" style='margin-left: 20px;font-size: 17px'>第".($k+1)."行,导入失败</font><br />";                }else{                    echo "<font color=\"green\" style='margin-left:20px;font-size: 17px'>第".($k+1)."行,导入成功</font><br />";                }            }        }else{            exit('请上传文件');        }    }    public function three($id=0){        if(request()->isPost()){            $id = input('id/d',0);            $x = input('x','','trim');            $y = input('y','','trim');            $z = input('z','','trim');            $xyz[] = $x;            $xyz[] = $y;            $xyz[] = $z;            $ret = Db::name('address')->where('id',$id)->update(['xyz'=>implode(',',$xyz),'update_time' => date('Y-m-d H:i:s')]);            if($ret){                $this->success('操作成功');            }else{                $this->error('操作失败');            }        }else{            $info = Db::name('address')->where('id',$id)->find();            $arr = $info['xyz']?explode(',',$info['xyz']):[];            $x = '';            $y = '';            $z = '';            if(count($arr) == 3){                $x = $arr[0];                $y = $arr[1];                $z = $arr[2];            }            $this->assign('x',$x);            $this->assign('y',$y);            $this->assign('z',$z);            $this->assign('id',$id);            return $this->fetch();        }    }    public function downImg(){        $id = input('id','');        $config = config('app.addr_url');        $code = $config.get_qrcode_str('address',$id);        $info = db('address')->where('id',$id)->find();        echo "<pre/>";        print_r($code);        die();    }    public function batchEditCate(){        $ids = input('ids','');        if(request()->isPost()){            if(empty($ids)){                $this->error('请选择地点');            }            $types = input('types');            if(empty($types)){                $this->error('请选择选择类型');            }            $res = Db::name('address')            ->where('id','in',explode(',',$ids))            ->update([                'types'=>$types,                'update_time'=>getTime()            ]);            if($res){                $this->success('操作成功',url('index'));            }else{                $this->error(model('Address')->getError());            }        }else{            $ts = model('Address')->getTypes();            $types = [];            foreach ($ts as $k=>$v){                $types[] = [                    'id' => $k,                    'title' => $v                ];            }            $this->assign('types',$types);            $address =db('address')->where('id','in',explode(',',$ids))->column('title');            $this->assign('address',implode(';',$address));            $this->assign('ids',$ids);            return $this->fetch();        }    }    public function importexcel1(){        set_time_limit(0);        ini_set("memory_limit", -1);        ob_flush();//清空缓存        flush();//刷新缓存        include_once env('root_path').'/extend/phpexcel/Classes/PHPExcel.php';        $orgId = $this->orgId;        if(request()->file()) {            $file = request()->file('file');            //获取文件后缀            $e = explode('.',$_FILES['file']['name']);            $ext = $e[count($e)-1];            if($ext == 'xls'){                \PHPExcel_IOFactory::createReader( 'Excel5');            }else{                \PHPExcel_IOFactory::createReader('Excel2007');            }            $newArr=['xls','xlsx'];            if(!in_array($ext,$newArr)){                exit('文件格式不正确');            }            // 移动到框架应用根目录/uploads/ 目录下            $info = $file->validate([ 'size'=>config('app.max_upload_file_size') ])                ->move(env('root_path') . 'public' . DIRECTORY_SEPARATOR . 'uploads'. DIRECTORY_SEPARATOR . 'files');            if(!$info){                exit('文件上传失败');            }            $img = './uploads/files/' . $info->getSaveName();            $filePath = str_replace('\\', '/', $img);            $newPath = \PHPExcel_IOFactory::load($filePath);            $excelArray = $newPath->getsheet(0)->toArray();   //转换为数组格式            array_shift($excelArray);  //删除第一个数组(标题);            if(empty($excelArray)){                exit('文件内容为空');            }            foreach ($excelArray as $k => $v) {                if($k > 0){                    if(!$v[1]){                        echo "<font color=\"red\" style='margin-left: 20px;font-size: 17px'>第".($k+1)."行,名称为空,未导入</font><br />";                        continue;                    }//                    if(!$v[4]){//                        echo "<font color=\"red\" style='margin-left: 20px;font-size: 17px'>第".($k+1)."行,类型为空,未导入</font><br />";//                        continue;//                    }                    $check = Db::name('address')                        ->where('org_id',$orgId)                        ->where('del',0)                        ->where('title',$v[1])                        ->find();                    if($check){                        echo "<font color=\"red\" style='margin-left: 20px;font-size: 17px'>第".($k+1)."行,名称已存在,未导入</font><br />";                        continue;                    }                    $typeId = [];                    if($v[4]){                        $type = explode('、',$v[4]);                        $types = model('Address')->getTypes();                        $types =  array_flip($types);                        foreach ($type as $k1=>$v1){                            if(isset($types[$v1])){                                $typeId[] = $types[$v1];                            }                        }//                        if(count($type)!=count($typeId) || empty($typeId)){//                            echo "<font color=\"red\" style='margin-left: 20px;font-size: 17px'>第".($k+1)."行,类型字段格式错误,未导入</font><br />";//                            continue;//                        }                    }                    $rData = [                        'org_id'=>$orgId,                        'title'=>$v[1],                        'sn'=>'',                        'remark'=>'',                        'types'=>$typeId?implode(',',$typeId):'',                        'create_time'=>getTime()                    ];                    $ret=Db::name('address')->insert($rData);                    if(!$ret){                        echo "<font color=\"red\" style='margin-left: 20px;font-size: 17px'>第".($k+1)."行,导入失败</font><br />";                    }else{                        echo "<font color=\"green\" style='margin-left:20px;font-size: 17px'>第".($k+1)."行,导入成功</font><br />";                    }                }                }        }else{            exit('请上传文件');        }    }    //excel导出    public function export() {        set_time_limit(0);        ini_set("memory_limit","1024M");        $title = input('title','','trim');        if($title){            $map[] = ['title','like','%'.$title.'%'];        }        $enable = input('enable','','trim');        if($enable != ''){            $map[] = ['enable','=',$enable];        }        $type = input('type','','trim');        if($type != ''){            $map[]=['','exp',Db::raw("FIND_IN_SET($type,types)")];        }        $map[] = ['del','=',0];        $map[] = ['org_id','=',$this->orgId];        $map= empty($map) ? true: $map;        //数据查询        $lists = db('address')->where($map)->order('id desc')->select();        $header = [            ['title' => 'id', 'name' => 'id','width'=>'10'],            ['title' => '名称', 'name' => 'title','width'=>'20'],        ];        $filename = '地点';        ExcelUtil::export($filename,$header,$lists);    }    public function delAll(){        if(request()->isPost()){            $data = request()->post();            $ids = isset($data['ids'])&&!empty($data['ids']) ? $data['ids']:[];            if(!$ids){                $this->error('请选择地点');            }            $res = Db::name('address')->whereIn('id',$ids)->setField('del',1);            if($res){                $this->success('操作成功',url('index'));            }else{                $this->error('操作失败');            }        }else{            $lists = Db::name('address')                ->where('del',0)                ->where('org_id',$this->orgId)                ->select();            $this->assign('lists',$lists);            return $this->fetch();        }    }}
 |