package cn.ibizlab.core.data.lite;

import cn.ibizlab.util.errors.BadRequestAlertException;
import cn.ibizlab.core.data.dto.DataObject;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Getter
@Setter
@NoArgsConstructor
@Accessors(chain = true)
@JsonIgnoreProperties(value = "handler")
public class DstSystemModel {

    /**
     * 系统标识
     */
    @JSONField(name = "pssystemid")
    @JsonProperty("pssystemid")
    private String pssystemid;

    /**
     * 系统名称
     */
    @JSONField(name = "pssystemname")
    @JsonProperty("pssystemname")
    private String pssystemname;

    /**
     * 结构
     */
    @JSONField(name = "sysstructure")
    @JsonProperty("sysstructure")
    private Map sysstructure;

    /**
     * 应用
     */
    @JSONField(name = "apps")
    @JsonProperty("apps")
    private List<App> apps;

    public DstSystemModel addApp(App app)
    {
        if(apps==null)
            apps=new ArrayList<>();
        apps.add(app.setSystemid(this.pssystemid));
        return this;
    }

    @Getter
    @Setter
    @NoArgsConstructor
    @Accessors(chain = true)
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    @JsonIgnoreProperties(ignoreUnknown = true)
    public static class App{
        private String id;
        private String label;
        private String systemid;
        private String fullname;
        private String type;
        private String group;
        private String icon;
        private Integer visabled;
        private String addr;
    }


    /**
     * 校验
     */
    @JSONField(name = "md5check")
    @JsonProperty("md5check")
    private String md5check;

    /**
     * 排序
     */
    @JSONField(name = "showorder")
    @JsonProperty("showorder")
    private Integer showorder;

    private Map<String,Object> extensionparams;


    public DstSystemModel setDynamicModelPath(String dynamic_model_path)
    {
        if(extensionparams==null)
            extensionparams=new HashMap<String,Object>();
        extensionparams.put("dynamic_model_path",dynamic_model_path);
        return this;
    }

    @JSONField(serialize = false)
    @JsonIgnore
    public String getDynamicModelPath()
    {
        if(extensionparams!=null&&extensionparams.get("dynamic_model_path")!=null)
            return extensionparams.get("dynamic_model_path").toString();
        return null;
    }

    public DstSystemModel setLastModify(Long lastModify)
    {
        if(extensionparams==null)
            extensionparams=new HashMap<String,Object>();
        extensionparams.put("last_modify",lastModify);
        return this;
    }

    @JSONField(serialize = false)
    @JsonIgnore
    public Long getLastModify()
    {
        if(extensionparams!=null&&extensionparams.get("last_modify")!=null)
            return DataObject.getLongValue(extensionparams.get("last_modify"),0L);
        return 0L;
    }

    public DstSystemModel fromPath(Path path)
    {
        try {
            if(!Files.exists(path))
                throw new BadRequestAlertException("读取文件失败","DstSystem",path.toString());
            JSONObject jo=JSON.parseObject(new String(Files.readAllBytes(path), StandardCharsets.UTF_8));
            this.setPssystemid(jo.getString("codeName"));
            this.setPssystemname(jo.getString("logicName"));
            this.setLastModify(path.toFile().lastModified());
            if(jo.containsKey("getAllPSApps"))
            {
                JSONArray array=jo.getJSONArray("getAllPSApps");
                array.forEach(obj->{
                    JSONObject app=(JSONObject)obj;
                    String appPath=app.getString("path");
                    if(!StringUtils.isEmpty(appPath))
                    {
                        String[] args=appPath.split("/");
                        if(args.length==3)
                        {
                            String appId=args[1];
                            this.addApp(new App().setId(appId).setLabel(appId));
                        }
                    }
                });
            }
            this.setDynamicModelPath(path.getParent().toAbsolutePath().toString());
        } catch (IOException e) {
            throw new BadRequestAlertException("读取文件失败","DstSystem",path.toString());
        }
        return this;
    }
}
