<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="奶牛编号" prop="speciesId">
        <el-input v-model="queryParams.speciesId" placeholder="请输入奶牛编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="品种" prop="breed">
        <el-input v-model="queryParams.breed" placeholder="请输入品种" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="物种类型" prop="speciesType">
        <el-select v-model="queryParams.speciesType" placeholder="请选择物种类型" clearable>
          <el-option
            v-for="dict in dict.type.species_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="性别" prop="sex">
        <el-select v-model="queryParams.sex" placeholder="请选择性别" clearable>
          <el-option v-for="dict in dict.type.species_sex" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input v-model="queryParams.age" placeholder="请输入年龄" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="体重（kg）" prop="weight">
        <el-input v-model="queryParams.weight" placeholder="请输入体重（kg）" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <!-- <el-form-item label="所属农场" prop="farmId">
        <el-input
          v-model="queryParams.farmId"
          placeholder="请输入所属农场"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->

      <el-form-item label="所属农场" prop="deptIdList">
        <treeselect v-model="queryParams.deptIdList" :options="deptOptions" multiple :flat="true" :limit="1"
          :limitText="count => `+${count}`" style="width:200px" :show-count="true" placeholder="请选所属农场" />
      </el-form-item>
      <el-form-item label="所属地块" prop="fieldIdList">
        <el-select v-model="queryParams.fieldIdList" placeholder="请选择地块" multiple collapse-tags filterable clearable>
          <el-option v-for="dict in fieldIdList" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="健康状态" prop="healthStatus">
        <el-select v-model="queryParams.healthStatus" placeholder="请选择健康状态" clearable>
          <el-option v-for="dict in dict.type.health_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="监测温度" prop="latestTempArray">
        <div style="display: flex; align-items: center; gap: 8px;">
          <el-input v-model="latestTempArray.latestTempMin" placeholder="最低温度" clearable style="width: 120px;"
            @keyup.enter.native="handleQuery" />
          <span>-</span>
          <el-input v-model="latestTempArray.latestTempMax" placeholder="最高温度" clearable style="width: 120px;"
            @keyup.enter.native="handleQuery" />
        </div>
      </el-form-item>

      <el-form-item label="监测时间" prop="latestTempTime">
        <el-date-picker v-model="queryParams.latestTempTimes" type="datetimerange" range-separator="至"
          start-placeholder="开始时间" end-placeholder="结束时间" value-format="yyyy-MM-dd HH:mm:ss" clearable />
      </el-form-item>



      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <!-- 统计面板 -->
    <div class="statistics-panel">
      <el-row :gutter="12">
        <el-col :xs="24" :sm="12" :md="8" :lg="4" :xl="4">
          <div class="stat-card published-card">
            <div class="stat-content">
              <div class="stat-title">异常状态数</div>
              <div class="stat-number">{{ statistics.exceptionCount || 0 }}</div>
              <div class="stat-desc">异常数量</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="4" :xl="4">
          <!-- <div class="stat-card tech-card">
            <div class="stat-content">
              <div class="stat-title">待处理建议数</div>
              <div class="stat-number">{{ statistics.pendingCount || 0 }}</div>
              <div class="stat-desc">建议数量</div>
            </div>
          </div> -->
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="4" :xl="4">
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="4" :xl="4">
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="4" :xl="4">
        </el-col>
      </el-row>
    </div>


    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['base:speciesInfo:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['base:speciesInfo:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['base:speciesInfo:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['base:speciesInfo:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="speciesInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键ID" align="center" prop="id" /> -->
      <el-table-column label="奶牛编号" align="center" prop="speciesId" />
      <el-table-column label="品种" align="center" prop="breed" />

      <el-table-column label="性别" align="center" prop="sex">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.species_sex" :value="scope.row.sex" />
        </template>
      </el-table-column>
      <el-table-column label="年龄" align="center" prop="age" />
      <el-table-column label="体重（kg）" align="center" prop="weight" />
      <el-table-column label="所属农场" align="center" prop="farmName" />
      <el-table-column label="所属地块" align="center" prop="fieldName" />
      <el-table-column label="最近监测温度" align="center" prop="latestTemp" />
      <el-table-column label="最近监测时间" align="center" prop="latestTempTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.latestTempTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="健康状态" align="center" prop="healthStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.health_status" :value="scope.row.healthStatus" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />

      <el-table-column label="缩略图" align="center" width="120">
        <template slot-scope="scope">
          <el-image 
            v-if="scope.row.thumbnailUrl" 
            :src="scope.row.thumbnailUrl"
            :preview-src-list="[scope.row.thumbnailUrl]"
            style="width: 80px; height: 80px; object-fit: cover; cursor: pointer;" 
            fit="cover"
            :hide-on-click-modal="true"
          >
            <div slot="error" class="image-slot">
              <i class="el-icon-video-play"></i>
            </div>
          </el-image>
          <div v-else class="thumbnail-placeholder">
            <i class="el-icon-video-play"></i>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-video-play" @click="handleViewVideo(scope.row)"
            v-hasPermi="['base:speciesInfo:view']">查看视频</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['base:speciesInfo:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['base:speciesInfo:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改物种基础信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="奶牛编号" prop="speciesId">
          <el-input v-model="form.speciesId" placeholder="请输入物种编号" />
        </el-form-item>
        <el-form-item label="品种" prop="breed">
          <el-input v-model="form.breed" placeholder="请输入品种" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择性别">
            <el-option v-for="dict in dict.type.species_sex" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="form.age" placeholder="请输入年龄" />
        </el-form-item>
        <el-form-item label="体重(kg)" prop="weight">
          <el-input v-model="form.weight" placeholder="请输入体重(kg)" />
        </el-form-item>


        <el-form-item label="所属农场" prop="farmId">
          <treeselect v-model="form.farmId" :options="enabledDeptOptions"
            @input="queryMachineNameFieldUser(form.farmId)" placeholder="请先选择所属农场" />
        </el-form-item>
        <el-form-item label="所属地块" prop="fieldId"> <!-- 修改这里 -->
          <el-select v-model="form.fieldId" placeholder="请选择作业地块" :disabled="!form.farmId || loadingFields"
            @change="handleFieldChange">
            <el-option v-for="item in fields" :key="item.id" :label="item.fieldName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="健康状态" prop="healthStatus">
          <el-radio-group v-model="form.healthStatus">
            <el-radio v-for="dict in dict.type.health_status" :key="dict.value" :label="parseInt(dict.value)">{{
              dict.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 视频播放对话框 -->
    <el-dialog title="视频播放" :visible.sync="videoVisible" width="800px" append-to-body @closed="closeVideo">
      <div class="video-dialog-content">
        <!-- Tab 切换 -->
        <el-tabs v-model="activeVideoTab" @tab-click="handleTabClick">
          <el-tab-pane label="正常视频" name="normal">
            <div class="video-container">
              <video ref="videoPlayerNormal" :src="normalVideoUrl" controls autoplay style="width: 100%; height: 100%;">
                您的浏览器不支持视频播放
              </video>
            </div>
          </el-tab-pane>
          <el-tab-pane label="感温视频" name="thermal">
            <div class="video-container">
              <video ref="videoPlayerThermal" :src="thermalVideoUrl" controls autoplay
                style="width: 100%; height: 100%;">
                您的浏览器不支持视频播放
              </video>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="videoVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

     
  </div>
</template>

<script>
import { getMachineNameFieldUser, MachineNameFieldUserText } from "@/api/base/machineWorkRecords"
import { listSpeciesInfo, getSpeciesInfo, delSpeciesInfo, addSpeciesInfo, updateSpeciesInfo, getCount } from "@/api/base/speciesInfo"
import { deptTreeSelect } from "@/api/system/user";
import { listFieldName } from "@/api/base/field"
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "SpeciesInfo",
  components: { Treeselect },
  dicts: ['species_type', 'health_status', 'species_sex'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物种基础信息表格数据
      speciesInfoList: [],
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 所属地块
      fieldIdList: [],
      // 过滤掉已禁用部门树选项
      enabledDeptOptions: undefined,
      // 是否显示弹出层
      open: false,
      fields: [],
      userName: [],
      loadingFields: false, // 新增字段，用于控制地块加载状态
      // 视频相关
      videoVisible: false,
      activeVideoTab: 'normal', // 默认显示正常视频
      normalVideoUrl: 'https://azn.gbdfarm.com/statics/2026/03/26/cs1235_20260326172707A034.mp4',
      thermalVideoUrl: 'https://azn.gbdfarm.com/statics/2026/03/26/add1_20260326174603A035.mp4',

  

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        speciesId: null,
        breed: null,
        speciesType: null,
        sex: null,
        age: null,
        weight: null,
        farmId: null,
        fieldId: null,
        latestTemp: null,
        latestTempTimes: null,
        healthStatus: null,
        deptIdList: [],
      },
      latestTempArray: {
        latestTempMin: null,
        latestTempMax: null,
      },
      // 统计数据
      statistics: {
        exceptionCount: 0,

      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        speciesId: [
          { required: true, message: "物种编号不能为空", trigger: "blur" }
        ],
        breed: [
          { required: true, message: "品种不能为空", trigger: "blur" }
        ],
        /* speciesType: [
          { required: true, message: "物种类型不能为空", trigger: "change" }
        ], */
        farmId: [
          { required: true, message: "所属农场不能为空", trigger: "blur" }
        ],
        fieldId: [
          { required: true, message: "所属地块不能为空", trigger: "blur" }
        ],
        healthStatus: [
          { required: true, message: "健康状态不能为空", trigger: "change" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList()
    this.getDeptTree();
    this.getFieldNameList();
    this.getStatistics();
  },
  methods: {

   

     /** 查看视频 */
    handleViewVideo(row) {
      this.activeVideoTab = 'normal'
      this.videoVisible = true

      this.$nextTick(() => {
        if (this.$refs.videoPlayerNormal) {
          this.$refs.videoPlayerNormal.play()
        }
      })
    },

    /** 查看视频 */
    handleViewVideo(row) {
      this.activeVideoTab = 'normal' // 重置为正常视频
      this.videoVisible = true

      // 确保视频在弹窗打开后自动播放
      this.$nextTick(() => {
        if (this.$refs.videoPlayerNormal) {
          this.$refs.videoPlayerNormal.play()
        }
      })
    },

    /** Tab 切换处理 */
    handleTabClick(tab) {
      // 切换 Tab 时暂停当前视频，播放新 Tab 的视频
      this.$nextTick(() => {
        if (tab.name === 'normal' && this.$refs.videoPlayerNormal) {
          if (this.$refs.videoPlayerThermal) {
            this.$refs.videoPlayerThermal.pause()
          }
          this.$refs.videoPlayerNormal.play()
        } else if (tab.name === 'thermal' && this.$refs.videoPlayerThermal) {
          if (this.$refs.videoPlayerNormal) {
            this.$refs.videoPlayerNormal.pause()
          }
          this.$refs.videoPlayerThermal.play()
        }
      })
    },

    /** 关闭视频 */
    closeVideo() {
      // 暂停所有视频并清空地址
      if (this.$refs.videoPlayerNormal) {
        this.$refs.videoPlayerNormal.pause()
      }
      if (this.$refs.videoPlayerThermal) {
        this.$refs.videoPlayerThermal.pause()
      }
      this.normalVideoUrl = ''
      this.thermalVideoUrl = ''

      // 重置 URL（延迟一下再设置，避免闪烁）
      this.$nextTick(() => {
        this.normalVideoUrl = 'https://azn.gbdfarm.com/statics/2026/03/26/cs1235_20260326172707A034.mp4'
        this.thermalVideoUrl = 'https://azn.gbdfarm.com/statics/2026/03/26/add1_20260326174603A035.mp4'
      })
    },

    /** 获取统计数据 */
    getStatistics() {
      const params = {
        speciesType: 0,
        healthStatus: 2
      }

      getCount(params).then(response => {
        this.statistics.exceptionCount = response.data || []
      }).catch(() => {
        this.statistics = {
          exceptionCount: 0,

        }
      })
    },

    handleFieldChange(value) {
      // 当用户选择地块时，确保选中的地块属于当前农场
      if (value && !this.fields.find(field => field.id === value)) {
        // 如果选中的地块不在当前农场的地块列表中，清空选中
        this.form.fieldId = null;
        this.$message.warning('该地块不属于当前农场');
      }
    },

    queryMachineNameFieldUser(farmId) {
      // 清空地块列表，避免选择不同农场时出现残留数据
      this.fields = [];

      // 如果没有农场 ID，直接返回
      if (!farmId) {
        return;
      }

      // 设置 loading 状态（可选）
      this.loadingFields = true;

      const data = {
        deptId: farmId
      }

      getMachineNameFieldUser(data).then(response => {
        this.fields = response.data.fields || [];

        // 如果响应中有默认地块，设置为选中状态
        if (response.data.defaultFieldId) {
          this.form.fieldId = response.data.defaultFieldId;
        } else if (this.form.fieldId && !this.fields.find(field => field.id === this.form.fieldId)) {
          // 如果当前选中的地块不在新农场的地块列表中，清空选中
          this.form.fieldId = null;
        }

        // 关闭 loading 状态
        this.loadingFields = false;
      }).catch(() => {
        this.loadingFields = false;
      });
    },
    queryMachineNameFieldUserTe() {
      const id = this.form.id;
      if (id != undefined) {
        getSpeciesInfo(id).then(response => {
          console.log("打开框")
          console.log(response.data.fieldId)
          this.form.fieldId = response.data.fieldId
        })
      }
    },

    /** 查询地块名称 **/
    getFieldNameList() {
      listFieldName().then(res => {
        this.fieldIdList = res;
        this.fieldIdList.forEach(x => {
          x.value = x.id;
          x.label = x.fieldName;
        })
      });
    },

    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
        this.enabledDeptOptions = this.filterDisabledDept(JSON.parse(JSON.stringify(response.data)))
      });
    },
    filterDisabledDept(deptList) {
      return deptList.filter(dept => {
        if (dept.disabled) {
          return false
        }
        if (dept.children && dept.children.length) {
          dept.children = this.filterDisabledDept(dept.children)
        }
        return true
      })
    },
    /** 查询物种基础信息列表 */
    getList() {
      this.loading = true
      listSpeciesInfo(this.queryParams).then(response => {
        this.speciesInfoList = response.rows
        this.total = response.total
        
        // 为每行数据生成视频缩略图
        this.$nextTick(() => {
          this.generateThumbnails()
        })
        
        this.loading = false
      })
    },

    /** 生成视频缩略图 */
    generateThumbnails() {
      console.log("生成视频缩略图")
      this.speciesInfoList.forEach((row, index) => {
        
          this.extractVideoFrame('https://azn.gbdfarm.com/statics/2026/03/26/cs1235_20260326172707A034.mp4', index)
        
      })

    },

     
    /** 提取视频第一帧 */
    extractVideoFrame(videoUrl, rowIndex) {
      const video = document.createElement('video')
      video.src = videoUrl
      video.crossOrigin = 'anonymous'
      video.muted = true
      
      
      
      video.addEventListener('loadeddata', () => {
        video.currentTime = 0.1
      })
      
      video.addEventListener('seeked', () => {
        const canvas = document.createElement('canvas')
        canvas.width = video.videoWidth || 320
        canvas.height = video.videoHeight || 240
        
        const ctx = canvas.getContext('2d')
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
        
        const thumbnailUrl = canvas.toDataURL('image/jpeg', 0.8)
        
        // 使用 Vue.set 确保响应式更新
        console.log(thumbnailUrl)
        this.$set(this.speciesInfoList[rowIndex], 'thumbnailUrl', thumbnailUrl)
        
        // 清理
        setTimeout(() => {
          video.src = ''
          video.load()
          canvas.remove()
        }, 100)
      })
      
      video.load()
    },
    
    // 新增：处理图片加载错误
    handleImageError(event) {
      console.log('图片加载失败:', event)
      // 可以在这里添加备用图片或显示错误信息
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        speciesId: null,
        breed: null,
        speciesType: null,
        sex: null,
        age: null,
        weight: null,
        farmId: null,
        fieldId: null,
        latestTemp: null,
        latestTempTime: null,
        latestTempTimes: null,
        healthStatus: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        latestTempArray: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.queryParams.params = {}
      // 处理时间范围查询
      if (this.queryParams.latestTempTimes && this.queryParams.latestTempTimes.length === 2) {
        /* this.queryParams.latestTempTimeStart = this.queryParams.latestTempTimes[0]
        this.queryParams.latestTempTimeEnd = this.queryParams.latestTempTimes[1] */

        this.queryParams.params["latestTempTimeStart"] = this.queryParams.latestTempTimes[0]
        this.queryParams.params["latestTempTimeEnd"] = this.queryParams.latestTempTimes[1]
      } else {
        this.queryParams.latestTempTimeStart = null
        this.queryParams.latestTempTimeEnd = null
      }
      // 检查监测温度范围是否完整且有效
      if (this.latestTempArray.latestTempMin !== null && this.latestTempArray.latestTempMax === null) {
        this.$message.error('请填写监测温度最大值');
        return;
      }
      if (this.latestTempArray.latestTempMin === null && this.latestTempArray.latestTempMax !== null) {
        this.$message.error('请填写监测温度最小值');
        return;
      }
      if (this.latestTempArray.latestTempMin !== null && this.latestTempArray.latestTempMax !== null) {
        if (this.latestTempArray.latestTempMin > this.latestTempArray.latestTempMax) {
          this.$message.error('监测温度最小值不能大于最大值');
          return;
        }
      }
      /* this.queryParams.latestTempMin = this.latestTempArray.latestTempMin
      this.queryParams.latestTempMax = this.latestTempArray.latestTempMax */
      this.queryParams.params["latestTempMin"] = this.latestTempArray.latestTempMin
      this.queryParams.params["latestTempMax"] = this.latestTempArray.latestTempMax
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.queryParams.latestTempTimes = []
      this.latestTempArray = {
        latestTempMin: null,
        latestTempMax: null,
      }
      this.queryParams.latestTempMin = null,
        this.queryParams.latestTempMax = null,
        this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加物种基础信息"
    },
    /** 修改按钮操作 */
    /* handleUpdate(row) {
      if (row.farmId != undefined) {
        const data = {
          deptId: row.farmId
        }
        MachineNameFieldUserText(data).then(response => {
          console.log("修改按钮")
          console.log(response.data.fields)
          this.fields = response.data.fields
        })
      }
      this.reset()
      const id = row.id || this.ids
      getSpeciesInfo(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改物种基础信息"
      })
    }, */
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids

      // 先获取详细信息
      getSpeciesInfo(id).then(response => {
        this.form = response.data

        // 临时存储原始的 fieldId 值
        const originalFieldId = this.form.fieldId

        // 如果有农场 ID，则获取对应的地块数据
        if (this.form.farmId != undefined && this.form.farmId != null) {
          const data = {
            deptId: this.form.farmId
          }
          MachineNameFieldUserText(data).then(response => {
            this.fields = response.data.fields

            // 使用 $nextTick 确保 DOM 更新后再设置 fieldId
            this.$nextTick(() => {
              // 优先使用 API 返回的 fieldId，否则使用原始值
              this.form.fieldId = response.data.fieldId || originalFieldId
            })

            // 直接打开对话框
            this.open = true
            this.title = "修改物种基础信息"
          })
        } else {
          // 如果没有农场 ID 也打开对话框
          this.open = true
          this.title = "修改物种基础信息"
        }
      })
    },




    /** 提交按钮 */
    submitForm() {
      this.form.speciesType = 0
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSpeciesInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
              this.getStatistics();
            })
          } else {
            addSpeciesInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
              this.getStatistics();
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除物种基础信息编号为"' + ids + '"的数据项？').then(function () {
        return delSpeciesInfo(ids)
      }).then(() => {
        this.getList()
        this.getStatistics();
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('base/speciesInfo/export', {
        ...this.queryParams
      }, `speciesInfo_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
<style lang="scss">


/* 图片插槽样式 */
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-size: 24px;
}

/* 缩略图占位符样式 */
.thumbnail-placeholder {
  width: 80px;
  height: 80px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
  border-radius: 4px;
}
/* 视频缩略图样式 */
.video-thumbnail {
  position: relative;
  width: 100px;
  height: 75px;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
  
  &:hover {
    transform: scale(1.05);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
  
  .thumbnail-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  
  .thumbnail-placeholder {
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 24px;
  }
}

/* 缩略图预览对话框样式 */
.thumbnail-preview-dialog {
  .el-dialog__body {
    padding: 20px;
    text-align: center;
  }
  
  .thumbnail-preview-content {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 400px;
    background: #f5f5f5;
    border-radius: 8px;
    
    .preview-image {
      max-width: 100%;
      max-height: 600px;
      object-fit: contain;
      border-radius: 4px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }
  }
}
/* 统计面板样式 */
.statistics-panel {
  margin-bottom: 16px;
  padding: 20px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
}

.statistics-panel .el-row {
  display: flex;
  justify-content: space-between;
}

.statistics-panel .el-col {
  flex: 1;
  max-width: none !important;
}

.stat-card {
  border-radius: 12px;
  padding: 16px;
  height: 120px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  transition: all 0.3s ease;
  cursor: pointer;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1), 0 2px 6px rgba(0, 0, 0, 0.05);
  position: relative;
  overflow: hidden;
  color: #fff;
  margin-bottom: 10px;
}

.stat-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15), 0 4px 10px rgba(0, 0, 0, 0.1);
}


.stat-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
}

.stat-title {
  font-size: 13px;
  font-weight: 600;
  color: rgba(255, 255, 255, 0.9);
  margin-bottom: 0;
  line-height: 1.2;
}

.stat-number {
  font-size: 32px;
  font-weight: 700;
  line-height: 1.0;
  margin: 6px 0;
  color: #fff;
}

.stat-desc {
  font-size: 11px;
  font-weight: 500;
  color: rgba(255, 255, 255, 0.85);
  line-height: 1.2;
  margin: 0;
}

/* 不同卡片的主题色 */
.total-card {
  background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
}

.tech-card {
  background: linear-gradient(135deg, #10b981 0%, #34d399 100%);
}

.policy-card {
  background: linear-gradient(135deg, #f59e0b 0%, #fbbf24 100%);
}

.published-card {
  background: linear-gradient(135deg, #ec4899 0%, #f472b6 100%);
}

.draft-card {
  background: linear-gradient(135deg, #06b6d4 0%, #38bdf8 100%);
}

/* 视频播放器样式 */
.video-container {
  width: 100%;
  height: 450px;
  background: #000;
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.video-container video {
  max-width: 100%;
  max-height: 100%;
  outline: none;
}

/* 视频对话框内容样式 */
.video-dialog-content {
  padding: 10px 0;
}

.video-dialog-content .el-tabs__content {
  padding: 0;
}

.video-dialog-content .el-tabs__item {
  font-size: 14px;
  font-weight: 500;
}

/* 调整 Tab 栏样式 */
.video-dialog-content ::v-deep .el-tabs__header {
  margin-bottom: 16px;
}

.video-dialog-content ::v-deep .el-tabs__nav-wrap::after {
  height: 2px;
}
</style>