package com.connor.sso.sso;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.connor.sso.sso.clientx.AppXSession;
import com.connor.sso.sso.mapper.ClassFieldBean;
import com.connor.sso.sso.mapper.FieldBean;
import com.connor.sso.sso.mapper.MyMapper;
import com.connor.sso.sso.mapper.SqlFieldBean;
import com.connor.sso.sso.util.LoginUtil;
import com.teamcenter.services.strong.classification.ClassificationService;
import com.teamcenter.services.strong.classification._2007_01.Classification;
import com.teamcenter.services.strong.core.DataManagementService;
import com.teamcenter.services.strong.core._2010_04.DataManagement;
import com.teamcenter.soa.client.Connection;
import com.teamcenter.soa.client.model.ModelObject;
import com.teamcenter.soa.client.model.ServiceData;
import com.teamcenter.soa.client.model.strong.Icm0;
import com.teamcenter.soa.client.model.strong.ItemRevision;
import com.teamcenter.soa.client.model.strong.WorkspaceObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
class TreeNode {
    private String id;
    private String parentId;
    private String name;
    private List<TreeNode> children = new ArrayList<>();

    public TreeNode(String id, String parentId,String name) {
        this.id = id;
        this.parentId = parentId;
        this.name = name;
    }

    @Override
    public String toString() {
        return "TreeNode{" +
                "id='" + id + '\'' +
                ", parentId='" + parentId + '\'' +
                ", name='" + name + '\'' +
                ", children=" + children +
                '}';
    }
// Getter 和 Setter


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getParentId() {
        return parentId;
    }

    public void setParentId(String parentId) {
        this.parentId = parentId;
    }

    public List<TreeNode> getChildren() {
        return children;
    }

    public void setChildren(List<TreeNode> children) {
        this.children = children;
    }
}
@RestController
@RequestMapping("/tc")
public class MyControl {

    @Autowired
    MyMapper mapper;
    @GetMapping("/getClassTree")
    public String getClassTree() {

        List<FieldBean> fieldBeans = mapper.selectTree();
        System.out.println("bean============"+fieldBeans.size());
        HashMap<String, String> map = new HashMap<>();
        String top = "";
        for (int i = 0; i < fieldBeans.size(); i++) {
            FieldBean fieldBean = fieldBeans.get(i);
            //根
            if((fieldBean.getPklassi() == null || fieldBean.getPklassi().isEmpty()) && (fieldBean.getParent() == null || fieldBean.getParent().isEmpty())){

               top = fieldBean.getPcid()+":"+fieldBean.getPname();
                //top = fieldBean.getPcid();
            }else if((fieldBean.getPklassi() == null || fieldBean.getPklassi().isEmpty()) && (fieldBean.getParent() != null && !fieldBean.getParent().isEmpty())){
                //map.put(fieldBean.getPcid(),fieldBean.getParent());
                map.put(fieldBean.getPcid()+":"+fieldBean.getPname(),fieldBean.getParent());
            }else if((fieldBean.getPklassi() != null && !fieldBean.getPklassi().isEmpty()) && (fieldBean.getParent() == null || fieldBean.getParent().isEmpty())){
                //map.put(fieldBean.getPcid(),fieldBean.getPklassi());

                map.put(fieldBean.getPcid()+":"+fieldBean.getPname(),fieldBean.getPklassi());
            }


        }

        // 存储所有节点
        Map<String, TreeNode> nodeMap = new HashMap<>();
        TreeNode root = new TreeNode(top.split(":")[0],"",top.split(":")[1]);
        nodeMap.put(top.split(":")[0],root);
        // 创建所有节点并放入 map 中
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String id = entry.getKey();
            String parentId = entry.getValue();
            String[] split = id.split(":");
            TreeNode node = new TreeNode(split[0], parentId,split[1]);
            nodeMap.put(split[0], node);

        }
        // 构建父子关系
        for (TreeNode node : nodeMap.values()) {
            if (node.getParentId() != null && nodeMap.containsKey(node.getParentId())) {
                TreeNode parent = nodeMap.get(node.getParentId());
                parent.getChildren().add(node);
            }
        }

        // 使用 FastJSON 输出树形结构
        String jsonTree = JSON.toJSONString(root, true); // true 表示格式化输出
        System.out.println(jsonTree);

