package com.chenyang.nse.bussiness.service.core.impl;

import com.chenyang.nse.bussiness.config.PropertiesLoaderUtils;
import com.chenyang.nse.bussiness.dao.core.ComplianceDirectoryDao;
import com.chenyang.nse.bussiness.dao.table.core.TCoreAttachmentDirectoryDao;
import com.chenyang.nse.bussiness.dao.table.core.TCoreComplianceDirectoryDao;
import com.chenyang.nse.bussiness.dao.table.core.fieldscope.TCoreFieldDirectoryDao;
import com.chenyang.nse.bussiness.dao.table.core.scopeproject.TProAttributeGroupDao;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreAttachmentDirectory;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreComplianceDirectory;
import com.chenyang.nse.bussiness.entity.orm.table.core.scopeproject.TProAttributeGroup;
import com.chenyang.nse.bussiness.entity.vo.datascope.ComplianceDirectoryVO;
import com.chenyang.nse.bussiness.service.core.ComplianceDirectoryService;
import com.chenyang.nse.bussiness.tools.io.FileTool;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

@Service
@Transactional
public class ComplianceDirectoryServiceImpl implements ComplianceDirectoryService {
   @Autowired
   private TCoreComplianceDirectoryDao tCoreComplianceDirectoryDao;
   @Autowired
   private ComplianceDirectoryDao complianceDirectoryDao;
   @Autowired
   private TProAttributeGroupDao tProAttributeGroupDao;
   @Autowired
   private TCoreAttachmentDirectoryDao tCoreAttachmentDirectoryDao;
   @Autowired
   private TCoreFieldDirectoryDao tCoreFieldDirectoryDao;

   public void complianceDirectorySave(MultipartFile file, TCoreAttachmentDirectory comdir) {
      String filename = file.getOriginalFilename();
      List<TCoreAttachmentDirectory> filelike = this.tCoreAttachmentDirectoryDao.getFileLike(comdir);
      if (!filelike.isEmpty()) {
         List<String> filelikename = new ArrayList();

         for(TCoreAttachmentDirectory name : filelike) {
            filelikename.add(name.getAttachment_name());
         }

         if (filelikename.contains(comdir.getAttachment_name())) {
            for(int i = 1; i < 1000; ++i) {
               if (!filelikename.contains(comdir.getAttachment_name() + " (" + i + ")")) {
                  filename = comdir.getAttachment_name() + " (" + i + ")." + comdir.getAttachment_form();
                  comdir.setAttachment_name(comdir.getAttachment_name() + " (" + i + ")");
                  break;
               }
            }
         } else {
            filename = file.getOriginalFilename();
         }
      }

      Properties props = new Properties();

      try {
         props = PropertiesLoaderUtils.loadAllProperties("config.properties");
      } catch (IOException e) {
         e.printStackTrace();
      }

      String path = props.getProperty("complianceDir");
      if (!FileTool.isFileExit(path)) {
         FileTool.createFolder(path);
      }

      File mappletfile = new File(path, filename);

      try {
         mappletfile.createNewFile();
         file.transferTo(mappletfile);
      } catch (Exception e) {
         System.out.println(e.toString());
         e.printStackTrace();
      }

      comdir.setCreate_date(new Date());
      this.tCoreAttachmentDirectoryDao.save(comdir);
   }

   public void complianceDirectorySaveEdit(TCoreAttachmentDirectory dir) {
      this.tCoreAttachmentDirectoryDao.updateAttachmentDirectory(dir);
   }

   public List<TCoreAttachmentDirectory> getselectfilelist(String id) {
      List<TCoreAttachmentDirectory> list = this.tCoreAttachmentDirectoryDao.queryAll(Order.desc("create_date"), new Criterion[]{Restrictions.eq("attachment_id", id)});
      return list;
   }

