<template>
  <Dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    :width="dialogWidth"
    :close-on-click-modal="false"
  >
    <ContentWrap>
      <Descriptions
        :data="detailData"
        labelClassName="label-class-name"
        label-align="left"
        direction="vertical"
        :column="8"
        :schema="allSchemas.detailSchema"
        :columns="2"
        width="200px"
      />
    </ContentWrap>
    <ContentWrap>
      <el-container>
        <el-aside width="320px">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>工艺路线</span>
                <el-button
                  type="text"
                  icon="el-icon-plus"
                  @click="opensearchTable"
                  style="float: right; padding: 3px 0"
                >添加工序</el-button>
              </div>
            </template>
            <el-table :data="processData" ref="tableProcess" style="width: 100%; height: 80%" @cell-dblclick="userAddNode">
              <el-table-column prop="code" label="工序编码"  />
              <el-table-column prop="name" label="工序名称" />
              <el-table-column prop="oper" label="" width="60">
                <template #default="scope">
                  <el-button size="mini" text @click="deleteNode(scope.row)" 
                    >移除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-aside>
        <el-main style="height: 320px;width: calc(100% - 980px);padding: 0px; margin:0px 20px">
          <div ref="graphContainer" ></div
        ></el-main>
        <el-aside width="640px">
          <el-tabs  v-model="activeName">
            <el-tab-pane label="工序工位" name="workstation">
              <el-table :data="workstationData" ref="tableWorkstations" style="width: 100%; height: 80%">
              <el-table-column prop="name" label="工作位置">
                <template #default="scope">
                  <el-button size="mini" text  style="width: 100%"
                    >{{ scope.row.name }}[{{ scope.row.code }}]</el-button
                  >
                </template>
              </el-table-column>
              <el-table-column prop="code" label="工序编码" width="180" v-if="false" />
            </el-table> 
            
            </el-tab-pane>
            <el-tab-pane label="工序物料" name="materials">
              <el-table :data="materialsData" ref="tableMaterials" style="width: 100%; height: 80%">
              <el-table-column prop="repMaterialCode" label="物料编码"/>
              <el-table-column prop="repMaterialCounts" label="物料数量" />
              <el-table-column prop="repMaterialModel" label="物料单位"  />
              <el-table-column prop="sourceMaterialCounts" label="需求物料数" >
                <template #default="scope">{{ getTotalcounts(scope.row.repMaterialCounts)}}</template>
              </el-table-column>
              <el-table-column prop="replaceFlag" label="是否替换" />
              
            </el-table>
          </el-tab-pane>
            <el-tab-pane label="工序人员" name="workers">
              <el-table :data="workerData" ref="tableWorker" style="width: 100%; height: 80%">
              <el-table-column prop="workerCode" label="人员编码"/>
              <el-table-column prop="workerName" label="人员昵称" />
              <el-table-column prop="workerWorkstation" label="所在工位" />
              <el-table-column prop="workerTeam" label="所属班组"  />
              <el-table-column prop="workerPost" label="岗位" />
              <el-table-column prop="abilityLevel" label="能力等级" />
            </el-table>
            </el-tab-pane>
            <el-tab-pane label="工序设备" name="equipments">
              <el-table :data="equipmentData" ref="tableEquipment" style="width: 100%; height: 80%">
              <el-table-column prop="equipmentCode" label="设备编码"/>
              <el-table-column prop="equipmentName" label="设备名称" />
              <el-table-column prop="equipmentWorkstation" label="关联工位" />
              <el-table-column prop="equipmentOper" label="操作说明"  />
            </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-aside>
        
      </el-container>
    </ContentWrap>
    <template #footer>
      <el-button @click="dialogVisible = false">发布计划</el-button>
    </template>
    <SearchTable ref="searchTableRef" @searchTableSuccess="searchTableSuccess"  />
  </Dialog>
  <!-- <SearchTable ref="searchTableRef" @searchTableSuccess="searchTableSuccess" /> -->
</template>

<script lang="ts" setup>

//import { dateFormatter } from '@/utils/formatTime'
import {
  start_node,
  end_node,
  createGraph,
  getNewNode
} from '@/views/mes/processroute/components/graphbase.data'
import * as orderDayconfigApi from '@/api/mes/orderDayconfig'
import  {ProcessSearch} from '../../publicUtil/processSearch.data'
import * as ProcessApi from '@/api/wms/process'
import { SearchTable } from '@/components/SearchTable'
import {  Graph } from '@antv/x6'
//import {TableForm} from '@/components/TableForm/src/TableForm.vue' // 引入TableForm.vue组件
const graphContainer = ref<HTMLElement | null>(null)
const graph = ref<Graph>()
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const activeName = ref('process')
const loading = ref(true)
const processData = ref([])
const queryParams:orderDayconfigApi.OrderDayQueryParamVo=ref()
const props = defineProps({
  // 查询弹窗是否显示筛选按钮
  isSearchFilterButtonHide: {
    type: Boolean,
    default: false
  },
  // 显示窗口宽度设置
  basicFormWidth: {
    type: String,
    default: ''
  },

  allSchemas: {
    type: Object,
    required: true,
    default: null
  }
})
const detailData = ref(props.allSchemas)
const route = useRoute() // 路由信息
const routeName = ref()
routeName.value = route.name
routeName.value = routeName.value.substring(0, routeName.value.length - 4) + 'Detail'
//const updateKey = ref(0)
const dialogWidth = ref()
const materialsData = ref()
const workerData=ref()
const equipmentData=ref()
const workstationData=ref()
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题

