<template>
  <div class="app-container">
    <el-card class="topCard">
      <div class="topDiv">
        <span>工位号：</span>
        <el-input
          v-model.trim="queryForm.stationKeyword"
          clearable
          size="small"
          placeholder="请输入工位号"
          style="width: 200px" />
        <span style="margin-left: 15px">登录状态：</span>
        <el-select v-model="queryForm.loginStatus" clearable size="small" placeholder="全部" style="width: 120px">
          <el-option label="已登录" :value="1" />
          <el-option label="未登录" :value="0" />
        </el-select>
        <span style="margin-left: 15px">产品型号：</span>
        <el-select v-model="queryForm.modelFlag" clearable size="small" placeholder="全部型号" style="width: 180px">
          <el-option v-for="item in productTypeList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-button type="primary" size="small" icon="el-icon-search" style="margin-left: 15px" @click="handleQuery">
          查询
        </el-button>
        <!-- <el-button size="small" icon="el-icon-refresh" style="margin-left: 10px" @click="refreshData">
          刷新
        </el-button> -->
        <el-divider direction="vertical" />
        <span class="currentProductLabel">当前生产型号：{{ currentProductModelLabel }}</span>
        <el-button size="small" type="warning" plain icon="el-icon-edit" @click="openCurrentModelDialog">
          生产产品
        </el-button>
        <span class="overlayTimeLabel">弹窗时间：{{ overlayTimeWindowLabel }}</span>
        <el-button size="small" type="primary" plain icon="el-icon-time" @click="openOverlayTimeDialog">
          弹窗时间
        </el-button>
      </div>

      <div class="statusSummary">
        <span class="summaryItem total">总工位：{{ stationCountSummary.total }}</span>
        <span class="summaryItem online">已登录：{{ stationCountSummary.online }}</span>
        <span class="summaryItem offline">未登录：{{ stationCountSummary.offline }}</span>
        <!-- <span class="summaryItem display">当前显示：{{ tableData.length }}</span> -->
      </div>

      <div v-loading="loading" class="stationGridWrap">
        <div v-if="tableData.length" class="stationGrid">
          <div
            v-for="item in tableData"
            :key="item.工位号"
            :class="['stationCard', item.登录状态值 === 1 ? 'online' : 'offline']"
            @click="openStationDetail(item)">
            <div class="stationHeader">
              <span class="stationNo">{{ item.工位号 }}</span>
              <el-tag v-if="item.登录状态值 === 1" size="mini" type="success">已登录</el-tag>
              <el-tag v-else size="mini" type="info">未登录</el-tag>
            </div>
            <div class="stationName">{{ item.工位名称 || '--' }}</div>
            <div class="stationInfo">姓名：{{ item.姓名 || '--' }}</div>
            <div class="stationInfo">{{ item.时间说明 }}：{{ item.操作时间 || '--' }}</div>
            <div class="stationModelTiny">加工型号：{{ item.加工型号展示 || '未配置' }}</div>
          </div>
        </div>
        <el-empty v-else description="暂无工位数据" :image-size="100" />
      </div>
    </el-card>

    <el-dialog
      :visible.sync="currentModelDialogVisible"
      :append-to-body="true"
      title="修改当前生产产品型号"
      width="420px">
      <el-form label-width="120px">
        <el-form-item label="当前产品型号">
          <el-select v-model="currentProductModelDraft" size="small" placeholder="请选择产品型号" style="width: 220px">
            <el-option v-for="item in productTypeList" :key="'current-' + item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="currentModelDialogVisible = false">取消</el-button>
        <el-button :loading="currentModelSaving" type="primary" size="small" @click="saveCurrentProductModel">
          保存
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="overlayTimeDialogVisible"
      :append-to-body="true"
      title="修改看板工位登录弹窗时间"
      width="460px">
      <el-form label-width="140px">
        <el-form-item label="弹窗开始时间">
          <el-time-picker
            v-model="overlayStartTimeDraft"
            size="small"
            value-format="HH:mm:ss"
            format="HH:mm:ss"
            placeholder="请选择开始时间"
            style="width: 240px" />
        </el-form-item>
        <el-form-item label="弹窗结束时间">
          <el-time-picker
            v-model="overlayEndTimeDraft"
            size="small"
            value-format="HH:mm:ss"
            format="HH:mm:ss"
            placeholder="请选择结束时间"
            style="width: 240px" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="overlayTimeDialogVisible = false">取消</el-button>
        <el-button :loading="overlayTimeSaving" type="primary" size="small" @click="saveOverlayTimeWindow">
          保存
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="detailDialogVisible"
      :append-to-body="true"
      title="工位详情"
      width="560px">
      <div v-if="selectedStation" class="detailBox">
        <div class="detailRow"><span class="label">工位号：</span>{{ selectedStation.工位号 }}</div>
        <div class="detailRow"><span class="label">工位名称：</span>{{ selectedStation.工位名称 }}</div>
        <div class="detailRow">
          <span class="label">登录状态：</span>
          <el-tag v-if="selectedStation.登录状态值 === 1" size="mini" type="success">已登录</el-tag>
          <el-tag v-else size="mini" type="info">未登录</el-tag>
        </div>
        <div class="detailRow"><span class="label">操作者工号：</span>{{ selectedStation.操作者工号 || '--' }}</div>
        <div class="detailRow"><span class="label">姓名：</span>{{ selectedStation.姓名 || '--' }}</div>
        <div class="detailRow"><span class="label">{{ selectedStation.时间说明 }}：</span>{{ selectedStation.操作时间 || '--' }}</div>
        <div class="detailRow detailModels">
          <span class="label">加工型号：</span>
          <template v-if="selectedStation.加工型号数组 && selectedStation.加工型号数组.length">
            <el-tag
              v-for="item in selectedStation.加工型号数组"
              :key="selectedStation.工位号 + '-detail-' + item"
              size="mini"
              style="margin-right: 6px; margin-bottom: 6px">
              {{ modelNameMap[item] || ('未知(' + item + ')') }}
            </el-tag>
          </template>
          <span v-else class="emptyText">未配置</span>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="detailDialogVisible = false">关闭</el-button>
        <el-button type="primary" size="small" icon="el-icon-setting" @click="openConfigFromDetail">配置加工型号</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="configDialogVisible"
      :append-to-body="true"
      title="配置工位可加工型号"
      width="520px"
      @close="closeConfigDialog">
      <el-form ref="configForm" :model="configForm" label-width="95px">
        <el-form-item label="工位号">
          <el-input v-model="configForm.stationNo" size="small" readonly style="width: 200px" />
        </el-form-item>
        <el-form-item label="可加工型号">
          <el-checkbox-group v-model="configForm.modelFlags">
            <el-checkbox
              v-for="item in productTypeList"
              :key="item.value"
              :label="item.value"
              style="margin-right: 20px; margin-bottom: 10px">
              {{ item.label }}
            </el-checkbox>
          </el-checkbox-group>
          <div class="tipText">未勾选表示该工位不允许生产该型号；全部不勾选即清空配置。</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeConfigDialog">取消</el-button>
        <el-button :loading="saveLoading" type="primary" size="small" @click="saveStationModelConfig">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
      saveLoading: false,
      queryForm: {
        stationKeyword: '',
        loginStatus: '',
        modelFlag: ''
      },
      tableDataSource: [],
      tableData: [],
      productTypeList: [],
      modelNameMap: {},
      currentProductModel: '',
      currentProductModelDraft: '',
      currentModelDialogVisible: false,
      currentModelSaving: false,
      overlayStartTime: '',
      overlayEndTime: '',
      overlayStartTimeDraft: '',
      overlayEndTimeDraft: '',
      overlayTimeDialogVisible: false,
      overlayTimeSaving: false,
      pollTimer: null,
      pollingBusy: false,
      detailDialogVisible: false,
      selectedStation: null,
      configDialogVisible: false,
      configForm: {
        stationNo: '',
        modelFlags: []
      }
    }
  },
  created() {
    this.initPageData()
  },
  beforeDestroy() {
    this.stopPolling()
  },
  computed: {
    currentProductModelLabel() {
      if (!this.currentProductModel) {
        return '未设置'
      }
      return this.modelNameMap[this.currentProductModel]
        ? `${this.modelNameMap[this.currentProductModel]}(${this.currentProductModel})`
        : this.currentProductModel
    },
    overlayTimeWindowLabel() {
      const start = this.overlayStartTime || '--:--:--'
      const end = this.overlayEndTime || '--:--:--'
      return `${start} ~ ${end}`
    },
    stationCountSummary() {
      const sourceList = this.tableDataSource || []
      let online = 0
      for (let i = 0; i < sourceList.length; i++) {
        if (Number(sourceList[i].登录状态值) === 1) {
          online++
        }
      }
      return {
        total: sourceList.length,
        online,
        offline: sourceList.length - online
      }
    }
  },
  methods: {
    initPageData() {
      this.loading = true
      this.getProductTypeList().then(() => {
        Promise.all([
          this.loadCurrentProductModel(),
          this.loadOverlayTimeWindow()
        ]).then(() => {
          this.getTableData()
          this.startPolling()
        }).catch(() => {
          this.getTableData()
          this.startPolling()
        })
      }).catch(() => {
        this.loading = false
      })
    },
    readPersistentValue(name) {
      const param = []
      param[0] = ['工位号', 'PLCS']
      param[1] = ['名称', name]
      const Data = this.CreateData('11', 'MES_持久化变量_读取', param)
      return this.ExecDatabase(Data).then(response => {
        const row = response.data && response.data.length ? response.data[0] : null
        return row && row.值 ? String(row.值).trim() : ''
      })
    },
    writePersistentValue(name, value) {
      const param = []
      param[0] = ['工位号', 'PLCS']
      param[1] = ['名称', name]
      param[2] = ['值', value || '']
      const Data = this.CreateData('12', 'MES_持久化变量_写入', param)
      return this.ExecDatabase(Data)
    },
    loadCurrentProductModel() {
      return this.readPersistentValue('生产产品型号').then(model => {
        this.currentProductModel = model
        this.currentProductModelDraft = model
        this.queryForm.modelFlag = model
      })
    },
    loadOverlayTimeWindow() {
      return Promise.all([
        this.readPersistentValue('看板工位登录状态弹窗开始时间'),
        this.readPersistentValue('看板工位登录状态弹窗结束时间')
      ]).then(values => {
        this.overlayStartTime = values[0] || ''
        this.overlayEndTime = values[1] || ''
      })
    },
    getProductTypeList() {
      const param = []
      this.productTypeList = []
      this.modelNameMap = {}
      const Data = this.CreateData('11', 'MES_基本变量_机型代码_查询', param)
      return this.ExecDatabase(Data).then(response => {
        const data = response.data || []
        for (let i = 0; i < data.length; i++) {
          const item = data[i]
          if (Number(item.是否禁用) === 1) {
            continue
          }
          const flag = String(item.发动机机型标志)
          const name = item.发动机型号
          this.productTypeList.push({
            label: `${name}(${flag})`,
            value: flag
          })
          this.modelNameMap[flag] = name
        }
      })
    },
    getTableData() {
      const param = []
      param[0] = ['产品型号', this.queryForm.modelFlag || '']
      const Data = this.CreateData('11', '测量数据工位_监控系统_操作者工号_视图_查询', param)
      this.ExecDatabase(Data).then(response => {
        const list = response.data || []
        const mappedList = list.map(item => {
          const operatorNo = item.操作者工号 === null || item.操作者工号 === undefined
            ? ''
            : String(item.操作者工号).trim()
          const isLogin = operatorNo !== ''
          const modelFlags = this.parseModelFlags(item.加工型号)
          const modelNames = modelFlags.map(flag => this.modelNameMap[flag] || flag)
          return {
            ...item,
            登录状态值: isLogin ? 1 : 0,
            时间说明: isLogin ? '登录时间' : '退出时间',
            加工型号数组: modelFlags,
            加工型号展示: modelNames.join('/')
          }
        })
        this.applyDiffUpdate(mappedList)
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    applyDiffUpdate(nextList) {
      const oldList = this.tableDataSource || []
      const oldMap = {}
      for (let i = 0; i < oldList.length; i++) {
        oldMap[oldList[i].工位号] = oldList[i]
      }
      const merged = []
      let changed = oldList.length !== nextList.length
      for (let i = 0; i < nextList.length; i++) {
        const next = nextList[i]
        const old = oldMap[next.工位号]
        if (old && this.isStationRowEqual(old, next)) {
          merged.push(old)
        } else {
          merged.push(next)
          changed = true
        }
      }
      if (changed) {
        this.tableDataSource = merged
        this.applyFilter()
      }
    },
    isStationRowEqual(oldRow, newRow) {
      return oldRow.操作者工号 === newRow.操作者工号 &&
        oldRow.姓名 === newRow.姓名 &&
        oldRow.操作时间 === newRow.操作时间 &&
        oldRow.时间说明 === newRow.时间说明 &&
        oldRow.加工型号展示 === newRow.加工型号展示 &&
        oldRow.登录状态值 === newRow.登录状态值
    },
    parseModelFlags(modelValue) {
      if (!modelValue) {
        return []
      }
      return String(modelValue)
        .split(',')
        .map(item => item.trim())
        .filter(item => item)
    },
    applyFilter() {
      const keyword = this.queryForm.stationKeyword ? this.queryForm.stationKeyword.trim() : ''
      const loginStatus = this.queryForm.loginStatus
      this.tableData = this.tableDataSource.filter(item => {
        const matchStation = !keyword || (item.工位号 && String(item.工位号).indexOf(keyword) > -1)
        const matchStatus = loginStatus === '' || loginStatus === null || loginStatus === undefined || Number(item.登录状态值) === Number(loginStatus)
        return matchStation && matchStatus
      })
    },
    handleQuery() {
      this.loading = true
      this.getTableData()
    },
    resetQuery() {
      this.queryForm.stationKeyword = ''
      this.queryForm.loginStatus = ''
      this.queryForm.modelFlag = this.currentProductModel || ''
      this.handleQuery()
    },
    refreshData() {
      this.loading = true
      this.getTableData()
    },
    startPolling() {
      this.stopPolling()
      this.pollTimer = setInterval(() => {
        if (this.pollingBusy) {
          return
        }
        this.pollingBusy = true
        const param = []
        param[0] = ['产品型号', this.queryForm.modelFlag || '']
        const Data = this.CreateData('11', '测量数据工位_监控系统_操作者工号_视图_查询', param)
        this.ExecDatabase(Data).then(response => {
          const list = response.data || []
          const mappedList = list.map(item => {
            const operatorNo = item.操作者工号 === null || item.操作者工号 === undefined
              ? ''
              : String(item.操作者工号).trim()
            const isLogin = operatorNo !== ''
            const modelFlags = this.parseModelFlags(item.加工型号)
            const modelNames = modelFlags.map(flag => this.modelNameMap[flag] || flag)
            return {
              ...item,
              登录状态值: isLogin ? 1 : 0,
              时间说明: isLogin ? '登录时间' : '退出时间',
              加工型号数组: modelFlags,
              加工型号展示: modelNames.join('/')
            }
          })
          this.applyDiffUpdate(mappedList)
          this.pollingBusy = false
        }).catch(() => {
          this.pollingBusy = false
        })
      }, 10000)
    },
    stopPolling() {
      if (this.pollTimer) {
        clearInterval(this.pollTimer)
        this.pollTimer = null
      }
    },
    openCurrentModelDialog() {
      this.currentProductModelDraft = this.currentProductModel || ''
      this.currentModelDialogVisible = true
    },
    openOverlayTimeDialog() {
      this.overlayStartTimeDraft = this.overlayStartTime || ''
      this.overlayEndTimeDraft = this.overlayEndTime || ''
      this.overlayTimeDialogVisible = true
    },
    saveCurrentProductModel() {
      this.currentModelSaving = true
      this.writePersistentValue('生产产品型号', this.currentProductModelDraft || '').then(() => {
        this.currentProductModel = this.currentProductModelDraft || ''
        this.queryForm.modelFlag = this.currentProductModel
        this.currentModelDialogVisible = false
        this.currentModelSaving = false
        this.$message.success('当前生产产品已更新')
        this.handleQuery()
      }).catch(() => {
        this.currentModelSaving = false
        this.$message.error('更新失败')
      })
    },
    saveOverlayTimeWindow() {
      if (!this.overlayStartTimeDraft || !this.overlayEndTimeDraft) {
        this.$message.warning('请完整选择开始和结束时间')
        return
      }
      this.overlayTimeSaving = true
      this.writePersistentValue('看板工位登录状态弹窗开始时间', this.overlayStartTimeDraft).then(() => {
        return this.writePersistentValue('看板工位登录状态弹窗结束时间', this.overlayEndTimeDraft)
      }).then(() => {
        this.overlayStartTime = this.overlayStartTimeDraft
        this.overlayEndTime = this.overlayEndTimeDraft
        this.overlayTimeDialogVisible = false
        this.overlayTimeSaving = false
        this.$message.success('看板弹窗时间已更新')
      }).catch(() => {
        this.overlayTimeSaving = false
        this.$message.error('更新失败')
      })
    },
    openConfigDialog(row) {
      this.configForm.stationNo = row.工位号
      this.configForm.modelFlags = row.加工型号数组 ? row.加工型号数组.slice() : []
      this.configDialogVisible = true
    },
    openStationDetail(row) {
      this.selectedStation = {
        ...row,
        加工型号数组: row.加工型号数组 ? row.加工型号数组.slice() : []
      }
      this.detailDialogVisible = true
    },
    openConfigFromDetail() {
      if (!this.selectedStation) {
        return
      }
      this.detailDialogVisible = false
      this.openConfigDialog(this.selectedStation)
    },
    closeConfigDialog() {
      this.configDialogVisible = false
      this.configForm.stationNo = ''
      this.configForm.modelFlags = []
    },
    saveStationModelConfig() {
      if (!this.configForm.stationNo) {
        this.$message.warning('工位号不能为空')
        return
      }
      const modelFlags = (this.configForm.modelFlags || [])
        .map(item => String(item))
        .sort((a, b) => Number(a) - Number(b))
      const param = []
      param[0] = ['工位号', this.configForm.stationNo]
      param[1] = ['加工型号', modelFlags.join(',')]
      const Data = this.CreateData('12', '测量数据工位_监控系统_工位加工型号_修改', param)
      this.saveLoading = true
      this.ExecDatabase(Data).then(response => {
        if (response.data && response.data.length > 0 && String(response.data[0].result) === '1') {
          this.$message.success(response.data[0].msg || '保存成功')
          this.closeConfigDialog()
          this.refreshData()
        } else {
          const msg = response.data && response.data.length > 0 ? response.data[0].msg : '保存失败'
          this.$message.error(msg || '保存失败')
        }
        this.saveLoading = false
      }).catch(() => {
        this.saveLoading = false
        this.$message.error('保存失败')
      })
    }
  }
}
</script>

<style scoped>
.topCard {
  margin: 5px;
}

.topDiv {
  margin-bottom: 10px;
}

.statusSummary {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
  padding: 8px 12px;
  background: #f8f9fb;
  border: 1px solid #ebeef5;
  border-radius: 8px;
}

.summaryItem {
  font-size: 13px;
  color: #606266;
  line-height: 20px;
}

.summaryItem.total {
  color: #303133;
  font-weight: 600;
}

.summaryItem.online {
  color: #67c23a;
}

.summaryItem.offline {
  color: #909399;
}

.summaryItem.display {
  color: #409eff;
}

.currentProductLabel {
  margin-right: 10px;
  color: #606266;
  font-size: 13px;
}

.overlayTimeLabel {
  margin-left: 10px;
  margin-right: 10px;
  color: #606266;
  font-size: 13px;
}

.stationGridWrap {
  min-height: 700px;
}

.stationGrid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 14px;
}

.stationCard {
  display: flex;
  flex-direction: column;
  min-height: 120px;
  border-radius: 10px;
  border: 2px solid transparent;
  padding: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.stationCard:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.stationCard.online {
  background: #f0f9eb;
  border-color: #67c23a;
}

.stationCard.offline {
  background: #f4f4f5;
  border-color: #909399;
}

.stationHeader {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 4px;
}

.stationNo {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.stationInfo {
  font-size: 13px;
  color: #606266;
  line-height: 20px;
  word-break: break-all;
}

.stationName {
  font-size: 13px;
  color: #606266;
  line-height: 18px;
  margin-bottom: 2px;
  word-break: break-all;
}

.stationModelTiny {
  margin-top: auto;
  padding-top: 6px;
  max-width: 100%;
  font-size: 11px;
  color: #909399;
  text-align: right;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.detailBox {
  line-height: 28px;
}

.detailRow {
  color: #303133;
}

.detailRow .label {
  display: inline-block;
  width: 95px;
  color: #909399;
}

.detailModels {
  margin-top: 4px;
}

.emptyText {
  color: #909399;
}

.tipText {
  margin-top: 8px;
  color: #909399;
  line-height: 20px;
}
</style>
