<template>
  <div class="andon-container">
    <!-- 动态加载所有ANDON类型 -->
    <div v-for="(andonType, index) in andonTypes" :key="andonType.安东类型代码" class="andon-row"
      :style="{ marginBottom: index === andonTypes.length - 1 ? '0' : '5px' }">
      <div class="andon-header">
        <div class="andon-title">{{ andonType.安东类型描述 }}</div>
        <div v-if="andonType.items.length > 0" class="andon-actions">
          <div class="action-btn call-btn" @click="callAndonClick(andonType.安东类型代码)" title="呼叫">
            <img src="../../assets/image/call.png" alt="">
            <span>呼叫</span>
          </div>
          <div class="action-btn reset-btn" @click="resetAndonClick(andonType.安东类型代码)" title="复位">
            <img src="../../assets/image/reset.png" alt="">
            <span>复位</span>
          </div>
        </div>
      </div>
      <div v-if="andonType.items.length > 0" class="andon-row-content">
        <div class="andon-info">
          <div v-for="(item) in andonType.items" :key="item.编号" :id="item.编号" class="andon-content"
            :style="{ backgroundColor: getAndonStyle(item) }" @click="selectItem(andonType.安东类型代码, item)">
            {{ item.编号描述 }}
          </div>
        </div>
      </div>
      <div v-else class="andon-content-none">无{{ andonType.安东类型描述 }}呼叫类型！</div>
    </div>
    <el-dialog :title="title1" :append-to-body="true" :visible.sync="dialogFormVisible4" center width="350px">
      <el-form ref="form1" v-model="form1" label-position="right" label-width="80px">
        <el-form-item label="呼叫工位" style="display: inline-block">
          <el-input v-model="form1.callStation" size="small" style="width: 230px;" readonly />
        </el-form-item>
        <el-form-item v-if="form1.callType === 1" label="呼叫人员" style="display: inline-block">
          <el-input v-model="form1.callPersonName" size="small" style="width: 230px;" readonly />
        </el-form-item>
        <el-form-item label="呼叫原因" style="display: inline-block">
          <el-tag v-for="(item, index) in form1.checkboxGroup" :key="index" type="warning" style="margin: 0 5px">
            {{ item.编号描述 }}
          </el-tag>
        </el-form-item>
        <div v-if="form1.callType === 2"
          style=" background-color: #13227a;position: relative;display: block;height: 1px;width: 100%;margin: 5px 0;" />
        <el-form-item v-if="form1.callType === 2" label="解除人员" style="display: inline-block">
          <el-input v-model="form1.callOffPerson" size="small" style="width: 230px;" placeholder="请输入解除人员工号" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button v-if="form1.callType === 1" class="el-icon-check" type="primary" size="mini"
          @click="callAndon(form1.callAndonType)">确认呼叫</el-button>
        <el-button v-if="form1.callType === 2" class="el-icon-check" type="primary" size="mini"
          @click="callOffAndon(form1.callAndonType)">确认解除</el-button>
        <el-button class="el-icon-close" size="mini" @click="dialogFormVisible4 = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form1: {
        callType: 1, // 1 呼叫 2 复位
        callAndonType: 0,
        callStation: '',
        callPersonName: '',
        callPersonCode: '',
        callOffPerson: '',
        checkboxGroup: []
      },
      andonTypes: [], // 动态ANDON类型列表
      checkboxGroups: {}, // 动态checkbox分组 { '1': [], '2': [], '3': [] }
      dialogFormVisible4: false,
      title: '',
      title1: '',
      index: '',
      count: '',
      userName: '',
      userAccount: '',
      publication: {
        topic: '',
        qos: 0,
        payload: ''
      },
      statediv1: false
    }
  },
  created() {
    this.form1.callStation = this.$store.state.station.stationNumber
    this.form1.callPersonName = this.$store.state.station.stationUserName
    this.form1.callPersonCode = this.$store.state.station.stationUserCount
    this.loadAndonTypes()
  },
  methods: {
    // 加载所有ANDON类型
    loadAndonTypes() {
      const param = []
      const Data = this.CreateData('11', 'ANDON_类型_查询', param)
      this.ExecDatabase(Data).then(response => {
        // 过滤掉禁用的类型（是否禁用 == 1）
        this.andonTypes = response.data
          .filter(type => type.是否禁用 !== 1)
          .map(type => ({
            安东类型代码: type.安东类型代码,
            安东类型简称: type.安东类型简称,
            安东类型描述: type.安东类型描述,
            安东呼叫描述: type.安东呼叫描述,
            items: []
          }))
        // 初始化checkbox分组
        this.andonTypes.forEach(type => {
          this.$set(this.checkboxGroups, type.安东类型代码, [])
        })
        // 加载每个类型的编号
        this.loadAndonItems()
      })
    },
    // 加载所有类型的编号数据
    loadAndonItems() {
      this.andonTypes.forEach(type => {
        const param = []
        param[0] = ['安东类型代码', type.安东类型代码]
        param[1] = ['工位号', this.$store.state.station.stationNumber]
        const Data = this.CreateData('11', 'ANDON_类型_编号_查询', param)
        this.ExecDatabase(Data).then(response => {
          type.items = response.data.map(item => ({
            编号: item.编号,
            编号描述: item.编号描述,
            编号描述2: item.编号描述2,
            颜色代码: item.颜色代码,
            color: '#13227a', // 设置默认文字颜色为深蓝色
            bgColor: '',
            states: '0'
          }))
        })
      })
    },
    // 通用选择方法
    selectItem(typeCode, item) {
      const checkboxGroup = this.checkboxGroups[typeCode]
      if (item.states === '0') {
        if (!checkboxGroup.find(i => i.编号 === item.编号)) {
          checkboxGroup.push({
            编号: item.编号,
            编号描述: item.编号描述,
            编号描述2: item.编号描述2,
            颜色代码: item.颜色代码,
            states: item.states
          })
          item.states = '1'
        }
        item.bgColor = document.getElementById(item.编号).style.backgroundColor
        // item.color = document.getElementById(item.编号).style.color
        document.getElementById(item.编号).style.backgroundColor = '#b3d8ff'
        // document.getElementById(item.编号).style.color = '#ffffff'
      } else if (item.states === '1') {
        item.states = '0'
        document.getElementById(item.编号).style.backgroundColor = this.getAndonStyle(item)
        // document.getElementById(item.编号).style.color = item.color
        const count = checkboxGroup.findIndex(i => i.编号 === item.编号)
        checkboxGroup.splice(count, 1)
      }
    },
    getAndonStyle(item) {
      if (item.颜色代码 === '1') {
        return '#ffd819'
      } else {
        return '#fff'
      }
    },
    // 呼叫按钮点击
    callAndonClick(typeCode) {
      const andonType = this.andonTypes.find(t => t.安东类型代码 === typeCode)
      const checkboxGroup = this.checkboxGroups[typeCode]
      if (checkboxGroup.length < 1) {
        this.$alert(`没有选择${andonType.安东类型描述}`, 'ANDON呼叫提示', {
          confirmButtonText: '确定'
        })
      } else {
        this.title1 = `${andonType.安东类型描述}呼叫确认`
        this.dialogFormVisible4 = true
        this.form1.callType = 1
        this.form1.callAndonType = typeCode
        this.form1.checkboxGroup = checkboxGroup
      }
    },
    // 复位按钮点击
    resetAndonClick(typeCode) {
      const andonType = this.andonTypes.find(t => t.安东类型代码 === typeCode)
      const checkboxGroup = this.checkboxGroups[typeCode]
      if (checkboxGroup.length < 1) {
        this.$alert(`没有选择${andonType.安东类型描述}`, 'ANDON复位提示', {
          confirmButtonText: '确定'
        })
      } else {
        this.title1 = `${andonType.安东类型描述}复位`
        this.dialogFormVisible4 = true
        this.form1.callType = 2
        this.form1.callAndonType = typeCode
        this.form1.checkboxGroup = checkboxGroup
        this.form1.callPersonCode = ''
      }
    },
    callAndon(type) {
      const callGroupStr = this.checkboxGroups[type].map(item => item.编号).join(',')
      const param = []
      param[0] = ['工位号', this.form1.callStation]
      param[1] = ['呼叫人', this.form1.callPersonName]
      param[2] = ['安东类型', type]
      param[3] = ['安东明细代码组', callGroupStr]
      const Data = this.CreateData('12', 'ANDON_呼叫状态_呼叫_循环', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data[0].result === '1') {
          this.$message({
            message: '呼叫成功',
            type: 'success'
          })
          // 触发设备报警
          fetch(`http://${window.g.interfaceURL}/TriggerDeviceAlarm`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              MsgId: Date.now().toString(),
              OpName: this.form1.callStation,
              AlarmText: '安东呼叫报警',
              AlarmCode: '10005'
            })
          }).catch(err => {
            console.warn('安东报警接口调用失败:', err)
          })
          this.loadAndonItems()
          // 清空所有checkbox
          Object.keys(this.checkboxGroups).forEach(key => {
            this.checkboxGroups[key] = []
          })
          this.dialogFormVisible4 = false
        } else {
          this.$message.error('失败')
        }
      })
    },
    callOffAndon(type) {
      if (this.form1.callOffPerson === '') {
        this.$message.error('请输入解除人员工号')
        return
      }
      const callGroupStr = this.checkboxGroups[type].map(item => item.编号).join(',')
      const param = []
      param[0] = ['工位号', this.form1.callStation]
      param[1] = ['解除人', this.form1.callOffPerson]
      param[2] = ['安东类型', type]
      param[3] = ['安东明细代码组', callGroupStr]
      const Data = this.CreateData('12', 'ANDON_呼叫状态_解除_循环', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data[0].result === '1') {
          this.$message({
            message: '解除成功',
            type: 'success'
          })
          this.loadAndonItems()
          // 清空所有checkbox
          Object.keys(this.checkboxGroups).forEach(key => {
            this.checkboxGroups[key] = []
          })
          this.dialogFormVisible4 = false
        } else {
          this.$message.error('失败')
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.andon-container {
  width: 100%;
  height: 100%;
  background-color: #d7dee6;
  padding: 5px;
  box-sizing: border-box;
  overflow-y: auto;
}

.andon-row {
  background-color: #fff;
  border-radius: 5px;
  margin: 0 0 5px 0;
  border: 1px solid #e8e8e8;
  overflow: hidden;

  &:last-child {
    margin-bottom: 0;
  }
}

.andon-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 10px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e8e8e8;
}

.andon-title {
  font-size: 1.1rem;
  font-weight: bolder;
  color: #333;
  display: flex;
  align-items: center;

  &::before {
    content: "";
    display: inline-block;
    width: 10px;
    height: 10px;
    background-color: #13227a;
    border-radius: 50%;
    margin-right: 8px;
  }
}

.andon-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.action-btn {
  display: flex;
  align-items: center;
  padding: 4px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;

  img {
    height: 24px;
    margin-right: 4px;
  }

  span {
    font-size: 0.9rem;
    font-weight: 500;
  }

  &:hover {
    transform: scale(1.05);
  }
}

.call-btn {
  background-color: #fff3e0;
  border: 1px solid #ff9800;

  span {
    color: #e65100;
  }

  &:hover {
    background-color: #ffe0b2;
  }
}

.reset-btn {
  background-color: #e8f5e9;
  border: 1px solid #4caf50;

  span {
    color: #2e7d32;
  }

  &:hover {
    background-color: #c8e6c9;
  }
}

.andon-row-content {
  padding: 8px;
}

.andon-info {
  display: flex;
  align-items: flex-start;
  justify-content: flex-start;
  flex-wrap: wrap;
  gap: 8px;
}

.andon-content {
  font-size: 1rem;
  color: #13227a;
  min-width: 140px;
  max-width: 200px;
  padding: 8px 15px;
  border: 1px solid #13227a;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.2s;
  text-align: center;

  &:hover {
    transform: scale(1.03);
    box-shadow: 0 2px 8px rgba(19, 34, 122, 0.2);
  }
}

.andon-content-none {
  padding: 15px;
  text-align: center;
  color: #999;
  font-size: 0.95rem;
}
</style>