        return jsonTree;
    }



    @PostMapping("/getClassFields")
    public String getClassField(@RequestBody String json) {

        JSONObject parse = (JSONObject) JSONObject.parse(json);
        String id = parse.getString("id");
        JSONObject result = new JSONObject();

        if(id == null || id.isEmpty()){
            result.put("result",false);
            result.put("msg","id不能为空!");
            return result.toString();
        }
        List<ClassFieldBean> maps = mapper.selectClassField(id);
        JSONArray fields = new JSONArray();
        for (int i = 0; i < maps.size(); i++) {
            ClassFieldBean bean = maps.get(i);
            JSONObject tempJsonObject = new JSONObject();
            tempJsonObject.put("fieldId",bean.getPunct());
            tempJsonObject.put("fieldName",bean.getPname());
            fields.add(tempJsonObject);
        }

        result.put("result",true);
        result.put("msg","success");
        result.put("fields",fields);
        return result.toString();
    }
    private AppXSession session;


    @PostMapping("/getClassData")
    public String getClassData(@RequestBody String json) {

        errorMsg = "";
        JSONObject parse = null;
        JSONObject result = new JSONObject();
        try{
            parse = (JSONObject) JSONObject.parse(json);
        }catch (Exception e){
            result.put("result",false);
            result.put("msg","json格式不对");
            return result.toString();
        }

        String id = parse.getString("id");

        if(id == null || id.isEmpty()){
            result.put("result",false);
            result.put("msg","id不能为空!");
            return result.toString();
        }


        List<SqlFieldBean> sqlFieldBeans = mapper.selectFields(id);
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT ");
        LinkedHashMap<String, ArrayList<Object>> stringArrayListLinkedHashMap = new LinkedHashMap<>();
        for (int i = 0; i < sqlFieldBeans.size(); i++) {
            SqlFieldBean sqlFieldBean = sqlFieldBeans.get(i);
            ArrayList<Object> strings = new ArrayList<>();
            strings.add(sqlFieldBean.getPunct());
            strings.add(sqlFieldBean.getPname());
            if(sqlFieldBean.getPdbindex() == 0){
                sql.append("p"+sqlFieldBean.getPref_options().toLowerCase());
                stringArrayListLinkedHashMap.put("p"+sqlFieldBean.getPref_options().toLowerCase(),strings);
            }else{
                sql.append("psm"+(sqlFieldBean.getPdbindex() < 10 ? "0" : "") + sqlFieldBean.getPdbindex());
                stringArrayListLinkedHashMap.put("psm"+(sqlFieldBean.getPdbindex() < 10 ? "0" : "") + sqlFieldBean.getPdbindex(),strings);
            }
            if(i != sqlFieldBeans.size() - 1){
                sql.append(",");
            }
        }
        sql.append(" from PICM0 p1 left join PITEMREVISION p3 on p3.puid = p1.rerefu  left join PITEM p4 on p4.puid = p3.ritems_tagu left join PWORKSPACEOBJECT p5 on p1.rerefu = p5.puid left join PG2_DESIGNREVISION p2 on p1.rerefu = p2.puid where p1.pcid = '");
        sql.append(id);
        sql.append("'");
        System.out.println("sql======"+sql.toString());
        List<Map<String, String>> lists = mapper.selectClassData(sql.toString());
       // System.out.println("lists=="+lists);
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < lists.size(); i++) {
            Map<String, String> tempMap = lists.get(i);

            JSONArray tempJsonArray = new JSONArray();
            JSONObject lineObject = new JSONObject();


            for (Map.Entry<String, ArrayList<Object>> map : stringArrayListLinkedHashMap.entrySet()
            ) {
                JSONObject tempObject = new JSONObject();
                String key = map.getKey();
                ArrayList<Object> value = map.getValue();
                if(tempMap != null && tempMap.containsKey(key)){
                    tempObject.put("fieldId",(Integer)value.get(0));
                    tempObject.put("fieldName",(String)value.get(1));
                    tempObject.put("fieldValue",tempMap.get(key));
                    tempJsonArray.add(tempObject);
                }else{
                    tempObject.put("fieldId",(Integer)value.get(0));
                    tempObject.put("fieldName",(String)value.get(1));
                    tempObject.put("fieldValue","");
                    tempJsonArray.add(tempObject);
                }

            }
            lineObject.put("line",tempJsonArray);

            jsonArray.add(lineObject);
        }

        result.put("result",true);
        result.put("msg","success");
        result.put("data",jsonArray);





        JSONArray conditionsArray = JSONObject.parseObject(json).getJSONArray("conditions");
        if(conditionsArray == null || conditionsArray.size() <= 0){
            return result.toString();
        }
        List<Condition> conditions = parseConditions(conditionsArray);



        JSONArray dataArray = result.getJSONArray("data");

        // 构造最终输出
        JSONObject resultJsonObject = new JSONObject();
        resultJsonObject.put("result", true);
        resultJsonObject.put("msg", "success");

        JSONArray filteredData = new JSONArray();

        for (int i = 0; i < dataArray.size(); i++) {
            JSONObject itemObject = dataArray.getJSONObject(i);
            JSONArray lineArray = itemObject.getJSONArray("line");
            if (matchesAllConditions(lineArray, conditions)) {
                filteredData.add(itemObject);
            }
        }

        System.out.println("errorMsg========"+errorMsg);
        if(!errorMsg.isEmpty()){
            JSONObject resultError = new JSONObject();
                resultError.put("result",false);
                resultError.put("msg",errorMsg);
                return resultError.toString();
        }


        resultJsonObject.put("data", filteredData);



        return resultJsonObject.toJSONString();