   public void save(ComplianceDirectoryVO scope) {
      if (scope.getTid() != null && !"".equals(scope.getTid())) {
         this.complianceDirectoryDao.updateScope(scope);
      } else if (scope.getFa_tid() == null) {
         scope.setTid(UUID.randomUUID().toString().replace("-", ""));
         List<TCoreComplianceDirectory> ll = this.tCoreComplianceDirectoryDao.queryAll();
         if (ll.size() > 0) {
            this.complianceDirectoryDao.insertAddFa(scope);
         } else {
            this.complianceDirectoryDao.insertAddZero(scope);
         }
      } else if (this.complianceDirectoryDao.ishavebro(scope).size() > 0) {
         scope.setTid(UUID.randomUUID().toString().replace("-", ""));
         this.complianceDirectoryDao.havebro(scope);
      } else {
         scope.setTid(UUID.randomUUID().toString().replace("-", ""));
         this.complianceDirectoryDao.nothavebro(scope);
      }

      String idPro = scope.getTid();
      this.saveColumn(scope, idPro);
   }

   public List<ComplianceDirectoryVO> getScopeTable(ComplianceDirectoryVO vo) {
      List<ComplianceDirectoryVO> list = this.complianceDirectoryDao.getDataScopeGroup(vo);
      list.forEach((l) -> {
         List<TProAttributeGroup> listGroup = this.tProAttributeGroupDao.queryAll(new Criterion[]{Restrictions.eq("group_id", l.getTid())});
         Map<String, String> map = new HashMap();
         listGroup.forEach((lg) -> map.put(lg.getColumnname(), lg.getColumnvalue()));
         l.setColumnsGroups(map);
      });
      List<ComplianceDirectoryVO> trees = this.buildTree(list, "全部");
      return trees;
   }

   private List<ComplianceDirectoryVO> buildTree(List<ComplianceDirectoryVO> list, String parentId) {
      List<ComplianceDirectoryVO> trees = new ArrayList();
      if (list.size() > 0) {
         for(ComplianceDirectoryVO entity : list) {
            String menuId = entity.getTid();
            String pid = entity.getFa_tid();
            if (parentId.equals(pid)) {
               List<ComplianceDirectoryVO> menuLists = this.buildTree(list, menuId);
               entity.setChildren(menuLists);
               trees.add(entity);
            }
         }
      }

      return trees;
   }

   public ComplianceDirectoryVO editbyid(String id) {
      TCoreComplianceDirectory o = (TCoreComplianceDirectory)this.tCoreComplianceDirectoryDao.queryAll(new Criterion[]{Restrictions.eq("id", id)}).get(0);
      String fatid = o.getFa_tid();
      ComplianceDirectoryVO vo = new ComplianceDirectoryVO();
      if ("全部".equals(fatid)) {
         vo.setFa_name("全部");
      } else {
         String faid = ((TCoreComplianceDirectory)this.tCoreComplianceDirectoryDao.queryAll(new Criterion[]{Restrictions.eq("id", id)}).get(0)).getFa_tid();
         vo.setFa_name(((TCoreComplianceDirectory)this.tCoreComplianceDirectoryDao.queryAll(new Criterion[]{Restrictions.eq("id", faid)}).get(0)).getDirectory_name());
      }

      vo.setTid(o.getId());
      vo.setEdition_id(o.getEdition_id());
      vo.setText(o.getDirectory_name());
      vo.setId(o.getDirectory_id());
      vo.setFa_tid(o.getFa_tid());
      vo.setNote(o.getNote());
      vo.setChinese_name(o.getChinese_name());
      vo.setForeigh_name(o.getForeigh_name());
      vo.setAbbreviation(o.getAbbreviation());
      vo.setPublic_name(o.getPublic_name());
      vo.setPublic_date(o.getPublic_date());
      vo.setImplementation_date(o.getImplementation_date());
      vo.setRevised_date(o.getRevised_date());
      vo.setApplication_state(o.getApplication_state());
      vo.setDirectory_type(o.getDirectory_type());
      vo.setCreate_user(o.getCreate_user());
      vo.setCreate_date(o.getCreate_date());
      vo.setProjectId(o.getProjectid());
      List<TProAttributeGroup> list = this.tProAttributeGroupDao.queryAll(new Criterion[]{Restrictions.eq("group_id", id)});
      Map<String, String> map = new HashMap();
      list.forEach((l) -> map.put(l.getColumnname(), l.getColumnvalue()));
      vo.setColumnsGroups(map);
      return vo;
   }

