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

class Cmsfields extends Model
{
	protected $autoWriteTimestamp = false;
	protected $json = ['config'];
    protected $jsonAssoc = true;
	// 添加
	public function add($data)
	{
		try{
			$this->createFields($data);
			$result = $this->allowField(true)->save($data);
			if($result) {
				return ['code'=>1 ,'msg'=>lang('addtrue')];
			} else {
				return ['code'=>0 ,'msg'=>lang('addfalse')];
			}
		} catch (\Exception $e) {
			return ['code'=>0 ,'msg'=>$e->getMessage()];
		}
	}

	// 编辑
	public function edit($data)
	{
		try{
			$result = $this->allowField(true)->isUpdate(true)->save($data);
			if($result) {
				return ['code'=>1 ,'msg'=>lang('edittrue')];
			} else {
				return ['code'=>0 ,'msg'=>lang('editfalse')];
			}
		} catch (\Exception $e) {
			return ['code'=>0 ,'msg'=>$e->getMessage()];
		}
	}

	// 删除
	public function del($data)
	{
		try{
			$cmsmodels_id = $data['cmsmodels_id'];
			$cmsmodel = new Cmsmodels();
			$cmsmodelinfo = $cmsmodel->get($cmsmodels_id)->toArray();
			$tablename = config('database.prefix').$cmsmodelinfo['tablename'];
			$fieldslist = $data['data'];
			if(strtolower(config('database.type')) == 'mysql') {
				foreach ($fieldslist as $v) {
					$field = $v['name'];
					Db::execute("ALTER TABLE `$tablename` DROP `$field`");
					$this->whereId($v['id'])->delete();
				}
			} else {
				// 创建临时表
				$newtable = $cmsmodelinfo['tablename'] = 'temp_'.time();
				$cmsmodel->createModelTable($cmsmodelinfo);
				// 创建自定义字段
				$except_fieldsid = array_column($fieldslist, 'id');
				// 删除字段信息
				$this->destroy($except_fieldsid);
				$newdiy_fields = $this->whereCmsmodelsId($cmsmodels_id)->select()->toArray();
				$namespace = 'app\\common\\model\\'.$cmsmodelinfo['classname'];
				$modelFields = (new $namespace)->getTableFields();
				if(!empty($newdiy_fields)) {
					foreach ($newdiy_fields as $v) {
						$this->createFields(['tablename' => config('database.prefix').$cmsmodelinfo['tablename'],'type' => $v['type'] ,'name' => $v['name']]);
					}
				}
				foreach ($modelFields as $kk => $vk) {
					if(in_array($vk,array_column($fieldslist, 'name'))) unset($modelFields[$kk]);
				}
				$new_fields = implode(',',array_merge($modelFields));
				$newtable = config('database.prefix').$newtable;
				Db::execute("INSERT INTO `$newtable`($new_fields) SELECT $new_fields FROM $tablename;");
				Db::execute("DROP TABLE `$tablename`;");
				Db::execute("ALTER TABLE `$newtable` RENAME TO `$tablename`;");
				
			}
			// $id = is_array($id) ? $id : array($id);
			// foreach ($id as $v) {
			// 	$info = $this->get($v);
			// 	$model = Cmsmodels::get($info->cmsmodels_id);
			// 	$tablename = config('database.prefix').$model->tablename;
			// 	$field = $info->getData('name');
			// 	if(strtolower(config('database.type')) == 'sqlite') {
			// 		$namespace = 'app\\common\\model\\'.$model->classname;
			// 		$modelFields = (new $namespace)->getTableFields();
			// 		unset($modelFields[array_search($field,$modelFields)]);
			// 		$fields = implode(',',$modelFields);
			// 		Db::execute("CREATE TABLE `temp` AS SELECT $fields FROM $tablename WHERE 1 = 1;");
			// 		Db::execute("DROP TABLE `$tablename`;");
			// 		Db::execute("ALTER TABLE `temp` RENAME TO `$tablename`;");
			// 	} else {
			// 		Db::execute("ALTER TABLE `$tablename` DROP `$field`");
			// 	}
			// 	$info->delete();
			// }
			return ['code'=>1 ,'msg'=>lang('deltrue')];
		} catch (\Exception $e) {
			return ['code'=>0 ,'msg'=>$e->getMessage()];
		}
	}

	// 关联
	public function cmsmodels()
	{
		return $this->belongsTo('Cmsmodels');
	}

	// 字段操作
	public function createFields($data)
	{
		$tablename = $data['tablename'];
		$type = $data['type'];
		$field = $data['name'];
        switch ($type) {
			case 'input': //文本框
			case 'select': //下拉
			case 'radio': //单选
			case 'checkbox': //多选
			case 'transfer': //穿梭框
			case 'color': //颜色
			case 'img': //单图
			case 'video': //单视频
			case 'file': //单文件
			case 'range': //时间段
			case 'hidden': //隐藏域
			case 'slider': //滑块
				if(strtolower(config('database.type') == 'sqlite')) {
					$sql = "ALTER TABLE `$tablename` ADD COLUMN `$field` TEXT NULL";
				} else {
					$sql = "ALTER TABLE `$tablename` ADD `$field` VARCHAR(255) NULL AFTER `site_id`";
				}
				break;

			case 'integer': //整数
			case 'datetime': //日期
				if(strtolower(config('database.type') == 'sqlite')) {
					$sql = "ALTER TABLE `$tablename` ADD COLUMN `$field` BIGINT NULL";
				} else {
					$sql = "ALTER TABLE `$tablename` ADD `$field` BIGINT NULL AFTER `site_id`";
				}
				break;

			case 'decimal': //小数
				if(strtolower(config('database.type') == 'sqlite')) {
					$sql = "ALTER TABLE `$tablename` ADD COLUMN `$field` DECIMAL(10,2) NULL";
				} else {
					$sql = "ALTER TABLE `$tablename` ADD `$field` DECIMAL(10,2) NULL AFTER `site_id`";
				}
				break;

			case 'textarea': //文本域
			case 'ueditor': //编辑器
			case 'ueditors': //多编辑器
			case 'layedit': //lay编辑器
			case 'imgs': //多图
			case 'files': //多文件
				if(strtolower(config('database.type') == 'sqlite')) {
					$sql = "ALTER TABLE `$tablename` ADD COLUMN `$field` TEXT NULL";
				} else {
					$sql = "ALTER TABLE `$tablename` ADD `$field` TEXT NULL AFTER `site_id`";
				}
				break;

			case 'switch': //开关
				if(strtolower(config('database.type') == 'sqlite')) {
					$sql = "ALTER TABLE `$tablename` ADD COLUMN `$field` INT NULL";
				} else {
					$sql = "ALTER TABLE `$tablename` ADD `$field` INT NULL AFTER `site_id`";
				}
				break;
		}
		Db::execute($sql);
	}
}