<?php
/**
 * [LJCMS] (C)2012-2099 LJdev,Inc.
 * <E-Mail：aspcms@qq.com>
 * Url http://www.liangjing.org
 *     http://www.8CMS.com
 * Update 2014.04.03
 */

class control extends oabase
{

    public function action_run()
    {

        TPL::display($this->cptpl . 'sign/index.tpl');
    }

    public function action_day_view()
    {
        TPL::display($this->cptpl . 'schedule/day_view.tpl');
    }

    public function action_add()
    {
        $user_id      = $_SESSION['USER_AUTH_KEY'];
        $beginToday   = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
        $endToday     = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
        $start_date   = date("Y-m-d H:i:s", $beginToday);
        $end_date     = date("Y-m-d H:i:s", $endToday);
        $model        = parent::model('sign', 'oa');
        $where        = " `user_id` = '$user_id' AND `state` = 'sign_in' AND `is_del` = 0 AND ( `create_time` >= '$start_date' AND `create_time` <= '$end_date'  )";
        $sign_in      = 0;
        $sign_out     = 0;
        $sign_in_info = $model->get_data1($where);
        if (!empty($sign_in_info)) {
            $sign_in        = 1;
            $where1         = " `user_id` = '$user_id' AND `state` = 'sign_out' AND `is_del` = 0 AND ( `create_time` >= '$start_date' AND `create_time` <= '$end_date'  )";
            $sign_back_info = $model->get_data1($where1);
            if (!empty($sign_back_info)) {
                $sign_out = 1;
            }
        }
        $var_array = array(
            'sign_in'  => $sign_in,
            'sign_out' => $sign_out,
        );
        unset($model);
        TPL::assign($var_array);
        //                 if (true == $this->isMobile()) {
        //                    TPL::display($this->cptpl.'Sign/add_m.tpl');
        //                    die;
        //                 }

        TPL::display($this->cptpl . 'Sign/add.tpl');
    }

    public function action_get_location()
    {
        $lat = $_POST['lat'];
        $lng = $_POST['lng'];
        // $place_url='http://api.map.baidu.com/geocoder/v2/?location='.$lat.','.$lng.'&output=json&ak=HApG6QKUwGzgpS0aEK6P5Xmt4eX1I6cI';
        $place_url = 'http://restapi.amap.com/v3/geocode/regeo?output=json&location=' . $lng . ',' . $lat . '&key=ae4cca5e1496e41d1716dbc6c92f132e';

        $json_place = file_get_contents($place_url);
        $place_arr  = json_decode($json_place, true);
        //  print_r($place_arr);die;
        $address          = $place_arr['regeocode']['formatted_address'];
        $data['status']   = 1;
        $data['lat']      = $lat;
        $data['lang']     = $lng;
        $data['time']     = date("Y-m-d H:i:s", time());
        $data['location'] = $address;
        echo json_encode($data);
    }

    public function action_get_location_baidu()
    {
        $lat              = $_POST['lat'];
        $lng              = $_POST['lng'];
        $place_url        = 'http://api.map.baidu.com/geocoder/v2/?location=' . $lat . ',' . $lng . '&output=json&ak=HApG6QKUwGzgpS0aEK6P5Xmt4eX1I6cI';
        $json_place       = file_get_contents($place_url);
        $place_arr        = json_decode($json_place, true);
        $address          = $place_arr['result']['formatted_address'];
        $data['status']   = 1;
        $data['lat']      = $lat;
        $data['lang']     = $lng;
        $data['time']     = date("Y-m-d H:i:s", time());
        $data['location'] = $address;
        echo json_encode($data);
    }

    public function action_read()
    {
        $id        = $_REQUEST['id'];
        $model     = parent::model('sign', 'oa');
        $vo        = $model->get_data($id);
        $var_array = array(
            'vo' => $vo,
        );

        unset($model);
        TPL::assign($var_array);
        TPL::display($this->cptpl . 'Sign/read.tpl');
    }

    public function action_json()
    {
        header("Cache-Control: no-cache, must-revalidate");
        header("Content-Type:text/html; charset=utf-8");
        $user_id    = $_SESSION['USER_AUTH_KEY'];
        $start_date = $_REQUEST["start_date"];
        $end_date   = $_REQUEST["end_date"];
        $model      = parent::model('sign', 'oa');
        $where      = " `user_id` = '$user_id' AND `is_del` = 0 AND ( `create_time` >= '$start_date' AND `create_time` <= '$end_date'  )";
        $list       = $model->get_list($where);
        exit(json_encode($list));
    }

