ExportUserDataListController.class.php 8.64 KB
<?php
/**
 * Created by PhpStorm.
 * User: liyifei2012it
 * Date: 17/10/12
 * Time: 20:57
 */

namespace Frontend\Controller\Callback;

use Com\PythonExcel;
use Common\Common\Constant;
use Common\Common\ExportDownload;
use Common\Common\User;
use Common\Common\ExamHelper;
use Common\Common\CourseHelper;
use Common\Model\CourseArticleModel;
use Common\Model\CourseCompleteModel;
use Common\Model\CourseStudyTimeModel;
use Org\Net\PHPZip;
use Think\Log;

class ExportUserDataListController extends AbstractController
{
    /**
     * ExportUserDataList
     * @author liyifei
     * @desc 导出员工数据总览
     * @param String dp_ids 组织ID(多个值时,以英文逗号分隔)
     * @param String role_ids 角色ID(多个值时,以英文逗号分隔)
     * @param String job_ids 岗位ID(多个值时,以英文逗号分隔)
     * @param String username 姓名
     * @return bool
     */
    public function Index()
    {

        // 验证请求数据
        $postData = $this->callBackData;

        Log::write('=========员工数据总览列表=====文件ID==' . $postData['id'], 'ERR', '', C('LOG_PATH') . date('y_m_d') . '.txt');
        Log::write('=========员工数据总览列表=====参数==' . print_r($postData, true), 'ERR', '', C('LOG_PATH') . date('y_m_d') . '.txt');

        // 组合搜索条件
        $conds = [];
        if (isset($postData['dp_ids'])) {
            $conds['dpIdList'] = $postData['dp_ids'];
            // 按部门条件查询时,表示部门是否递归查询人员 【0:不递归(默认值)、1:递归】
            $conds['departmentChildrenFlag'] = 1;
        }
        if (isset($postData['role_ids'])) {
            $conds['roleIdList'] = $postData['role_ids'];
        }
        if (isset($postData['job_ids'])) {
            $conds['jobIdList'] = $postData['job_ids'];
        }
        if (isset($postData['username'])) {
            $conds['memUsername'] = $postData['username'];
        }

        // 分页,导出数据限制到1000
        $limit = 1000;

        // 获取符合条件的人员UID
        $rows = [];
        $userServ = &User::instance();
        $userList = $userServ->listByConds($conds, $postData['page'], $limit);
        $userList = $userList['list'];

        if (!empty($userList)) {
            $uids = array_column($userList, 'memUid');

            // 调用西安代军完成考试、调研、培训数据方法
            $examHelper = &ExamHelper::instance();
            $examList = $examHelper->list_exam_train_questionnaire_data($userList);

            // 查询常规课程id集合
            $course_article = new CourseArticleModel();
            $course_article_list = $course_article->list_by_conds(['course_type' => 1], null, [], 'article_id,data_id,article_type');
            $articles = array_column($course_article_list, 'article_id');

            // 课程已完成数据
            $completeModel = new CourseCompleteModel();
            $completeList = $completeModel->completeTotalByUids($uids, $articles);
            if (!empty($completeList)) {
                $completeList = array_combine_by_key($completeList, 'uid');
            }

            // 课程学习时长
            $studyTimeModel = new CourseStudyTimeModel();
            $studyTimeList = $studyTimeModel->listStudyTimeByUids($uids, $articles);
            if (!empty($studyTimeList)) {
                $studyTimeList = array_combine_by_key($studyTimeList, 'uid');
            }

            // 可完成课程
            $courseHelper = &CourseHelper::instance();
            $userArticleIds = $courseHelper->articleCountByUsers($userList, $articles);

            foreach ($userList as $user) {
                $uid = $user['memUid'];

                // 组织
                $dpNames = !empty($user['dpName']) ? implode(',', array_column($user['dpName'], 'dpName')) : '';

                // TODO liyifei 用户可完成课程数(逻辑是否可优化)
                $articleIds = $userArticleIds[$user['memUid']];

                // 课程完成率
                $completeTotal = isset($completeList[$uid]['total']) ? (int)$completeList[$uid]['total'] : 0;
                $courseTotal = count($articleIds);
                $completeRate = $courseTotal == 0 ? '0%' : round($completeTotal / $courseTotal * 100, 2) . '%';

                // 学习时长
                $studyTime = isset($studyTimeList[$uid]['study_time']) ? (int)$studyTimeList[$uid]['study_time'] : 0;
                $studyTime = $this->secToTime($studyTime);

                // 考试及格率
                $examPassTotal = isset($examList[$uid]['exam_pass_total']) ? $examList[$uid]['exam_pass_total'] : 0;
                $examTotal = isset($examList[$uid]['exam_total']) ? $examList[$uid]['exam_total'] : 0;
                $examRate = $examTotal == 0 ? '0%' : round($examPassTotal / $examTotal * 100, 2) . '%';

                // 参与调研数
                $questionnaireTotal = isset($examList[$uid]['questionnaire_total']) ? $examList[$uid]['questionnaire_total'] : 0;

                // 参与培训次数
                $trainTotal = isset($examList[$uid]['train_total']) ? $examList[$uid]['train_total'] : 0;

                // Excel列数据
                $rows[] = [
                    $user['memUsername'],
                    $dpNames,
                    $user['memJob'],
                    $user['memRole'],
                    $completeTotal . '/' . $courseTotal,
                    $completeRate,
                    $studyTime,
                    $examPassTotal . '/' . $examTotal,
                    $examRate,
                    $questionnaireTotal,
                    $trainTotal,
                ];
            }
        }

        Log::write('=========员工数据总览数据列表=====生成文件数据==' . print_r($rows, true), 'ERR', '', C('LOG_PATH') . date('y_m_d') . '.txt');


        if (empty($rows)) {


            Log::write('=========员工数据总览生成完成=====文件ID==' . $postData['id'], 'ERR', '', C('LOG_PATH') . date('y_m_d') . '.txt');
            // 获取需要打包的目录
            $dir_tmp = ExportDownload::get_down_dir($postData['user_id'] . $postData['time'] . D_S . $postData['time'] . $postData['id'] . $postData['user_id']);

            $phpzip = new PHPZip();

            // 组装压缩文件名称
            $filename = ExportDownload::get_down_dir($postData['user_id'] . 'D' . microtime(true)) . microtime(true) . '.zip';

            // 打包文件
            $phpzip->zipDir($dir_tmp, $filename, false);

            // 更新状态
            $data = [
                'url' => $dir_tmp,
                'id' => $postData['id'],
                'size' => filesize($filename)
            ];

            ExportDownload::update_down_load($data);

            unlink($filename);

            return false;
        }

        // Excel首行标题
        $titles = ['员工姓名', '组织', '岗位', '角色', '课程完成数', '课程完成率', '课程学习时长', '考试及格数', '考试及格率', '参与调研数', '参与培训次数'];

        // 生成 Excel 并输出
        $realpath = ExportDownload::get_down_dir($postData['user_id'] . $postData['time'] . D_S . $postData['time'] . $postData['id'] . $postData['user_id']) . $postData['page'] . '.xls';
        PythonExcel::instance()->write($realpath, $titles, $rows);

        $params = [
            'user_id' => $postData['user_id'],
            'time' => $postData['time'],
            'id' => $postData['id'],
            'username' => $postData['username'],
            'dp_ids' => $postData['dp_ids'],
            'role_ids' => $postData['role_ids'],
            'job_ids' => $postData['job_ids'],
            'page' => intval($postData['page']) + 1
        ];

        $url = oaUrl('Frontend/Callback/ExportUserDataList');

        // 生成定时任务
        ExportDownload::set_Cron($params, $url, '员工数据总览_批量下载', 'USER_DATA_DOWN_Excel_' . $postData['id']);

        return true;
    }

    /**
     * 把秒数转换为时分秒的格式
     * @author liyifei
     * @param Int $times 时间,单位 秒
     * @return String
     */
    private function secToTime($times)
    {
        $result = '';

        if ($times > 0) {
            $hour = floor($times / 3600);
            $minute = floor(($times - 3600 * $hour) / 60);
            $second = floor((($times - 3600 * $hour) - 60 * $minute) % 60);
            if ($hour > 0) {
                $result .= "{$hour}时";
            }
            if ($minute > 0) {
                $result .= "{$minute}分";
            }
            if ($second > 0) {
                $result .= "{$second}秒";
            }
        }

        return empty($result) ? 0 : $result;
    }
}