<?php namespace Phpcmf\Field;
/**
 * https://www.besyun.com
 * BESCMS
 * 本文件是框架系统文件，二次开发时不可以修改本文件，可以通过继承类方法来重写此文件
 **/
class Join extends \Phpcmf\Library\A_Field {
	
	/**
     * 构造函数
     */
    public function __construct(...$params) {
        parent::__construct(...$params);
		$this->fieldtype = ['TEXT' => '']; // TRUE表全部可用字段类型,自定义格式为 array('可用字段类型名称' => '默认长度', ... )
		$this->defaulttype = 'TEXT'; // 当用户没有选择字段类型时的缺省值
    }
	
	/**
	 * 字段相关属性参数
	 *
	 * @param	array	$value	值
	 * @return  string
	 */
	public function option($option) {
	
        if ($option['field']) {
            foreach ($option['field'] as $k => $v) {
                if (!$v['field']) {
                    unset($option['field'][$k]);
                }
            }
        }

        $html = '';
        $max = dr_count($option['field'])+2;
        for ($i = 1; $i <= $max; $i++) {
            $html.= '<div class="form-group">
				<label class="col-md-2 control-label">'.dr_lang('表格第%s列', $i).'</label>
				<div class="col-md-9">
					<label><input type="text" placeholder="'.dr_lang('字段名').'" class="form-control" size="20" value="'.$option['field'][$i]['field'].'" name="data[setting][option][field]['.$i.'][field]"></label>
					<label><input type="text" placeholder="'.dr_lang('显示名').'" class="form-control" size="20" value="'.$option['field'][$i]['name'].'" name="data[setting][option][field]['.$i.'][name]"></label>
					<label><input type="text" placeholder="'.dr_lang('宽度').'" class="form-control" size="20" value="'.$option['field'][$i]['width'].'" name="data[setting][option][field]['.$i.'][width]"></label>
					</label>
                    <label><input type="text" placeholder="'.dr_lang('回调函数').'" class="form-control" size="20" value="'.$option['field'][$i]['func'].'" name="data[setting][option][field]['.$i.'][func]"></label>
					</label>
				</div>
			</div>';
        }
		
		return [$this->_search_field().'
				<div class="form-group">
                    <label class="col-md-2 control-label">'.dr_lang('关联表').'</label>
                    <div class="col-md-9">
                    <label><input type="text" class="form-control"  name="data[setting][option][table]" value="'.$option['table'].'"></label>
					<span class="help-block">'.dr_lang('输入表名称，不带表前缀，如：article').'</span>
                    </div>
                </div>
				<div class="form-group">
                    <label class="col-md-2 control-label">'.dr_lang('最大选择数').'</label>
                    <div class="col-md-9">
                    <label><input type="text" class="form-control" name="data[setting][option][limit]" value="'.$option['limit'].'"></label>
					<span class="help-block">'.dr_lang('最大能选择的数量限制').'</span>
                    </div>
                </div>
				<div class="form-group">
                    <label class="col-md-2 control-label">'.dr_lang('每页显示条数').'</label>
                    <div class="col-md-9">
                    <label><input type="text" class="form-control" name="data[setting][option][pagesize]" value="'.$option['pagesize'].'"></label>
					<span class="help-block">'.dr_lang('选择列表分页条数，按多少条数据分页').'</span>
                    </div>
                </div>'.$html.''];
	}
	
	/**
	 * 字段输出
	 */
	public function output($value) {
		return $value;
	}
	
	/**
	 * 字段入库值
	 */
	public function insert_value($field) {
		
		$data = \Phpcmf\Service::L('Field')->post[$field['fieldname']];
        $limit = intval($field['setting']['option']['limit']);
        if ($limit && $data && count($data) > $limit) {
            // 超限了
            $value = implode(',', dr_arraycut($data, $limit));
        } else {
            $value = !$data ? '' : implode(',', $data);
        }

		\Phpcmf\Service::L('Field')->data[$field['ismain']][$field['fieldname']] = $value;
	}
	
	/**
	 * 字段表单输入
	 *
	 * @param	string	$cname	字段别名
	 * @param	string	$name	字段名称
	 * @param	array	$cfg	字段配置
	 * @param	string	$value	值
	 * @return  string
	 */
    public function input($field, $value = '') {

        // 字段禁止修改时就返回显示字符串
        if ($this->_not_edit($field, $value)) {
            return $this->show($field, $value);
        }

        
        $is_show = 0;

        // 字段存储名称
        $name = $field['fieldname'];
		// 字段提示信息
		$tips = isset($field['setting']['validate']['tips']) && $field['setting']['validate']['tips'] ? '<span class="help-block" id="dr_'.$name.'_tips">'.$field['setting']['validate']['tips'].'</span>' : '';
		// 区域大小
        $area = \Phpcmf\Service::IS_MOBILE_USER() ? '["95%", "90%"]' : '["50%", "65%"]';
        // 关联表名称
		$table = isset($field['setting']['option']['table']) ? $field['setting']['option']['table'] : '';
		// 字段显示名称
        $text = ($field['setting']['validate']['required'] ? '<span class="required" aria-required="true"> * </span>' : '').dr_lang($field['name']);
        // 选择数量限制
        $limit = intval($field['setting']['option']['limit']);
        !$limit && $limit = 99999;

        if (!$table) {
            if (CI_DEBUG) {
                return $this->input_format($name, $text, '<div class="form-control-static" style="color:red">关联字段没有设置关联表名称</div>');
            }
            return $this->input_format($name, $text, '');
        } elseif (!\Phpcmf\Service::M()->is_table_exists($table)) {
            if (CI_DEBUG) {
                return $this->input_format($name, $text, '<div class="form-control-static" style="color:red">关联字段设置的表【'.$table.'】不存在</div>');
            }
            return $this->input_format($name, $text, '');
        }

        $value = $value ? trim($value, ',') : '';
        $mylist = [];
        if ($value && is_string($value)) {
            $arr = explode(',', $value);
            if ($arr) {
                $value = '';
                foreach ($arr as $a) {
                    $a = intval($a);
                    if ($a) {
                        $value.= ','.$a;
                    }
                }
                if ($value) {
                    $value = trim($value, ',');
                    $ids = array_values(array_filter(array_map('intval', explode(',', $value))));
                    $mylist = [];
                    if ($ids) {
                        $rows = \Phpcmf\Service::M()->db->table($table)->whereIn('id', $ids)->get();
                        $rows = $rows ? $rows->getResultArray() : [];
                        $map = [];
                        foreach ($rows as $r) {
                            $map[(int) $r['id']] = $r;
                        }
                        foreach ($ids as $id) {
                            if (isset($map[$id])) {
                                $mylist[] = $map[$id];
                            }
                        }
                    }
                }
            }
		}

        $tpl = is_file(MYPATH.'View/api_join_field_'.$field['fieldname'].'.html') ? MYPATH.'View/api_join_field_'.$field['fieldname'].'.html' : COREPATH.'View/api_join_field.html';
        if (!is_file($tpl)) {
            if (CI_DEBUG) {
                return $this->input_format($name, $text, '<div class="form-control-static" style="color:red">模板文件【'.$tpl.'】不存在</div>');
            }
            return $this->input_format($name, $text, '');
        }
        $code = file_get_contents($tpl);
        if (!$code) {
            if (CI_DEBUG) {
                return $this->input_format($name, $text, '<div class="form-control-static" style="color:red">模板文件【'.$tpl.'】内容为空</div>');
            }
            return $this->input_format($name, $text, '');
        }
        $file = \Phpcmf\Service::V()->code2php($code);
        ob_start();
        require $file;
        $str = ob_get_clean();

        $str.= $tips;
        $js = \Phpcmf\Service::L('js_packer');
        $str.= $js->pack('
		<script type="text/javascript">
		var dr_join_'.$name.'_btn = null;
		function dr_join_body_'.$name.'(btn) {
		    var $box = btn ? $(btn).closest(".scroller_'.$name.'_files") : $(".scroller_'.$name.'_files").first();
		    return $box.find("tbody.scroller_body").first();
		}
		function dr_join_len_'.$name.'(btn) {
		    var n = 0, seen = {}, $body = dr_join_body_'.$name.'(btn || dr_join_'.$name.'_btn);
		    $body.children("tr").each(function(){
		        var id = $(this).attr("id");
		        if (id && id.indexOf("dr_items_'.$name.'_") === 0 && !seen[id]) {
		            seen[id] = 1;
		            n++;
		        }
		    });
		    return n;
		}
		function dr_join_sortable_'.$name.'(btn) {
		    var $body = dr_join_body_'.$name.'(btn);
		    if ($body.data("ui-sortable")) {
		        return;
		    }
		    $body.sortable({
		        items: "> tr",
		        axis: "y",
		        containment: "parent",
		        helper: function(e, tr) {
		            var $originals = tr.children();
		            var $helper = tr.clone();
		            $helper.children().each(function(index) {
		                $(this).width($originals.eq(index).width());
		            });
		            return $helper;
		        }
		    });
		}
        dr_slimScroll_init(".scroller_'.$name.'_files", 300);
        dr_join_sortable_'.$name.'($(".scroller_'.$name.'_files").first());
		function dr_add_join_'.$name.'(btn) {
		    dr_join_'.$name.'_btn = btn;
		    var len = dr_join_len_'.$name.'(btn);
		    if (len >= '.$limit.') {
		        dr_tips(0, "'.dr_lang('关联数量不得超过%s个', $limit).'");
		        return;
		    }
		    var url = "'.dr_web_prefix('index.php?s=api&c=api&m=join&fid=').$field['id'].'&is_iframe=1";
            layer.open({
                type: 2,
                title: \'<i class="fa fa-cog"></i> '.dr_lang($field['name']).'\',
                fix:true,
                shadeClose: true,
                shade: 0,
                area: '.$area.',
                btn: ["'.dr_lang('关联').'"],
                success: function (json) {
                    if (json.code == 0) {
                        layer.close();
                        dr_tips(json.code, json.msg);
                    }
                },
                yes: function(index, layero){
                    var body = layer.getChildFrame(\'body\', index);
                    var $joinBody = dr_join_body_'.$name.'(dr_join_'.$name.'_btn);
                     // 延迟加载
                    var loading = layer.load(2, {
                        time: 10000
                    });
                    $.ajax({type: "POST",dataType:"json", url: url, data: $(body).find(\'#myform\').serialize(),
                        success: function(json) {
                            layer.close(loading);
                            if (json.code == 1) {
                                layer.close(index);
                                var len = dr_join_len_'.$name.'(dr_join_'.$name.'_btn);
                                if (len + json.data.ids.length > '.$limit.') {
                                    dr_tips(0, "'.dr_lang('关联数量超限').'");
                                    return;
                                }
                                for(var i in json.data.ids){
                                    var vid = json.data.ids[i];
                                    if (typeof vid != "undefined") {
                                        if($joinBody.find("#dr_items_'.$name.'_"+vid).length>0) {
                                          dr_tips(0, "'.dr_lang('已经存在').'");
                                          return;
                                        }
                                        if (dr_join_len_'.$name.'(dr_join_'.$name.'_btn) >= '.$limit.') {
                                            dr_tips(0, "'.dr_lang('关联数量超限').'");
                                            return;
                                        }
                                    }
                                }
                                 $joinBody.append(json.data.html);
                                dr_slimScroll_init(".scroller_'.$name.'_files", 300);
                                dr_tips(1, json.msg);
                            } else {
                                dr_tips(0, json.msg);
        
                            }
                            return false;
                        }
                    });
                    
                    return false;
                },
                content: url
            });
		
			
		}
		</script>', 0);
		
		return $this->input_format($name, $text, $str);
	}

    /**
     * 字段表单显示
     *
     * @param	string	$field	字段数组
     * @param	array	$value	值
     * @return  string
     */
    public function show($field, $value = null) {

        $cname = ($field['setting']['option']['title'] ? $field['setting']['option']['title'] : dr_lang('主题'));
        $value = @trim($value, ',');
        $mylist = [];
        $is_show = 1;
        $table = isset($field['setting']['option']['table']) ? $field['setting']['option']['table'] : '';
        if ($value && is_string($value) && $table) {
            $arr = explode(',', $value);
            if ($arr) {
                $value = '';
                foreach ($arr as $a) {
                    $a = intval($a);
                    if ($a) {
                        $value.= ','.$a;
                    }
                }
                if ($value) {
                    $value = trim($value, ',');
                    $ids = array_values(array_filter(array_map('intval', explode(',', $value))));
                    $mylist = [];
                    if ($ids) {
                        $rows = \Phpcmf\Service::M()->db->table($table)->whereIn('id', $ids)->get();
                        $rows = $rows ? $rows->getResultArray() : [];
                        $map = [];
                        foreach ($rows as $r) {
                            $map[(int) $r['id']] = $r;
                        }
                        foreach ($ids as $id) {
                            if (isset($map[$id])) {
                                $mylist[] = $map[$id];
                            }
                        }
                    }
                }
            }
        }

        $tpl = $field['fieldname'];
        $file = \Phpcmf\Service::V()->code2php(
            file_get_contents(is_file(MYPATH.'View/api_join_field_'.$tpl.'.html') ? MYPATH.'View/api_join_field_'.$tpl.'.html' : COREPATH.'View/api_join_field.html')
        );
        ob_start();
        require $file;
        $str = ob_get_clean();

        return $this->input_format($field['fieldname'], $field['name'], $str);
    }
}