<template>
  <div>
    <el-drawer
      v-model="isShowDrawer"
      title="详情"
      direction="rtl"
      size="80%"
      v-loading="detailLoading"
      :on-close="handleDrawerClose()"
    >
      <template #header>
        <div class="font-size-18px">
          <el-row :gutter="10">
            <el-col :span="22">
              {{ titleValueRef }}
              <el-tag type="info">[{{ titleNameRef }}]</el-tag>
            </el-col>
            <el-col :span="2">
              <el-button size="primary" @click="saveResult()" style="width: 100%">
                保存修改
              </el-button>
            </el-col>
          </el-row>
        </div>
      </template>

      <el-row :gutter="10" style="height: calc(100vh - 300px)">
        <el-col :span="6">
          <!-- <el-form>
            <el-form-item label="车间选择">
              <el-select
                :v-model="processListParmas.workshopCode"
                value-key="code"
                placeholder="Select"
                style="width: 240px"
              >
                <el-option
                  v-for="item in workshopCodeOptions"
                  :key="item.code"
                  :label="item.name"
                  :value="item"
                />
    </el-select>
            </el-form-item>
            <el-form-item label="产线选择">
              <el-select
                :v-model="processListParmas.productionLineCode"
                value-key="code"
                placeholder="Select"
                style="width: 240px"
              >
                <el-option
                  v-for="item in productionLineCodeOptions"
                  :key="item.code"
                  :label="item.name"
                  :value="item"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="">
              <el-button type="primary" @click="getProcessList">搜索</el-button>
            </el-form-item>
              
          </el-form> -->
          <el-table :data="processData" ref="tableProcess" style="width: 100%; height: 80%">
            <el-table-column prop="name" label="工序名称">
              <template #default="scope">
                <el-button size="mini" text @click="userAddNode(scope.row)" 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-col>
        <el-col :span="18"><div ref="graphContainer"></div></el-col>
      </el-row>
      <el-row style="height: 150px" :gutter="5">
        <el-col :span="6">
          <el-card class="footer-card">
            <template #header>
              <div class="card-header">
                <span>产品信息</span>
              </div>
            </template>
            <p>产品名称：{{ productData.name }}</p>
            <p>产品编码：{{ productData.code }}</p>
            <p>产品描述：{{ productData.desc1 }}</p>
          </el-card>
        </el-col>
        <el-col :span="6"
          ><el-card class="footer-card">
            <template #header>
              <div class="card-header">
                <span>设备信息</span>
              </div>
            </template>
            <p v-for="item in deviceList" :key="item" class="text item">{{ item.name }}</p>
          </el-card></el-col
        >
        <el-col :span="6"
          ><el-card class="footer-card">
            <template #header>
              <div class="card-header">
                <span>人员信息</span>
              </div>
            </template>
            <p v-for="item in workerList" :key="item" class="text item">{{ item.name }}</p>
          </el-card></el-col
        >
        <el-col :span="6"
          ><el-card class="footer-card">
            <template #header>
              <div class="card-header">
                <span>工位信息</span>
              </div>
            </template>
            <p>工位编码：{{ workStationData.name }}</p>
            <p>工位名称：{{ workStationData.code }}</p>
          </el-card></el-col
        >
      </el-row>
    </el-drawer>
  </div>
</template>
<script lang="ts" setup>
import { start_node, end_node, createGraph, registerNodes, getNewNode } from './graphbase.data'
import * as ProcessrouteApi from '@/api/mes/processroute'
import { Graph } from '@antv/x6'
import { table } from 'console'

