<?php

# 表单元素拼接

class formConnect{
    
    protected $options;
    
    public $base;
    
    public $db = array();
    
    public $_fid_hidden = array();

    public function connect($options = array()){        
        $this->options = $options;
        $that = $this->base;
        $tableID = $that->tid; # 表ID
        $post = array('c' => $that->name, 'm' => $options['method'].'AJAX');
        $nonce = $options['method'].$that->name; # 动作验证, 小写
        $action = $options['action']; # 操作名称
        $jump = $that->get_model_url(array('c' => $that->name)); # 提交成功后返回地址
        if ($this->_fid_hidden){
            $jump = $that->get_model_url(array('c' => $that->name, '_fid' => $this->_fid_hidden['id']));
        }
        if (isset($_GET['_from']) && $_GET['_from']){
            $jump = urldecode($_GET['_from']);
        }
        $form = $options['form_name']; # 表单名称
        $btn = $options['btn_name']; # 按钮名称
        
        $table = service::common_get_one('AdminTable', array('id' => $tableID), true, true);
        $db = array();
        if (isset($options['id'])){
            $this->db = $db = service::common_get_one($table['mode'], array('id' => intval($options['id'])));
        }
        # 字段合集
        $field = service::common_index_by_id('AdminField', array(
            'asc' => '_orderby, id',
            'where' => 'tid = ?',
            'param' => array($tableID)
        ), true);        
        echo form::start($form);
        if ($db){
            echo form::input_hidden('id', $db['id']);
        }
        echo form::input_hidden('tid', $tableID);
        echo form::nonce($that->admin['id'], $nonce);
        echo '<div class="tabson">';
        echo form::tip($that->admin['username'], $action);
        echo '<ul class="forminfo">';
        # 处理表单元素
        if ($field){
            foreach ($field as $item){
                $this->element($item, $db);
            }
        }
        # end
        echo form::submit('提交', $btn);
        echo '</ul>';
        echo '</div>';
        echo form::end();
        echo form::onclick($form, $btn, '提交', 
            $that->get_model_url($post), 
            $jump
        );
    }
    
    private function element($field, $db = array()){
        $value = $db ? $db[$field['name']] : ($field['content'] ? $field['content'] : '');
        switch ($field['_form']){
            case 'text': 
            case 'int':
            case 'float':
                $this->_input($field, $value);                
                break;
            case 'select':
            case 'select_int':
                $this->_select($field, $value);
                break;
            case 'textarea':
                $this->_textarea($field, $value);
                break;
            case 'radio':
            case 'radio_int':
                $value = $db ? intval($db[$field['name']]) : 0;
                $this->_radio($field, $value);
                break;
            case 'checkbox':
                $value = $db ? $db[$field['name']] : array();
                $this->_checkbox($field, $value);
                break;
            case 'singleImage':
                $this->_file($field, $value);
                break;
            case 'groupPictures':
                $this->_group($field, $value);
                break;
            case 'editor':
                $this->_editor($field, $value);
                break;
            case 'timepicker':
                $this->_timepicker($field, $value);
                break;
        }
    }
    
    private function _input($field, $value){
        $width = $field['_form'] == 'text' ? '' : 'width: 80px;';
        if ($field['connect_id']){
            $width = '';
        }
        $default = '';
        if ($this->_fid_hidden){
            $default = $this->_fid_hidden;
        }
        echo form::input(array(
            'title' => $field['tag'],
            'name' => $field['name'],
            'must' => $field['_must'],
            'placeholder' => '',
            'style' => $width,
            'value' => $value,
            'readonly' => 0,
            'connect' => $field['connect_id'],
            'connect_url' => $this->base->get_url(array('c' => 'database', 'm' => 'ajaxView', 'connect_id' => $field['connect_id'])),
            'connect_type' => $field['_form'],
            'db' => $this->db,
            '_fid' => $default
        ));
    }
    
