<template>
  <div class="app-container">
    <!-- 工具栏 -->
    <div class="head-container">
      <el-form
        :inline="true"
        class="demo-form-inline"
        label-position="right"
        label-width="80px"
        label-suffix=":"
      >
        <el-form-item label="监听端口">
          <el-input
            v-model="query.search"
            clearable
            style="width: 300px"
            size="mini"
            placeholder="请输入监听端口"
            class="filter-item"
          />
        </el-form-item>

        <!-- 新增滑块开关 -->
        <el-form-item label="设备监听">
          <el-switch
            v-model="rfidStatus"
            active-color="#13ce66"
            inactive-color="#ccc"
            @change="open"
          />
        </el-form-item>

        <rrOperation />
      </el-form>

      <crudOperation :permission="permission" />

      <!-- 表格 -->
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        size="mini"
        style="width: 100%;"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column prop="device_code" label="设备编号" />
        <el-table-column prop="ip" label="IP" />
        <el-table-column prop="status" label="连接状态">
          <template slot-scope="scope">
            <span :style="{ color: scope.row.status === 1 ? '#13ce66' : '#ff4949' }">
              {{ scope.row.status === 1 ? '已连接' : '未连接' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="start_time" label="开始连接时间" />
        <el-table-column
          prop="online_time"
          label="在线时间"
          :min-width="flexWidth('online_time', crud.data, '在线时间')"
        />
        <el-table-column
          prop="rfid"
          label="当前rfid值"
          :min-width="flexWidth('rfid', crud.data, '当前rfid值')"
        />
        <!--        <el-table-column prop="is_used" label="是否启用 ">-->
        <!--          <template slot-scope="scope">-->
        <!--            <el-switch-->
        <!--              v-model="scope.row.is_used"-->
        <!--              active-color="#409EFF"-->
        <!--              inactive-color="#F56C6C"-->
        <!--              @change="changeEnabled(scope.row, scope.row.is_used)"-->
        <!--            />-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column
          v-permission="['admin', 'mdPbMeasureunit:edit', 'mdPbMeasureunit:del']"
          fixed="right"
          label="操作"
          width="150px"
          align="center"
        >
          <template slot-scope="scope">
            <udOperation :data="scope.row" :permission="permission" />
          </template>
        </el-table-column>
      </el-table>

      <el-input
        v-model="logText"
        type="textarea"
        :rows="15"
        placeholder="设备运行日志..."
        readonly
        style="width: 100%; margin-top: 5px;"
      />

      <!-- 分页 -->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudRfid from './vehicle_rfid'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'

const defaultForm = {
  id: null,
  ip: null,
  port: null,
  device_code: null,
  is_used: true,
  online_time: null,
  create_id: null,
  create_name: null,
  create_time: null,
  update_id: null,
  update_name: null,
  update_time: null,
  status: null,
  start_time: null
}

export default {
  dicts: ['is_used'],
  name: 'VehicleRfid',
  components: { pagination, crudOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({
      title: '计量单位',
      url: 'api/rfid',
      optShow: {
        add: true
      },
      idField: 'id',
      sort: 'id,desc',
      crudMethod: { ...crudRfid }
    })
  },
  data() {
    return {
      intervalId: null,
      permission: {},
      rfidStatus: false, // 新增开关状态变量
      logText: '', // 展示日志内容
      logTextList: [], // 存储日志行数组（最多10条）
      query: {
        search: '8160' // 设置默认监听端口
      }
    }
  },
  mounted() {
    // 读写器定时器
    this.intervalId = setInterval(() => {
      this.crud.toQuery()
      this.updateLogFromResult()
    }, 3000)
  },
  beforeDestroy() {
    if (this.intervalId) {
      clearInterval(this.intervalId)
    }
  },
  methods: {
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    // updateLogFromResult() {
    //   const logList = this.crud.data.map(item => item.log).filter(log => !!log)
    //   if (logList.length === 0) return
    //   const newLog = logList.join('\n')
    //   //每次都添加日志
    //   this.logTextList.unshift(newLog) // 新日志放最前
    //   if (this.logTextList.length > 15) {
    //     this.logTextList.pop() // 最多保留10条
    //   }
    //   this.logText = this.logTextList.join('\n\n') // 更新展示内容
    // },
    updateLogFromResult() {
      const s = this.crud.data
      const logList = this.crud.data.map(item => item.log).filter(log => !!log)
      if (logList.length === 0) {
        return
      }
      const newLog = logList.join('\n')
      // 判断最新日志是否和旧的重复，避免重复添加
      if (!this.logTextList.includes(newLog)) {
        this.logTextList.unshift(newLog) // 新日志放最前
        if (this.logTextList.length > 15) {
          this.logTextList.pop() // 最多保留10条
        }
        this.logText = this.logTextList.join('\n\n') // 更新展示内容
      }
    },
    changeEnabled(data, val) {
      this.$confirm('此操作将改变' + data.device_code + '状态, 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        crudRfid.edit(data).then(() => {
          this.crud.notify('操作成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        }).catch(() => {
          data.is_used = !val
        })
      }).catch(() => {
        data.is_used = !val
      })
    },
    open(val) {
      debugger
      const payload = {
        port: this.query.search == null ? '8160' : this.query.search,
        isOpen: val ? '1' : '0'
      }
      crudRfid.open(JSON.stringify(payload)).then(res => {
        this.crud.toQuery()
        this.crud.notify('操作成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
      }).catch(() => {
        this.$message.error('操作失败')
        this.rfidStatus = !val
      })
    }
  }
}
</script>

<style scoped>
</style>