//import { async } from '@antv/x6/lib/registry/marker/async'
//import { object } from 'vue-types'
const graphContainer = ref<HTMLElement | null>(null)
defineOptions({ name: 'ProcessRouteConfig' })
const isShowDrawer = ref(false)
const detailLoading = ref(false)
const message = useMessage() // 消息弹窗
//const { t } = useI18n() // 国际化
const route = useRoute() // 路由信息
const routeName = ref()
routeName.value = route.name
routeName.value = routeName.value.substring(0, routeName.value.length - 4) + 'ProcessRouteConfig'
//const updateKey = ref(0)
const titleNameRef = ref()
const titleValueRef = ref()
const processRouteId = ref()
const processData = ref([]) //工序数据
const tableProcess = ref()
// const workshopCodeOptions = ref([{ code: '', name: '车间1' }])
// const productionLineCodeOptions = ref([{ code: '', name: '产线' }])
const productData = ref({ name: '', code: '', desc1: '--' }) //产品数据
const deviceList = ref([
  { name: '设备', code: '0000' },
  { name: '设备', code: '0000' }
]) //设备数据
const workerList = ref([{ name: '--' }, { name: '--' }]) //人员数据
const workStationData = ref({ name: '工位', code: '' }) //工位数据
//初始化图形组件
const graph = ref<Graph>()
const openDetail = async (rowData: any) => {
  rowData.value = rowData
  titleNameRef.value = rowData.value.processrouteCode
  titleValueRef.value = rowData.value.processName
  processRouteId.value = rowData.value.id
  let graphJson = JSON.parse(rowData.value.graphJson)
  isShowDrawer.value = true
  nextTick(() => {
    graph.value = createGraph(graphContainer.value as HTMLElement)
    graph.value.on('node:click', ({ e, x, y, node, view }) => {
      nodeClick(e, x, y, node, view)
    })
    graph.value.fromJSON(graphJson.cells)
  })
  getItembasicInfo(rowData.value.productCode)
}
//关闭后销毁图形组件
const handleDrawerClose = () => {
  //console.log('close')
  if (graph && graph.value != undefined) {
    //console.log(graph.value.toJSON())
  }
  
}
//**获取 工序信息 */
const getProcessInfo = async (id: number) => {
  const res = await ProcessrouteApi.getProcesInfo(id)
  return res
}

/** 获取产品信息 */
const getItembasicInfo = async (code: String) => {
  const res = await ProcessrouteApi.getProductInfo(code)
  productData.value = res
  //console.log(productData.value)
}
/** 获取设备列表 */
const getDeviceList = async (code: String) => {
  const res = await ProcessrouteApi.getDeviceList(code)
  deviceList.value = res.data
  //console.log(productData.value)
}
/** 获取工位信息 */
const getWorkStation = async (code: String) => {
  const res = await ProcessrouteApi.getWorkStation(code)
  workStationData.value = res.data
  //console.log(productData.value)
}
/** 获取人员信息列表 */
const getWorkerList = async (code: String) => {
  const res = await ProcessrouteApi.getWorkerList(code)
  workerList.value = res.data
  //console.log(productData.value)
}
const processListParmas = ref({
  workshopCode: '',
  productionLineCode: '',
  pageNum: 1,
  pageSize: 50
})
/**获取工序列表 */
const getProcessList = async () => {
  const res = await ProcessrouteApi.getProcessList(processListParmas.value)

  processData.value = res.list

  //return res
}
const nodeClick = (e, x, y, node, view) => {
  //console.log('nodeClick', e, x, y, node, view)
  let data = getProcessInfo(node.id)
  getDeviceList(node.id)
  getWorkerList(node.id)
  getWorkStation(node.id)
  message.info(data.toString())
}

//添加节点
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
        // tools: [
        //   {
        //     name: 'button-remove',
        //     args: { distance: -40 },
        //   },
        // ]
      })
      graph.value.addEdge({
        id: 'endEdge',
        source: noden.id, // 源节点 ID
        target: end.id
        // tools: [
        //   {
        //     name: 'button-remove',
        //     args: { distance: -40 },
        //   },
        // ]
      })
    }
  }
}
//-------
defineExpose({ openDetail, createGraph }) // 提供 open 方法，用于打开弹窗
onMounted(() => {
  registerNodes()

  getProcessList()
})
//保存图形
const saveResult = async () => {
  if (graph.value == undefined) {
    message.info('未设置任何的流程图信息，不能保存！')
    return
  }
  if (graph.value.getNodes().length < 3) {
    message.info('除了开始结束节点外至少需要设置一个节点！')
    return
  }
  let gdata = {
    processrouteCode: titleNameRef.value,
    graphJson: graph.value.toJSON(),
    processrouteId: processRouteId.value
  }

  let res = ProcessrouteApi.saveGraphData(gdata)
  if (res) {
    message.success('保存成功！')
  } else {
    message.error('保存失败！')
  }
  isShowDrawer.value = false
  handleDrawerClose()
  emit('close')
  //return res
}
// 验证图形
onUnmounted(() => {})
const emit = defineEmits([
  'close',
])
</script>
<style lang="scss">
.el-drawer__body {
  background: #f5f5f5 !important;
}

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