<?php
/**
* @author 龙虾 <15108148@qq.com>
* @version 2.0 2020-06-30
* @copyright 睿谷信息 <www.rgxx.com>
*/
namespace app\admin\controller;
use think\Controller;
use Request;
use app\admin\model\Cmsmodels;
use app\admin\model\Cmsfields;

class Cmsmodel extends Base
{
	// 模型列表
	public function index()
	{
		if(Request::isPost())
		{
			$data = Cmsmodels::when(!empty(Request::post('type')),function($query){
				$query->whereType(Request::post('type'));
			})->withAttr('hasClass',function($value,$data){
				return class_exists('app\\common\\model\\'.$data['classname']);
			})->order('torder')->append(['hasClass'])->paginate(Request::post('limit/d'))->toArray();
			return json(['code'=>0,'msg'=>lang('getdatatrue'),'data'=>$data['data'],'count'=>$data["total"]]);
		}
		return $this->fetch('');
	}

	// 添加
	public function add()
	{
		if(Request::isPost()) {
			$data = Request::post();
			$this->checkData($data);
			$result = (new Cmsmodels())->add($data);
			adminlog(2,'新增('.Cmsmodels::getLastsql().')',$result['code'] == 1?1:0);
			if ($result['code'] == 1) {
				$this->success($result['msg']);
			} else {
				$this->error($result['msg']);
			}
		}
		return $this->fetch();
	}

	// 编辑
	public function edit($id)
	{
		$info = Cmsmodels::get($id);
		if(empty($info)) $this->error(lang('norecord'));
		if(Request::isPost()) {
			$data = Request::post();
			$this->checkData($data);
			if(!empty($data['attamodel_id'])) {
				if (Cmsmodels::whereAttamodelId($data['attamodel_id'])->where('id','<>',$data['id'])->count() > 0) $this->error('附属表已被其他模型关联');
			}
			$result = (new Cmsmodels())->edit($data);
			adminlog(2,'编辑('.Cmsmodels::getLastsql().')',$result['code'] == 1?1:0);
			if ($result['code'] == 1) {
				$this->success($result['msg']);
			} else {
				$this->error($result['msg']);
			}
		}
		$attatables = Cmsmodels::whereType(5)->select();
		return $this->fetch('',compact('info','attatables'));
	}

	// 删除
	public function del()
	{
		if(Request::isPost()) {
			$data = Request::post();
			$result = (new Cmsmodels())->del($data['id']);
			adminlog(2,'删除('.Cmsmodels::getLastsql().')',$result['code'] == 1?1:0);
			if ($result['code'] == 1) {
				$this->success($result['msg']);
			} else {
				$this->error($result['msg']);
			}
		}
	}

	// 修复
	public function repair()
	{
		if(Request::isPost()) {
			$data = Request::only(['tablename','classname','type','name']);
			$result = (new Cmsmodels())->creatModelfile($data);
			if ($result) {
				$this->success('修复成功');
			} else {
				$this->error('修复失败，请检查common/model文件夹权限');
			}
		}
		return $this->fetch();
	}

	// 复制模型
	public function copy($cmsmodels_id)
	{
		$info = Cmsmodels::get($cmsmodels_id);
		if(empty($info)) $this->error(lang('norecord'));
		if(Request::isPost()) {
			$data = Request::post();
			$data['type'] = $info['type'];
			$this->checkData($data);
			$result = (new Cmsmodels())->copy($data);
			if ($result['code'] == 1) {
				$this->success($result['msg']);
			} else {
				$this->error($result['msg']);
			}
		}
		return $this->fetch('',compact('info'));
	}

	// 清除数据
	public function clear()
	{
		if(Request::isPost()) {
			$data = Request::post();
			$result = (new Cmsmodels())->clear($data['id']);
			adminlog(2,'删除('.Cmsmodels::getLastsql().')',$result['code'] == 1?1:0);
			if ($result['code'] == 1) {
				$this->success($result['msg']);
			} else {
				$this->error($result['msg']);
			}
		}
	}