const  graphJson =ref() 
/** 打开弹窗 */
const open = async (type: string, row?: any, titleName?: any) => {
  dialogVisible.value = true
  detailData.value = row
  dialogWidth.value = props.basicFormWidth + '%'
  queryParams.planNoDay=row.planNoDay
  queryParams.productCode=row.productCode
  queryParams.workroomCode=row.workroomCode
  queryParams.lineCode=row.lineCode
  queryParams.processrouteCode=row.processrouteCode
  queryParams.batchCode=row.batchCode
  //获取配置的
  
  if (titleName) {
    dialogTitle.value = t('action.' + titleName)
  } else {
    dialogTitle.value = t('action.' + type)
  }
  nextTick(() => {
    graph.value = createGraph(graphContainer.value as HTMLElement, true, 240, 320)
    graph.value.on('node:click', ({ e, x, y, node, view }) => {
      nodeClick(e, x, y, node, view)
    })
    getProcessroute()
    getConfigProcessRouteNode()
    
    
  })
}
const getTotalcounts=(a:any)=>{
  return detailData.value.planCount*a
}
//添加节点
const userAddNode = (row) => {
  if (graph && graph.value != undefined) {
    let node_template = getNewNode(row.code, row.name, row.code)
    node_template.x = end_node.value.x - 100
    node_template.y = end_node.value.y + 100
    let noden = graph.value.addNode(node_template)
    if (graph.value.getNodes().length == 1) {
      let start = graph.value.addNode(start_node.value)
      let end = graph.value.addNode(end_node.value)
      graph.value.addEdge({
        id: 'startEdge',
        source: start.id, // 源节点 ID
        target: noden.id
      })
      graph.value.addEdge({
        id: 'endEdge',
        source: noden.id, // 源节点 ID
        target: end.id
      })
    }
  }
}
//获取工序的BOM
const getProcessBom=async (code:any) => {
  queryParams.processCode=code
  let res = await orderDayconfigApi.getOrderDayBomByOrder(queryParams)
  materialsData.value=res
  
}
//获取配置的工艺路线信息
const getProcessroute = async () => {
  let res = await orderDayconfigApi.getConfigProcessRoute(queryParams)
  //console.log('ddddd',res)
  graphJson.value=JSON.parse(res.newGraphData)

  graph.value?.fromJSON(graphJson.value.cells)
}
//获取配置的工序信息
const getConfigProcessRouteNode= async () => {
  let res = await orderDayconfigApi.getConfigProcessRouteNode(queryParams)
  processData.value=res
}
//获取配置的工序工位
const getConfigProcessWorkstation= async (code:any) => {
  queryParams.processCode=code
  workstationData.value = await orderDayconfigApi.getConfigProcessWorkstation(queryParams)
 
}
//获取配置的工序人员
const getConfigProcessWorker= async (code:any) => {
  queryParams.processCode=code
  workerData.value = await orderDayconfigApi.getConfigProcessWorker(queryParams)
  
}
//获取配置的工序设备
const getConfigProcessEquipment= async (code:any) => {
  queryParams.processCode=code
  equipmentData.value = await orderDayconfigApi.getConfigProcessEquipment(queryParams)
  
}
const nodeClick = (e, x, y, node, view) => {
  getProcessBom(node.id)
  getConfigProcessWorkstation(node.id)
  getConfigProcessWorker(node.id)
  getConfigProcessEquipment(node.id)
  console.log('nodeClick',detailData.value)
}

const searchTableRef = ref()
 
const opensearchTable = (
) => {
  //console.log("opensearchTable")
  const _searchCondition = {}
  const _searchTableTitle = "工序查询"
  const _searchTableAllSchemas = ProcessSearch.allSchemas
  const _searchTablePage = ProcessApi.getProcessPage
  searchTableRef.value.open(
    _searchTableTitle,
    _searchTableAllSchemas,
    _searchTablePage,
    undefined,
    undefined,
    true,
    undefined,
    undefined,
    _searchCondition,
    false,
    true
  )
}

// 弹层确定返回所选数据
// val ： 弹层列表row 数据
const searchTableSuccess = (formField, searchField, val, type, row) => {
  //console.log("searchTableSuccess",val)
  if(val.length>0){
    val.forEach(item=>{
      if(processData.value.find(obj=>obj.code==item.code)==undefined){
      processData.value.push({code:item.code,name:item.name})}
    })
  }
  //emit('searchTableSuccess', formField, searchField, val, undefined, type, row)
}
const deleteNode=(row)=>{
    processData.value.splice(processData.value.indexOf(row),1)
    graph.value.removeNode(row.code)
  }

defineOptions({ name: 'sechledDetail' })
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
</script>
<style lang="scss">
.el-drawer__body {
  background: #f5f5f5 !important;
}

::v-deep(.label-class-name) {
  color: #dedede;
}
</style>
<style scoped lang="scss"></style>
