<template>
  <d2-container>
    <template #header>
      <div class="toolbar">
        <el-button size="mini" type="primary" icon="el-icon-refresh" :disabled="loading" @click="fetchData">
          {{ $t(key('refresh')) }}
        </el-button>
      </div>
    </template>

    <div v-loading="loading" class="alert-center">
      <el-empty v-if="!workstations.length" :description="$t('暂无数据')" />
      <div v-else class="station-grid">
        <div v-for="item in workstations" :key="item.workstation_id || item.id || item.name" class="station-card">
          <div class="station-title">
            <span>{{ $t(key('device_name')) }}: {{ item.name }}</span>
          </div>
          <div class="station-body">
            <el-badge :value="item.consecutive_error_device_count" type="primary">
              <el-button size="small" class="metric-btn">
                {{ $t(key('continuous_count')) }}
              </el-button>
            </el-badge>
            <el-badge :value="item.cumulative_error_device_count" type="warning">
              <el-button size="small" class="metric-btn">
                {{ $t(key('cumulative_count')) }}
              </el-button>
            </el-badge>
            <el-button
              v-if="Number(item.consecutive_error_device_count) > 0 || Number(item.cumulative_error_device_count) > 0"
              type="primary"
              size="mini"
              @click="openWorkstation(item)"
            >
              {{ $t(key('view_data')) }}
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <el-dialog
      :title="workstationDialogTitle"
      :visible.sync="workstationDialogVisible"
      fullscreen
      :before-close="closeWorkstationDialog"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card>
            <div slot="header">{{ $t(key('continuous')) }}</div>
            <el-table :data="consecutiveData" border v-loading="detailLoading">
              <el-table-column type="expand">
                <template #default="{ row }">
                  <div class="channel-list">
                    <el-badge
                      v-for="(value, channel) in row.consecutive_error_times"
                      :key="channel"
                      :value="value"
                    >
                      <el-button size="small" @click="clearSingle(row, 'continuous', channel)">
                        {{ $t(key('channel')) }} {{ Number(channel) + 1 }}
                      </el-button>
                    </el-badge>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="device_name" :label="$t(key('device_name'))" min-width="130" />
              <el-table-column prop="device_code" :label="$t(key('device_code'))" min-width="130" />
              <el-table-column prop="consecutive_error_channel_count" :label="$t(key('error_channel_count'))" min-width="120" />
              <el-table-column prop="consecutive_last_clear_date" :label="$t(key('last_clear_time'))" min-width="150" />
              <el-table-column prop="date" :label="$t(key('update_time'))" min-width="180" />
              <el-table-column :label="$t(key('operation'))" align="center" min-width="160">
                <template #default="{ row }">
                  <el-button size="mini" type="text" @click="openDetail(row, 'continuous')">
                    {{ $t(key('detail')) }}
                  </el-button>
                  <el-button size="mini" type="text" @click="clearDevice(row, 'continuous')">
                    {{ $t(key('clear')) }}
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card>
            <div slot="header">{{ $t(key('cumulative')) }}</div>
            <el-table :data="cumulativeData" border v-loading="detailLoading">
              <el-table-column type="expand">
                <template #default="{ row }">
                  <div class="channel-list">
                    <el-badge
                      v-for="(value, channel) in row.cumulative_error_times"
                      :key="channel"
                      :value="value"
                    >
                      <el-button size="small" @click="clearSingle(row, 'cumulative', channel)">
                        {{ $t(key('channel')) }} {{ Number(channel) + 1 }}
                      </el-button>
                    </el-badge>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="device_name" :label="$t(key('device_name'))" min-width="130" />
              <el-table-column prop="device_code" :label="$t(key('device_code'))" min-width="130" />
              <el-table-column prop="cumulative_error_channel_count" :label="$t(key('error_channel_count'))" min-width="120" />
              <el-table-column prop="cumulative_last_clear_date" :label="$t(key('last_clear_time'))" min-width="150" />
              <el-table-column prop="date" :label="$t(key('update_time'))" min-width="180" />
              <el-table-column :label="$t(key('operation'))" align="center" min-width="160">
                <template #default="{ row }">
                  <el-button size="mini" type="text" @click="openDetail(row, 'cumulative')">
                    {{ $t(key('detail')) }}
                  </el-button>
                  <el-button size="mini" type="text" @click="clearDevice(row, 'cumulative')">
                    {{ $t(key('clear')) }}
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </el-dialog>

    <el-dialog :title="detailTitle" :visible.sync="detailDialogVisible" width="80%">
      <el-table :data="detailData" border v-loading="detailTableLoading" height="600">
        <el-table-column prop="device_name" :label="$t(key('device_name'))" min-width="130" show-overflow-tooltip />
        <el-table-column prop="device_code" :label="$t(key('device_code'))" min-width="130" show-overflow-tooltip />
        <el-table-column prop="channel" :label="$t(key('channel_no'))" min-width="100" />
        <el-table-column prop="pin_code" :label="$t(key('error_code'))" min-width="120" />
        <el-table-column prop="msg" :label="$t(key('error_message'))" min-width="160" />
        <el-table-column prop="happen_time" :label="$t(key('error_time'))" min-width="160" />
      </el-table>
    </el-dialog>
  </d2-container>