    private function _select($field, $value){
        if ($field['connect_id']){
            $table = service::common_get_one('AdminTable', array('id' => $field['connect_id']), true, true); 
            $key = $table['_connect'];
            $model = $table['mode'];
            Doo::loader($model, ROOT.$table['model'].'/model/');
            $object = new $model();
            $arrs = $object->find(array('asArray' => true, 'desc' => 'id'));
            echo form::select($field['tag'], $field['name'], $field['_must'], $arrs, 'id::'.$key, 140, $value, 1);
        }else{
            $arrs = $this->_default_arr($field['content']);
            echo form::select($field['tag'], $field['name'], $field['_must'], $arrs, 'id::name', 140, $value);
        }
    }
    
    private function _textarea($field, $value){
        echo form::textarea(array(
            'title' => $field['tag'],
            'name' => $field['name'],
            'must' => $field['_must'],
            'placeholder' => '',
            'style' => 'height: 120px;',
            'value' => $value,
            'readonly' => 0
        ));
    }
    
    private function _default_arr($content){
        $arrs = array();
        $ex = explode("\n", $content);
        if ($ex){
            foreach ($ex as $v){
                if ($v){
                    list($id, $name) = explode('=', $v);
                    $arrs[$id] = array('id' => $id, 'name' => $name);
                }
            }
        }
        return $arrs;
    }
    
    private function _radio($field, $value){
        $arrs = $this->_default_arr($field['content']);
        $current = current($arrs);
        $first = $current['id'];        
        if ($value){
            $first = intval($value);
        }
        echo form::radio($field['tag'], $field['name'], $field['_must'], $arrs, 'id::name::'.$first);
    }
    
    private function _checkbox($field, $value){
        $arrs = $this->_default_arr($field['content']);
        $default = array();
        if ($value){
            $default = explode(',', $value);
        }
        echo form::checkbox($field['tag'], $field['name'], $field['_must'], $arrs, 'id::name', $default); 
    }
    
    private function _editor($field, $value){
        echo '<li><label>'.$field['tag'].form::_must($field['_must']).'</label>';
        echo '<table width="800"><tr><td>';
        echo '<script id="ueditor" name="'.$field['name'].'" type="text/plain">'.$value.'</script>';
        echo '</td></tr></table>';
        echo '</li>';
        echo '<script type="text/javascript">$(function(){var ue = UE.getEditor("ueditor");});</script>';
    }
    
    private function _file($field, $value){
        echo form::input(array(
            'title' => $field['tag'],
            'name' => $field['name'],
            'must' => $field['_must'],
            'placeholder' => '',
            'style' => '',
            'value' => $value,
            'readonly' => 0,
            'file' => $this->base->data['base_url']
        ));
    }
    
    private function _group($field, $value){
        echo '<li><label>'.$field['tag'].form::_must($field['_must']).'</label>';
        echo form::input_hidden($field['name'], $value);
        echo '<ul class="formGroupPic">';
        $list = array();
        if ($value){
            $list = explode('::', $value);
        }
        if ($list){
            foreach ($list as $url){
                echo '<li class="itemPic" onclick="$(this).remove(); _file_more_input_value();"><img src="'.$url.'?imageView/1/w/80/h/60" original="'.$url.'"/></li>';
            }
        }
        echo '<li class="addPic" onclick="_file(0, $(this));">+</li>';
        echo '</ul><br style="clear:both;"/>';
        echo '</li>';        
    }
    
    private function _timepicker($field, $value){
        echo '<li><label>'.$field['tag'].form::_must($field['_must']).'</label>';
        echo '<input type="hidden" name="'.$field['name'].'" value="'.$value.'" />';
        $date = '';
        $time = '';
        if ($value){
            $date = date('Y-n-j', $value);
            $time = date('H:i', $value);
        }
        echo '<input name="'.$field['name'].'_date" class="dfinput '.$field['name'].'_date" type="text" class="dfinput" value="'.$date.'" style="width: 90px;"/>';
        echo '&nbsp;&nbsp;';
        echo '<input name="'.$field['name'].'_time" class="dfinput '.$field['name'].'_time" type="text" class="dfinput" value="'.$time.'" style="width: 50px;"/>';
        echo '</li>';
        echo '<script>
            $(function(){
                $(".'.$field['name'].'_date").click(function(e){
                    e.stopPropagation();
                    $(this).lqdatetimepicker({
			css : \'datetime-day\',
			dateType : \'D\',
			selectback : function(){}
                    });
                });
                $(".'.$field['name'].'_time").click(function(e){
                    e.stopPropagation();
                    $(this).lqdatetimepicker({
                        css : \'datetime-hour\'
                    });
                });
            });
            </script>';
    }
    
