package cn.ibizlab.core.data.service.impl;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.*;

import cn.ibizlab.core.data.lite.EntityModel;
import cn.ibizlab.core.data.lite.LiteStorage;
import cn.ibizlab.core.data.model.POSchema;
import cn.ibizlab.core.data.model.PojoSchema;
import cn.ibizlab.core.data.model.TransUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.beans.factory.annotation.Value;
import cn.ibizlab.util.errors.BadRequestAlertException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Lazy;
import cn.ibizlab.core.data.domain.DOModel;
import cn.ibizlab.core.data.filter.DOModelSearchContext;
import cn.ibizlab.core.data.service.IDOModelService;


/**
 * 实体[业务实体] 无存储服务对象接口实现
 */
@Slf4j
@Service
public class DOModelServiceImpl implements IDOModelService {

    @Value("${ibiz.model.path:/app/file/model/}")
    private String modelPath;

    @Override
    public boolean create(DOModel et) {
        //代码实现
        return true;
    }

    public void createBatch(List<DOModel> list){
    }

    @Override
    public boolean update(DOModel et) {
        //代码实现
        return true;
    }

    public void updateBatch(List<DOModel> list){
    }

    @Override
    public boolean remove(String key) {
        return true;
    }

    public void removeBatch(Collection<String> idList){
    }

    @Override
    public DOModel get(String key) {
        DOModel doModel=new DOModel();
        PojoSchema schema= null;
        String[] args=key.split("[.]");
        String system=args[0];
        String entity=args[2];


        Path storePath = Paths.get(LiteStorage.MODEL_PATH,system,"repo",entity,"domain",entity+".json");
        if(!Files.exists(storePath))
        {
            EntityModel entityModel= LiteStorage.getEntityModel(system,entity);
            if(entityModel!=null) {
                schema=TransUtils.EntityModelModel2Schema(entityModel);
                if(schema!=null)
                {
                    for(String dsType:entityModel.getDsTypes())
                    {
                        POSchema poSchema=TransUtils.EntityModelModel2PO(entityModel,dsType);
                        if(poSchema!=null)
                        {
                            doModel.addPOSchema(dsType,poSchema);
                        }
                    }
                    if(doModel.getPoSchemas()!=null)
                    {
                        Path poPath = Paths.get(LiteStorage.MODEL_PATH,system,"repo",entity,"repository",entity+".json");
                        try {
                            File dir=poPath.getParent().toFile();
                            if(!dir.exists())
                                dir.mkdirs();
                            Files.write(poPath, JSON.toJSONBytes(doModel.getPoSchemas()), StandardOpenOption.CREATE);
                        } catch (Exception e) {
                            throw new BadRequestAlertException("保存文件失败","POSchemas",poPath.toString());
                        }
                    }
                    schema.writeTo(storePath);
                }



            }
        }
        else {
            schema = PojoSchema.fromPath(storePath);
            Path poPath = Paths.get(LiteStorage.MODEL_PATH,system,"repo",entity,"repository",entity+".json");
            if(Files.exists(poPath))
            {
                try {
                    LinkedHashMap map=JSON.parseObject(Files.readAllBytes(poPath), LinkedHashMap.class);
                    map.keySet().forEach(dsType->{
                        doModel.addPOSchema(dsType.toString(),JSON.parseObject(JSON.toJSONString(map.get(dsType)),POSchema.class));
                    });
                } catch (IOException e) {

                }
            }
        }


        if(schema!=null)
            doModel.setSchema(schema);
        else
            throw new BadRequestAlertException("未找到对应的模型","DOModel",key);

        return doModel;
    }

    @Override
    public DOModel getDraft(DOModel et) {
        return et;
    }

    @Override
    public boolean checkKey(DOModel et) {
        return false;
    }
    @Override
    @Transactional
    public boolean save(DOModel et) {
        //代码实现
        return true;
    }

    @Override
    public void saveBatch(List<DOModel> list) {
    }





    /**
     * 查询集合 数据集
     */
    @Override
    public Page<DOModel> searchDefault(DOModelSearchContext context) {
        return new PageImpl<DOModel>(new ArrayList(),context.getPageable(),0);
    }

}


