<template>
  <div class="leftcon">
    <!-- <img src="../../assets/images/workshop.png" alt="" /> -->
    <div class="lefttop">
      <el-form ref="form" :model="form" label-width="100px" :inline="true">
        <el-form-item label="车间">
          <el-select
            :disabled="this.getSopLook"
            v-model="form.workShop"
            placeholder="请选择车间"
            @change="handleselect"
          >
            <el-option
              v-for="item in this.workShopOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <!--        <el-select-->
          <!--          v-model="form.workShop"-->
          <!--          v-bind="$attrs"-->
          <!--          multiple-->
          <!--          style="width: 100%"-->
          <!--          placeholder="请选择线路"-->
          <!--          @change="handleSelect"-->
          <!--        >-->
          <!--          <div style="padding: 0 20px; line-height: 34px">-->
          <!--            <el-checkbox-->
          <!--              v-model="checkAll"-->
          <!--              :indeterminate="isIndeterminate"-->
          <!--              @change="handleCheckAllChange"-->
          <!--            >全选</el-checkbox-->
          <!--            >-->
          <!--          </div>-->
          <!--          <el-checkbox-group v-model="form.workShop">-->
          <!--            <el-option-->
          <!--              v-for="item in this.workShopOptions"-->
          <!--              :key="item.value"-->
          <!--              :label="item.label"-->
          <!--              :value="item.value"-->
          <!--            >-->
          <!--              <el-checkbox style="pointer-events: none" :label="item.value">-->
          <!--                {{ item.label }}-->
          <!--              </el-checkbox>-->
          <!--            </el-option>-->
          <!--          </el-checkbox-group>-->
          <!--        </el-select>-->
        </el-form-item>
        <el-form-item label="生产线">
          <el-select
            :disabled="this.getSopLook"
            v-model="form.producLine"
            placeholder="请选择生产线"
            @change="handleselectProductLine"
          >
            <el-option
              v-for="item in this.producLineOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <div class="leftbottom">
      <!-- <img src="../../assets/images/workshop.png" alt="" /> -->
      <img :src="imgsrc" alt="" v-if="imgsrc"/>
      <p v-else>—————— 请选择车间 ——————</p>
    </div>
  </div>
</template>

<script>
import { listAllWorkshop } from '@/api/mes/md/workshop'
import { getIsWorkareaList, getMapData } from '@/api/mes/wa/workarea'
import { selectIsSopById } from '@/api/mes/sop/sopindex'
import { mapActions, mapGetters } from 'vuex'

export default {
  props: {
    sopProps: {
      type: Array,
      default: () => []
    },
    jobProps: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      form: {
        checkAll: false,
        isIndeterminate: false,
        workShop: [],
        producLine: '',
        sopId: ''
      },
      workShopOptions: [],
      producLineOptions: [],
      imgsrc: ''
    }
  },
  watch: {
    'form.workShop': {
      handler(newVal) {
        if (newVal) {
          this.imgsrc = localStorage.getItem('img')
        }
      }
    },
    // 监听父组件传递的数据
    sopProps: {
      handler(newVal, oldVal) {
        console.log('sopProps 发生变化', newVal)
        this.form.workShop = newVal[0].workshopId
        this.form.producLine = newVal[0].workareaId

        // 确保 handleselect 完成后再调用 handleselectProductLine
        this.handleselect(newVal[0].workshopId)
          .then(() => {
            this.handleselectProductLine(newVal[0].workareaId)
          })
          .catch((error) => {
            console.error('处理车间下拉失败', error)
          })
        // 这里是为了拿到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)
        // 在这里处理 jobProps 变化后的逻辑
        this.form.workShop = newVal[0].workshopId
        this.form.producLine = newVal[0].workareaId
        this.form.sopId = newVal[0].sopId
        console.log(this.form.sopId,'form.sopId jobProps')
        // 确保 handleselect 完成后再调用 handleselectProductLine
        this.handleselect(newVal[0].workshopId)
          .then(() => {
            this.handleselectProductLine(newVal[0].workareaId)
          })
          .catch((error) => {
            console.error('处理车间下拉失败', error)
          })

        // 这里是为了拿到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.getworkshopList()
  },
  computed: {
    ...mapGetters('sopSelectPoints', ['getSopLook'])
  },
  methods: {
    ...mapActions('sopSelectPoints', [
      'setSelectSopPoints',
      'setPointTableData',
      'setSopEdit',
      'setMapData'
    ]),

    // 获取车间列表
    getworkshopList() {
      listAllWorkshop().then((response) => {
        console.log(response, '车间信息')
        this.workShopOptions = response.data.map((item) => {
          return {
            label: item.workshopName,
            value: item.workshopId,
            key: item.workshopCode,
            attr1: item.attr1
          }
        })
      })
    },

    // 单选车间下拉
    handleselect(value) {
      return new Promise((resolve, reject) => {
        getIsWorkareaList(value)
          .then((response) => {
            this.producLineOptions = response.data.map((item) => {
              return {
                label: item.workareaName,
                value: item.workareaId,
                key: item.workareaCode,
                map: item.map
              }
            })

            // 根据选择的车间更新 imgsrc
            const selectedWorkshop = this.workShopOptions.find(
              (item) => item.value === value
            )
            localStorage.setItem('img', selectedWorkshop.attr1)
            if (selectedWorkshop) {
              this.imgsrc = selectedWorkshop.attr1
            } else {
              this.imgsrc = '' // 如果没有找到，清空 imgsrc
            }

            console.log(this.producLineOptions, 'this.producLineOptions')
            resolve() // 异步操作成功后 resolve
          })
          .catch((error) => {
            console.error('获取生产线下拉列表失败', error)
            reject(error) // 异步操作失败后 reject
          })
      })
    },
    // 生产线下拉
    handleselectProductLine(val) {
      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 设置为空字符串
      }
console.log(this.form.sopId,'form.sopId')
      if (this.form.sopId) {
        data1 = this.form.sopId
      }

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

      //   利用组件逆传递 selectProductLine方法传递数据给兄弟组件
      const selectedOption = this.producLineOptions.filter((item) => {
        return item.value == val
      })
      const selectworkShop = this.workShopOptions.filter((item) => {
        return item.value == this.form.workShop
      })
      console.log(selectworkShop, selectedOption, 'workshop-components')
      // 触发自定义事件，传递 selectedOption[0] 数据给父组件
      console.log(selectedOption, 'selectedOption[0]', this.producLineOptions)
      this.$emit('product-line-selected', selectedOption[0])
      this.$emit('work-shop-selected', selectworkShop[0])
    },

    // 多选车间下拉框选择事件
    // handleSelect(value) {
    //   console.log(value, "value");
    //   const checkedCount = value.length;
    //   this.checkAll = checkedCount === this.workShopOptions.length;
    //   this.isIndeterminate =
    //     checkedCount > 0 && checkedCount < this.workShopOptions.length;
    //   const data = value.map((item) => {
    //     return item;
    //   });
    //   this.form.workShop = value.length > 0 ? data : [];
    //
    //   console.log(this.form.workShop, " form.workShop");
    // },
    // 全选事件
    handleCheckAllChange(val) {
      const data = this.workShopOptions.map((item) => {
        return item.value
      })
      this.form.workShop = val ? data : []
      this.isIndeterminate = false
    }
  }
}
</script>

<style scoped lang="scss">
.leftcon {
  width: 100%;
  height: 100%;
  background-size: 100% 100%;

  .lefttop {
    width: 100%;
    height: 60px;
  }

  .leftbottom {
    width: 1100px;
    height: 780px;
    margin: -16px 0 0 60px;

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

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