<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Class 帐号管理类
 */
class User extends MY_controller
{
    function __construct()
    {
        parent::__construct();
        $this->load->helper(array('form', 'url', 'date'));
        $this->load->model("user_model");
        $this->load->driver('cache', array('adapter' => 'apc', 'backup' => 'file'));
        /*if(array_key_exists("from",$this->session->userdata)){
            $this->user_model->set_collection_name("sso_users");
        }*/
        $this->load->library('MY_pagination');
        $this->assign("user_status", $this->user_status);
        $this->assign("user_types", $this->user_types);
    }

    /**
     * 帐号列表页
     */
    public function index()
    {
        $url = site_url("user/index?");
        $wheres = array();
        $order_info = array();
        $keyword = $this->input->get("keyword", TRUE);
        $user_type = $this->input->get("user_type", TRUE);
        $status = $this->input->get("status", TRUE);
        $order = $this->input->get("order", TRUE);
        $page_num = $this->input->get("per_page", TRUE);
        $page_size = $this->input->get("page_size", TRUE);
        if ($keyword) {
            $url .= "&keyword=" . $keyword;
        }
        if ($user_type) {
            $wheres['user_type'] = $user_type;
            $url .= "&user_type=" . $user_type;
        }
        if ($status) {
            $wheres['status'] = $status;
            $url .= "&status=" . $status;
        }
        if ($order) {
            $orders = explode(" ", $order);
            if (count($orders) == 2) {
                $order_info[$orders[0]] = $orders[1];
                $url .= "&order=" . $order;
            }
        }
        if ($page_size) {
            $this->page_size = $page_size;
            $url .= "&page_size=" . $page_size;
        }
        $count = $this->user_model->count_user($keyword, $wheres);
        $this->assign("count", $count);
        $config = $this->page_config($count, $this->page_size, $url);
        $this->my_pagination->initialize($config);
        if($page_num && $page_num>1) {
            $offset = (intval($page_num)-1)*$this->page_size;
        }else {
            $offset = 0;
        }
        $user_list = $this->user_model->list_user($this->page_size, $offset, $keyword, $wheres, $order_info);
        $this->assign("keyword", $keyword);
        $this->assign("user_type", $user_type);
        $this->assign("status", $status);
        $this->assign("order", $order);
        $this->assign("page_size", $this->page_size);
        $this->assign("page", $this->my_pagination->create_pages());
        $this->assign("user_list", $user_list);
        $this->display("user/index.html");
    }

    /**
     * 查看帐号详情
     * @param $user_id 帐号id
     */
    public function view($user_id)
    {
        $message = "";
        $user = $this->user_model->get_user_with_user_id($user_id);
        if($user){
            $this->assign("user",$user);
        }else{
            $message = "帐号信息不存在或者已经被删除";
        }
        $this->assign("message",$message);
        $this->display("user/view.html");
    }

