package com.connor.sso.sso.util;
//teamcenter.com/Schemas/Manufacturing/2018-11/StructureManagement



import com.connor.sso.sso.clientx.AppXSession;
import com.teamcenter.schemas.soa._2006_03.exceptions.ServiceException;
import com.teamcenter.services.loose.core._2006_03.FileManagement;
import com.teamcenter.services.strong.core.DataManagementService;
import com.teamcenter.services.strong.core.FileManagementService;
import com.teamcenter.services.strong.core.SessionService;
import com.teamcenter.services.strong.core._2007_01.DataManagement;
import com.teamcenter.services.strong.core._2007_06.DataManagement.ExpandGRMRelationsData;
import com.teamcenter.services.strong.core._2007_06.DataManagement.ExpandGRMRelationsPref;
import com.teamcenter.services.strong.core._2007_06.DataManagement.ExpandGRMRelationsResponse;
import com.teamcenter.services.strong.core._2007_06.DataManagement.RelationAndTypesFilter2;
import com.teamcenter.services.strong.core._2007_12.Session;
import com.teamcenter.services.strong.core._2008_06.DataManagement.SaveAsNewItemInfo;
import com.teamcenter.services.strong.core._2008_06.DataManagement.SaveAsNewItemResponse2;
import com.teamcenter.services.strong.query.SavedQueryService;
import com.teamcenter.services.strong.query._2006_03.SavedQuery.GetSavedQueriesResponse;
import com.teamcenter.services.strong.query._2006_03.SavedQuery.SavedQueryObject;
import com.teamcenter.services.strong.query._2007_06.SavedQuery.ExecuteSavedQueriesResponse;
import com.teamcenter.services.strong.query._2007_06.SavedQuery.SavedQueryInput;
import com.teamcenter.services.strong.query._2007_09.SavedQuery;
import com.teamcenter.soa.client.Connection;
import com.teamcenter.soa.client.FileManagementUtility;
import com.teamcenter.soa.client.GetFileResponse;
import com.teamcenter.soa.client.model.ModelObject;
import com.teamcenter.soa.client.model.Property;
import com.teamcenter.soa.client.model.ServiceData;
import com.teamcenter.soa.client.model.strong.*;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

public class KUtil {


    private static User loginedUser;
    public static DataManagementService dmService;
    private static Map<String, ModelObject> loadedObjects = new HashMap<String, ModelObject>();
    private static Map<String, ImanQuery> loadedQueries = new HashMap<String, ImanQuery>();
    private static SavedQueryService queryService;
    private static AppXSession session;

    private KUtil() {

    }
    public static void changeOwner(ModelObject newComp, User userOwn, Group group) {
        com.teamcenter.services.strong.core._2006_03.DataManagement.ObjectOwner objectOwner
                = new com.teamcenter.services.strong.core._2006_03.DataManagement.ObjectOwner();
        objectOwner.object = newComp;
        objectOwner.owner = userOwn;
        objectOwner.group = group;
        //更改所有者
        dmService.changeOwnership(new com.teamcenter.services.strong.core._2006_03.DataManagement.ObjectOwner[]{objectOwner});
    }

    public static void changeOwners(ModelObject[] newComps, User userOwn, Group group) {
        com.teamcenter.services.strong.core._2006_03.DataManagement.ObjectOwner[] mobjs =
                new com.teamcenter.services.strong.core._2006_03.DataManagement.ObjectOwner[newComps.length];
        for (int i = 0; i < newComps.length; i++) {
            com.teamcenter.services.strong.core._2006_03.DataManagement.ObjectOwner objectOwner =
                    new com.teamcenter.services.strong.core._2006_03.DataManagement.ObjectOwner();
            objectOwner.object = newComps[i];
            objectOwner.owner = userOwn;
            objectOwner.group = group;
            mobjs[i] = objectOwner;
        }
        dmService.changeOwnership(mobjs);
    }