//        try{
//            if(session == null){
//                System.out.println("开始登录");
//                LoginUtil loginUtil = new LoginUtil(SsoApplication.tcUrl,SsoApplication.user,SsoApplication.pass);
//                session = loginUtil.loginTC();
//                System.out.println("登录成功");
//            }
//            List<String> list = mapper.selectClassData(id);
//            System.out.println("list=================="+list.size());
//            DataManagementService service = DataManagementService.getService(AppXSession.getConnection());
//
//            ServiceData sd = service.loadObjects(new String[]{"AsFAAEbt526JcB"});
//              ModelObject[] foundObjs = new ModelObject[ sd.sizeOfPlainObjects()];
//            for( int k =0; k< sd.sizeOfPlainObjects(); k++) {
//                foundObjs[k] = sd.getPlainObject(k);
//            }
//
//          //  ServiceData sd = service.loadObjects(list.toArray(new String[0]));
//
//          //  ModelObject[] foundObjs = new ModelObject[ sd.sizeOfPlainObjects()];
////            for( int k =0; k< sd.sizeOfPlainObjects(); k++)
////            {
////                foundObjs[k] = sd.getPlainObject(k);
////                Classification.ClassificationObject classificationObject = (Classification.ClassificationObject)sd.getPlainObject(k);
////                Classification.ClassificationProperty[] properties = classificationObject.properties;
////                for (Classification.ClassificationProperty property : properties) {
////                    Integer sxId = property.attributeId;
////                    String value = property.values[0].dbValue;
////
////                    System.out.println("sxId="+sxId+"-----value="+value);
////                }
////            }
//
//
//            Connection connection = session.getConnection();
//            // 获取服务
//            ClassificationService classService = ClassificationService.getService(connection);
//            // 1. 批量获取分类对象
//            Classification.FindClassificationObjectsResponse classificationObjects1 = classService.findClassificationObjects(new WorkspaceObject[]{(ItemRevision)foundObjs[0]});
//            //获取分类对象
//            Map<WorkspaceObject, ModelObject[]> icos = classificationObjects1.icos;
//
//            if (icos.size() > 0) {
//                List<ModelObject> classObjs = new ArrayList<>();
//                for(Map.Entry<WorkspaceObject, ModelObject[]> entry : icos.entrySet()){
//                    if(entry.getValue() != null && entry.getValue().length > 0){
//                        System.out.println("key:"+entry.getKey().getUid());
//                        System.out.println("value::"+entry.getValue()[0].getUid());
//                        classObjs.add(entry.getValue()[0]);
//                    }
//                }
//                Classification.GetClassificationObjectsResponse classificationObjects =
//                        classService.getClassificationObjects(classObjs.toArray(new ModelObject[0]));
//                Map<ModelObject, Classification.ClassificationObject> classObjects = classificationObjects.clsObjs;
//                //获取对象和分类的映射
//                for (ModelObject mod : classObjects.keySet()) {
//                    Classification.ClassificationObject classificationObject = classObjects.get(mod);
//                    Classification.ClassificationProperty[] properties = classificationObject.properties;
//                    for (Classification.ClassificationProperty property : properties) {
//                        try{
//                            Integer sxId = property.attributeId;
//                            System.out.println("sxid==="+sxId);
//                            String value = property.values[0].dbValue;
//                            System.out.println("sxId="+sxId+"-----value="+value);
//
//                        }catch (Exception e){
//                            System.out.println("111111111111");
//                        }
//                    }
//                }
//            }
//
//
//        }catch (Exception e){
//            e.printStackTrace();
//        }

    }


