Project.php 11.7 KB
<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 项目管理
 *
 * @icon fa fa-circle-o
 */
class Project extends Backend
{

    /**
     * Project模型对象
     * @var \app\admin\model\Project
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Project;

        parent::_initialize();
        $this->Departmentmodel = new \app\admin\model\Department();

        $tree = Tree::instance();
        $tree->init(collection( $this->Departmentmodel->order('id asc')->select())->toArray(), 'pid');
        $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $categorydata = [0 => ['name' => __('None')]];
        foreach ($this->categorylist as $k => $v) {
            $categorydata[$v['id']] = $v;
        }

        $this->view->assign("parentList", $categorydata);

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage,则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['department','user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','project_name','all_working_hours','image','createtime','starttime','endtime']);
                $row->visible(['department']);
				$row->getRelation('department')->visible(['name']);
				$row->visible(['user']);
				$row->getRelation('user')->visible(['username']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function export()
    {
        if ($this->request->isPost()) {
            set_time_limit(0);
            $search = $this->request->post('search');
            $ids = $this->request->post('ids');
            $filter = $this->request->post('filter');
            $op = $this->request->post('op');
            $columns = $this->request->post('columns');

            $excel = new PHPExcel();

            $excel->getProperties()
                ->setCreator("FastAdmin")
                ->setLastModifiedBy("FastAdmin")
                ->setTitle("标题")
                ->setSubject("Subject");
            $excel->getDefaultStyle()->getFont()->setName('Microsoft Yahei');
            $excel->getDefaultStyle()->getFont()->setSize(12);

            $this->sharedStyle = new PHPExcel_Style();
            $this->sharedStyle->applyFromArray(
                array(
                    'fill'      => array(
                        'type'  => PHPExcel_Style_Fill::FILL_SOLID,
                        'color' => array('rgb' => '000000')
                    ),
                    'font'      => array(
                        'color' => array('rgb' => "000000"),
                    ),
                    'alignment' => array(
                        'vertical'   => PHPExcel_Style_Alignment::VERTICAL_CENTER,
                        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
                        'indent'     => 1
                    ),
                    'borders'   => array(
                        'allborders' => array('style' => PHPExcel_Style_Border::BORDER_THIN),
                    )
                ));

            $worksheet = $excel->setActiveSheetIndex(0);
            $worksheet->setTitle('标题');

            $whereIds = $ids == 'all' ? '1=1' : ['id' => ['in', explode(',', $ids)]];
            $this->request->get(['search' => $search, 'ids' => $ids, 'filter' => $filter, 'op' => $op]);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $line = 1;
            $list = [];
            $this->model
                ->field($columns)
                ->where($where)
                ->where($whereIds)
                ->chunk(100, function ($items) use (&$list, &$line, &$worksheet) {
                    $styleArray = array(
                        'font' => array(
                            'bold'  => true,
                            'color' => array('rgb' => 'FF0000'),
                            'size'  => 15,
                            'name'  => 'Verdana'
                        ));
                    $list = $items = collection($items)->toArray();
                    foreach ($items as $index => $item) {
                        $line++;
                        $col = 0;
                        foreach ($item as $field => $value) {

                            $worksheet->setCellValueByColumnAndRow($col, $line, $value);
                            $worksheet->getStyleByColumnAndRow($col, $line)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);
                            $worksheet->getCellByColumnAndRow($col, $line)->getStyle()->applyFromArray($styleArray);
                            $col++;
                        }
                    }
                });
            $first = array_keys($list[0]);
            foreach ($first as $index => $item) {
                $worksheet->setCellValueByColumnAndRow($index, 1, __($item));
            }

            $excel->createSheet();
            // Redirect output to a client’s web browser (Excel2007)
            $title = date("YmdHis");
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $title . '.xlsx"');
            header('Cache-Control: max-age=0');
            // If you're serving to IE 9, then the following may be needed
            header('Cache-Control: max-age=1');

            // If you're serving to IE over SSL, then the following may be needed
            header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
            header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
            header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
            header('Pragma: public'); // HTTP/1.0

            $objWriter = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
            $objWriter->save('php://output');
            return;
        }
    }


    public function downloadexcel($id){
        $workinghours=Db::name("workinghours")
            ->alias("a")
            ->join("user b","a.user_id=b.id")
            ->where("project_id",$id)
            ->select();
        $project=Db::name("project")->where("id",$id)->find();
        $file=$this->projectexcel($workinghours,$project);
    }

    /**
     *导出表
     */
    public function projectexcel($workinghours, $project)
    {
        vendor('phpoffice.phpexcel.PHPExcel');
        Vendor('phpoffice.phpexcel.Classes.PHPExcel');
        Vendor('phpoffice.phpexcel.Classes.PHPExcel.IOFactory.PHPExcel_IOFactory');
        //实例化
        $objExcel = new \PHPExcel();
        //设置文档属性
        $objWriter = \PHPExcel_IOFactory::createWriter($objExcel, 'Excel2007');
        //设置内容
        $objActSheet = $objExcel->getActiveSheet();
        $key = ord("A");
        $letter = explode(',', "A,B,C,D,E");
        $arrHeader = array('序号', '项目名称', '提交人', '工时', '提交时间');
        //填充表头信息
        $lenth = count($arrHeader);
        for ($i = 0; $i < $lenth; $i++) {
            $objActSheet->setCellValue("$letter[$i]1", "$arrHeader[$i]");
        };
        //填充表格信息
        foreach ($workinghours as $k => $v) {
            $j = $k + 1;
            $k += 2;
            $objActSheet->setCellValue('A' . $k, $j);
            $objActSheet->setCellValue('B' . $k, $project['project_name']);
            $objActSheet->setCellValue('C' . $k, $v['username']);
            $objActSheet->setCellValue('D' . $k, $v['working_hours']);
            $objActSheet->setCellValue('E' . $k, date("Y-m-d", $v['reporttime']));
        }
        $outfile = $project['project_name'] ."-". rand(10000, 99999) . ".xlsx";
        $objWriter->save('./datauploads/' . $outfile);

        $file = '../public/datauploads/' . $outfile; // 文件路径
        $filename = $outfile; // 下载时的文件名

        $objExcel->createSheet();
        // Redirect output to a client’s web browser (Excel2007)
        $title = date("YmdHis");
        header('Content-Disposition: attachment;filename="' . $outfile . '.xlsx"');
        $objWriter = \PHPExcel_IOFactory::createWriter($objExcel, 'Excel2007');
        $objWriter->save('php://output');
    }
    function download( $file_url , $new_name = '' ){
        $file_url='../public/datauploads/'.$file_url;
        if (!isset( $file_url )||trim( $file_url )== '' ){
            echo '500' ;
        }
        if (! file_exists ( $file_url )){ //检查文件是否存在
            echo '404' ;
        }
        $file_name = basename ( $file_url );
        $file_type = explode ( '.' , $file_url );
        $file_type = $file_type [ count ( $file_type )-1];
        $file_name =trim( $new_name == '' )? $file_name :urlencode( $new_name );
        $file_type = fopen ( $file_url , 'r' ); //打开文件
        //输入文件标签
        header( "Content-type: application/octet-stream" );
        header( "Accept-Ranges: bytes" );
        header( "Accept-Length: " . filesize ( $file_url ));
        header( "Content-Disposition: attachment; filename=" . $file_name );
        //输出文件内容
        echo fread ( $file_type , filesize ( $file_url ));
        fclose( $file_type );
    }
}