<template>
  <div class="app-container mes-admin-page">
    <el-card class="toolbar-card" shadow="never">
      <div class="toolbar">
        <div class="toolbar-left">
          <span class="toolbar-label">{{ $t('toolLife.stationLabel') }}</span>
          <el-select
            v-model="machineCode"
            clearable
            filterable
            :placeholder="$t('toolLife.selectAllPlaceholder')"
            size="small"
            style="width: 260px"
            @change="handleMachineChange"
            @clear="handleMachineChange">
            <el-option
              v-for="item in machineOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
          <el-button
            icon="el-icon-search"
            plain
            size="small"
            style="margin-left: 10px"
            type="primary"
            @click="searchData">{{ $t('toolLife.search') }}
          </el-button>
        </div>
        <div class="toolbar-right" v-if="selectedMachineName">
          <span class="machine-name">{{ selectedMachineName }}</span>
        </div>
      </div>
    </el-card>

    <div v-loading="loading" class="content-wrapper">
      <el-row :gutter="16" class="summary-row">
        <el-col :span="6">
          <div class="summary-card total">
            <div class="summary-title">{{ $t('toolLife.totalTools') }}</div>
            <div class="summary-main">
              <div class="summary-value">{{ summaryInfo.totalCount }}</div>
              <div class="summary-unit">{{ $t('toolLife.pieceUnit') }}</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="summary-card normal">
            <div class="summary-title">{{ $t('toolLife.normalTools') }}</div>
            <div class="summary-main">
              <div class="summary-value">{{ summaryInfo.normalCount }}</div>
              <div class="summary-unit">{{ normalRateText }}</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="summary-card warning">
            <div class="summary-title">{{ $t('toolLife.warningTools') }}</div>
            <div class="summary-main">
              <div class="summary-value">{{ summaryInfo.warningCount }}</div>
              <div class="summary-unit">{{ warningRateText }}</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="summary-card scrap">
            <div class="summary-title">{{ $t('toolLife.scrapTools') }}</div>
            <div class="summary-main">
              <div class="summary-value">{{ summaryInfo.scrapCount }}</div>
              <div class="summary-unit">{{ scrapRateText }}</div>
            </div>
          </div>
        </el-col>
      </el-row>

      <el-row :gutter="16" class="detail-row">
        <el-col :span="7" style="padding: 0">
          <el-card class="panel-card overview-card" shadow="never">
            <div slot="header" class="panel-header">
              <div style="height:32px;align-items: center;display: flex;justify-content: space-between;width:100%;color:#243447">
                <span>{{ $t('toolLife.statusOverview') }}</span>
                <span class="panel-subtitle">{{ $t('toolLife.statusOverviewSubtitle') }}</span>
              </div>

            </div>

            <div class="status-ring-wrapper">
              <div class="status-ring" :style="statusRingStyle">
                <div class="status-ring-inner">
                  <div class="status-ring-total">{{ summaryInfo.totalCount }}</div>
                  <div class="status-ring-label">{{ $t('toolLife.totalTools') }}</div>
                </div>
              </div>
            </div>


            <div class="bar-group">
              <div class="bar-item">
                <div class="bar-label">
                  <span>{{ $t('toolLife.normalRate') }}</span>
                  <span>{{ normalRateText }}</span>
                </div>
                <el-progress
                  :percentage="normalRate"
                  :stroke-width="14"
                  color="#10b981"
                  :show-text="false"/>
              </div>
              <div class="bar-item">
                <div class="bar-label">
                  <span>{{ $t('toolLife.warningRate') }}</span>
                  <span>{{ warningRateText }}</span>
                </div>
                <el-progress
                  :percentage="warningRate"
                  :stroke-width="14"
                  color="#f59e0b"
                  :show-text="false"/>
              </div>
              <div class="bar-item">
                <div class="bar-label">
                  <span>{{ $t('toolLife.scrapRate') }}</span>
                  <span>{{ scrapRateText }}</span>
                </div>
                <el-progress
                  :percentage="scrapRate"
                  :stroke-width="14"
                  color="#ef4444"
                  :show-text="false"/>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :span="17" style="padding: 0">
          <div slot="header" class="panel-header">
            <span>{{ $t('toolLife.detailTitle') }}</span>
            <span class="panel-subtitle">{{ $t('toolLife.detailSubtitle') }}</span>
          </div>
          <el-table
            :data="tableData"
            :header-cell-style="{ background: '#f3f6fb', color: '#3a4a5d' }"
            border
            height="520"
            size="mini"
            style="width: 100%">
            <el-table-column :label="$t('toolLife.sequence')" align="center" type="index" width="60"/>
            <el-table-column :label="$t('toolLife.stationColumn')" align="center" min-width="120">
              <template slot-scope="scope">
                {{ scope.row.设备编号 || '-' }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('toolLife.toolCode')" align="center" min-width="120">
              <template slot-scope="scope">
                {{ scope.row.刀具代码 || '-' }}
              </template>
            </el-table-column>
<!--              <el-table-column align="center" label="刀具名称" min-width="120">-->
<!--                <template slot-scope="scope">-->
<!--                  {{ scope.row.刀具名称 || '-' }}-->
<!--                </template>-->
<!--              </el-table-column>-->
<!--              <el-table-column align="center" label="刀具组号" min-width="110">-->
<!--                <template slot-scope="scope">-->
<!--                  {{ scope.row.刀具组号 || '-' }}-->
<!--                </template>-->
<!--              </el-table-column>-->
            <el-table-column :label="$t('toolLife.ratedLife')" align="center" min-width="100">
              <template slot-scope="scope">
                {{ formatNumber(scope.row.额定寿命) }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('toolLife.usedLife')" align="center" min-width="100">
              <template slot-scope="scope">
                {{ formatNumber(scope.row.已用寿命) }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('toolLife.warningValue1')" align="center" min-width="100">
              <template slot-scope="scope">
                {{ formatNumber(scope.row.预警值1) }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('toolLife.remainingLife')" align="center" min-width="100">
              <template slot-scope="scope">
                {{ formatNumber(getRemainingLife(scope.row)) }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('toolLife.lifeProgress')" align="center" min-width="150">
              <template slot-scope="scope">
                <div class="table-progress">
                  <el-progress
                    :text-inside="true"
                    :percentage="calcRate(scope.row.已用寿命, scope.row.额定寿命)"
                    :color="getRowProgressColor(scope.row)"
                    :stroke-width="12"/>
                </div>
              </template>
            </el-table-column>
            <el-table-column :label="$t('toolLife.status')" align="center" min-width="90">
              <template slot-scope="scope">
                <el-tag :type="getRowStatus(scope.row).type" size="mini">
                  {{ getRowStatus(scope.row).text }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>

      <div v-if="!loading && !tableData.length" class="empty-block">
        {{ $t('toolLife.noData') }}
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
      machineCode: '',
      selectedMachineName: '',
      machineOptions: [],
      tableData: [],
      summaryInfo: {
        totalCount: 0,
        normalCount: 0,
        warningCount: 0,
        scrapCount: 0
      }
    }
  },
  computed: {
    normalRate() {
      return this.calcCountRate(this.summaryInfo.normalCount, this.summaryInfo.totalCount)
    },
    warningRate() {
      return this.calcCountRate(this.summaryInfo.warningCount, this.summaryInfo.totalCount)
    },
    scrapRate() {
      return this.calcCountRate(this.summaryInfo.scrapCount, this.summaryInfo.totalCount)
    },
    normalRateText() {
      return this.normalRate.toFixed(1) + '%'
    },
    warningRateText() {
      return this.warningRate.toFixed(1) + '%'
    },
    scrapRateText() {
      return this.scrapRate.toFixed(1) + '%'
    },
    statusRingStyle() {
      const normalEnd = this.normalRate
      const warningEnd = this.normalRate + this.warningRate
      return {
        background: 'conic-gradient(#10b981 0% ' + normalEnd + '%, #f59e0b ' + normalEnd + '% ' + warningEnd + '%, #ef4444 ' + warningEnd + '% 100%)'
      }
    }
  },
  created() {
    this.getMachineOptions()
  },
  methods: {
    getMachineOptions() {
      this.machineOptions = []
      var param = []
      var Data = this.CreateData('11', '设备管理_刀具寿命_机床列表_查询', param)
      this.ExecDatabase(Data).then(response => {
        const list = response.data || []
        for (let i = 0; i < list.length; i++) {
          const machineCode = list[i].设备编号 || ''
          const machineName = list[i].设备名称 || machineCode
          if (machineCode) {
            this.machineOptions.push({
              label: machineName,
              value: machineCode,
              machineName: machineName
            })
          }
        }
        this.selectedMachineName = this.$t('toolLife.allStations')
        this.searchData()
      })
    },
    handleMachineChange(value) {
      if (!value) {
        this.selectedMachineName = this.$t('toolLife.allStations')
        this.searchData()
        return
      }
      const current = this.machineOptions.find(item => item.value === value)
      this.selectedMachineName = current ? current.machineName : ''
      this.searchData()
    },
    searchData() {
      this.loading = true
      var param = []
      param[0] = ['设备编号', this.machineCode || '']
      var Data = this.CreateData('11', '设备管理_刀具寿命_明细_查询', param)
      this.ExecDatabase(Data).then(response => {
        const list = response.data || []
        this.tableData = list
        this.buildSummary(list)
        this.loading = false
      }).catch(() => {
        this.loading = false
        this.tableData = []
        this.resetSummary()
        this.$message.error(this.$t('toolLife.queryFailed'))
      })
    },
    buildSummary(list) {
      let normalCount = 0
      let warningCount = 0
      let scrapCount = 0
      for (let i = 0; i < list.length; i++) {
        const status = this.getRowStatus(list[i]).text
        if (status === '正常') {
          normalCount++
        } else if (status === '预警') {
          warningCount++
        } else if (status === '报废') {
          scrapCount++
        }
      }
      this.summaryInfo = {
        totalCount: list.length,
        normalCount: normalCount,
        warningCount: warningCount,
        scrapCount: scrapCount
      }
    },
    resetSummary() {
      this.summaryInfo = {
        totalCount: 0,
        normalCount: 0,
        warningCount: 0,
        scrapCount: 0
      }
    },
    toNumber(value) {
      const num = Number(value)
      return isNaN(num) ? 0 : num
    },
    formatNumber(value) {
      const num = this.toNumber(value)
      if (num % 1 === 0) {
        return num
      }
      return num.toFixed(2)
    },
    calcRate(used, total) {
      const totalNum = this.toNumber(total)
      const usedNum = this.toNumber(used)
      if (totalNum <= 0) {
        return 0
      }
      let rate = usedNum / totalNum * 100
      if (rate < 0) {
        rate = 0
      }
      if (rate > 100) {
        rate = 100
      }
      return Number(rate.toFixed(1))
    },
    calcCountRate(count, total) {
      if (!total) {
        return 0
      }
      return Number((count / total * 100).toFixed(1))
    },
    getRemainingLife(row) {
      const remaining = this.toNumber(row.额定寿命) - this.toNumber(row.已用寿命)
      return remaining > 0 ? remaining : 0
    },
    getRowStatus(row) {
      const rated = this.toNumber(row.额定寿命)
      const used = this.toNumber(row.已用寿命)
      const warning = this.toNumber(row.预警值1)
      if (rated > 0 && used >= rated) {
        return {
          text: this.$t('toolLife.statusScrap'),
          type: 'danger'
        }
      }
      if (warning > 0 && used >= warning) {
        return {
          text: this.$t('toolLife.statusWarning'),
          type: 'warning'
        }
      }
      return {
        text: this.$t('toolLife.statusNormal'),
        type: 'success'
      }
    },
    getRowProgressColor(row) {
      const status = this.getRowStatus(row)
      if (status.type === 'danger') {
        return '#ef4444'
      }
      if (status.type === 'warning') {
        return '#f59e0b'
      }
      return '#10b981'
    }
  }
}
</script>

<style scoped>
.tool-life-page {
  background: #f5f7fb;
  min-height: calc(100vh - 84px);
}

.toolbar-card,
.panel-card {
  border: none;
  border-radius: 16px;
}

.toolbar {
  align-items: center;
  display: flex;
  justify-content: space-between;
  min-height: 42px;
}

.toolbar-left {
  align-items: center;
  display: flex;
  flex-wrap: wrap;
}

.toolbar-label {
  color: #4c5a67;
  font-size: 14px;
  margin-right: 8px;
}

.toolbar-right {
  color: #6b7785;
  font-size: 13px;
}

.machine-name {
  background: linear-gradient(135deg, #eef5ff, #f7fbff);
  border: 1px solid #dbeafe;
  border-radius: 999px;
  color: #1d4ed8;
  display: inline-block;
  padding: 7px 14px;
}

.content-wrapper {
  margin-top: 16px;
}

.summary-row {
  margin-bottom: 16px;
}

.summary-card {
  border-radius: 18px;
  color: #fff;
  height: 100px;
  min-height: 100px;
  overflow: hidden;
  padding: 14px 18px;
  position: relative;
}

.summary-card::after {
  background: rgba(255, 255, 255, 0.14);
  border-radius: 50%;
  content: '';
  height: 120px;
  position: absolute;
  right: -20px;
  top: -20px;
  width: 120px;
}

.summary-card.total {
  background: linear-gradient(135deg, #2563eb, #60a5fa);
}

.summary-card.normal {
  background: linear-gradient(135deg, #059669, #34d399);
}

.summary-card.warning {
  background: linear-gradient(135deg, #d97706, #fbbf24);
}

.summary-card.scrap {
  background: linear-gradient(135deg, #dc2626, #f87171);
}

.summary-title {
  font-size: 14px;
  opacity: 0.92;
}

.summary-main {
  align-items: flex-end;
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.summary-value {
  font-size: 28px;
  font-weight: 700;
  line-height: 1.2;
}

.summary-unit {
  font-size: 13px;
  opacity: 0.88;
  text-align: right;
}

.detail-row {
  margin-bottom: 16px;
}

.panel-header {
  align-items: center;
  display: flex;
  justify-content: space-between;
}

.panel-subtitle {
  color: #8a97a6;
  font-size: 12px;
}

.overview-card {
  min-height: 520px;
}

.status-ring-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 12px;
}

.status-ring {
  align-items: center;
  border-radius: 50%;
  display: flex;
  height: 220px;
  justify-content: center;
  width: 220px;
}

.status-ring-inner {
  align-items: center;
  background: #fff;
  border-radius: 50%;
  box-shadow: inset 0 0 30px rgba(37, 99, 235, 0.08);
  display: flex;
  flex-direction: column;
  height: 166px;
  justify-content: center;
  width: 166px;
}

.status-ring-total {
  color: #1f2937;
  font-size: 34px;
  font-weight: 700;
}

.status-ring-label {
  color: #7b8794;
  font-size: 13px;
  margin-top: 8px;
}

.status-list {
  background: #f8fafc;
  border-radius: 14px;
  margin-top: 22px;
  padding: 10px 14px;
}

.status-item {
  align-items: center;
  display: flex;
  min-height: 66px;
}

.status-dot {
  border-radius: 50%;
  height: 12px;
  margin-right: 12px;
  width: 12px;
}

.normal-dot {
  background: #10b981;
}

.warning-dot {
  background: #f59e0b;
}

.scrap-dot {
  background: #ef4444;
}

.status-text {
  flex: 1;
}

.status-name {
  color: #243142;
  font-size: 14px;
  font-weight: 600;
}

.status-desc {
  color: #8090a3;
  font-size: 12px;
  margin-top: 4px;
}

.status-count {
  color: #111827;
  font-size: 22px;
  font-weight: 700;
}

.bar-group {
  margin-top: 22px;
}

.bar-item {
  margin-bottom: 18px;
}

.bar-label {
  color: #495566;
  display: flex;
  font-size: 13px;
  justify-content: space-between;
  margin-bottom: 8px;
}

.table-progress {
  padding: 0 10px;
}

.empty-block {
  background: #fff;
  border: 1px dashed #d6deea;
  border-radius: 16px;
  color: #8a97a6;
  margin-top: 16px;
  padding: 28px 16px;
  text-align: center;
}

::v-deep .el-card__body {
  padding: 18px 20px;
}
</style>
