<?php

namespace app\admin\model;

use think\Db;
use think\Model;

class PostsModelx extends Model
{
    // 表名
    protected $name = 'PostsModelx';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;

    // 追加属性
    protected $append = [

    ];

    public static function getTypeList()
    {
        $typeList = [
            'string'   => __('String'),
            'text'     => __('Text'),
            'richtext'     => __('Richtext'),
            'number'   => __('Number'),
            'datetime' => __('Datetime'),
            'select'   => __('Select'),
            'selects'  => __('Selects'),
            'image'    => __('Image'),
            'images'   => __('Images'),
            'file'     => __('File'),
            'files'    => __('Files'),
            'checkbox' => __('Checkbox'),
            'radio'    => __('Radio'),
        ];
        return $typeList;
    }

    /**
     * 校验规则名称
     */
    public static function getRules(){
        return [
            "required" => __('Required'),
            "digits"=>"数字",
            "letters"=>"字母",
            "date"=>"日期",
            "time"=>"时间",
            "email"=>"邮箱",
            "url"=>"网址",
            "qq"=>"QQ号",
            "IDcard"=>"身份证",
            "tel"=>"座机电话",
            "mobile"=>"手机号",
            "zipcode"=>"邮编",
            "chinese"=>"中文",
            "username"=>"用户名",
            "password"=>"密码"
        ];
    }

    /**
     * 保存模型数据
     * @param string $modelname 模型
     * @param int $archiveid 文章ID
     * @param array $params 表单数据
     * @return bool
     */
    public static function saveExtraForm($modelname='', $archiveid=0, $params=[])
    {
        if (empty($modelname) || $archiveid==0 || empty($params)) return false;

        $mod = self::get(['name' => $modelname]);
        if (!$mod) return false;

        $fields = json_decode($mod['extra'],true);

        //格式化模型数据
        foreach ($fields as $k => $v) {
            if ($v['type']=='file' || $v['type']=='files'){
                foreach($params[$v['field']] as $item=>&$val){
                    if($val['url']==''){
                        unset($params[$v['field']][$item]);
                    }
                }
                $params[$v['field']] = empty($params[$v['field']])? ''
                        : json_encode($params[$v['field']], JSON_UNESCAPED_UNICODE);
            }
        }

        foreach ($params as $k => &$v)
        {
            $v = is_array($v) ? implode(',', $v) : $v;
        }
        $params['item_id'] = $archiveid ;

        $row = model('extra'.$modelname)->get(['item_id'=>$archiveid]);
        if($row) {
            $row->allowField(true)->save($params);
        }else {
            model('extra'.$modelname)->allowField(true)->save($params);
        }

        return true;
    }