    public function upload_url(){
        echo '<script>
            var file_manage_url = "'.$this->base->get_url(array('c' => 'upload', 'm' => 'index', 'cid' => PROJECT_ID)).'";
            var file_upload_url = "'.$this->base->get_url(array('c' => 'upload', 'm' => 'file', 'cid' => PROJECT_ID)).'";
            var file_delete_url = "'.$this->base->get_url(array('c' => 'upload', 'm' => 'delete', 'cid' => PROJECT_ID)).'";
            var file_edit_intro_url = "'.$this->base->get_url(array('c' => 'upload', 'm' => 'editIntro', 'cid' => PROJECT_ID)).'";
        </script>';
    }
    
    public function post($post = array()){
        $request = new request();
        $tid = intval($post['tid']);
        $table = service::common_get_one('AdminTable', array('id' => $tid), true, true);
        if (empty($table)){
            echo '<模型>不存在';
            return;
        }
        $id = 0;
        $db = array();
        if (isset($post['id'])){
            $id = intval($post['id']);
            $db = service::common_get_one($table['mode'], array('id' => $id));
            if (empty($db)){
                echo '<不存在>你要编辑的内容';
                return;
            }
            if ($this->base->admin['level'] == 1){
                # allow
            }else{
                $allowOthersToEdit = intval(service::get_option('allowOthersToEdit'));
                if ($allowOthersToEdit == 0){
                    echo '<权限不足>不能编辑其它人的内容';
                    return;
                }
            }
        }
        $fields = service::common_index_by_id('AdminField', array(
            'asc' => '_orderby, id',
            'where' => 'tid = ?',
            'param' => array($tid)
        ), true);  
        if (empty($fields)){
            echo '<模型>没有设置字段';
            return;
        }
        $arrs = array();
        $lian = array();
        foreach ($fields as $field){
            if ($field['_must']){
                # 必填
                if ($field['_form'] == 'timepicker'){
                    // contiune;
                }elseif (!isset($post[$field['name']]) || empty($post[$field['name']])){
                    echo "<必填 or 必选>".$field['tag'];
                    return;
                }
            }
            # 过滤
            if (isset($post[$field['name']])){
                $value = $post[$field['name']];                
                switch ($field['_form']){
                    case 'int':
                        $value = intval($request->sanitize($value, 'int'));
                        break;
                    case 'select':
                    case 'radio':
                        $value = is_numeric($value) ? intval($request->sanitize($value, 'int')) : $value;
                        break;
                    case 'float':
                        $value = floatval($request->sanitize($value, 'float'));
                        break;
                    case 'checkbox':
                        $value = implode(',', $value);
                        break;
                }
                if ($field['connect_id']){
                    $lian[] = $field['name']."_value";
                }
                $arrs[$field['name']] = $value;
            }
            # 特殊
            if ($field['_form'] == 'timepicker'){
                $_date = $post[$field['name'].'_date'];
                $_time = $post[$field['name'].'_time'];
                if ($field['_must']){
                    if (empty($_date) && empty($_time)){
                        echo "<必填 or 必选>".$field['tag'];
                        return;
                    }
                }
                if ($_date && $_time){
                    $arrs[$field['name']] = strtotime($_date.' '.$_time);
                }else{
                    $arrs[$field['name']] = 0;
                }
            }
        }
        $mode = $table['mode'];
        Doo::loadModel($mode);
        $object = new $mode();
        if ($id){
            $object->id = $id;
        }
        if ($arrs){
            foreach ($arrs as $field=>$value){
                $object->$field = $value;
            }
        }
        if ($lian){
            foreach ($lian as $field){
                $object->$field = $post[$field];
            }
        }
        $object->dateline = time();
        if ($id){
            if ($object->update()){
                service::do_action('formConnectPost', array($this->base, $id, $post));
                echo 'ok';
            }else{
                echo '<数据>更新失败';
            }
        }else{
            $object->adminid = $this->base->admin['id'];
            if ($last = $object->insert()){
                service::do_action('formConnectPost', array($this->base, $last, $post));
                echo 'ok';
            }else{
                echo '<数据>写入失败';
            }
        }
        return;
    }
    
