<template>
  <d2-container>
    <template #header>
      <div class="search-bar">
        <el-form ref="form" :inline="true" :model="form" size="mini">
          <el-form-item :label="$t(key('select_time'))" prop="time">
            <el-date-picker
              v-model="form.time"
              :default-time="['00:00:00', '23:59:59']"
              type="datetimerange"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm:ss"
              range-separator="~"
              :start-placeholder="$t(key('start_date'))"
              :end-placeholder="$t(key('end_date'))"
              style="width:360px"
            />
          </el-form-item>
          <el-form-item :label="$t(key('workstation'))" prop="workstation_id">
            <el-select
              v-model="form.workstation_id"
              filterable
              clearable
              :placeholder="$t(key('select_workstation'))"
              style="width:180px"
              @change="changeWorkstation"
            >
              <el-option
                v-for="item in workstationOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="device_code">
            <el-select
              v-model="form.device_code"
              filterable
              clearable
              :placeholder="$t(key('select_device'))"
              style="width:180px"
            >
              <el-option
                v-for="item in deviceOptions"
                :key="item.id || item.code"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button size="mini" type="primary" icon="el-icon-search" :disabled="loading" @click="onSearch">
              {{ $t(key('query')) }}
            </el-button>
            <el-button size="mini" icon="el-icon-refresh" :disabled="loading" @click="onReset">
              {{ $t(key('reset')) }}
            </el-button>
            <el-button size="mini" type="primary" icon="el-icon-download" :disabled="exportLoading" :loading="exportLoading" @click="handleExport">
              {{ $t(key('export')) }}
            </el-button>
          </el-form-item>
        </el-form>
      </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,
  getWorkstationSearch,
  devicePinCheckExport
} 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,
      exportLoading: false,
      form: {
        time: '',
        workstation_id: '',
        device_code: ''
      },
      workstationOptions: [],
      deviceOptions: [],
      workstations: [],
      currentWorkstation: null,
      workstationDialogVisible: false,
      workstationDialogTitle: '',
      consecutiveData: [],
      cumulativeData: [],
      detailDialogVisible: false,
      detailTitle: '',
      detailData: []
    }
  },
  mounted () {
    this.loadWorkstationOptions()
    this.fetchData()
  },
  methods: {
    normalizeData (res) {
      const data = res && res.data !== undefined ? res.data : res
      return data || []
    },
    normalizeList (res) {
      const data = this.normalizeData(res)
      if (Array.isArray(data)) return data
      if (Array.isArray(data.data)) return data.data
      if (Array.isArray(data.list)) return data.list
      if (Array.isArray(data.rows)) return data.rows
      return []
    },
    buildQueryParams () {
      return {
        ...this.form,
        page_no: 1,
        page_size: 1000
      }
    },
    loadWorkstationOptions () {
      getWorkstationSearch({ pin_check: 'pin_check' })
        .then(res => {
          this.workstationOptions = this.normalizeList(res)
        })
        .catch(() => {
          this.workstationOptions = []
        })
    },
    fetchData () {
      this.loading = true
      getPincheckWorkstation(this.buildQueryParams())
        .then(res => {
          this.workstations = this.normalizeList(res)
        })
        .finally(() => {
          this.loading = false
        })
    },
    onSearch () {
      this.fetchData()
    },
    onReset () {
      this.$refs.form.resetFields()
      this.deviceOptions = []
      this.fetchData()
    },
    changeWorkstation (workstationId) {
      this.form.device_code = ''
      const workstation = this.workstationOptions.find(item => String(item.id) === String(workstationId))
      this.deviceOptions = workstation && Array.isArray(workstation.devices) ? workstation.devices : []
    },
    isEmptyTime () {
      return !this.form.time || (Array.isArray(this.form.time) && !this.form.time.length)
    },
    async handleExport () {
      if (this.isEmptyTime()) {
        this.$message.error(this.$t(this.key('please_select_time')))
        return
      }
      if (!this.form.workstation_id) {
        this.$message.error(this.$t(this.key('please_select_workstation')))
        return
      }
      const confirmed = await this.$confirm(this.$t(this.key('export_confirm_message')), this.$t(this.key('prompt')), {
        confirmButtonText: this.$t(this.key('confirm')),
        cancelButtonText: this.$t(this.key('cancel')),
        type: 'warning',
        center: true
      }).catch(() => {
        this.$message.info(this.$t(this.key('clear_cancel')))
        return false
      })
      if (confirmed === false) return

      this.exportLoading = true
      try {
        await devicePinCheckExport({
          ...this.form,
          action: 'download'
        })
        this.$message.success(this.$t(this.key('create_download_task_success')))
        this.$router.push({ name: 'task' }).catch(() => {})
      } finally {
        this.exportLoading = 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 || item.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 || (this.currentWorkstation && this.currentWorkstation.workstation_id) || (this.currentWorkstation && this.currentWorkstation.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 || (this.currentWorkstation && this.currentWorkstation.workstation_id) || (this.currentWorkstation && this.currentWorkstation.id),
        name: row.device_name
      })
    }
  }
}
</script>

<style scoped>
.search-bar {
  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>
