package com.huigou.uasp.form.application.impl;

import com.alibaba.fastjson.JSONObject;
import com.huigou.data.query.model.QueryDescriptor;
import com.huigou.data.repository.GeneralRepository;
import com.huigou.uasp.bmp.common.application.BaseApplication;
import com.huigou.uasp.bmp.configuration.repository.SysDictionaryRepository;
import com.huigou.uasp.form.application.CommonUtilApplication;
import com.huigou.uasp.form.application.FormsDesignApplication;
import com.huigou.uasp.form.domain.model.FormAttribute;
import com.huigou.uasp.form.domain.model.FormSearchSql;
import com.huigou.uasp.form.domain.model.SafFormslist;
import com.huigou.uasp.form.domain.query.FormsAttributeQueryRequest;
import com.huigou.uasp.form.pojo.Options;
import com.huigou.uasp.form.pojo.PubProperty;
import com.huigou.uasp.form.pojo.Root;
import com.huigou.uasp.form.pojo.TableColumns;
import com.huigou.uasp.form.repository.FormAttributeRepository;
import com.huigou.uasp.form.repository.FormSearchSqlRepository;
import com.huigou.uasp.form.repository.SafFormslistRepository;
import com.huigou.uasp.util.Constant;
import com.huigou.uasp.util.Utils;
import net.sf.ezmorph.bean.MorphDynaBean;
import org.apache.commons.beanutils.DynaProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

//import com.huigou.util.CommonUtil;
//import com.huigou.util.SDO;
//import com.huigou.uasp.util.Utils;


@Service("formsDesignApplication")
public class FormsDesignApplicationImpl extends BaseApplication implements FormsDesignApplication { 

     static String QUERY_XML_FILE_PATH = "config/formdesign/safFormslist.xml";
     private String pagePath = "/customform/";
     
 	@Autowired
 	private GeneralRepository generalRepository;
 	
	@Autowired
	private SafFormslistRepository safFormslistRepository;

	@Autowired
	private FormAttributeRepository formAttributeRepository;

	@Autowired
	private FormSearchSqlRepository formSearchSqlRepository;
	@Autowired
	private  SysDictionaryRepository sysDictionaryRepository;
	@Autowired
	private CommonUtilApplication commonUtilApplication;


