ImportController.class.php 12.8 KB
<?php
/**
 * 圆圈付费 -解析人员导入模板
 * @author: 蔡建华
 */

namespace Apicp\Controller\ImportUser;

use Com\Cache;
use Com\PythonExcel;
use Common\Common\User;


class ImportController extends AbstractController
{

    const MAX_ROWS = 800; // 最多允许上传800条数据


    protected $_require_login = false;

    /**
     * Import
     *
     * @author 蔡建华
     * @desc 解析公共导人模板
     *
     * @param file file:true xls文件
     * @param string cache_sign 缓存标识
     *
     * @return array|bool
     * array(
     * 'error_count' => 3, // 错误条数
     * 'cache_sign' => '', // 缓存标识
     * 'user_list'=> array(  //
     * array(
     * 'memUsername' => '张三', // 用户姓名
     * 'memMobile' => '15629876789', // 用户手机
     * 'memEmail' => 'juxinggaozhao@163.com', //邮箱
     * 'memUid' => '', // 用户uid
     * 'memFace' => '', // 用户头像
     * )
     * )
     * )
     */
    public function Index_post()
    {
        // 获取上传文件详情
        $file = $_FILES['file'];

        // 缓存标识 上传毫秒级
        $cache_sign = I('post.cache_sign');

        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

        if (!$this->xls_validation($_FILES)) {
            // 验证文件基本信息
            return false;
        }
        if (!in_array($ext, array('csv', 'xls', 'xlsx'))) // xls文件名称
        {
            E('_ERR_FILE_EXT');
        }
        $filename = $file['tmp_name'];
        switch ($ext) {
            case 'xls':
            case 'xlsx':
                $data = PythonExcel::instance()->read($filename, 0, 0, 0, '2003');
                break;
            case 'csv':
                Vendor('PHPExcel.PHPExcel');
                setlocale(LC_ALL, 'zh_CN');
                $inputFileType = \PHPExcel_IOFactory::identify($filename);
                $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
                $objReader->setInputEncoding('GBK');
                $objPHPExcel = $objReader->load($filename);
                $sheet = $objPHPExcel->getSheet(0);
                $rows =array();
                foreach ($sheet->getRowIterator() as $key=>$row) {
                    //遍历行
                    $cellIterator = $row->getCellIterator();   //得到所有列
                    $cellIterator->setIterateOnlyExistingCells( false);
                    $cellvalue = array();
                    foreach ($cellIterator as $cell) {  //遍历列
                        if (!is_null($cell)) {
                            //如果列不给空就得到它的坐标和计算的值
                            $cellvalue[]=   $cell->getCalculatedValue();
                        }
                    }
                    $rows[] = $cellvalue;
                }
                $data = $rows;
        }
        $list = [];
        $error_list = [];
        if (count($data) > (self::MAX_ROWS + 1)) {
            // 超过最大允许上传数量
            E('_ERR_MAX_ROWS');
        } else {
            // 获取数据列表
            list($list, $error_list) = $this->get_excel_list($data);
        }

        if (empty($list) && empty($error_list)) {
            // 有效数据为空
            E('_EMPTY_XLS_DATA');
        }
        $user_list = [];

        $user = User::instance();
        $condition = array();
        $names = array_filter(array_column($list, 'username'), function ($v) {
            $value = trim($v);
            if (!empty($value)) {
                return $value;
            }
        });
        if (!empty($names)) {
            $condition['names'] = $names;
        }
        $mobiles = array_filter(array_column($list, 'mobile'), function ($v) {
            $value = trim($v);
            if (!empty($value)) {
                return $value;
            }
        });
        if (!empty($mobiles)) {
            $condition['mobiles'] = $mobiles;
        }
        $emails = array_filter(array_column($list, 'email'), function ($v) {
            $value = trim($v);
            if (!empty($value)) {
                return $value;
            }
        });

        if (!empty($emails)) {
            $condition['emails'] = $emails;
        }

        $user_all = array();
        if (!empty($condition)) {
            $user_all = $user->list_import_user($condition);
        }


        $tmp_mobile = array_column($user_all['list'], null, 'mobile');
        $tmp_email = array_column($user_all['list'], null, 'email');
        $tmp_username = array_column($user_all['list'], null, 'name');
        foreach ($list as $k => $v) {
            $user_info = array();
            $error = '';
            if (!empty($v['mobile']) && empty($v['email']) && empty($v['username'])) {
                // 根据手机号查询
                if (!array_key_exists($v['mobile'], $tmp_mobile)) {
                    $error = '此用户不存在';
                } else {
                    $user_info = $tmp_mobile[$v['mobile']];
                }
            } else {
                // 根据邮箱判断
                if (empty($v['mobile']) && !empty($v['email']) && empty($v['username'])) {
                    if (!array_key_exists($v['email'], $tmp_email)) {
                        $error = '此用户不存在';
                    } else {
                        $user_info = $tmp_email[$v['email']];
                    }
                } else {
                    // 根据姓名判断
                    if (empty($v['mobile']) && empty($v['email']) && !empty($v['username'])) {
                        if (!array_key_exists($v['username'], $tmp_username)) {
                            $error = '此用户不存在';
                        } else {
                            $user_info = $tmp_username[$v['username']];
                        }
                    } else {
                        if (!empty($v['mobile']) && !empty($v['email']) && empty($v['username'])) {
                            if (!array_key_exists($v['mobile'], $tmp_mobile)) {
                                $error = '此用户不存在';
                            } else {
                                $user_info = $tmp_mobile[$v['mobile']];
                            }
                            if ($user_info['email'] != $v['email']) {
                                $error = '手机号和邮箱不匹配';
                                $user_info = [];
                            }
                        } else {
                            if (!empty($v['mobile']) && empty($v['email']) && !empty($v['username'])) {
                                // 根据手机号和姓名查询
                                if (!array_key_exists($v['mobile'], $tmp_mobile)) {
                                    $error = '此用户不存在';
                                } else {
                                    $user_info = $tmp_mobile[$v['mobile']];
                                }

                                if ($user_info['name'] != $v['username']) {
                                    $error = '手机号和用户名不匹配';
                                    $user_info = [];
                                }
                            } else {
                                if (empty($v['mobile']) && !empty($v['email']) && !empty($v['username'])) {
                                    // 根据邮箱和姓名查询
                                    if (!array_key_exists($v['email'], $tmp_email)) {
                                        $error = '此用户不存在';
                                    } else {
                                        $user_info = $tmp_email[$v['email']];
                                    }
                                    if ($user_info['name'] != $v['username']) {
                                        $error = '用户名和邮箱不匹配';
                                        $user_info = array();
                                    }
                                } else {
                                    if (!empty($v['mobile']) && !empty($v['email']) && !empty($v['username'])) {
                                        if (!array_key_exists($v['mobile'], $tmp_mobile)) {
                                            $error = '此用户不存在';
                                        } else {
                                            $user_info = $tmp_mobile[$v['mobile']];
                                        }
                                        if ($user_info['name'] != $v['username'] || $user_info['email'] != $v['email']) {
                                            $error = '手机号,邮箱和姓名不匹配';
                                            $user_info = array();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (empty($user_info)) {
                $error_list[$k] = [
                    'username' => $v['username'],
                    'memEmail' => $v['email'],
                    'mobile' => (string)$v['mobile'],
                    'error' => trim($error, ',')
                ];
            } else {
                $user_list[] = [
                    'memUsername' => $user_info['name'],
                    'memMobile' => $user_info['mobile'],
                    'memEmail' => $user_info['email'],
                    'memUid' => $user_info['id'],
                    'memFace' => $user_info['faceUrl'],
                ];
            }
        }

        $cache =& Cache::instance();
        if (!empty($error_list) && empty($cache_sign)) {
            $cache_sign = NOW_TIME . rand(1, 999);
            $cache->set('Common.Import_User_' . $cache_sign, $error_list);
        } elseif (!empty($cache_sign) && !empty($user_list)) {
            $cache->set('Common.Import_User_' . $cache_sign, $error_list);
        }
        $this->_result = [
            'error_count' => count($error_list), // 错误数量
            'user_list' => $user_list, // 用户列表
            'cache_sign' => $cache_sign // 错误缓存标识
        ];
        return true;
    }

    /**
     * 验证数据
     *
     * @param array $file POST数据
     *
     * @return bool
     */
    protected function xls_validation($file = [])
    {
        // 请上传文件
        if (empty($file)) {

            E('_ERR_FILE_UNDEFINED');
        }

        // 文件上传失败
        if ($file['error'] > 0) {

            E('_ERR_UPLOAD_FILE');
        }

        // 文件大小判断(2M以内)
        if ($file['size'] > 1024 * 2 * 1024) {

            E('_ERR_FILE_SIZE');
        }

        return true;
    }

    /**
     * 获取head数据列表以及整合过的xls中数据列表
     *
     * @author houyingcai
     *
     * @param array $list xls数据列表
     *
     * @return array
     */

    protected function get_excel_list($list = [])
    {
        $data = [];
        $error_list = [];

        // 循环数据
        foreach ($list as $k => $v) {
            if ($k == 0) {
                // 去掉标题栏
                continue;
            }
            $error = '';
            if ($k == 1) {
                if (trim($v[0]) != '姓名' || trim($v[1]) != '手机号' || trim($v[2]) != '邮箱') {
                    // 错误的模板格式
                    E('_ERR_XLS_TEMPLATE');
                }

                // 去掉标题栏
                continue;
            }

            // 姓名和手机号,邮箱都不能为空
            if (empty($v[0]) && empty($v[1]) && empty($v[2])) {
                // 手机号和姓名有一个为空,跳过这条记录
                continue;
            } else {

                $phone = trim($v[1]);
                $email = trim($v[2]);
                if (!empty($phone) && (strlen($phone) != 11 || !is_numeric($phone))) {
                    $error .= ',手机号码格式有误';
                }
                if (!empty($email) && !preg_match('/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/', $email)) {
                    $error .= ',邮箱格式有误';
                }
                if (empty($error)) {
                    // 如果手机号不是11位数字
                    // 都不为空,解析数组赋值
                    $data[$k] = [
                        'username' => trim($v[0]),
                        'mobile' => strval($phone),
                        'email' => strval($email),
                    ];
                } else {
                    $error_list[$k] = array(
                        'username' => trim($v[0]),
                        'mobile' => strval($phone),
                        'email' => strval($email),
                        'error' => trim($error, ',')
                    );
                }
            }
        }

        return [$data, $error_list];
    }

}