    public function action_save()
    {

        $arr         = $_POST;
        $model       = parent::model('system', 'oa');
        $system_data = $model->getconfig("sign");
        $data        = array();
        foreach ($system_data as $val) {
            $data[$val['code']] = $val['val'];
        }
        $cofing_lang = $data['jing'];
        $cofing_lat  = $data['wei'];
        $distance    = $data['distance'];
        if ($arr['state'] == "sign_in") {
            $public = parent::model('public', 'oa');
            $mi     = $public->getdistance($cofing_lang, $cofing_lat, $arr['lang'], $arr['lat']);
            if ($mi >= $distance) {
                $msg['info'] = "不在打卡范围内";
                echo json_encode($msg);
                die;
            }
            $signin_start_time = $data['signin_start_time'];
            $sign_in_time      = date("Y-m-d") . " " . $signin_start_time;
            $late = '';
            if (time() >= strtotime($sign_in_time)) {
                $arr['status'] = "迟到";
                $late = ",迟到了".intval(((time() - strtotime($sign_in_time))/60))."分钟哦！";
            } else {
                $arr['status'] = "正常";
            }
            $msg = "上班打卡成功".$late;
        } elseif ($arr['state'] == "sign_out") {
            $public = parent::model('public', 'oa');
            $mi     = $public->getdistance($cofing_lang, $cofing_lat, $arr['lang'], $arr['lat']);
            if ($mi >= $distance) {
                $msg['info'] = "不在打卡范围内";
                echo json_encode($msg);
                die;
            }
            $signback_start_time = $data['signback_start_time'];
            $sign_out_time       = date("Y-m-d") . " " . $signback_start_time;
            //      echo $sign_out_time;die;
            $early_msg = '';
            if (time() >= strtotime($sign_out_time)) {
                $arr['status'] = "正常";
            } else {
                $arr['status'] = "早退";
                $early_msg = ",早退了".intval(((strtotime($sign_out_time) - time())/60))."分钟哦！";
            }
            $msg = "下班打卡成功".$early_msg;
        } elseif ($arr['state'] == "outside") {
            $arr['status'] = "外勤";
            $msg           = "打卡成功,在外出勤要格外小心";
        }
        $arr['jing']        = $arr['lang'];
        $arr['wei']         = $arr['lat'];
        $arr['address']     = $arr['location'];
        $arr['create_time'] = $arr['time'];
        unset($arr['lang']);
        unset($arr['lat']);
        unset($arr['location']);
        unset($arr['time']);
        $sign   = parent::model('sign', 'oa');
        $result = $sign->doAdd($arr);
        if (true === $result) {
            $res['status'] = 1;
            $res['info']   = $msg;
        } else {
            $res['info'] = "操作失败";
        }
        echo json_encode($res);
    }

    public function action_del()
    {
        $id = $_REQUEST['id'];

        $dept = parent::model('schedul', 'oa');

        $res = $dept->del($id);
        if ($res !== false) {//保存成功
            XHandle::halt('操作成功', $this->cpfile . '?c=Schedule', 0);
        } else {
            XHandle::halt('操作失败！', '', 1);
        }

    }

    //    考勤规则分界线

    public function action_Sign_rule()
    {
        $model       = parent::model('system', 'oa');
        $system_data = $model->getconfig("sign");
        $data        = array();
        foreach ($system_data as $val) {
            $data[$val['code']] = $val['val'];
        }
        
        $var_array = array(
            'sign_data' => $data,
        );
        unset($model);
        TPL::assign($var_array);
        TPL::display($this->cptpl . 'sign/sign_rule.tpl');
    }

    public function action_choice_address()
    {
        $model       = parent::model('system', 'oa');
        $system_data = $model->getconfig("sign");
        $data        = array();
        foreach ($system_data as $val) {
            $data[$val['code']] = $val['val'];
        }

        $var_array = array(
            'sign_data' => $data,
        );
        unset($model);
        TPL::assign($var_array);
        TPL::display($this->cptpl . 'sign/choice_address.tpl');
    }

