<template>
  <div class="workshop">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="workareaName"
            placeholder="请输入作业区域"
            clearable
            :disabled="isDisabled"
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
            @input="handleInputChange"
          />
        </div>
        <div class="head-container">
          <div v-if="isDisabled" class="overlay"></div>
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            @node-click="handleNodeClick"
            highlight-current
          />
        </div>
      </el-col>
      <el-col :span="4" :xs="24">
        <div class="middle">
          <img :src="imgsrc" alt="" v-if="imgsrc"/>
          <p v-else>—————— 请选择作业区域 ——————</p>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { listAllWorkshop } from '@/api/mes/md/workshop'
import { getMapDataApi } from '@/api/mes/wa/workarea'
import { selectIsSopById } from '@/api/mes/sop/sopindex-booz'
import { mapActions, mapGetters } from 'vuex'
import { listWorkarea } from '@/api/mes/wa/workarea'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import Treeselect from '@riophae/vue-treeselect'

export default {
  props: {
    sopProps: {
      type: Array,
      default: () => []
    },
    jobProps: {
      type: Array,
      default: () => []
    }
  },
  components: { Treeselect },
  data() {
    return {
      form: {
        checkAll: false,
        isIndeterminate: false,
        workShop: [],
        producLine: '',
        sopId: ''

      },
      workShopOptions: [],
      producLineOptions: [],
      imgsrc: '',
      // 部门树选项
      deptOptions: undefined,
      defaultProps: {
        children: 'children',
        label: 'label'

      },
      // 作业区域名称 树形结构
      workareaName: undefined,
      treeSelectMap: null,//单节点点击传递map
      queryParams: {
        current: 1,
        size: -1

      },
      isDisabled: false//控制编辑的时候禁止点击树形结构
    }
  },
  watch: {
    // 监听父组件传递的数据
    sopProps: {
      handler(newVal, oldVal) {
        if (newVal) {
          console.log('sopProps 发生变化', newVal)

          if (newVal[0].workareaId) {
            this.workareaName = newVal[0].workareaId  //新作业区域所返回
            this.handleselectProductLine(newVal[0].workareaId)

          }

          this.getTreeselect()
          // 这里是为了拿到sop模板里默认的隔离点选中的数据
          selectIsSopById(newVal[0].sopId).then((res) => {
            console.log(res, 'sop')
            const selectSopPoints = res.data.pointDetailVOList.map((item) => {
              return item.pointId
            })
            // 调用 Vuex action 来存储 selectSopPoints
            this.setSelectSopPoints(selectSopPoints)

            this.setSopEdit(true)
            // console.log(selectSopPoints, 'sop_selectePoints')
          })
        }

      },
      immediate: true // 立即执行一次，确保在组件初始化时也能捕获到 jobProps 的值
    },
    jobProps: {
      handler(newVal, oldVal) {
        console.log('jobProps 发生变化', newVal)

        if (newVal.length == 0) {
          this.setSopEdit(true)
          this.form.sopId = ''
        } else {

          this.isDisabled = true
          // 在这里处理 jobProps 变化后的逻辑
          if (newVal[0].workareaId) {
            this.workareaName = newVal[0].workareaId  //新作业区域所返回
            this.handleselectProductLine(newVal[0].workareaId, newVal[0].sopId)//获取已选隔离点的整个数据map
          }
          this.getTreeselect()//获取作业区域树
          this.form.sopId = newVal[0].sopId
          if (newVal[0].sopId !== null) {
            this.setSopEdit(false)
          } else {
            this.setSopEdit(true)
          }

          // 这里是为了拿到sop模板里默认的隔离点选中的数据a
          if (!newVal[0].EditBool) {
            selectIsSopById(newVal[0].sopId).then((res) => {
              console.log(res, 'sop')
              const selectSopPoints = res.data.pointDetailVOList.map((item) => {
                return item.pointId
              })

              // 调用 Vuex action 来存储 selectSopPoints
              this.setSelectSopPoints(selectSopPoints)
              this.setPointTableData(res.data)
              // this.setSopEdit(false)
              console.log(selectSopPoints, 'sop_selectePoints')
            })
          } else {
            const selectSopPoints = newVal[0].spoint.map((item) => {
              return item.pointId
            })
            this.setSelectSopPoints(selectSopPoints)
            this.setPointTableData(newVal[0].spoint)
            // this.setSopEdit(true)
          }
        }
      },
      immediate: true // 立即执行一次，确保在组件初始化时也能捕获到 jobProps 的值
    }
  },

  mounted() {
    this.getTreeselect()//获取作业区域下拉

    if (this.$route.query.sopId == 'null' || this.$route.query.ticketId == 'null') {
      console.log(this.isDisabled, 'isDisabled 我走这里')
      this.isDisabled = false
    } else {
      console.log(this.isDisabled, 'isDisabled 我走这里2')
      this.isDisabled = true
    }
  },
  computed: {
    ...mapGetters('sopSelectPoints', ['getSopLook', 'getMapData','getSopEdit'])
  },
  methods: {
    ...mapActions('sopSelectPoints', [
      'setSelectSopPoints',
      'setPointTableData',
      'setSopEdit',
      'setMapData'
    ]),
    // 区域下拉
    handleselectProductLine(val, sopId) {
      console.log(val, '区域下拉')

      // 获取区域map解析数据
      const data = val

      let data1 = ''
      let data2 = ''

      if (this.$route.query.sopId !== 'null' && this.$route.query.sopId) {
        data1 = this.$route.query.sopId
      } else if (
        this.$route.query.ticketId !== 'null' &&
        this.$route.query.ticketId
      ) {
        data2 = this.$route.query.ticketId // ticketId 存在时，data1 设置为空字符串
      }

      if (this.jobProps.length == 0) {
        console.log(
          this.jobProps,
          '如果jobProps是空数组表示编辑情况下修改sop为空值需要重新拿到所有渲染隔离点'
        )
        data2 = ''
      }

      if (sopId) {
        console.log(sopId, 'sopId------')
        data1 = sopId
      }

      getMapDataApi(data, data1, data2)
        .then((res) => {
          console.log(res, '获取区域map的解析数据')
          const mapdata = res.data
          this.setMapData(mapdata)

        })
        .catch((error) => {
          console.error('获取区域map数据失败', error)
        })

    },

    /** 查询作业区域下拉树结构 */
    getTreeselect() {
      listWorkarea(this.queryParams).then(response => {
        // console.log(response.data.records, '作业区域下拉树形结构');
        // 转换为树形结构
        this.deptOptions = this.transformToTree(response.data.records)
        // console.log(this.deptOptions, 'deptOptions')

        // 使用递归函数查找匹配的节点

        console.log(this.workareaName, 'name')
        const selectedTreeNode = this.findNodeById(this.deptOptions, this.workareaName)
        // 调用 handleNodeClick 方法
        if (selectedTreeNode) {
          this.handleNodeClick(selectedTreeNode)
        } else {
          console.log('未找到匹配的节点')
        }

      })
    },
    // 深层次遍历
    findNodeById(nodes, targetId) {
      for (let i = 0; i < nodes.length; i++) {
        const node = nodes[i]
        if (node.id === targetId) {
          return node
        }
        if (node.children && node.children.length > 0) {
          const foundNode = this.findNodeById(node.children, targetId)
          if (foundNode) {
            return foundNode
          }
        }
      }
      return null
    },
    /** 转换数据为树形结构 */
    transformToTree(records) {
      const recordMap = {} // 创建一个 Map 以存储所有记录
      const tree = [] // 最终返回的树形结构

      // 初始化所有记录到 Map
      records.forEach(record => {
        recordMap[record.workareaId] = {
          id: record.workareaId,
          label: record.workareaName,
          map: record.map,
          mapImg: record.mapImg,
          children: []

        }
      })

      // 遍历记录并构建树
      records.forEach(record => {
        const parentId = record.parentId

        if (parentId === '0') {
          // 如果是顶层节点，直接添加到树中
          tree.push(recordMap[record.workareaId])
        } else if (recordMap[parentId]) {
          // 如果有父节点，则将当前节点加入父节点的 children 中
          recordMap[parentId].children.push(recordMap[record.workareaId])
        }
      })

      return tree
    },

    // 树节点筛选逻辑
    filterNode(value, data) {
      if (!value) return true // 如果没有输入值，显示所有节点
      return data.label.indexOf(value) !== -1 // 判断节点 label 是否包含输入值
    },
    // 监听输入框变化
    handleInputChange() {
      this.$refs.tree.filter(this.workareaName) // 调用树的 filter 方法
    },
    // 节点单击事件
    handleNodeClick(data) {

      console.log(data, '单节点点击')
      this.treeSelectMap = data

      // 传递车间地图
      this.imgsrc = data.mapImg
      let workareaId = data.id
      let sopId = ''
      let ticketId = ''

      if (this.$route.query.sopId !== 'null' && this.$route.query.sopId) {
        sopId = this.$route.query.sopId
      } else if (
        this.$route.query.ticketId !== 'null' &&
        this.$route.query.ticketId
      ) {
        ticketId = this.$route.query.ticketId // ticketId 存在时，data1 设置为空字符串
      }

      if (this.jobProps.length == 0) {
        console.log(
          this.jobProps,
          '如果jobProps是空数组表示编辑情况下修改sop为空值需要重新拿到所有渲染隔离点'
        )
        ticketId = ''
      }
      if (this.form.sopId) {
        sopId = this.form.sopId
      }
      getMapDataApi(workareaId, sopId, ticketId)
        .then((res) => {
          console.log(res, '获取区域map的解析数据')
          const mapdata = res.data
          this.setMapData(mapdata)

        })
        .catch((error) => {
          console.error('获取区域map数据失败', error)
        })
      // 这里本来用的是没解析的json字符串 为了避免日后还需要取隔离点修改json所以我直接调用解析后的json 如果是新建sop只传递workareaId就能拿到已经解析过的 初始化的全部数据而且是未被标记选中的
      // if (this.$route.query.sopId === 'null' || this.$route.query.ticketId === 'null') {
      //   this.setMapData(data.map)
      //   console.log('设置了地图数据')
      // }else {
      //   this.setMapData(data.map)
      // }
      this.workareaName = data.label

      this.handleInputChange()
      this.$emit('work-shop-selected', data)
    }
  }
}
</script>


<style scoped>
.head-container {
  position: relative;
}

.overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.7); /* 半透明背景 */
  z-index: 1000; /* 确保覆盖层在树形结构之上 */
}

.workshop {
  width: 100%;
  height: 100%;
}

.middle {
  width: 950px;
  height: 850px;
  margin: 10px 0 0 60px;
  background-color: rgb(255, 255, 255);
  box-shadow: 0px 3px 12px 0px rgba(0, 0, 0, 0.12);

  img {
    width: 100%;
    height: 100%;
  }

  p {
    text-align: center;
    //margin: 30% 0;
    line-height: 850px;
  }
}
</style>
