import { deepClone, getAllChildren } from '@meta2d/core';

import axios from 'axios';
import { MessagePlugin } from 'tdesign-vue-next';
import i18n from '../i18n';
const $t = i18n.global.t;
export async function updateC() {
  MessagePlugin.loading($t('正在更新...'),2000);
  const scale = meta2d.store.data.scale;
  //所有需要更新的自定义组件
  let cPens = meta2d.store.data.pens.filter(
    (pen: any) => pen.name === 'combine' && pen.componentId
  );
  meta2d.canvas.opening = true;
 // let replacePens = []; //所有需要替换
//  cPens.forEach((pen) => {
 //   replacePens.push(getAllChildren(pen, meta2d.store));
 // });
  let cMap = {};
  cPens.forEach((pen: any) => {
    if (!cMap[pen.componentId]) {
      cMap[pen.componentId] = [];
    }
    cMap[pen.componentId].push(pen.id);
  });
  //let deletePens = [];
  for (let key in cMap) {
    const newData = await axios.post(`/api/data/v.component/get`, {
      id: key,
      projection: 'data,id,name',
    });
    if(!newData){
      continue;
    }
    for (let i = 0; i < cMap[key].length; i++) {
      let id = cMap[key][i];
      let componentDatas = deepClone(newData.data.componentDatas);
      componentDatas[0].componentId = key;
      componentDatas.forEach((item)=>{
          item.originId = item.id;
      })
      let beforeP:any = meta2d.store.pens[id];
      let beforePens = deepClone(getAllChildren(beforeP, meta2d.store));
      let rect = beforeP.calculative.worldRect; //meta2d.getPenRect(beforeP);
      //更新新组件大小位置
      componentDatas[0].width = rect.width/scale;
      componentDatas[0].height = rect.height/scale;
      componentDatas[0].x = rect.x;
      componentDatas[0].y = rect.y;
      // deletePens.push(beforeP);
      //删除原组件
      meta2d.delete([beforeP], true);

      //更新新组件
      //拖拽前ids
      const beforeIds = componentDatas.map((pen) => pen.id);
      await meta2d.canvas.dropPens(
        componentDatas,
        {
          x: rect.x + rect.width / 2,
          y: rect.y + rect.height / 2,
        }
      );
      //拖拽前ids
      const afterIds = componentDatas.map((pen) => pen.id);

      // meta2d.addPens(deepClone(componentDatas));
      let childrenMap = {};
      componentDatas.forEach((pen) => {
        let idIdx = afterIds.indexOf(pen.id);
        let matchPen:any = beforePens.find((p: any) => p.originId ===beforeIds[idIdx]);
        if (matchPen) {
          //更新更新的图元id为原拖拽到画布的id
          meta2d.changePenId(pen.id, matchPen.id);
          childrenMap[pen.id] = matchPen.id;
          if(matchPen.connectedLines){
            //更新连接关系中的锚点id
            for(let j=0;j<matchPen.anchors.length;j++){
              let line = matchPen.connectedLines.find((_line)=>_line.anchor===matchPen.anchors[j].id);
              if(line){
                line.anchor = pen.anchors[j].id;
              }
            }
          }
          pen.connectedLines = deepClone(matchPen.connectedLines);
          //  pen.originId = matchPen.originId;

          //已经绑定了数据点
          if(matchPen.realTimes&&matchPen.realTimes.length){
            let bindPts =  matchPen.realTimes.filter((item)=>item.bind);
            if( bindPts.length ){
              bindPts.forEach((item)=>{
                  let idx = pen.realTimes?.findIndex((f)=>f.key===item.key);
                  if(idx!==-1){
                    // pen.form[idx].dataIds = item.dataIds;
                    pen.realTimes.splice(idx,1,deepClone(item)); //更新
                  }else{
                    pen.realTimes.push(deepClone(item)); //新增
                  }
              })
            }
            //已经初始化的数据-属性值不需要更新。
            let beforeKv = {};
            matchPen.realTimes.forEach((item)=>{
              beforeKv[item.key] = matchPen[item.key];
            });
            beforeKv['id'] = pen.id;
            meta2d.setValue(beforeKv,{render:false,doEvent:false,history:false});  
          }
        }
      });
      meta2d.changePenId(componentDatas[0].id, beforeP.id);
      componentDatas[0].connectedLines = deepClone(beforeP.connectedLines);
      componentDatas[0].children = componentDatas[0].children.map((item) => {
        if (childrenMap[item]) {
          return childrenMap[item];
        }else return item;
      });

      //父节点绑定了数据点
      if(beforeP.realTimes&&beforeP.realTimes.length){
        let bindPts =  beforeP.realTimes?.filter((item)=>item.bind);
        if( bindPts.length ){
          bindPts.forEach((item)=>{
              let idx = componentDatas[0].realTimes.findIndex((f)=>f.key===item.key);
              if(idx!==-1){
                componentDatas[0].realTimes.splice(idx,1,deepClone(item)); //更新
              }else{
                componentDatas[0].realTimes.push(deepClone(item)); //新增
              }
          })
        }
        //已经初始化的数据-属性值不需要更新。
        let beforeKv = {};
        beforeP.realTimes.forEach((item)=>{
          beforeKv[item.key] = beforeP[item.key];
        });
        beforeKv['id'] = componentDatas[0].id; 
        meta2d.setValue(beforeKv,{render:false,doEvent:false,history:false});
      }
     // componentDatas[0].originId = beforeP.originId;
      //componentDatas[0].componentId = beforeP.componentId;
      // meta2d.addPens(deepClone(componentDatas));
    }
  }
  //删除原组件
  // meta2d.delete(deletePens);
  meta2d.inactive(); // dropPens默认会选中新添加的图元，这里取消选中
  meta2d.render(true);
  meta2d.initBinds(); //初始化绑定
  // MessagePlugin.closeAll();
}