	private QueryDescriptor getQueryDescriptor(String entityName) {
	    return this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, entityName);
	}

	@Override
	 @Transactional   
	 /* 旧的方法  old */
	public Map <String,Object> saveFormAttribute(FormsAttributeQueryRequest queryRequest,SafFormslist form) {
		  Map <String, Object>map = new HashMap<String, Object>();
		  map.put("success", "1");
		try {
		  List <Root> rootList=queryRequest.getRootList();
	
		  String mainTableName=queryRequest.getTableName();
		  
		// List <FormAttribute> attrList=this.formAttributeRepository.findByFormIdAndType(form.getId(),1);  //主表属性
	      form.setJson(queryRequest.getJson());
	      this.safFormslistRepository.saveAndFlush(form);
	      
		   //删除主表单的属性配置
	      this.formAttributeRepository.deleteFormAttributeByFormIdAndTableName(form.getId(),mainTableName);
	      
		  //获取主表所有字段元素
	      List<Map<String, Object>> mainFieldLists=commonUtilApplication.queryFormTableFields(queryRequest.getFormNo(),mainTableName);
	
	      //遍历表单属性列表
	      int sequence=0;
	      for (Root root:rootList){
	    	  
    		  root.setFormId(form.getId());
    		  root.setFormNo(form.getFormNo());  
    		  
	    	  if ("table".equals(root.getType())){  // 明细表格列表

	    		  map=saveTableAttribute(root);
	    
	     	  } else {      //主表表单

	     		  map=saveFormAttribute(root,mainFieldLists,sequence);
	     		  sequence=Integer.parseInt(map.get("sequence").toString());
	     		  
	     	  }
            /*  if ("grid".equals(root.getType())){  // 表单列表
           	  saveFormAttribute(form.getId(),root,1);
	    	  }
              if ("input".equals(root.getType())){  // text组件
              }
              if ("textarea".equals(root.getType())){  //textarea 组件
               if ("date".equals(root.getType())){  // date组件
                 if ("select".equals(root.getType())){  // select组件
                if ("radio".equals(root.getType())){   // radios组件
            	  
              }*/
	      }
	
		} catch (Exception e) {
			map.put("success", "0");
		    map.put("reason", e.getMessage());
            e.printStackTrace();
        } 
		 return map;
	}
    
    //保存表单属性
	private Map <String,Object>  saveFormAttribute(Root root,List<Map<String, Object>> fieldLists,int  sequence){
		 Map <String, Object>map = new HashMap<String, Object>();
		  map.put("success", "1");
		  map.put("reason","");
		 
		  List <TableColumns>tableList=root.getTableColumns();
		   int tableType=1;
		   PubProperty property=null;
		try{

			
	   if (tableList==null){  //不是在Grid中添加的表单标签
		      sequence++;
		      property=new PubProperty();
		      Utils.CopyBean(root, property);
		      map=saveAttributeDetail(property,fieldLists,tableType,sequence);
	   } else {
	       for (TableColumns tableColumns:tableList){ 
	    	   sequence++;
	    	   property=new PubProperty();
			   Utils.CopyBean(tableColumns, property);
			   property.setFormId(root.getFormId());
			   property.setFormNo(root.getFormNo());
			   map=saveAttributeDetail(property,fieldLists,tableType,sequence);
		
		   }
	     }
	     map.put("sequence", sequence);
	  } catch (Exception e) {
			map.put("success", "0");
		    map.put("reason", e.getMessage());
		  e.printStackTrace();
	   }
		return map;
	}
   
	//保存明细表格的属性 
	private Map <String,Object>  saveTableAttribute(Root root){
		 Map <String, Object>map = new HashMap<String, Object>();
		  map.put("success", "1");
		  map.put("reason","");
		  List <TableColumns>tableList=root.getTableColumns();
		  List<Map<String, Object>>  fieldLists=new ArrayList<Map<String, Object>>();
		  int tableType=2;
		  int s=0;
		try{
			PubProperty property=null;
			if (tableList!=null&&tableList.size()>0){
			  if (tableList.get(0).getTable()!=null){
				fieldLists=commonUtilApplication.queryFormTableFields(root.getFormNo(),tableList.get(0).getTable());
			  }
		      //删除表单的配置
 		      this.formAttributeRepository.deleteFormAttributeByFormIdAndTableName(root.getFormId(),tableList.get(0).getTable());
			}

	       for (TableColumns tableColumns:tableList){ 
	    	   property=new PubProperty();
			   Utils.CopyBean(tableColumns, property);
			   property.setFormId(root.getFormId());
			   property.setFormNo(root.getFormNo());
			   map=saveAttributeDetail(property,fieldLists,tableType,s);
	           s++;
		    }
	   
	  } catch (Exception e) {
			map.put("success", "0");
		    map.put("reason", e.getMessage());
		  e.printStackTrace();
	   }
		return map;
	}
	
	//保存标签详细属性
	private  Map <String,Object> saveAttributeDetail(PubProperty root,List<Map<String, Object>> fieldLists,int tableType,int sequence){
		          Map <String, Object>map = new HashMap<String, Object>();
		 		  map.put("success", "1");
		 		  String reason="";
		 	try{	  
		 		  FormAttribute formAttribute=new FormAttribute();   		
				  formAttribute.setId(Utils.createUuid());
				  formAttribute.setFormId(root.getFormId());
				  formAttribute.setTableName(root.getTable());
				  formAttribute.setTableType(tableType);
			      formAttribute.setAttrCode(root.getModel());
			      formAttribute.setAttrName(root.getName());
			      Map <String,Object>fieldMap=null;
			      
			      String metaId="";
			      for (int x=0;x<fieldLists.size();x++) {
			    	  fieldMap=fieldLists.get(x);
			    	  if (root.getModel().equals(fieldMap.get("fieldCode").toString())){
			    		  metaId=fieldMap.get("id").toString();
			    		  break;
			    	  }
			      }
			      formAttribute.setMetaId(metaId);
			      if (root.getOptions().getFormat()!=null){
			    	  if (Constant.DATE_TAG.equals(root.getType())){
			    		formAttribute.setDataFormat(root.getType());
			    	  } else {
			            formAttribute.setDataFormat(root.getOptions().getFormat());
			    	  }
			      } else {
			    	  formAttribute.setDataFormat("string");
			      }
			
			      formAttribute.setStatus(1);
			      formAttribute.setFieldTag(root.getType());
			      
			      if ("input".equals(root.getType())){  //input -->text 
			    	 formAttribute.setFieldTag(Constant.INPUT_TAG);
			      }
			      if (Constant.SELECT_TAG.equals(root.getType())){
			    	  String dataSourceType=Constant.DATASOURCETYPE_NO;
			    	 if (root.getOptions().getDataType()!=null&&!"".equals(root.getOptions().getDataType())){
			    		 dataSourceType=root.getOptions().getDataType();
			    	 }
			    	 formAttribute.setDataSourceType(dataSourceType);
			      }
			      if  (Constant.CHECKBOX_TAG.equals(root.getType())||Constant.RADIOS_TAG.equals(root.getType())){
			  
			    	  String dataSourceType=Constant.DATASOURCETYPE_FIX;//默认是自定义的数据  
			    	  if (root.getOptions().getDictionary()!=null&&!"".equals(root.getOptions().getDictionary())){
			    		   dataSourceType=Constant.DATASOURCETYPE_DICT;
			    		   formAttribute.setDataSource(root.getOptions().getDictionary());
			    	  } else {
			    		 
			    	      List <MorphDynaBean>optionbeans= (List <MorphDynaBean>)root.getOptions().getOptions();
			    	      DynaProperty[] tabdynaProperties=null;
			    	      JSONObject backData = new JSONObject();
			    	      String key="",val="";
			    	      Object  attrVal =null;
			    	      String  attrName ="";int k=1;
			    	     for (MorphDynaBean tbeans:optionbeans){
			    		     tabdynaProperties = tbeans.getDynaClass().getDynaProperties();
				 		        for(int m=0; m<tabdynaProperties.length;m++){
				 			       attrName = tabdynaProperties[m].getName();//属性名称 第一个是options 
				 			       attrVal = tbeans.get(attrName);//属性值      checkbox 只有 value ？
				 			      System.out.println(attrName+"===attrVal===="+attrVal.toString().trim());
				 			      if (attrVal!=null){
				 			         if ("label".equals(attrName)){  //radio返回label value;checkbox 只有 value 
				 			    	   key=attrVal.toString().trim();
				 			         } else {
				 			    	   val=attrVal.toString().trim();
				 			         }
				 			       }
				 		         }
				 		         if ("".equals(key)){ //checkbox返回没有label
				 		           key=String.valueOf(k);  
				 		         }
				 		         backData.put(key,val);
			    	             k++;
		    	             }
			    	         formAttribute.setDataSource(backData.toJSONString());  
			    	   }
			    		formAttribute.setDataSourceType(dataSourceType);
			      }
			      if (Constant.EASYSEARCH_TAG.equals(root.getType())){
			    	   Options option=(Options)root.getOptions();
					   List <MorphDynaBean>optionbeans= option.getOptions();//(List <MorphDynaBean>)(Options)root.getOptions();
					   DynaProperty[] tabdynaProperties=null;
					   Object attrVal=null;
					   String attrName="";
		
					    MorphDynaBean tabbean=optionbeans.get(1);  //位于第二个   Treebox位于第一个
			 			// object=new TableColumns(); 
			 			tabdynaProperties = tabbean.getDynaClass().getDynaProperties();
			 		    // for(int x=0; x<tabdynaProperties.length;x++){
			 			    attrName = tabdynaProperties[0].getName();//属性名称 第一个是options 
			 			    attrVal = tabbean.get(attrName);//属性值
			 			   List <MorphDynaBean>querybeans=(List <MorphDynaBean>)tabbean.get(attrName);
			 			    attrVal=((MorphDynaBean)querybeans.get(0)).get("queryName");
			 			
			 			  //  System.out.println(attrName+"==yy==="+attrVal);
			 			    formAttribute.setDataSource(attrVal.toString()); 
			 			    formAttribute.setDataSourceType(Constant.DATASOURCETYPE_SQL);  //
			 			    formAttribute.setFieldTag(Constant.SELECT_TAG);
			 			    
			           //更新SAF_FORM_SEARCH_SQL
			 			List <FormSearchSql> slist=this.formSearchSqlRepository.searchSqlByFormNoAndSearchName(root.getFormNo(),attrVal.toString());
			 			if  (slist!=null&&slist.size()>0){
			 				FormSearchSql formSearchSql=slist.get(0);
			 				formSearchSql.setTargetField(root.getModel()); //设置关联字段 
			 				formSearchSql.setTableName(root.getTable());
			 				formSearchSql.setCreatedDate(new Date());
			 				this.formSearchSqlRepository.saveAndFlush(formSearchSql);
			 			}
			 			
			      }

	    		  if (root.getOptions().getCustomClass()!=null){  //增加样式
	    			  formAttribute.setCssStyle(root.getOptions().getCustomClass());
	    		  }
			      formAttribute.setMustInput(root.getOptions().getRequired()?1:0);
			      
			      if (tableType==1){ //主表
			        formAttribute.setDisplayListing(1);
			      }
			      formAttribute.setSequence(sequence);

			      formAttribute.setCreatedDate(new Date());
				  
			      if (!"".equals(metaId)){ //字段存在 才保存 
			          this.formAttributeRepository.save(formAttribute);
			      } else {
			    	  if ("".equals(reason)){
			    	  	  reason="没有找到字段:";
			    	   } else {
			    		  reason+=root.getModel()+",";
			    	  }
			    	  System.out.println("没有找到字段:"+root.getModel());
			      }
		 		   map.put("reason",reason);
		 	  } catch (Exception e) {
					map.put("success", "0");
				    map.put("reason", e.getMessage());
				    e.printStackTrace();
			  }
		 	return map;
			          
	}
	
	 @Override
	 public String getUserDictFolderIds(String dictName) {
	        StringBuffer sb=new StringBuffer();
	        sb=sb.append("select id from SA_CommonTree t start with name = '").append(dictName).append("' connect by t.parent_id= prior id");
	        String sql = sb.toString();
	        List<String> ids = this.sqlExecutorDao.queryToList(sql, String.class, null);
	        String resultIds = String.join(",", ids);
	        return resultIds;
	 }
   
	//查询表单的数据字典
	@Override
	public List <Map <String,Object>>  getFormDataDict(String dictName){
	       String folderId=getUserDictFolderIds(dictName);
	       String sql="select a.code,a.name from sa_dictionary a where a.folder_id='"+folderId+"'";
	       List<Map <String,Object>> data = this.sqlExecutorDao.queryToListMap(sql,null);
 	       return data;
	}
	
    //获取数据库中所有的函数或过程  
	@Override
	public List <Map <String,Object>>  getDBFunctionsOrProceduce(String type){
	   String sql = getQueryDescriptor("queryFormFunctionOrProcduce").getSql();
	    return this.sqlExecutorDao.queryToListMap(sql,type);
	}
	
}