    /**
     * 更新帐号信息
     */
    public function update()
    {
        $cahce_branch = $this->cache->get('branchs');
        $msg=array();
        $data = array();
        $msg['code'] = 1;
        $msg['icon'] = 2;
        $data['user_id']=$user_id = $this->input->post("user_id",true);
        $old_user = $this->user_model->get_user_with_user_id($user_id);
        $data['username']=$username = $this->input->post("username",true);
        $password = $this->input->post("password",true);
        $repassword = $this->input->post("repassword",true);
        $data['name']=$name = $this->input->post("name",true);
        $data['mobile']=$mobile = $this->input->post("mobile",true);
        $data['email']=$email = $this->input->post("email",true);
        $branch_id = $this->input->post("branch",true);
        if($branch_id != "") {
            $branchs = array();
            for ($i = 0;$i<count($branch_id);$i++){
                $branchs[] = array('branch_id' => $branch_id[$i], 'branch_type' => $cahce_branch[$branch_id[$i]]['branch_type']);
            }
            $data['branch'] = $branchs;
        }else{
            $data['branch'] = array(array('branch_id' => "", 'branch_type' => ""));
        }
        $data['user_type']=$user_type = $this->input->post("user_type",true);
        if(!$username){
            $msg['code'] = 0;
            $msg['msg'] = "帐号名不能为空!";
        }
        if(!preg_match_all("/^[a-zA-Z\d_]{5,18}$/",$username) && $msg['code']){
            $msg['code'] = 0;
            $msg['msg'] = "帐号名格式不正确,只支持英文和数字,最小长度为5,最大长度为18!";
        }
        if($this->user_model->is_exists("username",$username,$old_user['username']) && $msg['code']){
            $msg['code'] = 0;
            $msg['msg'] = "该帐号名已存在请换一个。";
        }
        if($password && strlen($password)<8 && $msg['code']){
            $msg['code'] = 0;
            $msg['msg'] = "密码格式不正确,最小长度为8!";
        }
        if($password && $password != $repassword && $msg['code']){
            $msg['code'] = 0;
            $msg['msg'] = "两次密码输入不一致,请检查。";
        }
        if(!$name && $msg['code']){
            $msg['code'] = 0;
            $msg['msg'] = "姓名不能为空!";
        }
        if(!preg_match('/[a-zA-Z\x{4e00}-\x{9fa5}]/u', $name)  && $msg['code']){
            $msg['code'] = 0;
            $msg['msg'] = "姓名格式不正确,正能是中文或者英文!";
        }
        if(!$mobile && $msg['code']) {
            $msg['code'] = 0;
            $msg['msg'] = "手机号码不能为空!";
        }
        if(!preg_match('/^0?(13|14|15|17|18)[0-9]{9}$/', $mobile) && $msg['code']){
            $msg['code'] = 0;
            $msg['msg'] = "手机号码格式不正确!";
        }
        if($this->user_model->is_exists("mobile",$mobile,$old_user['mobile']) && $msg['code']){
            $msg['code'] = 0;
            $msg['msg'] = "该手机号已存被使用请换一个。";
        }
        if(!$email && $msg['code']) {
            $msg['code'] = 0;
            $msg['msg'] = "邮箱不能为空!";
        }
        if(!preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/', $email) && $msg['code']){
            $msg['code'] = 0;
            $msg['msg'] = "邮箱格式不正确!";
        }
        if($this->user_model->is_exists("email",$email,$old_user['email']) && $msg['code']){
            $msg['code'] = 0;
            $msg['msg'] = "该邮箱已存被使用请换一个。";
        }
        if($user_type == 2 && $branch_id =="" && $msg['code']){
            $msg['code'] = 0;
            $msg['msg'] = "帐号类型为工程师时,必须填写分支机构。";
        }
        if($msg['code']){
            $this->user_model->update_user($data);
            $msg['icon'] = 1;
            $msg['msg'] = "帐号信息更新成功!";
        }
        $this->response($msg);
    }

    /**
     * 验证是否存在
     * @param null $old_val 原数据
     */
    public function validate($old_val=NULL){
        $field = $this->input->post("name",true);
        $value = $this->input->post("param",true);
        if($field == "username"){
            $msg = "帐号名已存在!";
        }
        if($field == "mobile"){
            $msg = "手机号码已存在!";
        }
        if($field == "email"){
            $old_val = urldecode($old_val);
            $msg = "邮箱已存在!";
        }
        if($this->user_model->is_exists($field,$value,$old_val)){
            $this->response(array("info"=>$msg,"status"=>"n"));
        }else{
            $this->response(array("info"=>"已验证通过!","status"=>"y"));
        }
    }

    /**
     * 增加帐号
     */
    public function add()
    {
        $id = $this->create_id();
        $this->assign("user_id", $id);
        $this->display("user/add.html");
    }

