<template>
  <a-layout style="height: 100%; padding: 5px; padding-left: 0px">
    <a-layout-content style="padding: 5px; height: 100%; border: 1px solid #d1dbe5">
      <a-card class="box-card" style="padding: 0px;" :body-style='{ padding: "5px", height: "100%" }'>
        <lt-a-form contendPadding="0px" style="border-width: 0px">
          <a-form ref="refhub" :inline="false" :model="form" :inline-message="true" :rules="rules" label-width="100px"
            style="width: 100%;" :labelCol="{
              span: 6
            }">
            <a-row>
              <a-col :span="24">
                <a-form-item label="描述" name="description">
                  <a-input v-model:value="form.description" :readonly="Status > 0 || ifCanBeEdite == false" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row style="height: 220px;width: 100%;border-left: 1px solid #d1dbe5;" v-if="form.cellType == 'HubOut'">
              <div style="width: 100%;height: 100%;">
                <lt-a-table :data="showOutInfo" :show-overflow-tooltip="true" ref="refTable" :searchBox="false" fill
                  :fit="false" style="border: 0px; border-left-width: 1px" bordered :highlight-current-row="true"
                  :dataSource="showOutInfo" :showToolBar="false" :showEditInDialog="false" :pagination="false"
                  :columns="HubOutColumns" size="small">
                </lt-a-table>
              </div>
            </a-row>
            <a-row style="height: 220px;width: 100%;border-left: 1px solid #d1dbe5;" v-if="form.cellType == 'HubIn'">
              <lt-a-table :show-overflow-tooltip="true" ref="refTable" :searchBox="false" fill :fit="false"
                style="border: 0px; border-left-width: 1px" bordered :highlight-current-row="true"
                :dataSource="showInfo" :showToolBar="false" :showEditInDialog="false" :pagination="false"
                :columns="HubInColumns" size="small">
                <template #headerCell="{ column }">
                  <template v-if="column.dataIndex === 'operate'">
                    <span>
                      <a-button type="text" title="新增" size="small"
                        style=" color: dodgerblue;font-weight: bold;margin: 0px;" @click="handleAdd">
                        <template #icon>
                          <i class="icon icon-plus "></i>
                        </template>
                      </a-button>
                      <a-button type="text" title="删除" size="small"
                        style=" color: dodgerblue;font-weight: bold;margin: 0px;" @click="handleDelshowInfo">
                        <template #icon>
                          <i class="icon icon-trash"></i>
                        </template>
                      </a-button>
                    </span>
                  </template>
                </template>
              </lt-a-table>
            </a-row>
            <a-row
              style="text-align: center;display: flex;padding: 5px;border-left: 1px solid #d1dbe5;border-top: 1px solid #d1dbe5;;">
              <div style="margin: auto;">
                <a-button v-on:click="handleConfirm" type="primary">
                  <template #icon>
                    <check-outlined />
                  </template>确认</a-button>
                <a-button v-on:click="handleReset" style="margin-left: 10px;">
                  <template #icon>
                    <reload-outlined />
                  </template>
                  重置
                </a-button>
              </div>
            </a-row>
          </a-form>
        </lt-a-form>
      </a-card>
    </a-layout-content>
  </a-layout>
</template>

<script setup lang="tsx">
import { events } from '../../../../bus';
import { reactive, ref, watch, computed, onBeforeMount } from 'vue';
import { GuidID } from "../../commonMethods/commonMethods"
import { Modal } from 'ant-design-vue';
import { cloneDeep } from 'lodash-es';

const props = defineProps({
  formData: {
    type: Object,
    default() {
      return null;
    },
  },
  ifCanBeEdite: {
    type: Boolean,
    default: false
  },
})

type formDataStruct={
  index: string
    ExecId: string
    showExecId: string[] //界面显示用的ID
}

const form = reactive({
  cellType: "", //集线器类型  HubIn:输入类型   HubOut:输出类型
  description: "", //集线器名称
  Script: [], //出现前连接点
  hubID: "",
})

let edgesArray = ref([])  //连接到集线器上的线条
let showOutInfo = ref([])
let HubOutOption = ref([]) //进线的时候可选择的出线器选项
let showInfo = ref([] as formDataStruct[])
let Status = ref(0)//当前工艺生产状态
const rules = {
  description: [
    {
      required: true,
      message:
        "该项不能为空",
    },
  ],
};
const refhub = ref("")

const HubOutColumns = computed(() => {
  let cols = [
    {
      dataIndex: "ExecId",
      title: "ExecId",
      width: 100,
      customRender: function (record:any) {
        const curCols = record.column
        const cueRecord = record.record
        return (
          <a-input
            size="small"
            autofocus={true}
            readonly={true}
            v-model:value=
            {
              cueRecord[curCols.dataIndex]
            }
          />
        )
      }
    },
    {
      dataIndex: "label",
      title: "描述信息",
      width: 200,
      customRender: function (record:any) {
        const curCols = record.column
        const cueRecord = record.record
        return (
          <a-input
            size="small"
            autofocus={true}
            readonly={true}
            v-model:value=
            {
              cueRecord[curCols.dataIndex]
            }
          />
        )
      }
    }
  ]
  return cols

})

