<?php

namespace app\admin\controller\posts;

use app\common\controller\Backend;

use think\Exception;
use think\Db;
use think\exception\ErrorException;
/**
 * 模型管理
 *
 * @icon fa fa-circle-o
 */
class Modelx extends Backend
{
    
    /**
     * Model模型对象
     */
    protected $model = null;
    protected $noNeedRight = ['rulelist'];
    
    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('PostsModelx');

    }

    /**
     * Index
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('pkey_name'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->where($where)
                    ->field('extra', true)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
    	$this->view->assign('typeList', $this->model->getTypeList());
        return $this->view->fetch();
    }
    
    /**
     * Edit
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                try
                {
                    //是否采用模型验证
                    if ($this->modelValidate)
                    {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false)
                    {
                        $this->success();
                    }
                    else
                    {
                        $this->error($row->getError());
                    }
                }
                catch (think\exception\PDOException $e)
                {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = json_decode($row['extra'], true);
        unset($row['extra']);
        $row['extra']=$params;
        $this->view->assign("row", $row);
        $this->view->assign('typeList', $this->model->getTypeList());
        return $this->view->fetch();
    }


    /**
     * 字段设置
     */
    public function fieldset()
    {
        if($this->request->isAjax()) {
            $ids = $this->request->post('ids/a');
            $fieldset = $this->request->post('fieldset');
            if(!empty($fieldset)){
                $row = $this->model->get($ids);
                if(!$row)
                    $this->error(__('No Results were found'));

                $modelx = $row['name'];
                $modelname = $row['title'];
                $tablename = config('database.prefix') . 'extra' . $row->name;

                //do check && make sql
                $json = json_decode($fieldset,true);
                $sql = $cols = [];
                foreach ($json as $k=>$v){
                    switch (strtolower($v['type'])){
                        case "string":
                            $v['length'] = isset($v['length']) ? $v['length']>0 && $v['length']<256 ? $v['length'] : 255: 255;
                            $cols[$v['field']] = 'varchar(' . $v['length'] . ')';
                            $sql[$v['field']] = "`". $v['field'] . "` VARCHAR(" . $v['length'] . ") NOT NULL DEFAULT '' COMMENT '". $v['fieldname'] . "' ";
                            break;
                        case "number":
                            $v['float'] = isset($v['float']) ? $v['float']<=0? 0 : $v['float']<3 ? $v['float']: 2: 0;
                            if($v['float']==0) {
                                $sql[$v['field']] = "`" . $v['field'] . "` INT(10) NOT NULL DEFAULT '0' COMMENT '". $v['fieldname'] . "' ";
                                $cols[$v['field']] = 'int(10)';
                            }else{
                                $cols[$v['field']] = 'float(10,'.$v['float'].')';
                                $sql[$v['field']] = "`" . $v['field'] . "` FLOAT(10,". $v['float'] . ") NOT NULL DEFAULT '0.0' COMMENT '". $v['fieldname'] . "' ";
                            }
                            break;
                        case "datetime":
                            $sql[$v['field']] = "`". $v['field'] . "` INT(10) NOT NULL DEFAULT '0' COMMENT '". $v['fieldname'] . "' ";
                            $cols[$v['field']] = 'int(10)';
                            break;
                        case "textarea": case"richtext": case"editor":
                            $sql[$v['field']] = "`". $v['field'] . "` TEXT NOT NULL DEFAULT '' COMMENT '". $v['fieldname'] . "' ";
                            $cols[$v['field']] = 'text';
                            break;
                        case "images": case"files":
                            $sql[$v['field']] = "`". $v['field'] . "` TEXT NOT NULL DEFAULT '' COMMENT '". $v['fieldname'] . "' ";
                            $cols[$v['field']] = 'text';
                            break;
                        case "image":  case "file":
                            $sql[$v['field']] = "`". $v['field'] . "` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '". $v['fieldname'] . "' ";
                            $cols[$v['field']] = 'varchar(255)';
                            break;
                        case "select": case "selects": case "checkbox": case"radio":
                            $sql[$v['field']] = "`". $v['field'] . "` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '". $v['fieldname'] . "' ";
                            $cols[$v['field']] = 'varchar(255)';
                            break;
                        default:
                            break;
                    }
                }
                //save
                $result = $row->save(['extra'=>$fieldset]);
                if ($result === false){
                    $this->error($row->getError());
                }
                unset($row);

                if(Db::query("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='". config('database.database') . "' AND TABLE_NAME='". $tablename . "';"))
                {
                    $columns=[];
                    foreach (Db::query("SHOW COLUMNS FROM `" . $tablename . "`;") as $k=>$v){
                        if($v['Field']!='id' && $v['Field']!='item_id'){
                            $columns[$v['Field']] = $v['Type'];
                        }
                    }

                    $arr = array_diff_key($cols, $columns);
                    $alterSql = [];
                    foreach ($arr as $k=>$v){
                        $alterSql[$k] = " ADD COLUMN " . $sql[$k];
                        unset($cols[$k]);
                    }
                    $arr=array_intersect_assoc($columns, $cols);
                    foreach ($arr as $k => $v) {
                        unset($cols[$k]);
                        unset($columns[$k]);
                    }
                    foreach($columns as $k=>$v){
                        if(isset($cols[$k])) {
                            $alterSql[$k] = " MODIFY COLUMN " . $sql[$k] ;
                        } else {
                            $alterSql[$k] = " DROP COLUMN `" . $k . "` ";
                        }
                    }
                    $execSql = "ALTER TABLE `".$tablename."` ". join(',',$alterSql) . ";";
                }else {
                    $fieldset = join(", ", $sql);
                    $execSql = <<<EOF
CREATE TABLE IF NOT EXISTS `{$tablename}` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`item_id` int(10) unsigned NOT NULL DEFAULT '0',
{$fieldset},
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 COMMENT='{$modelname}模型';
EOF;
                }
                //echo $execSql;exit;
                try {
                    Db::execute($execSql);

                    $modname = ucfirst(str_replace(config('database.prefix'), '', $tablename));

                    $modclass = <<<EOF
<?php
namespace app\\common\\model;
use think\\Model;

class {$modname} extends Model
{
    protected \$name = '{$modname}';
}
EOF;

                    //创建模型
                    try{
                        file_put_contents(APP_PATH . 'common' . DS . 'model' . DS .$modname. '.php', $modclass);

                    }catch(\think\Exception $e){
                        $this->error($e->getMessage());
                    }

                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            }
        }
        
        //$this->view->assign("params", $params);
        $this->view->assign('typeList', $this->model->getTypeList());
        return $this->view->fetch();
    }

    /**
     * 修改字段状态
     */
    public function chgstatus($ids=null)
    {
        if ($this->request->isAjax())
        {
            $row = $this->model->get($ids);
            if (!$row)
                $this->error();

            if(empty($row['extra']))
                $this->error();

            $field = $this->request->post('field');
            $params = json_decode($row['extra'],true);

            foreach($params as $k => &$v){
                if($v['field']==$field){
                    $v['status'] = $v['status']=='hidden' ? 'normal' : 'hidden';
                }
            }
            $params = json_encode($params, JSON_UNESCAPED_UNICODE);

            $result = $row->save(['extra'=>$params]);
            if ($result !== false)
            {
                $this->success();
            }
            else
            {
                $this->error($row->getError());
            }
        }
    }

    public function rulelist()
    {
        $search = $this->request->post('searchValue');
        $rules = $this->model->getRules();
        if($search){
            $result[] = ['id'=> $search, 'name'=> $rules[$search]];
        }else {
            foreach ($rules as $k => $v) {
                $result[] = ['id' => $k, 'name' => $v];
            }
        }
        return ['list'=>$result];

    }

    /**
     * 检查模型名称是否可用
     */
    public function check()
    {
        $params = $this->request->post("row/a");
        if ($params)
        {

            $result = $this->model->get($params);
            if ($result!=false)
            {
                $this->error( __('Name already exist'));
            }
            else
            {
                $this->success();
            }
        }
        else
        {
            $this->error( __('Invalid parameters'));
        }
    }

    public function check_element_available()
    {
        if($this->request->isAjax()) {
            $modelid = $this->request->post('id');
            $val = $this->request->post('value');

            $m = $this->model->get($modelid);
            $tablename = config('database.prefix') . 'extra' . $m->name;

            if (Db::query("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='" . config('database.database') . "' AND TABLE_NAME='" . $tablename . "';")) {

                foreach (Db::query("SHOW COLUMNS FROM `" . $tablename . "`;") as $k => $v) {
                    if ($v['Field'] == $val) {
                        //return json(['error' => __('Field already exist')]);
                        $this->error(__('Field already exist'));
                    }
                }
            }
            //return json(['ok' => '']);
            $this->success();
        }
    }
}