    /**
     * 保存帐号数据
     */
    public function save(){
        $cahce_branch = $this->cache->get('branchs');
        $msg=array();
        $data = array();
        $msg['code'] = 1;
        $msg['icon'] = 2;
        $data['user_id']=$user_id = $this->input->post("user_id",true);
        $data['username']=$username = $this->input->post("username",true);
        $password = $this->input->post("password",true);
        $repassword = $this->input->post("repassword",true);
        $data['name']=$name = $this->input->post("name",true);
        $data['mobile']=$mobile = $this->input->post("mobile",true);
        $data['email']=$email = $this->input->post("email",true);
        $branch_id = $this->input->post("branch",true);
        if($branch_id != "") {
            $branchs = array();
            for ($i = 0;$i<count($branch_id);$i++){
                $branchs[] = array('branch_id' => $branch_id[$i], 'branch_type' => $cahce_branch[$branch_id[$i]]['branch_type']);
            }
            $data['branch'] = $branchs;
        }else{
            $data['branch'] = array(array('branch_id' => "", 'branch_type' => ""));
        }
        $data['user_type']=$user_type = $this->input->post("user_type",true);
        if(!$username){
            $msg['code'] = 0;
            $msg['msg'] = "帐号名不能为空!";
        }elseif(!preg_match_all("/^[a-zA-Z\d_]{5,18}$/",$username) && $msg['code']){
            $msg['code'] = 0;
            $msg['msg'] = "帐号名格式不正确,只支持英文和数字,最小长度为5,最大长度为18!";
        }elseif($this->user_model->is_exists("username",$username) && $msg['code']){
            $msg['code'] = 0;
            $msg['msg'] = "该帐号名已存在请换一个。";
        }
        if(!$password && $msg['code']){
            $msg['code'] = 0;
            $msg['msg'] = "密码不能为空!";
        }elseif(strlen($password)<8 && $msg['code']){
            $msg['code'] = 0;
            $msg['msg'] = "密码格式不正确,最小长度为8!";
        }
        if($password != $repassword && $msg['code']){
            $msg['code'] = 0;
            $msg['msg'] = "两次密码输入不一致,请检查。";
        }
        if(!$name && $msg['code']){
            $msg['code'] = 0;
            $msg['msg'] = "姓名不能为空!";
        }elseif(!preg_match('/[a-zA-Z\x{4e00}-\x{9fa5}]/u', $name)  && $msg['code']){
            $msg['code'] = 0;
            $msg['msg'] = "姓名格式不正确,正能是中文或者英文!";
        }
        if(!$mobile && $msg['code']) {
            $msg['code'] = 0;
            $msg['msg'] = "手机号码不能为空!";
        }elseif(!preg_match('/^0?(13|14|15|17|18)[0-9]{9}$/', $mobile) && $msg['code']){
            $msg['code'] = 0;
            $msg['msg'] = "手机号码格式不正确!";
        }elseif($this->user_model->is_exists("mobile",$mobile) && $msg['code']){
            $msg['code'] = 0;
            $msg['msg'] = "该手机号已存被使用请换一个。";
        }
        if(!$email && $msg['code']) {
            $msg['code'] = 0;
            $msg['msg'] = "邮箱不能为空!";
        }elseif(!preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/', $email) && $msg['code']){
            $msg['code'] = 0;
            $msg['msg'] = "邮箱格式不正确!";
        }elseif($this->user_model->is_exists("email",$email) && $msg['code']){
            $msg['code'] = 0;
            $msg['msg'] = "该邮箱已存被使用请换一个。";
        }
        if($user_type == 2 && $branch_id =="" && $msg['code']){
            $msg['code'] = 0;
            $msg['msg'] = "帐号类型为工程师时,必须填写分支机构。";
        }
        if($msg['code']){
            $data['password']= hash_hmac('sha256',$password,$this->config->item('secret_key'));
            $data['create_time'] = new MongoDB\BSON\UTCDateTime(time()*1000);
            $data['status'] = "10";
            $data['last_login_time'] = "";
            $this->user_model->insert_user($data);
            $msg['icon'] = 1;
            $msg['msg'] = "帐号信息保存成功!";
        }
        $this->response($msg);
    }

    /**
     * 删除帐号数据
     * @param $user_id 帐号ID
     */
    public function delete($user_id)
    {
        $data['icon'] = 1;
        if ($user_id) {
            if($user_id != 1) {
                $user = $this->user_model->get_user_with_user_id($user_id);
                if ($user) {
                    $this->user_model->delete_user($user_id);
                    $data['msg'] = "帐号删除成功!";
                } else {
                    $data['icon'] = 2;
                    $data['msg'] = "帐号信息不存在或者已经被删除!";
                }
            }else{
                $data['icon'] = 2;
                $data['msg'] = "系统预定义的账户不允许删除!";
            }
        } else {
            $data['icon'] = 2;
            $data['msg'] = "参数错误请刷新后重试!";
        }
        $this->response($data);
    }

    /**
     * 禁用帐号
     * @param $user_id 帐号Id
     */
    public function stopuse($user_id){
        $data['icon'] = 1;
        if ($user_id) {
            $user = $this->user_model->get_user_with_user_id($user_id);
            if($user) {
                $user['status'] = "40";
                $this->user_model->update_user($user);
                $data['msg'] = "帐号停用成功!";
            }else{
                $data['icon'] = 2;
                $data['msg'] = "帐号信息不存在或者已经被删除!";
            }
        } else {
            $data['icon'] = 2;
            $data['msg'] = "参数错误请刷新后重试!";
        }
        $this->response($data);
    }