   private void saveColumn(ComplianceDirectoryVO obj, String idPro) {
      try {
         Class clazz = obj.getClass();
         if (idPro != null && !"".equals(idPro)) {
            this.tProAttributeGroupDao.remove(new Criterion[]{Restrictions.eq("group_id", idPro)});
         }

         obj.getColumnsGroups().entrySet().forEach((map) -> {
            TProAttributeGroup tag = new TProAttributeGroup();
            tag.setId(UUID.randomUUID().toString().replace("-", ""));
            tag.setGroup_id(idPro);
            tag.setColumnname((String)map.getKey());
            tag.setColumnvalue((String)map.getValue());
            this.tProAttributeGroupDao.save(tag);
         });
      } catch (Exception e) {
         e.printStackTrace();
      }

   }

   public void remove(String id) {
      TCoreComplianceDirectory ds = (TCoreComplianceDirectory)this.tCoreComplianceDirectoryDao.queryUnique(new Criterion[]{Restrictions.eq("id", id)});
      List<Map<String, Object>> relatedList = this.tCoreComplianceDirectoryDao.relatedfandson(ds.getDirectory_id());
      List<String> listname = new ArrayList();

      for(Map<String, Object> a : relatedList) {
         listname.add((String)a.get("id"));
      }

      this.tCoreFieldDirectoryDao.remove(new Criterion[]{Restrictions.in("scope_id", listname)});

      for(ComplianceDirectoryVO t : this.complianceDirectoryDao.getselfandson(ds.getDirectory_id())) {
         String strF = t.getAttachment_name() + "." + t.getAttachment_form();
         Properties props = new Properties();

         try {
            props = PropertiesLoaderUtils.loadAllProperties("config.properties");
         } catch (IOException e) {
            e.printStackTrace();
         }

         String path = props.getProperty("complianceDir");
         path = path + strF;
         File fileTemp = new File(path);
         if (fileTemp.exists()) {
            fileTemp.delete();
         }

         this.tCoreAttachmentDirectoryDao.remove(new Criterion[]{Restrictions.eq("id", t.getTid())});
      }

      this.complianceDirectoryDao.delselfandson(ds.getDirectory_id());

      for(ComplianceDirectoryVO complianceDirectoryVO : this.complianceDirectoryDao.findbroandhisson(ds.getDirectory_id(), ds.getFa_tid())) {
         if (ds.getFa_tid().equals(complianceDirectoryVO.getFa_tid())) {
            this.complianceDirectoryDao.updatebro(complianceDirectoryVO.getTid());
         } else {
            this.complianceDirectoryDao.updatebroson(complianceDirectoryVO.getTid(), ds.getDirectory_id());
         }
      }

   }

   public void removeTask(String fileid) {
      this.tCoreAttachmentDirectoryDao.remove(new Criterion[]{Restrictions.eq("id", fileid)});
   }

   public TCoreAttachmentDirectory editTask(String fileid) {
      TCoreAttachmentDirectory data = (TCoreAttachmentDirectory)this.tCoreAttachmentDirectoryDao.queryUnique(new Criterion[]{Restrictions.eq("id", fileid)});
      return data;
   }

   public String getmaxdatetid(String edition_id) {
      String id = "";
      List<Map<String, Object>> tmax = this.tCoreComplianceDirectoryDao.getmaxdatetid(edition_id);
      if (!tmax.isEmpty()) {
         id = (String)((Map)tmax.get(0)).get("id");
      }

      return id;
   }