	// 表单配置
	public function config($model_id)
	{
		$modelinfo = Cmsmodels::get($model_id);
		$config = $modelinfo->config;
		//halt($config);
		if(empty($modelinfo) || $modelinfo['modeltype'] != 3) $this->error(lang('norecord'));
		if(Request::isPost()) {
			$data = Request::post();
            unset($data[config('app.admin.token_name')]);
            $modelinfo->config = $data;
            $result = $modelinfo->save();
            if ($result) {
				$this->success(lang('edittrue'));
			} else {
				$this->error(lang('editfalse'));
			}
		}
		return $this->fetch('',compact('config'));
	}

	// 字段列表
	public function fieldslist()
	{
		if(Request::isPost()) {
			$data = Cmsfields::when(!empty(Request::post('cmsmodels_id')),function($query){
				$query->whereCmsmodelsId(Request::post('cmsmodels_id'));
			})->withAttr('typeinfo',function($value,$data){
				return config('fieldtype.list')[$data['type']];
			})->append(['typeinfo'])->with('cmsmodels')->when(!empty(Request::post('order')),function($query){
				$query->order(Request::post('order.field'),Request::post('order.type'));
			},function($query){
				$query->order('torder');
			})->paginate(Request::post('limit/d'))->toArray();
			return json(['code'=>0,'msg'=>lang('getdatatrue'),'data'=>$data['data'],'count'=>$data["total"]]);
		}
		return $this->fetch();
	}

	// 添加字段
	public function addfields($cmsmodels_id)
	{
		$modelinfo = Cmsmodels::get($cmsmodels_id);
		if(empty($modelinfo)) $this->error(lang('norecord'));
		if(Request::isPost()) {
			$data = Request::post();
			$this->checkFieldsData($data);
            // unset($data[config('app.admin.token_name')]);
            if(in_array($data['name'],$this->getDiyModelFields($modelinfo['classname']))) $this->error('字段已存在');
            $data['tablename'] = config('database.prefix').$modelinfo['tablename'];
            $result = (new Cmsfields())->add($data);
            adminlog(2,'新增('.Cmsfields::getLastsql().')',$result['code'] == 1?1:0);
            if ($result['code'] == 1) {
				$this->success($result['msg']);
			} else {
				$this->error($result['msg']);
			}
		}
		return $this->fetch('',compact('modelinfo'));
	}

	// 编辑字段
	public function editfields($id)
	{
		$info = Cmsfields::withAttr('typeinfo',function($value,$data){
			return config('fieldtype.list')[$data['type']];
		})->get($id);
		if(empty($info)) $this->error(lang('norecord'));
		if(Request::isPost()) {
			$data = Request::post();
			$this->checkFieldsData($data);
            // unset($data[config('app.admin.token_name')]);
            $result = (new Cmsfields())->edit($data);
            adminlog(2,'编辑('.Cmsfields::getLastsql().')',$result['code'] == 1?1:0);
            if ($result['code'] == 1) {
				$this->success($result['msg']);
			} else {
				$this->error($result['msg']);
			}
		}
		return $this->fetch('',compact('info'));
	}

	// 删除字段
	public function delfields()
	{
		if(Request::isPost()) {
			$data = Request::post();
			$result = (new Cmsfields())->del($data);
			adminlog(2,'删除('.Cmsfields::getLastsql().')',$result['code'] == 1?1:0);
			if ($result['code'] == 1) {
				$this->success($result['msg']);
			} else {
				$this->error($result['msg']);
			}
		}
	}

	// 验证
	private function checkData($data)
	{
		$validate = new \app\admin\validate\Cmsmodels;
		if(!$validate->check($data)) {
			$this->error($validate->getError());
		}
	}

	// 字段验证
	private function checkFieldsData($data)
	{
		if(!isset($data['list_switch'])) {
			$validate = new \app\admin\validate\Cmsfields;
			if(!$validate->check($data)) {
				$this->error($validate->getError());
			}
		}
	}

	// 自定义模型字段验证
	private function getDiyModelFields($classname)
	{
		$namespace = 'app\\common\\model\\'.$classname;
		return (new $namespace)->getTableFields();
	}
}