private String errorMsg = "";




    private List<Condition> parseConditions(JSONArray conditionsArray) {
        List<Condition> conditions = new ArrayList<>();
        for (int i = 0; i < conditionsArray.size(); i++) {
            JSONObject conditionObj = conditionsArray.getJSONObject(i);
            Condition cond = new Condition();
            cond.fieldId = conditionObj.getString("fieldId");
            cond.operator = conditionObj.getString("operator").trim();
            cond.value = conditionObj.getString("value");
            cond.min = conditionObj.getString("min");
            cond.max = conditionObj.getString("max");
            conditions.add(cond);
        }
        return conditions;
    }

    private boolean matchesAllConditions(JSONArray lineArray, List<Condition> conditions) {
        Map<String, String> fieldMap = new HashMap<>();

        // 构建 fieldId -> fieldValue 映射
        for (int i = 0; i < lineArray.size(); i++) {
            JSONObject fieldObj = lineArray.getJSONObject(i);
            String fieldId = fieldObj.getString("fieldId");
            String fieldValue = fieldObj.getString("fieldValue");
            fieldMap.put(fieldId, fieldValue);
        }

        for (Condition cond : conditions) {
            String fieldValue = fieldMap.get(cond.fieldId);
            if (fieldValue == null) continue; // 忽略不存在的字段

            if (!evaluateCondition(fieldValue, cond)) {
                return false;
            }
        }
        return true;
    }

    private boolean evaluateCondition(String fieldValue, Condition cond) {
        switch (cond.operator) {
            case "等于":
                return fieldValue.equals(cond.value);
            case "不等于":
                return !fieldValue.equals(cond.value);
            case "小于":
                return compare(fieldValue, cond.value) < 0;
            case "小于等于":
                return compare(fieldValue, cond.value) <= 0;
            case "大于":
                return compare(fieldValue, cond.value) > 0;
            case "大于等于":
                return compare(fieldValue, cond.value) >= 0;
            case "包含":
                return fieldValue.contains(cond.value);
            case "不包含":
                return !fieldValue.contains(cond.value);
            case "开始以":
                return fieldValue.startsWith(cond.value);
            case "结束以":
                return fieldValue.endsWith(cond.value);
            case "开始不是以":
                return !fieldValue.startsWith(cond.value);
            case "结束不是以":
                return !fieldValue.endsWith(cond.value);
            case "是空的":
                return fieldValue.isEmpty();
            case "不是空的":
                return !fieldValue.isEmpty();
            case "介于":
                try {
                    double val = Double.parseDouble(fieldValue);
                    double minVal = Double.parseDouble(cond.min);
                    double maxVal = Double.parseDouble(cond.max);
                    return val >= minVal && val <= maxVal;
                } catch (NumberFormatException e) {
                    return false;
                }
            default:
                //throw new IllegalArgumentException("不支持的操作符: " + cond.operator);
                errorMsg = "不支持的操作符: " + cond.operator;
                return false;
        }
    }

    private int compare(String a, String b) {
        try {
            return Double.compare(Double.parseDouble(a), Double.parseDouble(b));
        } catch (NumberFormatException e) {
            return a.compareTo(b); // 字符串比较
        }
    }

    private static class Condition {
        String fieldId;
        String operator;
        String value;
        String min;
        String max;
    }

















    /**
     * 批量获取分类属性
     * @param
     * @param ids
     * @return
     */
    public void batchGetClassificationAttributes(ItemRevision[] workspaceObjects, List<String> ids, LinkedHashMap<String,List<String>> attrExportMap, DataManagementService dmService) {

        try {


            Connection connection = session.getConnection();
            // 获取服务
            ClassificationService classService = ClassificationService.getService(connection);
            // 1. 批量获取分类对象
            Classification.FindClassificationObjectsResponse classificationObjects1 = classService.findClassificationObjects(workspaceObjects);
            //获取分类对象
            Map<WorkspaceObject, ModelObject[]> icos = classificationObjects1.icos;

            if (icos.size() > 0) {
                List<ModelObject> classObjs = new ArrayList<>();
                for(Map.Entry<WorkspaceObject, ModelObject[]> entry : icos.entrySet()){
                    if(entry.getValue() != null && entry.getValue().length > 0){
                        System.out.println("key:"+entry.getKey().getUid());
                        System.out.println("value::"+entry.getValue()[0].getUid());
                        classObjs.add(entry.getValue()[0]);
                    }
                }
                Classification.GetClassificationObjectsResponse classificationObjects =
                        classService.getClassificationObjects(classObjs.toArray(new ModelObject[0]));
                Map<ModelObject, Classification.ClassificationObject> classObjects = classificationObjects.clsObjs;
                //获取对象和分类的映射
                for (ModelObject mod : classObjects.keySet()) {
                    Classification.ClassificationObject classificationObject = classObjects.get(mod);
                    Classification.ClassificationProperty[] properties = classificationObject.properties;
                    for (Classification.ClassificationProperty property : properties) {
                        Integer sxId = property.attributeId;
                        String value = property.values[0].dbValue;
                    }
                }
            }

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

    }