    public function data($tid = 0, $url = array(), $options = array()){
        $table = service::common_get_one('AdminTable', array('id' => $tid), true, true);
        $fields = service::common_index_by_id('AdminField', array(
            'asc' => '_orderby, id',
            'where' => 'tid = ?',
            'param' => array($tid)
        ), true);
        # 筛选项
        $search = service::common_index_by_id('AdminField', array('asc' => 'id', 'where' => '_soso = 1 and tid = ?', 'param' => array($this->base->tid)));
        $search_html = '';
        $search_value = array();
        $search_key = array();
        $search_connect = array();
        $text = array();
        $urlso = '';
        if ($search){
            $search_html .= '<div class="search_self">';
            foreach ($search as $so){
                if ($so['connect_id']){
                    $search_connect[] = $so['name'];
                }
                $value = '';
                if ($this->base->request->hasQuery($so['name'])){
                    $value = $this->base->request->get($so['name']);
                    $search_value[$so['name']] = $value;
                }
                if ($so['_options']){
                    $ex = explode("\n", $so['_options']);  
                    $search_html .= '<select class="search-select" name="'.$so['name'].'">';
                    $search_html .= '<option value="">-- '.$so['tag'].' --</option>';
                    foreach ($ex as $op){
                        list($_k, $_v) = explode('=', $op);
                        $selected = ($value || is_numeric($value)) && $value == $_k ? ' selected' : '';
                        $search_html .= '<option value="'.$_k.'"'.$selected.'>'.$_v.'</option>';
                    }
                    $search_html .= '</select>';
                }else{
                    $text[] = $so['tag'];
                    $search_key[] = $so['name'];
                }
            }            
            if ($text){
                $key = '';
                if ($this->base->request->hasQuery('key')){
                    $key = $this->base->request->get('key');
                    $search_value['key'] = $key;
                }
                $title = implode(', ', $text);
                $search_html .= '<input id="search-key" type="text" class="dfinput" value="'.$key.'" style="width: 120px;" placeholder="'.$title.'" title="'.$title.'"/>';
            }
            $jumpurl = $this->base->get_model_url($url);
            $search_html .= '<input type="button" value="搜索" class="search-btn" onclick="_search_common();"/></div>';
            $search_html .= '<script>
        function _search_common(){
            var search_fields = [];
            $(".search_self select").each(function(){
                var field = $(this).attr("name");
                var value = $(this).val();
                search_fields.push(field + "=" + value);
            });
            search_fields.push("key=" + $(".search_self #search-key").val());
            location.href = "'.$jumpurl.'&" + search_fields.join("&");
        }
        $(function(){
            $(".search-select").uedSelect({width: 140});
        });
    </script>';
        }
        $this->base->data['search'] = $search_html;
        # 筛选项 end
        $shows = array();
        $lists = array();
        if ($fields){
            foreach ($fields as $field){
                if ($field['_view']){
                    $shows[$field['name']] = $field;
                }
                switch ($field['_form']){
                    case 'select':
                    case 'radio':
                    case 'checkbox':
                    case 'radio_int':
                    case 'select_int':
                        $field['content'] = $this->_default_arr($field['content']);
                        break;
                }
                $lists[$field['name']] = $field;
            }
        }
        if ($this->base->admin['level'] == 1){
            # allow
        }else{
            $allowOthersToEdit = intval(service::get_option('allowOthersToEdit'));
            if ($allowOthersToEdit == 0){
                if (isset($options['where'])){
                    $options['where'] .= ' and adminid = '.$this->base->admin['id'];
                }else{
                    $options['where'] = 'adminid = '.$this->base->admin['id'];
                }
            }
        }
        # 筛选项条件
        if ($search_value && isset($search_value['key'])){
            $key = $search_value['key'];
            unset($search_value['key']);
            $where = array();
            foreach ($search_value as $field=>$value){
                if ($value || is_numeric($value)){
                    if (strstr($value, ',')){
                        list($min, $max) = explode(',', $value);
                        $where[] = "(".$field." >= '".$min."' and ".$field." <= '".$max."')";
                        if ($search_connect && in_array($field, $search_connect)){
                            $where[] = "(".$field."_value >= '".$min."' and ".$field."_value <= '".$max."')";
                        }
                    }else{
                        $where[] = $field."='".$value."'";
                        if ($search_connect && in_array($field, $search_connect)){
                            $where[] = $field."_value='".$value."'";
                        }
                    }
                    $urlso .= '&'.$field.'='.$value;
                }
            }
            if ($search_key && $key){
                $key_implode = array();
                foreach ($search_key as $field){
                    $key_implode[] = $field." like '%".$key."%'";
                    if ($search_connect && in_array($field, $search_connect)){
                        $key_implode[] = $field."_value like '%".$key."%'";
                    }
                }
                if ($key_implode){
                    $where[] = "(".implode(' or ', $key_implode).")";
                    $urlso .= '&key='.$key;
                }
            }
            if ($where){
                if (isset($options['where'])){
                    $options['where'] .= ' and '.implode(' and ', $where);
                }else{
                    $options['where'] = implode(' and ', $where);
                }
            }
        }
        # 筛选项条件 end
        $this->base->data['table'] = $table;
        $this->base->data['shows'] = $shows;
        $this->base->data['fields'] = $lists;
        $this->base->data['next'] = service::common_index_by_id('AdminTable', array('asc' => 'id', 'where' => 'fid = ?', 'param' => array($tid)), true);
        $this->base->data['result'] = service::common_query($table['mode'], $this->base->get_model_url($url).$urlso, $this->base->page, $options);
    }
    