    /**
     * 通过SOA创建ITEM对象
     *
     * @param itemID
     *            创建对象的ID
     * @param itemRev
     *            创建对象的版本
     * @param itemType
     *            创建对象的类型
     * @param itemName
     *            创建对象的名称
     * @param itemDesc
     *            创建对象的描述
     * @param unit
     *            创建对象的单位
     * @param itemPropMap
     *            创建对象的ITEM属性
     * @param itemRevPropMap
     *            创建对象的版本属性
     * @param itemRevMasterPropMap
     *            创建对象的版本表单属性
     */
    public static Item createNewItemSoa(
            String itemID, String itemRev, String itemType, String itemName,
            String itemDesc, String unit, Map<String, String> itemPropMap,
            Map<String, String> itemRevPropMap,
            Map<String, String> itemRevMasterPropMap, Group group, User userOwn, ItemRevision zcRev) {
        Item newComp = null;
        try {
            DataManagementService datamanagementservice = DataManagementService
                    .getService(AppXSession.getConnection());
            com.teamcenter.services.strong.core._2006_03.DataManagement.CreateItemsResponse createitemsresponse = null;
            // 设置创建对象的主要属性
            com.teamcenter.services.strong.core._2006_03.DataManagement.ItemProperties aitemproperties[] = new com.teamcenter.services.strong.core._2006_03.DataManagement.ItemProperties[1];
            aitemproperties[0] = new com.teamcenter.services.strong.core._2006_03.DataManagement.ItemProperties();
            aitemproperties[0].clientId = Integer.toString(1);
            aitemproperties[0].description = itemDesc;
            aitemproperties[0].itemId = itemID;
            aitemproperties[0].name = itemName;
            aitemproperties[0].revId = itemRev;
            aitemproperties[0].type = itemType;
            aitemproperties[0].uom = unit;
            ArrayList<com.teamcenter.services.strong.core._2006_03.DataManagement.ExtendedAttributes> list = new ArrayList<com.teamcenter.services.strong.core._2006_03.DataManagement.ExtendedAttributes>();
            // 设置item对象的扩展属性
            if (itemPropMap != null) {
                com.teamcenter.services.strong.core._2006_03.DataManagement.RevisionIds revids = null;
                com.teamcenter.services.strong.core._2006_03.DataManagement.ExtendedAttributes extendedattributesItem = new com.teamcenter.services.strong.core._2006_03.DataManagement.ExtendedAttributes();
                extendedattributesItem = new com.teamcenter.services.strong.core._2006_03.DataManagement.ExtendedAttributes();
                extendedattributesItem.objectType = itemType;
                extendedattributesItem.attributes = itemPropMap;
                list.add(extendedattributesItem);
            }
            // 设置REV的扩展属性
            if (itemRevPropMap != null) {
                com.teamcenter.services.strong.core._2006_03.DataManagement.ExtendedAttributes extendedattributesRev = new com.teamcenter.services.strong.core._2006_03.DataManagement.ExtendedAttributes();
                extendedattributesRev = new com.teamcenter.services.strong.core._2006_03.DataManagement.ExtendedAttributes();
                extendedattributesRev.objectType = itemType + "Revision";
                extendedattributesRev.attributes = itemRevPropMap;
                list.add(extendedattributesRev);
            }
            // 设置REVMASTER的扩展属性
            if (itemRevMasterPropMap != null) {
                com.teamcenter.services.strong.core._2006_03.DataManagement.ExtendedAttributes extendedattributesRevMaster = new com.teamcenter.services.strong.core._2006_03.DataManagement.ExtendedAttributes();
                extendedattributesRevMaster = new com.teamcenter.services.strong.core._2006_03.DataManagement.ExtendedAttributes();
                extendedattributesRevMaster.objectType = itemType
                        + "RevisionMaster";
                extendedattributesRevMaster.attributes = itemRevMasterPropMap;
                list.add(extendedattributesRevMaster);
            }
            // 添加扩展属性
            if (list.size() != 0) {
                com.teamcenter.services.strong.core._2006_03.DataManagement.ExtendedAttributes extendedattributes[] = null;
                extendedattributes = new com.teamcenter.services.strong.core._2006_03.DataManagement.ExtendedAttributes[list
                        .size()];
                for (int i = 0; i < list.size(); i++) {
                    extendedattributes[i] = list.get(i);
                }
                aitemproperties[0].extendedAttributes = extendedattributes;
            }
            ModelObject tccomponent1 = null;
            String s1 = "";
            createitemsresponse = datamanagementservice.createItems(
                    aitemproperties, tccomponent1, s1);
            if (createitemsresponse.serviceData.sizeOfPartialErrors() == 0) {
                newComp = createitemsresponse.output[0].item;

                changeOwner(newComp,userOwn,group);
                changeOwner(createitemsresponse.output[0].itemRev,userOwn,group);
                com.teamcenter.services.strong.core._2006_03.DataManagement.Relationship[]
                        rela_vec = new com.teamcenter.services.strong.core._2006_03.DataManagement.Relationship[1];
                com.teamcenter.services.strong.core._2006_03.DataManagement.Relationship
                        one_rela = new com.teamcenter.services.strong.core._2006_03.DataManagement.Relationship();
                one_rela.clientId = "";
                one_rela.primaryObject = createitemsresponse.output[0].itemRev;
                one_rela.secondaryObject = zcRev;
                one_rela.relationType = "IMAN_METarget";
                one_rela.userData = null;
                rela_vec[0] = one_rela;
                dmService.createRelations(rela_vec);
            }else {
                System.out.println(createitemsresponse.serviceData.getPartialError(0).getMessages()[0]);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("创建对象[item_id= " + itemID + " / rev =" + itemRev
                    + " / name= " + itemName + "]失败");
        }
        return newComp;
    }
    public static Item saveAsItem(ItemRevision rev, String itemId, String revId, String name, Group group, User userOwn, ItemRevision gyrev){
        DataManagementService service1 = DataManagementService.getService(AppXSession.getConnection());

        SaveAsNewItemInfo[] infos =
                new SaveAsNewItemInfo[1];
        SaveAsNewItemInfo info =
                new SaveAsNewItemInfo();
        info.baseItemRevision = rev;
        info.newItemId = itemId;
        info.name = name;
        info.newRevId = revId;
        info.clientId = "clientId";

        infos[0] = info;

        try {
//            service1.revise()
//            service1.revise()
            System.out.println("开始另存");
            SaveAsNewItemResponse2 saveAsNewItem = service1.saveAsNewItem2(infos);
            System.out.println("结束另存");
            ServiceData serviceData = saveAsNewItem.serviceData;
            KUtil.checkPartialError(serviceData);
            int sizeOfCreatedObjects = saveAsNewItem.serviceData.sizeOfCreatedObjects();
            System.out.println("另存对象个数："+sizeOfCreatedObjects);
            Item createdObject = null;
            if(saveAsNewItem.serviceData.sizeOfCreatedObjects()>0){
                for (int t = 0; t < sizeOfCreatedObjects; t++) {
                    ModelObject modj = saveAsNewItem.serviceData.getCreatedObject(t);
                    if (modj instanceof Item) {
                        System.out.println("开始修改所有权");
                        createdObject = (Item) saveAsNewItem.serviceData.getCreatedObject(t);
                        try {
                            refreshAndGetProperties(createdObject, new String[] {"revision_list","bom_view_tags"});

                            ModelObject[] revisionList = createdObject.get_revision_list();
                            System.out.println("开始修改所有权");
                            changeOwner(createdObject,userOwn,group);
                            changeOwner(revisionList[0],userOwn,group);
                            System.out.println("结束修改所有权");
                            removeRelation("IMAN_METarget", revisionList[0]);
                            if(gyrev != null) {
                                com.teamcenter.services.strong.core._2006_03.DataManagement.Relationship[]
                                        rela_vec = new com.teamcenter.services.strong.core._2006_03.DataManagement.Relationship[1];
                                com.teamcenter.services.strong.core._2006_03.DataManagement.Relationship
                                        one_rela = new com.teamcenter.services.strong.core._2006_03.DataManagement.Relationship();
                                one_rela.clientId = "";
                                //one_rela.primaryObject = createitemsresponse.output[0].itemRev;
                                one_rela.primaryObject = revisionList[0];
                                one_rela.secondaryObject = gyrev;
                                one_rela.relationType = "IMAN_METarget";
                                one_rela.userData = null;
                                rela_vec[0] = one_rela;
                                dmService.createRelations(rela_vec);
                            }
                            ModelObject[] bom_view_tags = createdObject.get_bom_view_tags();
                            if(bom_view_tags!=null && bom_view_tags.length>0) {
                                changeOwner(bom_view_tags[0],userOwn,group);
                            }



                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }

//                System.out.println("createdObject"+createdObject);
                return createdObject;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void removeRelation(String relationType, ModelObject revision) throws Exception {
        refreshAndGetProperties(revision, new String[] { relationType });
        ModelObject[] modelObjectArrayValue = revision.getPropertyObject(relationType).getModelObjectArrayValue();
        byte b;
        int i;
        ModelObject[] arrayOfModelObject1;
        for (i = (arrayOfModelObject1 = modelObjectArrayValue).length, b = 0; b < i; ) {
            ModelObject modelObject = arrayOfModelObject1[b];
            com.teamcenter.services.strong.core._2006_03.DataManagement.Relationship[] rela_vec = new com.teamcenter.services.strong.core._2006_03.DataManagement.Relationship[1];
            com.teamcenter.services.strong.core._2006_03.DataManagement.Relationship one_rela = new com.teamcenter.services.strong.core._2006_03.DataManagement.Relationship();
            one_rela.clientId = "Connor";
            one_rela.primaryObject = revision;
            one_rela.secondaryObject = modelObject;
            one_rela.relationType = relationType;
            one_rela.userData = null;
            rela_vec[0] = one_rela;
            ServiceData serviceData = dmService.deleteRelations(rela_vec);
            b++;
        }
    }
    public static void getChildTask(ScheduleTask fnd0SummaryTask, ArrayList<ScheduleTask> child_tasks){
        try {
            child_tasks.add(fnd0SummaryTask);
            KUtil.refreshAndGetProperties(fnd0SummaryTask, "child_task_taglist");
            ScheduleTask[] child_task_taglist = fnd0SummaryTask.get_child_task_taglist();
            for(ScheduleTask scheduleTask:child_task_taglist){
                getChildTask(scheduleTask,child_tasks);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    public static void checkLogin() throws Exception {
        if (loginedUser == null) {
            throw new Exception("请先登录");
        }
    }

    public static User getLoginUser() {
        return loginedUser;
    }


    public static GroupMember findGroupMember(String group, String role, String userId)
    {
        ImanQuery query = null;
        GroupMember groupMember = null;

        SavedQueryService queryService = SavedQueryService.getService(session.getConnection());
        DataManagementService dmService= DataManagementService.getService(session.getConnection());
        try
        {
            GetSavedQueriesResponse savedQueries = queryService.getSavedQueries();
            if (savedQueries.queries.length == 0)
            {
                System.out.println("There are no saved queries in the system.");
                return groupMember;
            }

            for (int i = 0; i < savedQueries.queries.length; i++)
            {

                if (savedQueries.queries[i].name.equals("__EINT_group_members"))
                {
                    query = savedQueries.queries[i].query;
                    break;
                }
            }
        }
        catch (ServiceException e)
        {
            System.out.println("GetSavedQueries service request failed.");
            System.out.println(e.getMessage());
            return groupMember;
        }

        if (query == null)
        {
            System.out.println("There is not an '__EINT_group_members' query.");
            return groupMember;
        }

//        try
//        {
        com.teamcenter.services.strong.query._2008_06.SavedQuery.QueryInput savedQueryInput[] = new com.teamcenter.services.strong.query._2008_06.SavedQuery.QueryInput[1];
        savedQueryInput[0] = new com.teamcenter.services.strong.query._2008_06.SavedQuery.QueryInput();
        savedQueryInput[0].query = query;
        savedQueryInput[0].entries = new String[3];
        savedQueryInput[0].values = new String[3];
        savedQueryInput[0].entries[0] = "Group";
        savedQueryInput[0].values[0] = "*";
        savedQueryInput[0].entries[1] = "Role";
        savedQueryInput[0].values[1] = "*";
        savedQueryInput[0].entries[2] = "User";
        savedQueryInput[0].values[2] = userId;
        savedQueryInput[0].maxNumToReturn = 25;

        SavedQuery.SavedQueriesResponse savedQueryResult = queryService.executeSavedQueries(savedQueryInput);
        SavedQuery.QueryResults found = savedQueryResult.arrayOfResults[0];

        int length = found.objectUIDS.length;

        String[] uids = new String[length];
        for( int ii = 0; ii < length; ii++)
        {
            uids[ii]= found.objectUIDS[ii];
        }
        ServiceData sd = dmService.loadObjects(uids);
        ModelObject[] foundObjs = new ModelObject[ sd.sizeOfPlainObjects()];
        for( int k =0; k< sd.sizeOfPlainObjects(); k++)
        {
            foundObjs[k] = sd.getPlainObject(k);
        }
        groupMember = (GroupMember) foundObjs[0];
//        }
//        catch (Exception e)
//        {
//            System.out.println("ExecuteSavedQuery service request failed.");
//            System.out.println(e.getMessage());
//        }
        return groupMember;
    }

    public synchronized static ModelObject UidToString(String uid) {


        ServiceData sd = dmService.loadObjects(new String[] {uid});
//         ModelObject[] foundObjs = new ModelObject[ sd.sizeOfPlainObjects()];

        if(sd.sizeOfPartialErrors()>0) {


            return null;
        }


        return sd.getPlainObject(0);

    }



    public synchronized static AppXSession login(String url, String user, String password) throws Exception {
        System.out.println("登录到TC：" + user + "url" + url);
        String group = "";
        String role = "";

        System.out.println("开始连接服务器："+url+ new Date());
        session = new AppXSession(url);

        try {
            System.out.println("开始登录" +new Date());
            loginedUser = session.login(user, password, group, role);

            System.out.println("登陆成功");
//            loginedUser.get_de
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("登录失败");
        }
        if (loginedUser == null) {
            throw new Exception("登录到Teamcenter失败");
        }
        dmService = DataManagementService.getService(AppXSession.getConnection());
        queryService = SavedQueryService.getService(AppXSession.getConnection());
        return session;
    }

    public static void getProperties(ModelObject modelObject, String... properties) throws Exception {
        loadedObjects.put(modelObject.getUid(), modelObject);
        ServiceData resp = dmService.getProperties(new ModelObject[]{modelObject}, properties);
        checkPartialError(resp);
    }

    public static void refreshAndGetProperties(ModelObject modelObject, String... properties) throws Exception {
        System.out.println("开始刷新");
        ServiceData resp = dmService.refreshObjects(new ModelObject[]{modelObject});
        System.out.println("结束刷新");
        checkPartialError(resp);
        System.out.println("获取属性");
        getProperties(modelObject, properties);
        System.out.println("结束属性");
    }

    public static List<ModelObject> getGRMChildren(ModelObject modelObject, String relation, String[] typeNames) throws Exception {
        List<ModelObject> res = new ArrayList<ModelObject>();
        ExpandGRMRelationsPref pref = new ExpandGRMRelationsPref();
        RelationAndTypesFilter2 filter = new RelationAndTypesFilter2();
        filter.relationName = relation;
        filter.objectTypeNames = typeNames;
        pref.expItemRev = false;
        pref.info = new RelationAndTypesFilter2[]{filter};
        ExpandGRMRelationsResponse resp = dmService.expandGRMRelationsForPrimary(new ModelObject[]{modelObject}, pref);
        checkPartialError(resp.serviceData);
        ExpandGRMRelationsData[] datas = resp.output[0].otherSideObjData;
        int len = KUtil.getLen(datas);
        for (int i = 0; i < len; i++) {
            ExpandGRMRelationsData data = datas[i];
            ModelObject[] cc = data.otherSideObjects;
            int childCnt = KUtil.getLen(cc);
            for (int j = 0; j < childCnt; j++) {
                res.add(cc[i]);
            }
        }
        return res;
    }

    public synchronized static void logoutAndClearCache2() {
        if (loginedUser == null) {
            return;
        }
//        KUtil.log(logger, "注销并释放资源");
        try {
            if (loadedObjects.size() > 0) {
                dmService.unloadObjects(loadedObjects.values().toArray(new ModelObject[]{}));
            }
        } catch (Exception e) {
            e.printStackTrace();
//            KUtil.log(logger, "卸载对象失败", e);
        }
        try {
            setByPass(false);
        } catch (Exception e) {
            e.printStackTrace();
//            KUtil.log(logger, "关闭旁路失败", e);
        }
        session.logout();
        loginedUser = null;
//        KUtil.log(logger, "已结束");
    }

    public static void checkPartialError(ServiceData data) throws Exception {
        if (data.sizeOfPartialErrors() > 0) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < data.sizeOfPartialErrors(); i++) {
                for (String msg : data.getPartialError(i).getMessages()) {
                    sb.append(msg + "\r\n");
                }
            }
            if (sb.length() > 0) {
                throw new Exception(sb.toString());
            }
        }
    }

    public static boolean isEmpty(String str) {
        return str == null || "".equals(str.trim());
    }

    public static ImanQuery findQuery(String queryName) throws Exception {
        if (KUtil.isEmpty(queryName)) {
            throw new Exception("查询名称不可为空");
        }
        if (loadedQueries.containsKey(queryName)) {
            return loadedQueries.get(queryName);
        }
        GetSavedQueriesResponse resp = queryService.getSavedQueries();
        checkPartialError(resp.serviceData);
        int len = resp.queries == null ? 0 : resp.queries.length;
        for (int i = 0; i < len; i++) {
            SavedQueryObject queryObj = resp.queries[i];
            if (queryName.equals(queryObj.name)) {
                loadedQueries.put(queryName, queryObj.query);
                return queryObj.query;
            }
        }
        throw new Exception("未找到保存的查询“" + queryName + "”");
    }

    public static List<ModelObject> query(ImanQuery query, String[] entries, String[] values) throws Exception {
        List<ModelObject> res = new ArrayList<ModelObject>();
        SavedQueryInput input = new SavedQueryInput();
        input.query = query;
        input.entries = entries;
        input.values = values;
        input.resultsType = 0;
        ExecuteSavedQueriesResponse resp = queryService.executeSavedQueries(new SavedQueryInput[]{input});
        checkPartialError(resp.serviceData);
        for (ModelObject e : resp.arrayOfResults[0].objects) {
            res.add(e);
        }
        return res;
    }

    public static void setByPass(boolean b) throws Exception {
        Session.StateNameValue[] propPairs = new Session.StateNameValue[1];
        propPairs[0] = new Session.StateNameValue();
        propPairs[0].name = new String("bypassFlag");
        propPairs[0].value = new String(Property.toBooleanString(b));
        ServiceData data = SessionService.getService(AppXSession.getConnection()).setUserSessionState(propPairs);
        checkPartialError(data);
    }

    public static void setProperty(ModelObject mo, String propName, String propValue) throws Exception {
        Map<String, DataManagement.VecStruct> properties = new HashMap<String, DataManagement.VecStruct>();
        DataManagement.VecStruct vec = new DataManagement.VecStruct();
        vec.stringVec = new String[]{propValue};
        properties.put(propName, vec);
        ServiceData sd = dmService.setProperties(new ModelObject[]{mo}, properties);
        checkPartialError(sd);
    }

    public static void openByPass() {
        Session.StateNameValue[] propPairs = new Session.StateNameValue[1];
        propPairs[0] = new Session.StateNameValue();
        (propPairs[0]).name = "bypassFlag";
        (propPairs[0]).value = Property.toBooleanString(true);
        ServiceData data = SessionService.getService(AppXSession.getConnection()).setUserSessionState(propPairs);
    }

    public static void closeByPass() {
        Session.StateNameValue[] propPairs = new Session.StateNameValue[1];
        propPairs[0] = new Session.StateNameValue();
        (propPairs[0]).name = "bypassFlag";
        (propPairs[0]).value = Property.toBooleanString(false);
        ServiceData data = SessionService.getService(AppXSession.getConnection()).setUserSessionState(propPairs);
    }
    public static File[] getDatasetFile(Dataset dataset, DataManagementService dm, String fmsurl) throws Exception {
        if (dataset == null) {
            return null;
        }
        ModelObject[] mo = new ModelObject[]{dataset};
        dm.refreshObjects(mo);
        dm.getProperties(mo, new String[]{"ref_list"});
        ModelObject[] files = dataset.get_ref_list();
        if (files.length == 0) {
            return null;
        }
        ImanFile imanFile = (ImanFile) files[0];
//        imanFile.get_fi
        dm.getProperties(new ModelObject[]{imanFile}, new String[]{"original_file_name"});
        String fileName = imanFile.get_original_file_name();
        String[] url = new String[]{fmsurl};
        GetFileResponse resp = null;
        try {
            FileManagementUtility fm = new FileManagementUtility(AppXSession.getConnection(), null, null, url,"D:\\");
            resp = fm.getFiles(new ModelObject[]{imanFile});
            throwServiceDataError(resp);
        } catch (Exception e) {
//            e.printStackTrace();

            FileManagementUtility fm = new FileManagementUtility(AppXSession.getConnection(), null, null, new String[]{fmsurl.replaceAll("Server1","Server2")}, "D:\\");
            resp = fm.getFiles(new ModelObject[]{imanFile});
            throwServiceDataError(resp);

        }

        File[] respFiles = resp.getFiles();
        File targetFile = new File("D:\\" + fileName);
        if (respFiles.length > 0) {
            respFiles[0].renameTo(targetFile);
        }

        dm.deleteObjects(new ModelObject[] {dataset});

        return new File[]{targetFile};
    }
    public static void throwServiceDataError(GetFileResponse serviceData) throws Exception {
        if (serviceData.sizeOfPartialErrors() > 0) {
            StringBuilder errInfo = new StringBuilder();
            for (int i = 0; i < serviceData.sizeOfPartialErrors(); i++) {
                for (String msg : serviceData.getPartialError(i).getMessages()) {
                    errInfo.append(msg + "\n");
                }
            }
            throw new Exception(errInfo.toString());
        }
    }
    public static Dataset createDataset(ItemRevision revision, DataManagementService dmService, String name) throws Exception {
        Dataset dataset = null;
        openByPass();
        com.teamcenter.services.strong.core._2010_04.DataManagement.DatasetInfo[] datasetInfos = new com.teamcenter.services.strong.core._2010_04.DataManagement.DatasetInfo[1];
        datasetInfos[0] = new com.teamcenter.services.strong.core._2010_04.DataManagement.DatasetInfo();
        datasetInfos[0].name = name;
        datasetInfos[0].type = "PDF";
        datasetInfos[0].description = "TCServerCreate";
        com.teamcenter.services.strong.core._2010_04.DataManagement.CreateDatasetsResponse response = dmService.createDatasets(datasetInfos);
        dataset = response.datasetOutput[0].dataset;
        com.teamcenter.services.strong.core._2006_03.DataManagement.Relationship[]
                rela_vec = new com.teamcenter.services.strong.core._2006_03.DataManagement.Relationship[1];
        com.teamcenter.services.strong.core._2006_03.DataManagement.Relationship
                one_rela = new com.teamcenter.services.strong.core._2006_03.DataManagement.Relationship();
        one_rela.clientId = "";
        one_rela.primaryObject = revision;
        one_rela.secondaryObject = dataset;
        one_rela.relationType = "IMAN_specification";
        one_rela.userData = null;
        rela_vec[0] = one_rela;

        //解除锁定对象
        dmService.refreshObjects2(new ModelObject[]{revision, dataset}, false);

        //创建关系
        com.teamcenter.services.strong.core._2006_03.DataManagement.CreateRelationsResponse
                reResp = null;
        int breakTime = 0;
        boolean createSuccess = false;
        while (!createSuccess){
            try {
                reResp= dmService.createRelations(rela_vec);
                createSuccess = true;
            }catch (Exception e){
                createSuccess = false;
                System.out.println("创建关系失败:");
            }
            breakTime ++;

            Thread.sleep(1000);

            if(breakTime > 15){
                System.out.println("循环15秒创建关系依旧失败，不再创建关系");
                break;
            }
        }
        System.out.println("开始更改所有者");
        //获取版本的所有者和所有组
        dmService.getProperties(new ModelObject[]{revision}, new String[]{"owning_user", "owning_group"});

        User ownUser = (User) revision.get_owning_user();
        Group ownGroup = (Group) revision.get_owning_group();
        com.teamcenter.services.strong.core._2006_03.DataManagement.ObjectOwner objectOwner
                = new com.teamcenter.services.strong.core._2006_03.DataManagement.ObjectOwner();
        objectOwner.object = dataset;
        objectOwner.owner = ownUser;
        objectOwner.group = ownGroup;
        Date sourcetime = new Date();
        //更改所有者
        dmService.changeOwnership(new com.teamcenter.services.strong.core._2006_03.DataManagement.ObjectOwner[]{objectOwner});
        System.out.println("结束更改所有者");
        dmService.refreshObjects2(new ModelObject[]{revision, dataset}, false);
        if (reResp!=null && reResp.serviceData.sizeOfPartialErrors() > 0) {
            System.out.println("下挂数据集失败");
//            logger.info(String.format("对版本对象[%s]数据集对象[%s]下挂数据集失败[%s]"));
            return null;
        }
        System.out.println("结束创建关系");
        closeByPass();
        return dataset;
    }

    public static void upload(String filePath, DataManagementService dmService, Dataset dataset, String fmsurl){

        Connection connection = AppXSession.getConnection();
        System.out.println("开始上传文件"+dataset.getUid());
        FileManagementService service = FileManagementService.getService(AppXSession.getConnection());
//    	Connection connection = com.teamcenter.clientx.Session.getConnection();
        openByPass();
        String[] url = { fmsurl };
        ModelObject[] mo = new ModelObject[]{dataset};
        dmService.refreshObjects(mo);
        FileManagementUtility fm = null;
        try {
            fm = new FileManagementUtility(connection, null, null, url, null);
            System.out.println(fm);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        FileManagement.DatasetFileInfo fileInfo = new FileManagement.DatasetFileInfo();
//        File file=new File(filePath);
//        if(file.exists()) {
//
//        }
        fileInfo.fileName = filePath;
        fileInfo.allowReplace = true;
        fileInfo.isText = false;
        fileInfo.namedReferencedName = "PDF_Reference";//"PDF_Reference";
        FileManagement.GetDatasetWriteTicketsInputData inputData = new FileManagement.GetDatasetWriteTicketsInputData();
        inputData.dataset = dataset;
        inputData.createNewVersion = false;
        inputData.datasetFileInfos = new FileManagement.DatasetFileInfo[]{fileInfo};
        ServiceData sd = fm.putFiles(new FileManagement.GetDatasetWriteTicketsInputData[]{inputData});
        try {
            throwServiceDataError(sd);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        dmService.refreshObjects(mo);
        System.out.println("上传文件完成");
        closeByPass();
    }


    public static void throwServiceDataError(ServiceData serviceData) throws Exception {
        if (serviceData.sizeOfPartialErrors() > 0) {
            StringBuilder errInfo = new StringBuilder();
            for (int i = 0; i < serviceData.sizeOfPartialErrors(); i++) {
                for (String msg : serviceData.getPartialError(i).getMessages()) {
                    errInfo.append(msg + "\n");
                }
            }
            throw new Exception(errInfo.toString());
        }
    }

    public static List<ModelObject> query(String queryName, String[] entries, String[] values) throws Exception {
//        KUtil.log(logger, "执行查询 %s %s = %s", queryName, Arrays.toString(entries), Arrays.toString(values));
        SavedQueryService queryService = SavedQueryService.getService(session.getConnection());
        ImanQuery query = null;
        GetSavedQueriesResponse savedQueries = queryService.getSavedQueries();
        for (int i = 0; i < savedQueries.queries.length; i++) {
            if (!savedQueries.queries[i].name.equals(queryName))
            {
                continue;
            }
            query = savedQueries.queries[i].query;
            break;
        }
        if (query == null) {
            System.out.println("There is not an " + queryName + " query.");
            return null;
        }
        List<ModelObject> res = new ArrayList<ModelObject>();
        SavedQueryInput input = new SavedQueryInput();
        input.query = query;
        input.entries = entries;
        input.values = values;
        input.resultsType = 0;
        ExecuteSavedQueriesResponse resp = queryService.executeSavedQueries(new SavedQueryInput[]{input});
        checkPartialError(resp.serviceData);
        for (ModelObject e : resp.arrayOfResults[0].objects) {
            res.add(e);
        }
        return res;
    }


    public static <E> int getLen(E[] arr) {
        return arr == null ? 0 : arr.length;
    }


    public static String getMessage(Exception e) {
        String message = e.getLocalizedMessage();
        if (KUtil.isEmpty(message)) {
            message = e.getClass().getName() + " - 无详细信息";
        }
        return message;
    }



}