    public function action_save_sign()
    {
        $data_type = $_POST['data_type'];
        if ($data_type == 'sign') {
            $this->set_val('signin_start_time', 'sign');
            $this->set_val('signback_start_time', 'sign');
            $this->set_val('address', 'sign');
            $this->set_val('jing', 'sign');
            $this->set_val('wei', 'sign');
            $this->set_val('distance', 'sign');
            XHandle::halt('编辑成功', $this->cpfile . '?c=Sign&a=Sign_rule', 0);
            die;
        }
    }

    function set_val($key, $type)
    {
        $model             = parent::model('system', 'oa');
        $data['val']       = $_POST[$key];
        $data['data_type'] = $type;
        $data=$this->SafeFilter($data);
        $vo                = $model->getconfiginfo($key);
        if (!empty($vo)) {
            $id   = $vo['id'];
            $list = $model->save($data, $id);
        } else {
            $list = $model->add($data);
        }

        if ($list !== false) {
            return true;
        } else {
            return false;
        }
    }

    ///请假加班  分界线
    public function action_leave()
    {
        $user_id   = $_SESSION['USER_AUTH_KEY'];
        $model     = parent::model('leave', 'oa');
        $searchsql = " AND user_id='$user_id'";
        list($total, $data) = $model->getList(array('page' => $this->page, 'pagesize' => $this->pagesize, 'searchsql' => $searchsql));
        $url       = XRequest::getPhpSelf();
        $url       .= '?c=Sign&a=leave';
        $var_array = array(
            'page'      => $this->page,
            'nextpage'  => $this->page + 1,
            'prepage'   => $this->page - 1,
            'pagecount' => ceil($total / $this->pagesize),
            'pagesize'  => $this->pagesize,
            'total'     => $total,
            'showpage'  => XPage::index($total, $this->pagesize, $this->page, $url, 10),
            'list'      => $data,
        );
        unset($model);
        TPL::assign($var_array);
        TPL::display($this->cptpl . 'sign/leave.tpl');
    }

    public function action_add_leave()
    {
        $id     = $_REQUEST['id'];
        $opmode = "add";
        if ($id) {
            $opmode = "edit";
            $model  = parent::model('leave', 'oa');
            $vo     = $model->get_top_menu_data($id);

        }
        $var_array = array(
            'opmode' => $opmode,
            'vo'     => $vo
        );
        TPL::assign($var_array);
        TPL::display($this->cptpl . 'sign/add_leave.tpl');
    }

    public function action_save_leave()
    {
        $arr = $_POST;
        if ($arr['time'] == '') {
            $data['info'] = "时间不能为空";
            echo json_encode($data);
            die;
        }
        if ($arr['hour'] == '') {
            $data['info'] = "时长不能为空";
            echo json_encode($data);
            die;
        }
        if ($arr['type'] == '') {
            $data['info'] = "类型不能为空";
            echo json_encode($data);
            die;
        }
        if ($arr['content'] == '') {
            $data['info'] = "原因不能为空";
            echo json_encode($data);
            die;
        }
        
        $id    = $arr['id'];
        $arr=$this->SafeFilter($arr);
        $model = parent::model('leave', 'oa');
        if ($arr['opmode'] == 'add') {
            $result = $model->doadd($arr);
        } else {
            $result = $model->doEdit($id, $arr);
        }
        if (true === $result) {
            $data['status'] = 1;
            $data['info']   = "编辑成功";
        } else {
            $data['info'] = "编辑失败";
        }
        echo json_encode($data);
    }

    public function action_del_leave()
    {
        $id = $_REQUEST['id'];

        $dept = parent::model('leave', 'oa');

        $res = $dept->del($id);
        if ($res !== false) {//保存成功
            XHandle::halt('操作成功', $this->cpfile . '?c=Sign&a=leave', 0);
        } else {
            XHandle::halt('操作失败！', '', 1);
        }

    }