   public void removeByEdition(String editionid) {
      this.tCoreFieldDirectoryDao.remove(new Criterion[]{Restrictions.eq("edition_id", editionid)});
      this.tProAttributeGroupDao.removeAssCompliance(editionid);
      this.tCoreAttachmentDirectoryDao.removeAttaCompliance(editionid);
      this.tCoreComplianceDirectoryDao.remove(new Criterion[]{Restrictions.eq("edition_id", editionid)});
   }

   private void saveScopeData(TCoreComplianceDirectory data) {
      this.tCoreComplianceDirectoryDao.save(data);
      String fid = data.getId();
      data.getGroups().forEach((g) -> {
         g.setGroup_id(fid);
         this.tProAttributeGroupDao.save(g);
      });
      if (data.getChildrens().size() > 0) {
         data.getChildrens().forEach((c) -> {
            c.setFa_tid(fid);
            this.saveScopeData(c);
         });
      }

   }

   private void saveScopeDataMap(Map<String, TCoreComplianceDirectory> map) {
      TCoreComplianceDirectory all = (TCoreComplianceDirectory)map.get("全部");
      List<TCoreComplianceDirectory> fathers = all.getChildrens();
      fathers.forEach((f) -> this.saveScopeData(f));
   }

   public void saveExcelData(List<List<String>> list, String user, String editionid) throws Exception {
      Map<String, TCoreComplianceDirectory> map = new HashMap();
      map.put("全部", new TCoreComplianceDirectory());
      list.stream().forEach((row) -> {
         String uuid = UUID.randomUUID().toString().replace("-", "");
         TCoreComplianceDirectory tds = new TCoreComplianceDirectory();

         for(int j = 12; j < row.size() && j % 2 == 0 && null != row.get(j); ++j) {
            TProAttributeGroup attr = new TProAttributeGroup();
            attr.setColumnname((String)row.get(j));
            attr.setColumnvalue((String)row.get(j + 1));
            attr.setColumnnum(String.valueOf((j - 1) / 2));
            tds.getGroups().add(attr);
            ++j;
         }

         tds.setDirectory_id((String)row.get(0));
         tds.setDirectory_name((String)row.get(1));
         tds.setNote((String)row.get(2));
         tds.setFa_tid((String)row.get(0));
         tds.setChinese_name((String)row.get(3));
         tds.setForeigh_name((String)row.get(4));
         tds.setAbbreviation((String)row.get(5));
         tds.setPublic_name((String)row.get(6));
         tds.setPublic_date((String)row.get(7));
         tds.setRevised_date((String)row.get(8));
         tds.setImplementation_date((String)row.get(9));
         tds.setApplication_state((String)row.get(10));
         tds.setDirectory_type((String)row.get(11));
         tds.setCreate_user(user);
         tds.setEdition_id(editionid);
         tds.setCreate_date(new Date());
         map.put(row.get(0), tds);
      });
      map.entrySet().forEach((row) -> {
         if (((String)row.getKey()).length() > 3) {
            String fscope = ((TCoreComplianceDirectory)row.getValue()).getDirectory_id().substring(0, ((TCoreComplianceDirectory)row.getValue()).getDirectory_id().length() - 3);
            TCoreComplianceDirectory fdata = (TCoreComplianceDirectory)map.get(fscope);
            List<TCoreComplianceDirectory> childrens = fdata.getChildrens();
            childrens.add(row.getValue());
         } else if (((String)row.getKey()).length() == 3) {
            ((TCoreComplianceDirectory)row.getValue()).setFa_tid("全部");
            ((TCoreComplianceDirectory)map.get("全部")).getChildrens().add(row.getValue());
         }

      });
      this.saveScopeDataMap(map);
   }

   public String checkName(String directoryname, String projectId) {
      List<TCoreComplianceDirectory> list = this.tCoreComplianceDirectoryDao.queryAll(new Criterion[]{Restrictions.eq("directory_name", directoryname), Restrictions.eq("projectid", projectId)});
      return list.isEmpty() ? "yes" : "no";
   }
}
