package com.tykj.workflowcore.model_layer.service.impl;

import com.tykj.workflowcore.base.result.ApiException;

import com.tykj.workflowcore.model_layer.dao.AggregationDao;
import com.tykj.workflowcore.model_layer.dao.TableInfoDao;


import com.tykj.workflowcore.model_layer.entity.Aggregation;
import com.tykj.workflowcore.model_layer.entity.TableInfo;

import com.tykj.workflowcore.model_layer.entity.vo.AggregationVO;
import com.tykj.workflowcore.model_layer.myEnum.AggregationType;
import com.tykj.workflowcore.model_layer.myEnum.ModelType;
import com.tykj.workflowcore.model_layer.service.AggregationService;
import com.tykj.workflowcore.model_layer.utils.AggregationUtil;
import com.tykj.workflowcore.model_layer.utils.SessionUtil;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @ClassName AggregationImpl
 * @Description TODO
 * @Author WWW
 * @Date 2021/4/1 17:24
 * @Version 1.0
 */
@Service
public class AggregationImpl implements AggregationService {

    @Autowired
    TableInfoDao tableInfoDao;

    @Autowired
    AggregationDao aggregationDao;
    @Autowired
    SessionUtil sessionUtil;

    @Override
    @Transactional(rollbackOn = Exception.class)
    public void addAggregation(AggregationVO aggregationVO) {
        //获取主表XML
        Integer mainTableId = aggregationVO.getMainTableId();
        Optional<TableInfo> mainTableById = tableInfoDao.findById(mainTableId);
        if (mainTableById.isPresent()){
        }else {
            throw new ApiException("主表不存在!");
        }
        //改CLASS名字
        TableInfo tableInfoEx = tableInfoDao.save(aggregationVO.getTableInfo());
        try {
            createAggregationObjectXml(aggregationVO.getAggregations(), null, tableInfoEx.getId(), mainTableById.get());
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        tableInfoDao.save(tableInfoEx);
    }

//    假设获得的是一份XML
    public  void createAggregationObjectXml(List<Aggregation> aggregations,
                                               Aggregation parentAggregation,
                                               Integer tableInfoExId,
                                               TableInfo mainTableInfo) throws DocumentException {
        //这里需要一个class标签，

        String parentModeName;
        if (parentAggregation!=null){
            //如果不是第一层,则通过parentAggregation,查出副表的XML字符串
            //将XML字符串转换为XML对象
            //取出Class标签,将Class标签赋值给elementClass
            Optional<TableInfo> sideTableInfoOptional = tableInfoDao.findById(parentAggregation.getSideTableId());
            if (sideTableInfoOptional.isPresent()){
            }else {
                throw new ApiException("id为："+parentAggregation.getSideTableId()+"的副表不存在");
            }
            parentModeName = sideTableInfoOptional.get().getModelName();
        }else {
            //如果是第一层 则通过rootElement 查出副表的XML字符串
            //取出Class标签,将Class标签赋值给elementClass
            parentModeName = mainTableInfo.getModelName();
        }
        //循环
        for (int i = 0; i < aggregations.size(); i++) {
            Aggregation aggregationChild = aggregations.get(i);
            if (aggregationChild.getAggregations()!=null&&aggregationChild.getAggregations().size()>0){
                createAggregationObjectXml(aggregationChild.getAggregations(), aggregationChild, tableInfoExId, mainTableInfo);
                aggregationToXmlElement(aggregationChild, tableInfoExId, parentModeName);
            }else {
                //addSet
                aggregationToXmlElement(aggregationChild, tableInfoExId, parentModeName);

            }
            aggregationDao.save(aggregationChild);
        }

        return;
    }

    public void aggregationToXmlElement(Aggregation aggregation,Integer tableInfoExId,String parentModelName){
        //设置tableInfoExId
        aggregation.setTableInfoExId(tableInfoExId);

        Optional<TableInfo> sideTableById = tableInfoDao.findById(aggregation.getSideTableId());
        if (!sideTableById.isPresent()){
            throw new ApiException("id为："+aggregation.getSideTableId()+"的副表不存在");
        }
        if (aggregation.getRelationship().equals(AggregationType.ONE_TO_ONE)){
            return;
        }
        if (aggregation.getRelationship().equals(AggregationType.ONE_TO_MANY)){
            return;
        }
        if (aggregation.getRelationship().equals(AggregationType.MANY_TO_MANY)){
            //如果是多对多需要 为 aggregationRelationship 生成连接的KEY
            String mainTableConnectionKey = parentModelName+"_Id";
            String sideTableConnectionKey = sideTableById.get().getModelName()+"_Id";
            aggregation.setMainTableConnectionKey(mainTableConnectionKey);
            aggregation.setSideTableConnectionKey(sideTableConnectionKey);
            //如果是多对多需要 为 aggregationRelationship 生成连接的中间表名
            String connectionTableName = parentModelName+"_"+sideTableById.get().getModelName()+"_"+ (UUID.randomUUID().toString().substring(0,8));
            aggregation.setConnectionTableName(connectionTableName);
            //Util.addManyToMany
            return;
        }
        return ;
    }

//
//    @Override
//    public void addAggregation(AggregationVO aggregationVO) {
//        Integer mainTableId = aggregationVO.getMainTableId();
//        Optional<TableInfo> byId = tableInfoDao.findById(mainTableId);
//        TableInfo tableInfo = new TableInfo();
//        List<String> modelNames = tableInfoDao.findAll()
//                .stream()
//                .map(TableInfo::getModelName)
//                .collect(Collectors.toList());
//            if (byId.isPresent()){
//                if (modelNames.contains(aggregationVO.getModelName())){
//                    throw new ApiException("表名已经存在！");
//                }
//                else {
//                    tableInfo.setModelType(ModelType.VIRTUAL);
//                    tableInfo = tableInfoDao.save(aggregationVO.getTableInfo());
//                }
//            }else {
//                throw new ApiException("主表不存在！");
//            }
//            saveAggregation(aggregationVO,tableInfo.getId());
//
//
//
//    }
//
//    public void saveAggregation(AggregationVO aggregationVO,Integer tableInfoId){
//        Aggregation aggregation=new Aggregation();
//        aggregation.setConnectionTableName(aggregationVO.getModelName())
//                .setRelationship(aggregationVO.getAggregations().get(0).getRelationship())
//                .setMainTableConnectionKey(aggregationVO.getAggregations().get(0).getMainTableConnectionKey())
//                .setSideTableId(aggregationVO.getAggregations().get(0).getSideTableId())
//                .setTableInfoExId(tableInfoId)
//                .setSideTableConnectionKey(aggregationVO.getAggregations().get(0).getSideTableConnectionKey());
//        aggregationDao.save(aggregation);
//    }
}