    public function action_leave_shen()
    {
        $dept      = parent::model('dept', 'oa');
        $dept_id   = $_SESSION['dept_id'];
        $deptinfo  = $dept->get_top_menu_data($dept_id);
        $searchsql = " AND status='0'";
        if ($deptinfo['pid'] != 0) {
            $user      = parent::model('user', 'oa');
            $where     = "dept_id='$dept_id' AND is_del='0'";
            $user_list = $user->get_List($where);
            $search    = "";
            foreach ($user_list as $v) {
                $search .= $v['id'] . ",";
            }
            $search    = substr($search, 0, strlen($search) - 1);
            $searchsql .= " AND user_id in ($search)";
        }
        $model = parent::model('leave', 'oa');

        list($total, $data) = $model->getList(array('page' => $this->page, 'pagesize' => $this->pagesize, 'searchsql' => $searchsql));
        $url       = XRequest::getPhpSelf();
        $url       .= '?c=Sign&a=leave';
        $var_array = array(
            'page'      => $this->page,
            'nextpage'  => $this->page + 1,
            'prepage'   => $this->page - 1,
            'pagecount' => ceil($total / $this->pagesize),
            'pagesize'  => $this->pagesize,
            'total'     => $total,
            'showpage'  => XPage::index($total, $this->pagesize, $this->page, $url, 10),
            'list'      => $data,
        );
        unset($model);
        TPL::assign($var_array);
        TPL::display($this->cptpl . 'sign/leave_shen.tpl');
    }

    public function action_leave_replay()
    {
        $id        = $_REQUEST['id'];
        $var_array = array(
            'id' => $id,
        );
        TPL::assign($var_array);
        TPL::display($this->cptpl . 'sign/leave_reply.tpl');
    }

    public function action_leave_edit()
    {
        $id   = $_REQUEST['id'];
        $type = $_REQUEST['type'];
        if ($type == 1) {
            $arr['status']   = 1;
            $arr['shen_msg'] = "审核通过";
        } elseif ($type == 2) {
            $arr['status']   = 2;
            $arr['shen_msg'] = $_REQUEST['replay'];
        }
        $arr['auditor']     = $_SESSION['user_name'];
        $arr['update_time'] = time();
        //   print_r($arr);die;
        $model = parent::model('leave', 'oa');

        $result = $model->doEdit($id, $arr);

        if (true === $result) {
            $data['status'] = 1;
            $data['info']   = "编辑成功";
        } else {
            $data['info'] = "编辑失败";
        }
        echo json_encode($data);
    }

    public function action_sign_count()
    {
        $keyword                  = $_POST['keyword'];
        $eq_dept_id               = $_POST['eq_dept_id'];
        $be_create_time           = $_POST['be_create_time'];
        $en_create_time           = $_POST['en_create_time'];
        $search['keyword']        = $keyword;
        $search['eq_dept_id']     = $eq_dept_id;
        $search['be_create_time'] = $be_create_time;
        $search['en_create_time'] = $en_create_time;

        $dept     = parent::model('dept', 'oa');
        $dept_id  = $_SESSION['dept_id'];
        $deptinfo = $dept->get_top_menu_data($dept_id);
        $user     = parent::model('user', 'oa');
        $where    = " AND is_del='0'";
        if ($deptinfo['pid'] != 0) {
            $where = " AND dept_id='$dept_id'";
        }
        if ($keyword != '') {
            $where .= " AND name LIKE '%" . $keyword . "%'";
        }
        list($total, $data) = $user->getList(array('page' => $this->page, 'pagesize' => $this->pagesize, 'searchsql' => $where));

        $model = parent::model('sign', 'oa');
        foreach ($data as $key => $value) {
            $user_id   = $value['id'];
            $searchsql = "is_del='0' AND user_id='$user_id'";
            if ($be_create_time != '') {
                $searchsql .= " AND ( `create_time` >= '$be_create_time' AND `create_time` <= '$en_create_time'  )";
            }
            $data[$key]['late']          = $model->get_count($searchsql, '迟到');
            $data[$key]['leave']         = $model->get_count($searchsql, '早退');
            $data[$key]['normal']        = $model->get_count($searchsql, '正常');
            $dept_id                     = $value['dept_id'];
            $position_id                 = $value['position_id'];
            $sql1                        = "SELECT * FROM " . DB_PREFIXOA . "dept WHERE id='" . $dept_id . "'";
            $dept                        = parent::$obj->fetch_first($sql1);
            $sql2                        = "SELECT * FROM " . DB_PREFIXOA . "position WHERE id='" . $position_id . "'";
            $position                    = parent::$obj->fetch_first($sql2);
            $data[$key]['dept_name']     = $dept['name'];
            $data[$key]['position_name'] = $position['name'];
        }
        $url       = XRequest::getPhpSelf();
        $url       .= '?c=Sign&a=sign_count';
        $var_array = array(
            'page'      => $this->page,
            'nextpage'  => $this->page + 1,
            'prepage'   => $this->page - 1,
            'pagecount' => ceil($total / $this->pagesize),
            'pagesize'  => $this->pagesize,
            'total'     => $total,
            'showpage'  => XPage::index($total, $this->pagesize, $this->page, $url, 10),
            'list'      => $data,
            'search'    => $search
        );
        unset($model);
        TPL::assign($var_array);
        TPL::display($this->cptpl . 'sign/sign_count.tpl');
    }