</template>

<script>
import { i18nMixin } from '@/composables/useI18n'
import {
  getPincheckWorkstation,
  getDevicePinCheckList,
  getPinCheckDetail,
  setPinCheckClean,
  setPinCheckCleanSingle
} from '@/api/planning-production/alert-center'

export default {
  name: 'planning-production-alert-center',
  mixins: [i18nMixin('page.planning_production.alert_center')],
  data () {
    return {
      loading: false,
      detailLoading: false,
      detailTableLoading: false,
      workstations: [],
      currentWorkstation: null,
      workstationDialogVisible: false,
      workstationDialogTitle: '',
      consecutiveData: [],
      cumulativeData: [],
      detailDialogVisible: false,
      detailTitle: '',
      detailData: []
    }
  },
  mounted () {
    this.fetchData()
  },
  methods: {
    normalizeData (res) {
      const data = res && res.data !== undefined ? res.data : res
      return data || []
    },
    fetchData () {
      this.loading = true
      getPincheckWorkstation({})
        .then(res => {
          this.workstations = this.normalizeData(res)
        })
        .finally(() => {
          this.loading = false
        })
    },
    openWorkstation (item) {
      this.currentWorkstation = item
      this.workstationDialogTitle = this.$t(this.key('workstation_detail'), { device_name: item.name })
      this.workstationDialogVisible = true
      this.fetchDeviceDetails(item)
    },
    fetchDeviceDetails (item) {
      this.detailLoading = true
      getDevicePinCheckList({ device_category_id: item.workstation_id })
        .then(res => {
          const data = this.normalizeData(res)
          this.consecutiveData = data.consecutive_data || []
          this.cumulativeData = data.cumulative_data || []
        })
        .finally(() => {
          this.detailLoading = false
        })
    },
    closeWorkstationDialog () {
      this.workstationDialogVisible = false
    },
    openDetail (row, type) {
      this.detailDialogVisible = true
      this.detailTableLoading = true
      this.detailTitle = this.$t(this.key(type === 'continuous' ? 'continuous_detail' : 'accumulated_detail'), {
        device_name: row.device_name,
        device_code: row.device_code
      })
      getPinCheckDetail({
        device_category_id: row.workstation_id,
        device_code: row.device_code,
        type
      })
        .then(res => {
          this.detailData = this.normalizeData(res)
        })
        .finally(() => {
          this.detailTableLoading = false
        })
    },
    confirmClear (handler) {
      this.$confirm(this.$t(this.key('clear_confirm')), this.$t(this.key('prompt')), {
        confirmButtonText: this.$t(this.key('confirm')),
        cancelButtonText: this.$t(this.key('cancel')),
        type: 'warning',
        center: true
      })
        .then(handler)
        .catch(() => {
          this.$message.info(this.$t(this.key('clear_cancel')))
        })
    },
    clearDevice (row, type) {
      this.confirmClear(() => {
        return setPinCheckClean({
          device_code: row.device_code,
          type
        }).then(() => {
          this.refreshAfterClear(row)
        })
      })
    },
    clearSingle (row, type, channel) {
      this.confirmClear(() => {
        return setPinCheckCleanSingle({
          device_code: row.device_code,
          type,
          indexs: channel
        }).then(() => {
          this.refreshAfterClear(row)
        })
      })
    },
    refreshAfterClear (row) {
      this.$message.success(this.$t(this.key('clear_success')))
      this.fetchData()
      this.fetchDeviceDetails({
        workstation_id: row.workstation_id,
        name: row.device_name
      })
    }
  }
}
</script>

<style scoped>
.toolbar {
  margin-bottom: -18px;
}
.alert-center {
  height: 100%;
  overflow: auto;
}
.station-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 14px;
}
.station-card {
  min-height: 220px;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  background: #fff;
  text-align: center;
  overflow: hidden;
}
.station-title {
  min-height: 58px;
  border-bottom: 1px solid #dcdfe6;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 8px;
  font-size: 14px;
}
.station-body {
  display: flex;
  flex-direction: column;
  gap: 18px;
  align-items: center;
  padding: 22px 10px;
}
.metric-btn {
  width: 170px;
  white-space: normal;
}
.channel-list {
  display: flex;
  flex-wrap: wrap;
  gap: 18px;
  padding: 10px;
}
</style>