    /**
     * 启用帐号
     * @param $user_id 帐号Id
     */
    public function restore($user_id){
        $data['icon'] = 1;
        if ($user_id) {
            $user = $this->user_model->get_user_with_user_id($user_id);
            if($user) {
                $user['status'] = "10";
                $this->user_model->update_user($user);
                $data['msg'] = "帐号恢复成功!";
            }else{
                $data['icon'] = 2;
                $data['msg'] = "帐号信息不存在或者已经被删除!";
            }
        } else {
            $data['icon'] = 2;
            $data['msg'] = "参数错误请刷新后重试!";
        }
        $this->response($data);
    }

    /**
     * 修改帐号密码
     * @param $user_id 帐号ID
     */
    public function change_password($user_id){
        $data['code'] = 0;
        $message = "";
        $user = $this->user_model->get_user_with_user_id($user_id);
        if($user){
            $this->assign("user",$user);
        }else{
           $message = "帐号信息不存在或者已经被删除!";
        }
        if($this->input->post()){
            $password = $this->input->post("password",true);
            $repassword = $this->input->post("repassword",true);
            if($password) {
                if ($this->session->user_type != "1") {
                    $old_password =  hash_hmac('sha256',$this->input->post("old_password", true),$this->config->item('secret_key'));
                    if ($old_password != $user['password']) {
                        $data['icon'] = 2;
                        $data['msg'] = "旧密码不正确,请重新输入!";
                    } elseif ($password != $repassword) {
                        $data['icon'] = 2;
                        $data['msg'] = "两次密码输入不一致,请重新输入!";
                    } else {
                        $user['password'] = hash_hmac('sha256',$password,$this->config->item('secret_key'));
                        $this->user_model->update_user($user);
                        $data['code'] = 1;
                        $data['icon'] = 1;
                        $data['msg'] = "密码修改成功!";
                    }
                } else {
                    if ($password != $repassword) {
                        $data['icon'] = 2;
                        $data['msg'] = "两次密码输入不一致,请重新输入!";
                    } else {
                        $user['password'] =  hash_hmac('sha256',$password,$this->config->item('secret_key'));
                        $this->user_model->update_user($user);
                        $data['code'] = 1;
                        $data['icon'] = 1;
                        $data['msg'] = "密码修改成功!";
                    }
                }
            }else{
                $data['code'] = 1;
                $data['icon'] = 1;
                $data['msg'] = "放弃修改密码!";
            }
            $this->response($data);
        }else{
            $this->assign("message",$message);
            $this->display("user/change_password.html");
        }
    }

    /**
     * 批量删除帐号
     */
    public function delete_all(){
        $ids = rtrim($this->input->post("ids",true),",");
        $ids = explode(",",$ids);
        if(count($ids)<1){
            $data['icon'] = 2;
            $data['msg'] = "参数错误请刷新后重试!";
        }else{
            $this->user_model->delete_all_user($ids);
            $data['icon'] = 1;
            $data['msg'] = "批量删除帐号成功!";
        }
        $this->response($data);
    }

    /**
     * 批量禁用帐号
     */
    public function disable_all(){
        $ids = rtrim($this->input->post("ids",true),",");
        $ids = explode(",",$ids);
        if(count($ids)<1){
            $data['icon'] = 2;
            $data['msg'] = "参数错误请刷新后重试!";
        }else{
            $wheres = array('user_id'=>array('$in'=>$ids));
            $this->user_model->set_val("status",$wheres,"40");
            $data['icon'] = 1;
            $data['msg'] = "批量禁用帐号成功!";
        }
        $this->response($data);
    }

    /**
     * 批量启用帐号
     */
    public function enable_all(){
        $ids = rtrim($this->input->post("ids",true),",");
        $ids = explode(",",$ids);
        if(count($ids)<1){
            $data['icon'] = 2;
            $data['msg'] = "参数错误请刷新后重试!";
        }else{
            $wheres = array('user_id'=>array('$in'=>$ids));
            $this->user_model->set_val("status",$wheres,"10");
            $data['icon'] = 1;
            $data['msg'] = "批量启用帐号成功!";
        }
        $this->response($data);
    }


}