    /**
     * 生成模型表单
     * @param $modelname 模型名称
     * @param $archiveid 文章ID
     * @return string
     */
    public static function getExtraForm($modelname, $archiveid=null)
    {
        $mod = self::get(['name'=>$modelname]);
        if(!$mod) return '';
        if(!isset($mod['extra']) || empty($mod['extra'])) return '';

        $row = empty($archiveid)? null :
            model('extra'.$mod['name'])->get(['item_id'=> $archiveid]);

        $params = json_decode($mod['extra'], true);

        $controls = $controlid = $cssname = '';
        $controlPrefix = 'row';
        $btnUpload = __('Upload'); $btnChoose = __('Choose'); $btnAppend = __('Append');
        $input = '<input type="%s" id="c-%s" name="'. $controlPrefix . '[%s]" value="%s" class="form-control %s" data-rule="%s" data-tip="%s" %s>';
        $textarea = '<textarea name="'. $controlPrefix . '[%s]" id="c-%s" class="form-control %s" data-rule="%s" data-tip="%s" %s>%s</textarea>';
        $checkbox = '<label for="c-%s"><input type="checkbox" id="c-%s" name="'. $controlPrefix . '[%s][]" value="%s" %s>%s</label>';
        $radio = '<label for="c-%s"><input type="radio" id="c-%s" name="'. $controlPrefix . '[%s]" value="%s" %s>%s</label>';

        $html = [];
        foreach ($params as $k => $v){
            if(isset($v['status']) && $v['status']=='hidden') continue;
            $defaultValue = !isset($row[$v['field']]) ? $v['value']
                    : empty($row[$v['field']]) ? $v['value'] : $row[$v['field']] ;

            $controlid = $v['field'] . substr(md5($v['field'].microtime()),0,6);

            switch(strtolower($v['type'])){
                case 'string':
                case 'number':
                case 'datetime':
                    $cssname = $v['type']=='datetime'?'datetimepicker':'';
                    $controls = sprintf($input, ($v['type']=='number'?'number':'text'), $controlid, $v['field'], $defaultValue, $cssname, $v['rule'], $v['tip'], $v['extend']);
                    break;
                case 'text':
                case 'richtext':
                    $cssname = $v['type']=='richtext'?'editor':'';
                    $controls = sprintf($textarea, $v['field'], $controlid,  $cssname, $v['rule'], $v['tip'], $v['extend'], $defaultValue);
                    break;
                case  'checkbox':
                case  'radio':
                    $items = explode('||', $v['vars']);
                    $controls='';
                    $defaultValue=explode(',',$defaultValue);
                    for($i=0;$i<count($items);$i++) {
                        if(empty($items[$i])) continue;
                        if(!strpos($items[$i], "=")) $items[$i].="=";
                        $item = explode('=',$items[$i]);
                        $item[1]= empty($item[1])?$item[0]:$item[1];
                        if(is_array($defaultValue)) {
                            $isChecked = in_array($item[1], $defaultValue) ? ' checked' : '';
                        }else{
                            $isChecked = $item[1]==$defaultValue ? ' checked' : '';
                        }
                        $controlid = $v['field'].'-'.substr(md5($item[1]),0,6);
                        $controls .= sprintf(${$v['type']}, $controlid, $controlid, $v['field'], $item[1], $v['extend'].$isChecked, $item[0]);
                    }
                    $controlid = 'none';
                    $controls = sprintf('<div class="%s">%s</div>', $v['type'], $controls);
                    break;
                case 'select':
                case  'selects':
                    $items = explode('||', $v['vars']);
                    $options = '';
                    $defaultValue=explode(',',$defaultValue);
                    for($i=0;$i<count($items);$i++) {
                        if(empty($items[$i])) continue;
                        if(!strpos($items[$i], "=")) $items[$i].="=";
                        $item = explode('=',$items[$i]);
                        $item[1]= empty($item[1])?$item[0]:$item[1];
                        if(is_array($defaultValue)) {
                            $isChecked = in_array($item[1], $defaultValue) ? ' selected' : '';
                        }else{
                            $isChecked = $item[1]==$defaultValue ? ' selected' : '';
                        }
                        $options .= sprintf('<option value="%s" %s>%s</option>', $item[1], $isChecked, $item[0]);
                    }

                    $extend = $v['type']=='selects'?'multiple ':' ';
                    $extend .= $v['extend'];
                    $controls = <<<EOF
<select id="c-{$controlid}" name="{$controlPrefix}[{$v['field']}]" class="form-control selectpicker" data-tip="{$v['tip']}" {$extend}>
    {$options}
</select>
EOF;
                    break;
                case  'image':
                case  'images':
                    $multi = $v['type']=='image'? 'false' : 'true';
                    $controls = <<<EOF
<div class="form-inline">
    <input id="c-{$controlid}" class="form-control" size="45" name="{$controlPrefix}[{$v['field']}]" type="text" value="{$defaultValue}" data-tip="{$v['tip']}">
    <span><button type="button" id="plupload-{$controlid}" class="btn btn-danger plupload" data-input-id="c-{$controlid}" data-multiple="{$multi}" data-mimetype="image/*" data-preview-id="{$controlid}-preview"><i class="fa fa-upload"></i> {$btnUpload}</button></span>
    <span><button type="button" id="fachoose-{$controlid}" class="btn btn-primary fachoose" data-input-id="c-{$controlid}" data-multiple="{$multi}" data-mimetype="image/*"><i class="fa fa-list"></i> {$btnChoose}</button></span>
    <ul class="row list-inline plupload-preview" id="{$controlid}-preview"></ul>
</div>
EOF;

                    break;
                case 'file':
                case 'files':
                    $mimetype = '*/*';
                    $lab1 = __('Title'); $lab2 = __('File');

                    $edit = '';
                    $index=0;
                    if (!empty($defaultValue)){
                        $defaultValue=json_decode($defaultValue, true);
                        foreach($defaultValue as $key => $file)
                        {
                            $controlid = substr($v['type'],0,1).substr(md5($file['id'].microtime()),0,6);

                            if ($v['type']=='file'){
                                $btns = <<<EOF
            <span><button type="button" id="plupload-pa-{$controlid}0" class="btn btn-danger plupload" data-input-id="pa-{$controlid}-0" data-attach-id="pa-{$controlid}-i-0" data-title-id="pa-{$controlid}-t-0" data-mimetype="{$mimetype}" data-multiple="false" data-upload-success="productattachcallback"><i class="fa fa-upload"></i> {$btnUpload}</button></span>
            <span><button type="button" id="fachoose-pa-{$controlid}0" class="btn btn-primary fachoose" data-input-id="pa-{$controlid}-0" data-attach-id="pa-{$controlid}-i-0" data-title-id="pa-{$controlid}-t-0" data-mimetype="{$mimetype}" data-multiple="false"><i class="fa fa-list"></i> {$btnChoose}</button></span>
EOF;
                            }else {
                                $btns = <<<EOF
            <span class="btn btn-sm btn-danger btn-remove"><i class="fa fa-times"></i></span>
EOF;
                            }

                            $edit .= <<<EOF
        <dd class="form-inline">
            <input type="hidden" name="{$controlPrefix}[{$v['field']}][{$index}][id]" id="pa-{$controlid}-i-0" value="{$file['id']}" />
            <input type="text" name="{$controlPrefix}[{$v['field']}][{$index}][title]" id="pa-{$controlid}-t-0" class="form-control" value="{$file['title']}" size="23" />
            <input type="text" name="{$controlPrefix}[{$v['field']}][{$index}][url]" id="pa-{$controlid}-0" class="form-control" value="{$file['url']}" size="10"  />
            {$btns}
        </dd>
EOF;
                            $index++;
                        }
                    }
                    else {
                        $controlid = substr($v['type'],0,1).substr(md5(microtime()),0,5);
                        $edit = <<<EOF
        <dd class="form-inline">
            <input type="hidden" name="{$controlPrefix}[{$v['field']}][{$index}][id]" id="pa-{$controlid}-i-0" value="" />
            <input type="text" name="{$controlPrefix}[{$v['field']}][{$index}][title]" id="pa-{$controlid}-t-0" class="form-control" value="" size="23" />
            <input type="text" name="{$controlPrefix}[{$v['field']}][{$index}][url]" id="pa-{$controlid}-0" class="form-control" size="10"  />
            <span><button type="button" id="plupload-pa-{$controlid}0" class="btn btn-danger plupload" data-input-id="pa-{$controlid}-0" data-attach-id="pa-{$controlid}-i-0" data-title-id="pa-{$controlid}-t-0" data-mimetype="{$mimetype}" data-multiple="false" data-upload-success="productattachcallback"><i class="fa fa-upload"></i> {$btnUpload}</button></span>
            <span><button type="button" id="fachoose-pa-{$controlid}0" class="btn btn-primary fachoose" data-input-id="pa-{$controlid}-0" data-attach-id="pa-{$controlid}-i-0" data-title-id="pa-{$controlid}-t-0" data-mimetype="{$mimetype}" data-multiple="false"><i class="fa fa-list"></i> {$btnChoose}</button></span>
        </dd>
EOF;
                    }

                    $append = $v['type']=='files'?'<dd><a href="javascript:;" class="btn-append btn btn-sm btn-success"><i class="fa fa-plus"></i>'.$btnAppend.'</a></dd>':'';

                    $controls = <<<EOF
<div class="form-inline">
    <dl class="fieldlist" rel="{$index}" data-name="{$controlPrefix}[{$v['field']}]">
        <dd>
            <ins>{$lab1}</ins>
            <ins>{$lab2}</ins>
        </dd>
        {$edit}
        {$append}
    </dl>
</div>
EOF;

                    $controlid = 'none';
                    break;
            }

            $html[] = <<<EOF
            <div class="form-group">
                <label for="c-{$controlid}" class="control-label col-xs-12 col-sm-2">{$v['fieldname']}:</label>
                <div class="col-xs-12 col-sm-8">
                    {$controls}
                </div>
            </div>
EOF;
        }
        return sprintf('<div class="blockmodel" id="model_%s">%s</div>', $mod['name'], implode('',$html));
    }






}
