Department.php 9.9 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 Department extends Backend
{

    /**
     * Depart模型对象
     * @var \app\admin\model\Depart
     */
    protected $model = null;
    protected $noNeedRight = ['tree'];

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

        $tree = Tree::instance();
        $tree->init(collection($this->model->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);
    }

    public function tree()
    {
        $id = $this->request->get('id');
        $departModel = new \app\admin\model\Department();
        $departList = $departModel->where(['pid' => ($id == '#' ? 0 : $id)])->select();

        $chanelList = [];
        if ($id == '#') {
            $text = "全部";
            $chanelList[-1] = ['id' => -1, 'type' => 'total', 'text' => $text, 'parent' => "#"];
        }

        foreach ($departList as $k => $v) {
            $departModel = new \app\admin\model\Department();
            if ($departModel->where(['pid' => $v->id])->find()) {
                $children = true;
            } else {
                $children = false;
            }

            $chanelList[$v->id] = ['id' => $v->id, 'text' => $v->name, 'type' => "folder", 'children' => $children, 'parent' => empty($v->pid) ? "#" : $v->pid, 'state' => ['opened' => false]];
        }

        $chanelList = array_values($chanelList);

        return json($chanelList);
    }


    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $search = $this->request->request("search");
            $type = $this->request->request("type");

            //构造父类select列表选项数据
            $list = [];

            foreach ($this->categorylist as $k => $v) {
                if ($search) {
                    if ($v['type'] == $type && stripos($v['name'], $search) !== false || stripos($v['nickname'], $search) !== false) {
                        if ($type == "all" || $type == null) {
                            $list = $this->categorylist;
                        } else {
                            $list[] = $v;
                        }
                    }
                } else {
                    if ($type == "all" || $type == null) {
                        $list = $this->categorylist;
                    } elseif ($v['type'] == $type) {
                        $list[] = $v;
                    }
                }
            }
            $total = count($list);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($params['pid'] != $row['pid']) {
                    $childrenIds = Tree::instance()->init(collection(\app\admin\model\Department::select())->toArray())->getChildrenIds($row['id'], true);
                    if (in_array($params['pid'], $childrenIds)) {
                        $this->error(__('上级部门不能是它的子部门或它自己'));
                    }
                }

                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    //根据部门id获取所有子部门
    public function getDepartIdById($id = 6)
    {
        $array = Db::name('department')->select();
        //第一步 构造数据
        $items = array();
        foreach ($array as $value) {
            $items[$value['id']] = $value;
        }
        //第二部 遍历数据 生成树状结构
        $tree = array();
        foreach ($items as $key => $value) {
            if (isset($items[$value['pid']])) {
                $items[$value['pid']]['son'][] = &$items[$key];
            } else {
                $tree[] = &$items[$key];
            }
        }
        return $tree;
    }


//递归获取所有的子分类的ID
    function get_all_child($id = 6, $array = [])
    {

        $arr = array();
        if (!$array) {
            $array = Db::name('department')->select();
            $arr[] = (int)$id;
        }


        foreach ($array as $v) {
            if ($v['pid'] == $id) {
                $arr[] = $v['id'];
                $arr = array_merge($arr, $this->get_all_child($v['id'], $array));
            };
        };
        return $arr;
    }

    public function send($openid, $name, $code)
    {
        $data = [
            'first' => ['value' => '水库警告', 'color' => '#000000'],
            'keyword1' => ['value' => $name, 'color' => '#000000'],
            'keyword2' => ['value' => date('Y-m-d H:i', time()), 'color' => '#000000'],
            'keyword3' => ['value' => '水位超过预警!', 'color' => '#000000'],
            'remark' => ['value' => '设备监测到水位超过预警值,请及时处理', 'color' => '#000000'],
        ];
        $template_id = '001';
        $uri = 'https://www.ynzhsk.cn/index/index/updateWxtemplate?code=' . $code . '&openid=' . $openid;
        $text = \addons\weixin\library\WechatTemplateService::sendTemplateOrApp($openid, $template_id, $data, $uri);
        return $text;
    }

    /**
     * 根据部门id查询自己及其子级有水库ids
     */
    public function getSKIds()
    {
        $param = $this->request->param();
        $arr = [];
        if (!empty($param['depart_id'])) {
            $arr = get_all_next_depart_ids($param['depart_id']);
        }
        $this->success('', null, implode(",", $arr));
    }

    public function downloadexcel($id)
    {
        $department = Db::name("department")->where('id', $id)->find();
        $workinghours=Db::name("workinghours")
            ->alias("a")
            ->join("user b","a.user_id=b.id")
            ->join("project c","a.project_id=c.id")
            ->where("a.department_id",$id)
            ->field("project_name,working_hours,reporttime,username")
            ->select();
        $file=$this->projectexcel($workinghours,$department);

    }
    /**
     *导出表
     */
    public function projectexcel($workinghours, $department)
    {
        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,F");
        $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, $department['name'])->getDefaultColumnDimension()->setWidth(20);
            $objActSheet->setCellValue('C' . $k, $v['project_name']);
            $objActSheet->setCellValue('D' . $k, $v['username']);
            $objActSheet->setCellValue('E' . $k, $v['working_hours']);
            $objActSheet->setCellValue('F' . $k, date("Y-m-d", $v['reporttime']));
        }
        $outfile = $department['name'] ."-". rand(10000, 99999) . ".xlsx";
        $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');
    }
}