package com.huigou.uasp.model.controller;


import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.huigou.cache.SystemCache;
import com.huigou.data.domain.model.CommonDomainConstants;
import com.huigou.data.repository.GeneralRepository;
import com.huigou.uasp.annotation.ControllerMapping;
import com.huigou.uasp.bmp.fn.impl.OrgFun;
import com.huigou.uasp.client.CommonController;



import com.huigou.uasp.form.application.SafFormslistApplication;
import com.huigou.uasp.meta.domain.model.MetaData;
import com.huigou.uasp.model.application.DbTablesApplication;
import com.huigou.uasp.model.domain.model.DbTables;
import com.huigou.uasp.model.domain.model.TablesMeta;
import com.huigou.uasp.model.domain.query.DbTablesQueryRequest;
import com.huigou.uasp.model.repository.DbTablesRepository;
import com.huigou.uasp.model.repository.TablesMetaRepository;
import com.huigou.uasp.util.Utils;
import com.huigou.util.SDO;

/**
 * 
 * @author lxh
 * @date 2019年08月10日
 * @return
 * @Description 数据库设置的控制类
 */

@Controller
@ControllerMapping(value = "dbSettings")
public class DataBaseSettingsController extends CommonController{

	@Autowired
	private DbTablesRepository dbTablesRepository;
	
	@Autowired
	private TablesMetaRepository tablesMetaRepository;
	
	@Autowired
	private GeneralRepository generalRepository;
	 @Autowired
	 private OrgFun orgFun;
	 
	 Logger logger = Logger.getLogger(getClass());
	
	
	@Autowired
	DbTablesApplication dbTablesApplication;
	
	@Autowired
	SafFormslistApplication syfFormsApplication;
	
	
	@Override
	protected String getPagePath(){
		return "/formdesign/model/";
	}
		
	//跳转到数据库设置界面
	public String forwardDatabaseSettingsList(){
		 // Boolean isExpAndImp = false;
		 //    if (this.orgFun.hasManageType(this.getOperator().getPersonMemberId(), "mbExpAndImp")){
		 //   	  isExpAndImp = true;//有权限，
		  //    }else{
		 //   	  isExpAndImp = false;//无权限
		  //    }
		  //    this.putAttribute("isExpAndImp", isExpAndImp);
		return forward("databaseSettings");
	}
	
	/**
	 * 查询表名列表
	 * @return
	 */
	public String queryDbTables() {
		SDO sdo = this.getSDO();
		try {
			DbTablesQueryRequest queryRequest = sdo.toQueryRequest(DbTablesQueryRequest.class);
			Map<String, Object> data = this.dbTablesApplication.queryDbTables(queryRequest);
			return toResult(data);
		} catch (Exception e) {
			return error(e);
		}
	}
	
				
	/**
	 * 查询表
	 * @return
	 */
	public String slicedQueryDbTables() {
		SDO sdo = this.getSDO();
		DbTablesQueryRequest queryRequest = sdo.toQueryRequest(DbTablesQueryRequest.class);
		String parentId = sdo.getString(CommonDomainConstants.PARENT_ID_FIELD_NAME);
		Integer nodeType = sdo.getInteger("nodeType");
	//	if(nodeType != 3){
			Map<String, Object> data = this.dbTablesApplication.querySubDbTables(queryRequest);
			return toResult(data);
	//	}else{
//			Propertyclass propertyclass = queryPropertyclassList(parentId);
//			TaskpropertyClassQueryRequest tQueryRequest = new TaskpropertyClassQueryRequest();
//			if(StringUtil.isNotBlank(propertyclass.getPropertyClassid())){
//				tQueryRequest.setId(propertyclass.getPropertyClassid());
//			}
//			tQueryRequest.setPmId(parentId);
//			List <Map<String, Object>> data = this.taskpropertyClassApplication.queryTaskpropertyClass(tQueryRequest);
//			return packGridDataAndResult(data);
	//	}
	
	}
	
	public String  slicedQueryDbTablesFields(){
		SDO sdo = this.getSDO();
		DbTablesQueryRequest queryRequest = sdo.toQueryRequest(DbTablesQueryRequest.class);
		String parentId = sdo.getString(CommonDomainConstants.PARENT_ID_FIELD_NAME);
		Integer nodeType = sdo.getInteger("nodeType");
	//	if(nodeType != 3){
			Map<String, Object> data = this.dbTablesApplication.querySubDbTableFields(queryRequest);
			return toResult(data);
	}
	
	//跳转到添加用户表页面
	public String forwardUserTables(){
		SDO sdo = this.getSDO();
		String id=sdo.getString("parentId");
		if (id!=null&&!"".equals(id)){
			DbTables dbTables=this.dbTablesRepository.findOne(id);
		   if ("2".equals(dbTables.getType())){ //是基础表类型 
			  this.putAttribute("parentId",dbTables.getParentId());
	          return forward("userTablesList", dbTables);
		   } else { //是类别
			   this.putAttribute("parentId",sdo.getString("parentId"));
			   return forward("userTablesList");
		   }
		}else{
		   this.putAttribute("parentId",sdo.getString("parentId"));
		}
		return forward("userTablesList");
	}
	