const HubInColumns = computed(() => {
  let cols = [
    {
      title: '操作',
      align: 'center',
      dataIndex: 'operate',
      width: 70,
      customRender: ({ record, rowIndex, column }:any) => {
        return getDelBtn(record)
      }
    },
    {
      dataIndex: "showExecId",
      title: "出线器",
      width: 200,
      customRender: function (record:any) {
        const curCols = record.column
        const cueRecord = record.record
        return (
          <a-cascader
            size="small"
            v-model:value=
            {
              cueRecord[curCols.dataIndex]
            }
            options={HubOutOption.value}
            placeholder="Please select" />
        )
      }
    },
  ]
  return cols
})

const getDelBtn = function (record:any) {
  return (
    <a-button type="text" title="删除" size="small" style="height: 24px; color: dodgerblue;font-weight: bold;" onClick={() => {
      handleDelshowInfo(record)
    }} >
      <i class="icon icon-trash"></i>
    </a-button>
  )
}


watch(() => props.formData, () => {
  initFormVal()
})
const initFormVal = function () {
  const newValue = props.formData
  if (newValue && typeof newValue != 'undefined') {
    if (newValue.cell.cellType == "HubIn" || newValue.cell.cellType == "HubOut") {
      const cell = newValue.cell;
      const graph = newValue.graph;
      form.hubID = cell.id;
      form.cellType = cell.cellType ? cell.cellType : "";
      form.description = cell.description ? cell.description : "";
      form.Script = cell.Script ? cell.Script : [];
      Status.value = typeof cell.Status == 'undefined' ? 0 : cell.Status;
      showInfo.value = cell.Script ? cell.Script : [];
      getEdges(cell, graph); //获取下拉选项
      getAllHubOut(graph);
    }
  }
}

const handleAdd = function () {
  let temp = {
    index: GuidID(),
    ExecId: "",
    showExecId: [], //界面显示用的ID
  } as formDataStruct;

  showInfo.value.push(temp);
}
const handleDelshowInfo = function (row:any) {
  for (let i = 0; i < showInfo.value.length; i++) {
    if (showInfo.value[i].index == row.index) {
      showInfo.value.splice(i, 1);
      break;
    }
  }
}

const formateShowString = function (cell:any) {
  if (!cell.edges || cell.edges.length == 0) {
    return [];
  }
  let targetEdge = cell.edges.filter((item:any) => {
    return item.target.id == cell.id;
  });
  let tempArray = [];
  for (let i = 0; i < targetEdge.length; i++) {
    let temp = {
      value: targetEdge[i].source.id,
      label: targetEdge[i].value,
    };
    let copy = cloneDeep(temp)
  
    tempArray.push(copy);
  }
  return tempArray;
}
const getAllHubOut = function (graph:any) {
  let cells = graph.getModel().cells;
  HubOutOption.value = [];
  for (let i in cells) {
    if (cells[i].cellType) {
      if (cells[i].cellType == "HubOut") {
        let temp = {
          value: cells[i].id,
          label: cells[i].description ? cells[i].description : cells[i].value,
          children: formateShowString(cells[i]),
        };
        let copy = cloneDeep(temp)
        //@ts-ignore
        HubOutOption.value.push(copy);
      }
    }
  }
}

const getEdges = function (cell:any, graph:any) {
  edgesArray.value = [];
  let edges = cell.edges;
  showOutInfo.value = [];
  if (!edges) {
    return;
  }
  for (let i = 0; i < edges.length; i++) {
    if (edges[i].target.id == cell.id) {
      let temp = {
        index: i + 1,
        ExecId: edges[i].source.id, //集线器原始工艺Id
        label: edges[i].value,
        TargetID: edges[i].id,
      };
      let copy = cloneDeep(temp)
     //@ts-ignore
      showOutInfo.value.push(copy);
    }
  }
}
const getLeafScript = function () {
  for (let i = 0; i < showInfo.value.length; i++) {
    showInfo.value[i].ExecId = getShowExcID(
      showInfo.value[i].showExecId
    );
  }
}
const getShowExcID = function (data:any) {
  let target = "";
  let tempArray = cloneDeep(data)
 
  for (let i = 0; i < tempArray.length; i++) {
    let targetID = HubOutOption.value.filter((item) => {
      //@ts-ignore
      return item.value == tempArray[i];
    });
    if (targetID.length > 0) {
      tempArray.splice(i, 1);
    }
    target = tempArray[0];
  }
  return target;
}
const handleConfirm = function () {
  if(refhub.value){
    //@ts-ignore
    refhub.value.validate().then(values => {
    if (!form.cellType) {
      Modal.warning({
        title: "警告",
        content: "请选择集线器类型!"
      })
    }
    if (form.cellType == "HubOut") {
      form.Script = showOutInfo.value;
    } else {
      getLeafScript(); //在提交数据之前，从级联器中选择需要最终提交的数据
      //@ts-ignore
      form.Script = showInfo.value;
    }
    var propertyData = {
      data: form,
      type: form.cellType,
    };
    events.emit("porpertyChange", propertyData);
  })

  }
 

}
const handleReset = function () {
  //初始化的时候，将页面初始化成初始结构
  //   $.extend(true, form, this.dataStruct);

}


onBeforeMount(() => {
  initFormVal()
})

</script>

<style scoped>
.header-bread {
  margin-top: 8px;
  margin-left: 10px;
  font-size: 16px;
  font-weight: bold;
}

.codeRow {
  height: 500px;
}
</style>