    public function action_leave_count()
    {
        $keyword                  = $_POST['keyword'];
        $eq_dept_id               = $_POST['eq_dept_id'];
        $be_create_time           = $_POST['be_create_time'];
        $en_create_time           = $_POST['en_create_time'];
        $type                     = $_POST['type'];
        $search['keyword']        = $keyword;
        $search['eq_dept_id']     = $eq_dept_id;
        $search['be_create_time'] = $be_create_time;
        $search['en_create_time'] = $en_create_time;
        $search['type']           = $type;
        $searchsql                = "";
        if ($keyword != '') {
            $searchsql .= " AND user_name LIKE '%" . $keyword . "%'";
        }
        if ($eq_dept_id != '') {
            $searchsql .= " AND dept_id='$eq_dept_id'";
        }
        if ($type != '') {
            $searchsql .= " AND type='$type'";
        }
        if ($be_create_time != '') {
            $searchsql .= " AND ( `time` >= '$be_create_time' AND `time` <= '$en_create_time'  )";
        }
        $model = parent::model('leave', 'oa');
        list($total, $data) = $model->getList(array('page' => $this->page, 'pagesize' => $this->pagesize, 'searchsql' => $searchsql));
        // print_r($data);
        $dept = parent::model('dept', 'oa');
        // $list=$node->get_grouplist();
        $menu        = array();
        $menu        = $dept->get_menu_list();
        $publicmodel = parent::model('public', 'oa');
        $tree        = $publicmodel->list_to_tree($menu);

        $url       = XRequest::getPhpSelf();
        $url       .= '?c=Sign&a=leave_count';
        $var_array = array(
            'page'      => $this->page,
            'nextpage'  => $this->page + 1,
            'prepage'   => $this->page - 1,
            'pagecount' => ceil($total / $this->pagesize),
            'pagesize'  => $this->pagesize,
            'total'     => $total,
            'showpage'  => XPage::index($total, $this->pagesize, $this->page, $url, 10),
            'list'      => $data,
            'menu'      => $publicmodel->select_tree_menu($tree, $eq_dept_id),
            'search'    => $search
        );
        unset($model);
        TPL::assign($var_array);
        TPL::display($this->cptpl . 'sign/leave_count.tpl');
    }

    public function isMobile()
    {
        // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
        if (isset($_SERVER['HTTP_X_WAP_PROFILE'])) {
            return true;
        }
        // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
        if (isset($_SERVER['HTTP_VIA'])) {
            // 找不到为flase,否则为true
            return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
        }
        // 脑残法，判断手机发送的客户端标志,兼容性有待提高。其中'MicroMessenger'是电脑微信
        if (isset($_SERVER['HTTP_USER_AGENT'])) {
            $clientkeywords = array('nokia', 'sony', 'ericsson', 'mot', 'samsung', 'htc', 'sgh', 'lg', 'sharp', 'sie-', 'philips', 'panasonic', 'alcatel', 'lenovo', 'iphone', 'ipod', 'blackberry', 'meizu', 'android', 'netfront', 'symbian', 'ucweb', 'windowsce', 'palm', 'operamini', 'operamobi', 'openwave', 'nexusone', 'cldc', 'midp', 'wap', 'mobile', 'MicroMessenger');
            // 从HTTP_USER_AGENT中查找手机浏览器的关键字
            if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
                return true;
            }
        }
        // 协议法，因为有可能不准确，放到最后判断
        if (isset ($_SERVER['HTTP_ACCEPT'])) {
            // 如果只支持wml并且不支持html那一定是移动设备
            // 如果支持wml和html但是wml在html之前则是移动设备
            if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
                return true;
            }
        }
        return false;
    }
}

?>