	/**
	 * 查询当前用户下的所有表
	 * @return
	 */
	public String queryUserTables() {
		SDO sdo = this.getSDO();
		try {
			DbTablesQueryRequest queryRequest = sdo.toQueryRequest(DbTablesQueryRequest.class);
			Map<String, Object> data = this.dbTablesApplication.queryUserTables(queryRequest);
			return toResult(data);
		} catch (Exception e) {
			return error(e);
		}
	}
	//判断表名是否已经存在
	public String findExistTableName() {
		SDO sdo = this.getSDO();
		try {
			DbTablesQueryRequest queryRequest = sdo.toQueryRequest(DbTablesQueryRequest.class);
			Map<String, Object> data = this.dbTablesApplication.queryExistTableName(queryRequest);
			return toResult(data);
		} catch (Exception e) {
			return error(e);
		}
	}
	/*
	 * 保存选择的表
	 */
	public String saveUserTables(){
		SDO sdo = this.getSDO();
		//String nodeId = sdo.getString("nodeId"); //pmId
		//String tableName=sdo.getString("tableName");
		String id=sdo.getString("parentId");
		DbTablesQueryRequest queryRequest = sdo.toQueryRequest(DbTablesQueryRequest.class);
		List<Object> plist=sdo.getList("detailData1");
		//  String id ="";
		if (plist!=null&&plist.size()>0){
		   id = this.dbTablesApplication.saveUserTables(queryRequest,plist);
		}
		return success(id);
	}
	//删除选中的表
	public String  deleteUserTables(){
		//SDO sdo = this.getSDO();
		List <String>ids=getSDO().getIds();
		//SyfForms  entity = (SyfForms) sdo.toObject(SyfForms.class);
		this.dbTablesApplication.deleteUserTables(ids);
		return success();
	}
	
	//删除分类 
	public String  deleteModelClassData(){
		List <String>ids=getSDO().getIds();
		//SyfForms  entity = (SyfForms) sdo.toObject(SyfForms.class);
		this.dbTablesApplication.deleteModelClassData(ids);
		return success();
		
	}
	
	
	 //跳转新增分类页面
    public String loadModelClassDetail() {
        SDO sdo = this.getSDO();
        String id = sdo.getString("id");
        String parentId = sdo.getString("parentId");
       // MetaData mdmMetaData = new MetaData();
       // mdmMetaData.setClassifyId(id);
        if (!"".equals(id)){
        	DbTables dbTables=this.dbTablesRepository.findOne(id);
        	 return forward("databaseClassData",dbTables);
        } else {
          this.putAttribute("id",id);
          this.putAttribute("parentId",parentId);
          return forward("databaseClassData");
        }
    }
	
    //保存模型分类
    public String saveModelClassData(){
    	SDO sdo = this.getSDO();
    	 String id = sdo.getString("id");
    	 DbTables dbTables=null;
    	 if (!"".equals(id)){
    		  dbTables=this.dbTablesRepository.findOne(id);
    		  dbTables.setTableName(sdo.getString("tableName"));
    		  dbTables.setName(sdo.getString("name"));

    	 } else {
    	    dbTables=new DbTables();
    	    dbTables.setParentId(sdo.getString("parentId"));
    	    dbTables.setId(Utils.createUuid());
    	    dbTables.setTableName(sdo.getString("tableName"));
    	   dbTables.setName(sdo.getString("name"));
    	    dbTables.setType("1");
    	    dbTables.setStatus(1);
    	 }
    	this.dbTablesRepository.save(dbTables);
    	
    	return success(dbTables.getId());
    }
    
  //删除指定的字段 
  	public String  deleteUserTableFields(){
   	  List <String>ids=getSDO().getIds();
  	//SyfForms  entity = (SyfForms) sdo.toObject(SyfForms.class);
   	  List<TablesMeta> dblist = this.tablesMetaRepository.findAll(ids); 
  	  this.tablesMetaRepository.delete(dblist);
  	  return success();
  	}
  	
  	
	  /**
     * 分页查询待选择的元数据
     * @return
     */
	public String queryAlternativeMetaLists() {
		SDO sdo = getSDO();
		DbTablesQueryRequest queryRequest = sdo.toQueryRequest(DbTablesQueryRequest.class);
		Map<String, Object> data = this.dbTablesApplication.queryAlternativeMetaLists(queryRequest);
		//return toResult(data);
		return this.toResult(data);
	}
	
	/**
	 * 查询已经选择的元数据 
	 * @return
	 */
	public String querySelectedMetaLists(){
		SDO sdo = this.getSDO();
		DbTablesQueryRequest queryRequest = sdo.toQueryRequest(DbTablesQueryRequest.class);
		List<Map<String, Object>> data = this.dbTablesApplication.querySelectedMetaLists(queryRequest);
		return packGridDataAndResult(data);
	}
	
	
	 //发布数据模型 
	 public String publishToModelRecordTable(){
		  Map<String, Object> data =new HashMap<String, Object>();
		  SDO sdo = this.getSDO();
		  String tableId=sdo.getString("tableId");System.out.println("==tableId========="+tableId);
		  //List<MdmModelRecord> list=this.dmdmModelRecordRepository.findById(modelId);
		  DbTablesQueryRequest queryRequest = sdo.toQueryRequest(DbTablesQueryRequest.class); 
		  data=this.dbTablesApplication.publishToModelRecordTable(tableId,"0");
		//  Object map = data.get("result");
		 /* if (map == null || "".equals(map)) {
			  MdmModelRecord mdmModelRecord = this.mdmModelRecordApplication.loadMdmModelRecord(modelId);
			  mdmModelRecord.setPublished(1);
			  this.mdmModelRecordRepository.save(mdmModelRecord);
		   }*/
		return toResult(data); 
	 }
//**************************************************************************************************//	
	//跳转到表单设置界面
	public String forwardFormmanageList(){
			return forward("formmanageList");
	}
	

  
	
}
