\<template>
  <div class="app-container">
    <!-- 顶部操作区 -->
    <el-card class="topCard">
      <div class="operation-area">
        <!-- 物料选择 -->
        <div class="select-group">
          <span class="label">物料选择:</span>
          <el-select 
            v-model="selectedMaterials" 
            placeholder="请选择物料(可多选)" 
            multiple 
            filterable 
            clearable
            remote 
            :remote-method="searchMaterials" 
            size="small" 
            style="width: 400px"
            @change="handleMaterialChange"
          >
            <el-option
              v-for="item in materialOptions"
              :key="item.物料编码"
              :label="`${item.物料编码} - ${item.物料描述}`"
              :value="item.物料编码"
              size="mini"
            />
          </el-select>
        </div>
        
        <!-- 点位选择 -->
        <div class="select-group">
          <span class="label">起始点:</span>
          <el-select 
            v-model="startPoint" 
            placeholder="请选择起始点位" 
            filterable
            size="small" 
            style="width: 200px"
          >
            <el-option
              v-for="item in locationPoints"
              :key="item.PointCode"
              :label="`${item.PointCode} - ${item.PointName}`"
              :value="item.PointCode"
            />
          </el-select>
          
          <span class="arrow">→</span>
          
          <span class="label">目标点:</span>
          <el-select 
            v-model="endPoint" 
            placeholder="请选择目标点位" 
            filterable
            size="small" 
            style="width: 200px"
          >
            <el-option
              v-for="item in locationPoints"
              :key="item.PointCode"
              :label="`${item.PointCode} - ${item.PointName}`"
              :value="item.PointCode"
            />
          </el-select>
        </div>
        
        <!-- 操作按钮 -->
        <div class="button-group">
          <el-button type="primary" size="small" icon="el-icon-s-promotion" @click="createTask">生成任务</el-button>
          <el-button type="success" size="small" icon="el-icon-refresh" @click="refreshRealtimeData">刷新实时</el-button>
          <el-button type="warning" size="small" icon="el-icon-time" @click="showHistoryDialog">历史记录</el-button>
          <el-button type="warning" size="small" icon="el-icon-location" @click="showPointManagement">点位管理</el-button>
        </div>
      </div>
    </el-card>

    <!-- 实时数据展示区 -->
    <el-card class="realtime-card">
      <div slot="header" class="card-header">
        <span class="card-title">
          <i class="el-icon-monitor" style="margin-right: 8px; color: #409EFF;"></i>实时任务数据
        </span>
        <div class="header-actions">
          <el-tag 
            :type="realtimeFilter === '' ? 'primary' : 'info'"
            size="small"
            @click="realtimeFilter = ''; getRealtimeData()"
            style="cursor: pointer; margin-right: 5px;"
          >
            全部
          </el-tag>
          <el-tag 
            type="warning"
            size="small"
            @click="realtimeFilter = 'PENDING'; getRealtimeData()"
            style="cursor: pointer; margin-right: 5px;"
          >
            待执行
          </el-tag>
          <el-tag 
            type="success"
            size="small"
            @click="realtimeFilter = 'RUNNING'; getRealtimeData()"
            style="cursor: pointer;"
          >
            执行中
          </el-tag>
        </div>
      </div>
      
      <el-table
        :data="realtimeData"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        element-loading-text="数据加载中"
        v-loading="loading"
        border
        size="mini"
        height="588px"
        style="width: 100%"
      >
        <el-table-column label="序号" type="index" align="center" width="60"/>
        <el-table-column prop="TaskNo" label="任务编号" align="center" width="150"/>
        <el-table-column prop="AGVCode" label="AGV编号" align="center" width="120"/>
        <el-table-column prop="MaterialNames" label="物料名称" align="center" width="200" show-overflow-tooltip/>
        <el-table-column prop="CurrentPoint" label="当前位置" align="center" width="100"/>
        <el-table-column prop="TargetPoint" label="目标点位" align="center" width="100"/>
        <el-table-column label="任务状态" align="center" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.TaskStatus)" size="small">
              {{ getStatusText(scope.row.TaskStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="Progress" label="进度" align="center" width="150">
          <template slot-scope="scope">
            <el-progress 
              :percentage="scope.row.Progress || 0" 
              :color="scope.row.Progress === 100 ? '#67C23A' : '#409EFF'"
              :stroke-width="14"
            />
          </template>
        </el-table-column>
        <el-table-column prop="Speed" label="速度(m/s)" align="center" width="90"/>
        <el-table-column prop="Battery" label="电量" align="center" width="120">
          <template slot-scope="scope">
            <div class="battery-display">
              <i 
                class="el-icon-battery" 
                :style="{color: getBatteryColor(scope.row.Battery)}"
              />
              <span>{{ scope.row.Battery }}%</span>
            </div>
          </template>
        </el-table-column> -->
        <el-table-column prop="Operator" label="操作人" align="center" width="100"/>
        <el-table-column prop="UpdateTime" label="更新时间" align="center" width="160"/>
        <el-table-column label="操作" align="center" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button 
              v-if="scope.row.TaskStatus === 'PENDING'"
              type="text" 
              icon="el-icon-video-play" 
              size="mini" 
              style="color: #67C23A;"
              @click="startTask(scope.row)"
            >开始</el-button>
            <!-- <el-button 
              type="text" 
              icon="el-icon-video-pause" 
              size="mini" 
              style="color: #E6A23C;"
              @click="pauseTask(scope.row)"
              :disabled="scope.row.TaskStatus !== 'RUNNING'"
            >暂停</el-button> -->
            <el-button 
              type="text" 
              icon="el-icon-circle-close" 
              size="mini" 
              style="color: #F56C6C;"
              @click="cancelTask(scope.row)"
            >取消</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 点位管理对话框 -->
    <el-dialog 
      :visible.sync="pointManagementVisible" 
      title="点位管理" 
      center 
      width="1200px"
      @opened="getLocationPoints"
    >
      <div class="point-management-header">
        <el-button type="primary" size="small" icon="el-icon-plus" @click="showAddPointDialog">新增点位</el-button>
        <div class="filter-group">
          <span class="label">点位类型:</span>
          <el-select v-model="pointTypeFilter" placeholder="全部" clearable size="small" style="width: 150px" @change="getLocationPoints">
            <el-option label="仓库" value="WAREHOUSE"/>
            <el-option label="工位" value="STATION"/>
            <el-option label="充电桩" value="CHARGING"/>
          </el-select>
        </div>
      </div>
      
      <el-table
        :data="locationPoints"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        border
        size="mini"
        height="500px"
        style="margin-top: 15px;"
      >
        <el-table-column label="序号" type="index" align="center" width="60"/>
        <el-table-column prop="PointCode" label="点位编码" align="center" width="120"/>
        <el-table-column prop="PointName" label="点位名称" align="center" width="150"/>
        <el-table-column prop="PointType" label="点位类型" align="center" width="120">
          <template slot-scope="scope">
            <el-tag :type="getPointTypeTag(scope.row.PointType)" size="small">
              {{ getPointTypeText(scope.row.PointType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="Area" label="所属区域" align="center" width="120"/>
        <el-table-column prop="XCoordinate" label="X坐标" align="center" width="100"/>
        <el-table-column prop="YCoordinate" label="Y坐标" align="center" width="100"/>
        <el-table-column prop="Description" label="描述" align="center" show-overflow-tooltip/>
        <el-table-column prop="Status" label="状态" align="center" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.Status === 'ACTIVE' ? 'success' : 'danger'" size="small">
              {{ scope.row.Status === 'ACTIVE' ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-edit" size="mini" @click="showEditPointDialog(scope.row)">编辑</el-button>
            <el-button 
              type="text" 
              icon="el-icon-delete" 
              size="mini" 
              style="color: #F56C6C;" 
              @click="deletePoint(scope.row)"
              :disabled="scope.row.Status === 'INACTIVE'"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 新增/编辑点位对话框 -->
    <el-dialog 
      :visible.sync="pointFormVisible" 
      :title="isEditPoint ? '编辑点位' : '新增点位'" 
      center 
      width="600px"
      @closed="resetPointForm"
    >
      <el-form ref="pointForm" :model="pointForm" :rules="pointRules" label-width="100px" size="small">
        <el-form-item label="点位编码" prop="PointCode">
          <el-input v-model="pointForm.PointCode" placeholder="请输入点位编码(如A1,B2)"/>
        </el-form-item>
        <el-form-item label="点位名称" prop="PointName">
          <el-input v-model="pointForm.PointName" placeholder="请输入点位名称"/>
        </el-form-item>
        <el-form-item label="点位类型" prop="PointType">
          <el-select v-model="pointForm.PointType" placeholder="请选择点位类型" style="width: 100%">
            <el-option label="仓库" value="WAREHOUSE"/>
            <el-option label="工位" value="STATION"/>
            <el-option label="充电桩" value="CHARGING"/>
          </el-select>
        </el-form-item>
        <el-form-item label="所属区域">
          <el-input v-model="pointForm.Area" placeholder="请输入所属区域"/>
        </el-form-item>
        <el-form-item label="X坐标">
          <el-input-number v-model="pointForm.XCoordinate" :precision="2" :step="1" style="width: 100%"/>
        </el-form-item>
        <el-form-item label="Y坐标">
          <el-input-number v-model="pointForm.YCoordinate" :precision="2" :step="1" style="width: 100%"/>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="pointForm.Description" type="textarea" :rows="3" placeholder="请输入点位描述"/>
        </el-form-item>
        <el-form-item v-if="isEditPoint" label="状态">
          <el-radio-group v-model="pointForm.Status">
            <el-radio label="ACTIVE">启用</el-radio>
            <el-radio label="INACTIVE">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="pointFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitPointForm">确定</el-button>
      </div>
    </el-dialog>

    <!-- 历史记录对话框 -->
    <el-dialog 
      :visible.sync="historyDialogVisible" 
      title="AGV任务历史记录" 
      center 
      width="1400px"
      @opened="getHistoryData"
    >
      <div class="history-filter">
        <span class="label">物料筛选:</span>
        <el-select 
          v-model="historyMaterialFilter" 
          placeholder="请输入物料编码" 
          filterable 
          clearable 
          remote
          :remote-method="searchMaterials"
          size="small" 
          style="width: 250px"
        >
          <el-option
            v-for="item in materialOptions"
            :key="item.物料编码"
            :label="item.物料编码"
            :value="item.物料编码"
          />
        </el-select>
        
        <span class="label" style="margin-left: 20px;">时间范围:</span>
        <el-date-picker
          v-model="historyDateRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          size="small"
          value-format="yyyy-MM-dd HH:mm:ss"
          style="width: 380px;"
        />
        
        <el-button type="primary" plain size="small" icon="el-icon-search" @click="getHistoryData" style="margin-left: 20px;">查询</el-button>
      </div>
      
      <el-table
        :data="historyData"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        v-loading="historyLoading"
        border
        size="mini"
        height="500px"
        style="margin-top: 20px;"
      >
        <el-table-column label="序号" type="index" align="center" width="60"/>
        <el-table-column prop="TaskNo" label="任务编号" align="center" width="150"/>
        <el-table-column prop="AGVCode" label="AGV编号" align="center" width="120"/>
        <el-table-column prop="MaterialCode" label="物料编码" align="center" width="150"/>
        <el-table-column prop="MaterialName" label="物料名称" align="center" width="200" show-overflow-tooltip/>
        <el-table-column prop="StartPoint" label="起始点" align="center" width="100"/>
        <el-table-column prop="EndPoint" label="目标点" align="center" width="100"/>
        <el-table-column label="任务状态" align="center" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.TaskStatus === 'FINISHED' ? 'success' : 'danger'" size="small">
              {{ getHistoryStatusText(scope.row.TaskStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="StartTime" label="开始时间" align="center" width="160"/>
        <el-table-column prop="EndTime" label="结束时间" align="center" width="160"/>
        <el-table-column prop="Duration" label="耗时(秒)" align="center" width="100"/>
        <el-table-column prop="Operator" label="操作人" align="center" width="100"/>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'

const AGV_MOVE_API = 'http://192.168.2.92:9981/api/zk/call_agv_move_web'

export default {
  data() {
    return {
      // 物料相关
      selectedMaterials: [],
      materialOptions: [],
      
      // 点位相关
      locationPoints: [],
      startPoint: '',
      endPoint: '',
      pointTypeFilter: '',
      
      // 点位管理
      pointManagementVisible: false,
      pointFormVisible: false,
      isEditPoint: false,
      pointForm: {
        ID: null,
        PointCode: '',
        PointName: '',
        PointType: 'STATION',
        Area: '',
        XCoordinate: 0,
        YCoordinate: 0,
        Description: '',
        Status: 'ACTIVE'
      },
      pointRules: {
        PointCode: [
          { required: true, message: '请输入点位编码', trigger: 'blur' }
        ],
        PointName: [
          { required: true, message: '请输入点位名称', trigger: 'blur' }
        ],
        PointType: [
          { required: true, message: '请选择点位类型', trigger: 'change' }
        ]
      },
      
      // 实时数据
      realtimeData: [],
      realtimeFilter: '',
      loading: false,
      
      // 历史数据
      historyDialogVisible: false,
      historyData: [],
      historyLoading: false,
      historyMaterialFilter: '',
      historyDateRange: [],
      
      // 定时刷新
      refreshTimer: null,
      
      // AGV编号生成
      agvCounter: 1
    }
  },
  
  created() {
    this.getLocationPoints()
    this.getRealtimeData()
    //this.startAutoRefresh()
  },
  
  beforeDestroy() {
    this.stopAutoRefresh()
  },
  
  methods: {
    // ========== 点位管理相关方法 ==========
    
    // 显示点位管理对话框
    showPointManagement() {
      this.pointManagementVisible = true
    },
    
    // 获取点位数据
    getLocationPoints() {
      var param = []
      param[0] = ['点位类型', this.pointTypeFilter || '']
      param[1] = ['状态', 'ACTIVE']
      
      var Data = this.CreateData('11', '生产管理_物料机器人_点位查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data && response.data.length > 0) {
          this.locationPoints = response.data
        } else {
          this.locationPoints = []
        }
      }).catch(error => {
        console.error('获取点位失败:', error)
        this.$message.error('获取点位失败')
      })
    },
    
    // 显示新增点位对话框
    showAddPointDialog() {
      this.isEditPoint = false
      this.resetPointForm()
      this.pointFormVisible = true
    },
    
    // 显示编辑点位对话框
    showEditPointDialog(row) {
      this.isEditPoint = true
      this.pointForm = {
        ID: row.ID,
        PointCode: row.PointCode,
        PointName: row.PointName,
        PointType: row.PointType,
        Area: row.Area,
        XCoordinate: row.XCoordinate,
        YCoordinate: row.YCoordinate,
        Description: row.Description,
        Status: row.Status
      }
      this.pointFormVisible = true
    },
    
    // 提交点位表单
    submitPointForm() {
      this.$refs.pointForm.validate(valid => {
        if (valid) {
          var param = []
          if (this.isEditPoint) {
            // 编辑点位
            param[0] = ['ID', this.pointForm.ID]
            param[1] = ['点位编码', this.pointForm.PointCode]
            param[2] = ['点位名称', this.pointForm.PointName]
            param[3] = ['点位类型', this.pointForm.PointType]
            param[4] = ['区域', this.pointForm.Area || '']
            param[5] = ['X坐标', this.pointForm.XCoordinate]
            param[6] = ['Y坐标', this.pointForm.YCoordinate]
            param[7] = ['描述', this.pointForm.Description || '']
            param[8] = ['状态', this.pointForm.Status]
            
            var Data = this.CreateData('12', '生产管理_物料机器人_修改点位', param)
            this.ExecDatabase(Data).then(response => {
              if (response.data && response.data[0] && response.data[0].result === 1) {
                this.$message.success('修改点位成功')
                this.pointFormVisible = false
                this.getLocationPoints()
              } else if (response.data[0].result === '编码重复') {
                this.$message.error('点位编码已存在')
              } else {
                this.$message.error('修改点位失败')
              }
            }).catch(error => {
              console.error('修改点位失败:', error)
              this.$message.error('修改点位失败')
            })
          } else {
            // 新增点位
            param[0] = ['点位编码', this.pointForm.PointCode]
            param[1] = ['点位名称', this.pointForm.PointName]
            param[2] = ['点位类型', this.pointForm.PointType]
            param[3] = ['区域', this.pointForm.Area || '']
            param[4] = ['X坐标', this.pointForm.XCoordinate]
            param[5] = ['Y坐标', this.pointForm.YCoordinate]
            param[6] = ['描述', this.pointForm.Description || '']
            
            var Data = this.CreateData('11', '生产管理_物料机器人_新增点位', param)
            this.ExecDatabase(Data).then(response => {
              if (response.data && response.data[0] && response.data[0].Result === 1) {
                this.$message.success('新增点位成功')
                this.pointFormVisible = false
                this.getLocationPoints()
              } else if (response.data[0].Result === '编码重复') {
                this.$message.error('点位编码已存在')
              } else {
                this.$message.error('新增点位失败')
              }
            }).catch(error => {
              console.error('新增点位失败:', error)
              this.$message.error('新增点位失败')
            })
          }
        }
      })
    },
    
    // 删除点位
    deletePoint(row) {
      this.$confirm(`确认删除点位 ${row.PointCode} - ${row.PointName}?`, '提示', {
        type: 'warning'
      }).then(() => {
        var param = []
        param[0] = ['ID', row.ID]
        
        var Data = this.CreateData('11', '生产管理_物料机器人_删除点位', param)
        this.ExecDatabase(Data).then(response => {
          if (response.data && response.data[0] && response.data[0].Result === 1) {
            this.$message.success('删除点位成功')
            this.getLocationPoints()
          } else if (response.data[0].Result === '点位使用中') {
            this.$message.error('该点位正在被任务使用，无法删除')
          } else {
            this.$message.error('删除点位失败')
          }
        }).catch(error => {
          console.error('删除点位失败:', error)
          this.$message.error('删除点位失败')
        })
      }).catch(() => {})
    },
    
    // 重置点位表单
    resetPointForm() {
      if (this.$refs.pointForm) {
        this.$refs.pointForm.resetFields()
      }
      this.pointForm = {
        ID: null,
        PointCode: '',
        PointName: '',
        PointType: 'STATION',
        Area: '',
        XCoordinate: 0,
        YCoordinate: 0,
        Description: '',
        Status: 'ACTIVE'
      }
    },
    
    // ========== 物料相关方法 ==========
    
    // 搜索物料
    searchMaterials(query) {
      if (!query) {
        this.materialOptions = []
        return
      }
      var param = []
      param.push(["过滤", query])
      var Data = this.CreateData('11', '生产管理_物料机器人_物料查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data && response.data.length > 0) {
          this.materialOptions = response.data
        }
      }).catch(error => {
        console.error('查询物料失败:', error)
      })
    },
    
    // 物料选择改变
    handleMaterialChange(val) {
      console.log('选择的物料:', val)
    },
    
    // ========== 任务相关方法 ==========
    
    // 生成任务
    createTask() {
      // if (this.selectedMaterials.length === 0) {
      //   this.$message.error('请选择物料')
      //   return
      // }
      if (!this.startPoint) {
        this.$message.error('请选择起始点位')
        return
      }
      if (!this.endPoint) {
        this.$message.error('请选择目标点位')
        return
      }
      if (this.startPoint === this.endPoint) {
        this.$message.error('起始点和目标点不能相同')
        return
      }
      
      const taskNo = 'TASK' + Date.now() + this.agvCounter++
      const agvCode = 'AGV' + String(this.agvCounter).padStart(3, '0')
      
      const materialNames = this.selectedMaterials.map(code => {
        const material = this.materialOptions.find(item => item.物料编码 === code)
        return material ? material.物料描述 : code
      }).join(',')
      
      var param = []
      param[0] = ['任务编号', taskNo]
      param[1] = ['AGV编号', agvCode]
      param[2] = ['物料编码', this.selectedMaterials.join(',')]
      param[3] = ['物料名称', materialNames]
      param[4] = ['起始点位', this.startPoint]
      param[5] = ['目标点位', this.endPoint]
      param[6] = ['操作人', this.$store.state.user.name]
      
      var Data = this.CreateData('12', '生产管理_物料机器人_创建任务', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data && response.data[0] && response.data[0].result === '1') {
          this.$message.success('任务创建成功')
          this.getRealtimeData()
          this.selectedMaterials = []
          this.startPoint = ''
          this.endPoint = ''
        } else {
          this.$message.error('任务创建失败')
        }
      }).catch(error => {
        console.error('创建任务失败:', error)
        this.$message.error('任务创建失败')
      })
    },
    
    // 获取实时数据
    getRealtimeData() {
      this.loading = true
      var param = []
      param[0] = ['AGV编号', '']
      param[1] = ['状态', this.realtimeFilter]
      
      var Data = this.CreateData('11', '生产管理_物料机器人_查询实时数据', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data && response.data.length > 0) {
          this.realtimeData = response.data
        } else {
          this.realtimeData = []
        }
        this.loading = false
      }).catch(error => {
        console.error('获取实时数据失败:', error)
        this.loading = false
        this.realtimeData = []
      })
    },
    
    // 刷新实时数据
    refreshRealtimeData() {
      this.getRealtimeData()
      this.$message.success('已刷新')
    },
    
    // 开始任务
    startTask(row) {
      this.$confirm('确认开始该任务?', '提示', {
        type: 'info'
      }).then(() => {
        this.callAgvMove(row).then(() => {
          return this.updateTaskStatus(row)
        }).then(() => {
          this.$message.success('任务已开始')
          this.getRealtimeData()
        }).catch(error => {
          console.error('开始任务失败:', error)
          this.$message.error(error.message || '操作失败')
        })
      }).catch(() => {})
    },

    // 调用 AGV 搬运接口
    callAgvMove(row) {
      const fromBin = row.CurrentPoint || row.StartPoint
      const toBin = row.TargetPoint || row.EndPoint

      if (!row.TaskNo || !fromBin || !toBin) {
        return Promise.reject(new Error('任务点位信息不完整，无法下发AGV任务'))
      }

      const data = {
        entityName: 'ContainerTransportOrder',
        entityValues: [
          {
            id: row.TaskNo,
            kind: 'Luck',
            status: 'Building',
            priority: 10,
            fromBin,
            toBin
          }
        ]
      }

      return axios.post(AGV_MOVE_API, data).then(response => {
        const result = response.data || {}
        console.log(response)
        const isSuccess = Array.isArray(result.ids) && result.ids.indexOf(row.TaskNo) !== -1 && !result.code
        if (!isSuccess) {
          const message = result.message || result.code || 'AGV任务下发失败'
          return Promise.reject(new Error(message))
        }
        return result
      })
    },

    // 更新 MES 任务状态
    updateTaskStatus(row) {
      var param = []
      param[0] = ['任务编号', row.TaskNo]
      param[1] = ['状态', 'RUNNING']
      param[2] = ['进度', row.Progress || 0]
      param[3] = ['速度', 0.5]
      param[4] = ['电量', 100]
      param[5] = ['X坐标', null]
      param[6] = ['Y坐标', null]
      param[7] = ['方向', '']

      var Data = this.CreateData('12', '生产管理_物料机器人_更新任务状态', param)
      return this.ExecDatabase(Data).then(response => {
        if (response.data && response.data[0] && response.data[0].result === '1') {
          return response
        }
        return Promise.reject(new Error('任务状态更新失败'))
      })
    },
    
    // 暂停任务
    // pauseTask(row) {
    //   this.$confirm('确认暂停该任务?', '提示', {
    //     type: 'warning'
    //   }).then(() => {
    //     var param = []
    //     param[0] = ['任务编号', row.TaskNo]
    //     param[1] = ['状态', 'PAUSED']
    //     param[2] = ['进度', row.Progress || 0]
    //     param[3] = ['速度', 0]
    //     param[4] = ['电量', row.Battery || 100]
    //     param[5] = ['X坐标', null]
    //     param[6] = ['Y坐标', null]
    //     param[7] = ['方向', '']
        
    //     var Data = this.CreateData('12', '生产管理_物料机器人_更新任务状态', param)
    //     this.ExecDatabase(Data).then(response => {
    //       if (response.data && response.data[0] && response.data[0].result === '1') {
    //         this.$message.success('任务已暂停')
    //         this.getRealtimeData()
    //       } else {
    //         this.$message.error('操作失败')
    //       }
    //     }).catch(error => {
    //       console.error('暂停任务失败:', error)
    //       this.$message.error('操作失败')
    //     })
    //   }).catch(() => {})
    // },
    
    //取消任务
    cancelTask(row) {
      this.$confirm('确认取消该任务?', '提示', {
        type: 'warning'
      }).then(() => {
        var param = []
        param[0] = ['任务编号', row.TaskNo]
        param[1] = ['状态', 'CANCELED']
        
        var Data = this.CreateData('12', '生产管理_物料机器人_完成任务', param)
        this.ExecDatabase(Data).then(response => {
          if (response.data && response.data[0] && response.data[0].result === '1') {
            this.$message.success('任务已取消')
            this.getRealtimeData()
          } else {
            this.$message.error('操作失败')
          }
        }).catch(error => {
          console.error('取消任务失败:', error)
          this.$message.error('操作失败')
        })
      }).catch(() => {})
    },
    
    // ========== 历史记录相关方法 ==========
    
    // 显示历史记录对话框
    showHistoryDialog() {
      this.historyDialogVisible = true
    },
    
    // 获取历史数据
    getHistoryData() {
      this.historyLoading = true
      var param = []
      param[0] = ['物料编码', this.historyMaterialFilter || '']
      param[1] = ['开始时间', this.historyDateRange && this.historyDateRange[0] ? this.historyDateRange[0] : '']
      param[2] = ['结束时间', this.historyDateRange && this.historyDateRange[1] ? this.historyDateRange[1] : '']
      
      var Data = this.CreateData('11', '生产管理_物料机器人_查询历史数据', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data && response.data.length > 0) {
          this.historyData = response.data
        } else {
          this.historyData = []
        }
        this.historyLoading = false
      }).catch(error => {
        console.error('获取历史数据失败:', error)
        this.historyLoading = false
        this.historyData = []
      })
    },
    
    // ========== 自动刷新相关方法 ==========
    
    // 开始自动刷新
    startAutoRefresh() {
      this.refreshTimer = setInterval(() => {
        this.getRealtimeData()
      }, 5000)
    },
    
    // 停止自动刷新
    stopAutoRefresh() {
      if (this.refreshTimer) {
        clearInterval(this.refreshTimer)
        this.refreshTimer = null
      }
    },
    
    // ========== 工具方法 ==========
    
    // 获取任务状态类型
    getStatusType(status) {
      const typeMap = {
        'PENDING': 'warning',
        'RUNNING': 'success',
        'PAUSED': 'info',
        'FINISHED': 'primary',
        'CANCELED': 'danger'
      }
      return typeMap[status] || 'info'
    },
    
    // 获取任务状态文本
    getStatusText(status) {
      const textMap = {
        'PENDING': '待执行',
        'RUNNING': '执行中',
        'PAUSED': '已暂停',
        'FINISHED': '已完成',
        'CANCELED': '已取消'
      }
      return textMap[status] || status
    },
    
    // 获取历史任务状态文本
    getHistoryStatusText(status) {
      const textMap = {
        'FINISHED': '已完成',
        'CANCELED': '已取消',
        'FAILED': '失败'
      }
      return textMap[status] || status
    },
    
    // 获取点位类型标签
    getPointTypeTag(type) {
      const tagMap = {
        'WAREHOUSE': 'primary',
        'STATION': 'success',
        'CHARGING': 'warning'
      }
      return tagMap[type] || 'info'
    },
    
    // 获取点位类型文本
    getPointTypeText(type) {
      const textMap = {
        'WAREHOUSE': '仓库',
        'STATION': '工位',
        'CHARGING': '充电桩'
      }
      return textMap[type] || type
    },
    
    // 获取电池颜色
    getBatteryColor(battery) {
      if (battery > 60) return '#67C23A'
      if (battery > 30) return '#E6A23C'
      return '#F56C6C'
    }
  }
}
</script>

<style scoped lang="scss">
.app-container {
  padding: 10px;
}
.el-button{
  width: auto;
}
.operation-area {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
  padding: 10px 0;
  
  .select-group {
    display: flex;
    align-items: center;
    gap: 10px;
    
    .label {
      white-space: nowrap;
      color: #606266;
      font-size: 14px;
    }
    
    .arrow {
      font-size: 20px;
      color: #409EFF;
      font-weight: bold;
    }
  }
  
  .button-group {
    display: flex;
    gap: 10px;
    margin-left: auto;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .card-title {
    font-size: 16px;
    font-weight: bold;
    color: #303133;
  }
  
  .header-actions {
    display: flex;
    gap: 10px;
  }
}

.battery-display {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
  
  i {
    font-size: 16px;
  }
}

// 点位管理样式
.point-management-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .filter-group {
    display: flex;
    align-items: center;
    gap: 10px;
  }
}

.history-filter {
  display: flex;
  align-items: center;
  padding: 10px 0;
  
  .label {
    white-space: nowrap;
    color: #606266;
    font-size: 14px;
  }
}

// 响应式设计
@media screen and (max-width: 1200px) {
  .operation-area {
    flex-direction: column;
    align-items: flex-start;
    
    .button-group {
      margin-left: 0;
    }
  }
}
</style>