    public function table($options = array(), $jump = array()){
        if (empty($jump)){
            $jump = array('c' => $this->base->name);
            if ($this->_fid_hidden){
                $jump = array('c' => $this->base->name, '_fid' => $this->_fid_hidden['id']);
            }
        }
        $this->data($this->base->tid, $jump, $options);
        $this->base->data['controller'] = $this->base->name;
        $this->base->data['_fid_input'] = $this->_fid_hidden;
        $from = '';
        if (isset($this->base->from)){
            $from = $this->base->from;
        }
        $this->base->data['from'] = $from;
        $this->base->data['jump'] = $jump;        
        $this->base->renderc_admin('database/table', $this->base->data);
    }
    
    public function delete($id, $tid){
        $table = service::common_get_one('AdminTable', array('id' => $tid), true, true);
        $db = service::common_get_one($table['mode'], array('id' => $id), false);
        if ($this->base->admin['level'] == 1){
            # allow
        }else{
            $allowOthersToEdit = intval(service::get_option('allowOthersToEdit'));
            if ($allowOthersToEdit == 0){
                if ($db->adminid != $this->base->admin['id']){
                    echo '<权限不足>不能删除别人的内容';
                    return;
                }
            }
        }
        # 检查是否有下级数据
        $next = service::common_index_by_id('AdminTable', array('where' => 'fid = ?', 'param' => array($tid)));
        if ($next){
            $connect_field = strtolower($table['mode']).'id';
            foreach ($next as $model){
                $count = service::common_count($model['mode'], array('where' => $connect_field.' = ?', 'param' => array($id)));
                if ($count){
                    echo '<删除失败>【'.$model['tag'].'管理】存在相关数据';
                    return;
                }
            }
        }
        $db->delete();
        service::do_action('formConnectDelete', array($this->base, $id));
        echo 'ok';
        return;
    }

}
