<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="农机编号" prop="machineCode">
        <el-input v-model="queryParams.machineCode" placeholder="请输入农机编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="农机名称" prop="machineName">
        <el-input v-model="queryParams.machineName" 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="taskName">
        <el-input v-model="queryParams.taskName" placeholder="请输入作业名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>



      <el-form-item label="作业类型" prop="taskType">
        <el-select v-model="queryParams.taskType" placeholder="请选择作业类型" clearable>
          <el-option v-for="dict in dict.type.machine_work_task_type" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>


      <el-form-item label="作业状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择作业状态" clearable>
          <el-option v-for="dict in dict.type.machine_work_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>


      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker v-model="daterangeStartTime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker v-model="daterangeEndTime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="操作员" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入操作员" clearable @keyup.enter.native="handleQuery" />
      </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>

    <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:machineWorkRecords: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:machineWorkRecords: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:machineWorkRecords: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:machineWorkRecords:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="machineWorkRecordsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" :fixed="false" />
      <el-table-column label="作业单号" align="center" prop="id" width="200">
        <template slot-scope="scope">
          <span>{{ scope.row.id || '—' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="农机编号" align="center" prop="machineCode" />
      <el-table-column label="农机名称" align="center" prop="machineName" />
      <el-table-column label="农机类型" align="center" prop="machineType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.agricultural_machine_type" :value="scope.row.machineType" />
        </template>
      </el-table-column>

      <el-table-column label="所属农场" align="center" prop="deptName" />
      <el-table-column label="作业地块" align="center" prop="fieldName" />
      <el-table-column label="作业名称" align="center" prop="taskName" />
      <el-table-column label="作业类型" align="center" prop="taskType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.machine_work_task_type" :value="scope.row.taskType" />
        </template>
      </el-table-column>


      <el-table-column label="作业状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.machine_work_status" :value="scope.row.status" />
        </template>
      </el-table-column>

      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="作业时长(小时)" align="center" prop="workHours" />
      <el-table-column label="作业面积(亩)" align="center" prop="workArea" />
      <el-table-column label="油耗(升)" align="center" prop="fuelConsumption" />
      <el-table-column label="操作员" align="center" prop="userName" />
      <el-table-column label="备注" align="center" prop="remark">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.remark" placement="top"
            :disabled="!scope.row.remark">
            <span class="remark-text">{{ scope.row.remark }}</span>
          </el-tooltip>
        </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-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['base:machineWorkRecords:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['base:machineWorkRecords: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="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- 编辑时显示作业单号 -->
        <el-row :gutter="20" v-if="title.indexOf('修改') !== -1">
          <el-col :span="24">
            <el-form-item label="作业单号" prop="workOrderId">
              <el-input v-model="form.workOrderId" placeholder="系统自动生成" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第一步：选择所属农场（必填） -->
        <el-row :gutter="20">
          <el-col :span="24">
            <!-- <el-form-item label="所属农场" prop="farmName">
              <el-select v-model="form.farmName" placeholder="请先选择所属农场" style="width: 100%" @change="handleFarmChange">
                <el-option v-for="farm in farmOptions" :key="farm.value" :label="farm.label" :value="farm.value" />
              </el-select>
            </el-form-item> -->
            <el-form-item label="所属农场" prop="farmId">
              <treeselect v-model="form.farmId" :options="enabledDeptOptions" :show-count="true"
                @input="queryMachineNameFieldUser(form.farmId)" placeholder="请先选择所属农场" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二步：根据农场过滤的字段 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="农机名称" prop="machineId">
              <!-- <el-select v-model="form.machineName" placeholder="请选择农机" style="width: 100%"
                @change="handleMachineNameChange" :disabled="!form.farmName">
                <el-option v-for="machine in filteredMachineOptions" :key="machine.value" :label="machine.label"
                  :value="machine.value" />
              </el-select> -->

              <el-select v-model="form.machineId" placeholder="请选择农机" :disabled="!form.farmId">
                <el-option v-for="item in machinesList" :key="item.id" :label="item.machineName" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="作业地块" prop="fieldId">
              <!-- <el-select v-model="form.fieldName" placeholder="请选择作业地块" style="width: 100%" :disabled="!form.farmName">
                <el-option v-for="field in filteredFieldOptions" :key="field.value" :label="field.label"
                  :value="field.value" />
              </el-select> -->

              <el-select v-model="form.fieldId" placeholder="请选择作业地块" :disabled="!form.farmId">
                <el-option v-for="item in fields" :key="item.id" :label="item.fieldName" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="操作员" prop="operatorId">
              <!-- <el-select v-model="form.operatorName" placeholder="请选择操作员" filterable style="width: 100%"
                :disabled="!form.farmName">
                <el-option v-for="operator in filteredOperatorOptions" :key="operator.value" :label="operator.label"
                  :value="operator.value" />
              </el-select> -->

              <el-select v-model="form.operatorId" placeholder="请选择操作员" :disabled="!form.farmId">
                <el-option v-for="item in userName" :key="item.userId" :label="item.nickName" :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="作业类型" prop="taskType">
              <el-select v-model="form.taskType" placeholder="请选择作业类型" style="width: 100%">
                <el-option v-for="dict in dict.type.machine_work_task_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="作业名称" prop="taskName">
              <el-input v-model="form.taskName" placeholder="请输入作业名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="作业状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择作业状态" style="width: 100%">
                <el-option v-for="dict in dict.type.machine_work_status" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker clearable v-model="form.startTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择开始时间" style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker clearable v-model="form.endTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择结束时间" style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
            </el-form-item>
          </el-col>
        </el-row>
      </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>
  </div>
</template>

<script>
import { listMachineWorkRecords, getMachineWorkRecords, delMachineWorkRecords, addMachineWorkRecords, updateMachineWorkRecords, getMachineNameFieldUser } from "@/api/base/machineWorkRecords"
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: "MachineWorkRecords",
  components: {
    Treeselect
  },
  dicts: ['machine_work_task_type', 'machine_work_status', 'agricultural_machine_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 农机作业记录表格数据
      machineWorkRecordsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 开始时间范围
      daterangeStartTime: [],
      // 结束时间范围
      daterangeEndTime: [],

      // 部门树选项
      deptOptions: undefined,
      // 过滤掉已禁用部门树选项
      enabledDeptOptions: undefined,
      // 所属地块
      fieldIdList: [],
      machinesList: [],
      fields: [],
      userName: [],



      // 字典数据
      statusOptions: [
        { value: '0', label: '待开始' },
        { value: '1', label: '进行中' },
        { value: '2', label: '已完成' },
        { value: '3', label: '已取消' }
      ],
      taskTypeOptions: [
        { value: '0', label: '耕地' },
        { value: '1', label: '收割' },
        { value: '2', label: '播种' },
        { value: '3', label: '施肥' },
        { value: '4', label: '灌溉' }
      ],
      machineTypeOptions: [
        { value: '0', label: '拖拉机' },
        { value: '1', label: '收割机' },
        { value: '2', label: '播种机' },
        { value: '3', label: '施肥机' },
        { value: '4', label: '灌溉机' }
      ],
      // 农机选项列表
      machineOptions: [],
      // 农场选项列表
      farmOptions: [],
      // 地块选项列表
      fieldOptions: [],
      // 操作员选项列表
      operatorOptions: [],
      // 过滤后的选项列表
      filteredMachineOptions: [],
      filteredFieldOptions: [],
      filteredOperatorOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        machineCode: null,
        machineName: null,
        farmName: null,
        fieldName: null,
        taskName: null,
        taskType: null,
        status: null,
        operatorName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        farmId: [
          { required: true, message: "所属农场不能为空", trigger: "change" }
        ],
        machineId: [
          { required: true, message: "农机名称不能为空", trigger: "change" }
        ],
        fieldId: [
          { required: true, message: "作业地块不能为空", trigger: "change" }
        ],
        taskName: [
          { required: true, message: "作业名称不能为空", trigger: "blur" }
        ],
        taskType: [
          { required: true, message: "作业类型不能为空", trigger: "change" }
        ],
        status: [
          { required: true, message: "作业状态不能为空", trigger: "change" }
        ],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "change" }
        ],
        endTime: [
          { required: true, message: "结束时间不能为空", trigger: "change" }
        ],
        operatorId: [
          { required: true, message: "操作员不能为空", trigger: "change" }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getDeptTree()
    this.getFieldNameList()

    this.getMachineOptions()
    this.getFarmOptions()
    this.getFieldOptions()
    this.getOperatorOptions()

  },
  methods: {

    queryMachineNameFieldUser(farmId) {
      if (farmId === undefined || farmId === null || farmId === '') {
        this.fields = [];
        this.machinesList = [];
        this.userName = [];
        return;
      }
      console.log(farmId)
      getMachineNameFieldUser(farmId).then(response => {
        this.fields = response.data.fields
        this.machinesList = response.data.machinesList
        this.userName = response.data.users
      })

    },

    /** 查询地块名称 **/
    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
      })
    },

    /** 获取农机选项 */
    getMachineOptions() {
      // 模拟数据，实际应该从API获取，包含农场关联
      this.machineOptions = [
        { value: 'M001', label: '拖拉机A型', farmId: 'F001', machineCode: 'M001', machineType: '0' },
        { value: 'M002', label: '收割机B型', farmId: 'F002', machineCode: 'M002', machineType: '1' },
        { value: 'M003', label: '播种机C型', farmId: 'F003', machineCode: 'M003', machineType: '2' },
        { value: 'M004', label: '拖拉机B型', farmId: 'F001', machineCode: 'M004', machineType: '0' },
        { value: 'M005', label: '施肥机A型', farmId: 'F002', machineCode: 'M005', machineType: '3' }
      ]
    },
    /** 获取农场选项 */
    getFarmOptions() {
      // 模拟数据，实际应该从API获取
      this.farmOptions = [
        { value: 'F001', label: '东部农场' },
        { value: 'F002', label: '西部农场' },
        { value: 'F003', label: '南部农场' }
      ]
    },
    /** 获取地块选项 */
    getFieldOptions() {
      // 模拟数据，实际应该从API获取，包含农场关联
      this.fieldOptions = [
        { value: 'FD001', label: '东部-1号地块', farmId: 'F001' },
        { value: 'FD002', label: '东部-2号地块', farmId: 'F001' },
        { value: 'FD003', label: '东部-3号地块', farmId: 'F001' },
        { value: 'FD004', label: '西部-1号地块', farmId: 'F002' },
        { value: 'FD005', label: '西部-2号地块', farmId: 'F002' },
        { value: 'FD006', label: '南部-1号地块', farmId: 'F003' },
        { value: 'FD007', label: '南部-2号地块', farmId: 'F003' }
      ]
    },
    /** 获取操作员选项 */
    getOperatorOptions() {
      // 模拟数据，实际应该从API获取，包含农场关联
      this.operatorOptions = [
        { value: 'OP001', label: '张三', farmId: 'F001' },
        { value: 'OP002', label: '李四', farmId: 'F002' },
        { value: 'OP003', label: '王五', farmId: 'F003' },
        { value: 'OP004', label: '赵六', farmId: 'F001' },
        { value: 'OP005', label: '钱七', farmId: 'F002' }
      ]
    },
    /** 查询农机作业记录列表 */
    getList() {
      this.loading = true
      this.queryParams.params = {}
      if (null != this.daterangeStartTime && '' != this.daterangeStartTime) {
        this.queryParams.params["beginStartTime"] = this.daterangeStartTime[0]
        this.queryParams.params["endStartTime"] = this.daterangeStartTime[1]
      }
      if (null != this.daterangeEndTime && '' != this.daterangeEndTime) {
        this.queryParams.params["beginEndTime"] = this.daterangeEndTime[0]
        this.queryParams.params["endEndTime"] = this.daterangeEndTime[1]
      }



      listMachineWorkRecords(this.queryParams).then(response => {
        this.machineWorkRecordsList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    /** 添加示例数据 */
    addExampleData() {
      const now = new Date()
      const yesterday = new Date(now)
      yesterday.setDate(yesterday.getDate() - 1)

      // 生成固定的示例作业单号
      const exampleWorkOrderId1 = 'Z20250723154530001'
      const exampleWorkOrderId2 = 'Z20250723160015002'
      const exampleWorkOrderId3 = 'Z20250724080000003'

      const exampleData = [
        {
          id: 1, // 数字类型主键
          workOrderId: exampleWorkOrderId1, // 作业单号
          machineCode: 'M001',
          machineName: 'M001', // 对应农机选项的value
          machineType: '0', // 拖拉机
          farmName: 'F001', // 对应农场选项的value
          fieldName: 'FD001', // 对应地块选项的value
          taskName: '春季耕地',
          taskType: '0', // 耕地
          status: '2', // 已完成
          startTime: this.formatDateTime(yesterday, 8, 30),
          endTime: this.formatDateTime(yesterday, 11, 45),
          workDuration: 3.25,
          workArea: 15.5,
          fuelConsumption: 25.8,
          operatorName: 'OP001', // 对应操作员选项的value
          remark: '土壤湿度适宜，作业顺利完成'
        },
        {
          id: 2, // 数字类型主键
          workOrderId: exampleWorkOrderId2, // 作业单号
          machineCode: 'M002',
          machineName: 'M002', // 对应农机选项的value
          machineType: '1', // 收割机
          farmName: 'F002', // 对应农场选项的value
          fieldName: 'FD004', // 对应地块选项的value
          taskName: '小麦收割',
          taskType: '1', // 收割
          status: '1', // 进行中
          startTime: this.formatDateTime(now, 9, 15),
          endTime: null,
          workDuration: 2.5,
          workArea: 10.2,
          fuelConsumption: 18.5,
          operatorName: 'OP002', // 对应操作员选项的value
          remark: '小麦成熟度良好，预计今日完成收割'
        },
        {
          id: 3, // 数字类型主键
          workOrderId: exampleWorkOrderId3, // 作业单号
          machineCode: 'M003',
          machineName: 'M003', // 对应农机选项的value
          machineType: '2', // 播种机
          farmName: 'F003', // 对应农场选项的value
          fieldName: 'FD006', // 对应地块选项的value
          taskName: '玉米播种',
          taskType: '2', // 播种
          status: '0', // 待开始
          startTime: this.formatDateTime(new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1), 8, 0),
          endTime: null,
          workDuration: 0,
          workArea: 20,
          fuelConsumption: 0,
          operatorName: 'OP003', // 对应操作员选项的value
          remark: '计划明日开始播种作业'
        }
      ]

      this.machineWorkRecordsList = exampleData
      this.total = exampleData.length
    },

    /** 格式化日期时间 */
    formatDateTime(date, hour, minute) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(hour || 0).padStart(2, '0')
      const minutes = String(minute || 0).padStart(2, '0')

      return `${year}-${month}-${day} ${hours}:${minutes}:00`
    },

    /** 生成作业单号 */
    generateWorkOrderId(customDate) {
      // 格式: ZYYYYMMDDHHMMSSNN
      const now = customDate || new Date()

      // 获取年月日
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')

      // 获取时分秒
      const hours = String(now.getHours()).padStart(2, '0')
      const minutes = String(now.getMinutes()).padStart(2, '0')
      const seconds = String(now.getSeconds()).padStart(2, '0')

      // 生成3位随机序号，避免同一秒内重复
      const randomNum = String(Math.floor(Math.random() * 1000)).padStart(3, '0')

      // 组合成最终的作业单号，确保格式为 ZYYYYMMDDHHMMSSNN
      return `Z${year}${month}${day}${hours}${minutes}${seconds}${randomNum}`
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        workOrderId: null,
        machineCode: null,
        machineName: null,
        machineType: null,
        farmName: null,
        fieldName: null,
        taskName: null,
        taskType: null,
        startTime: null,
        endTime: null,
        operatorName: null,
        status: '0', // 默认待开始
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      // 清空过滤选项
      this.filteredMachineOptions = []
      this.filteredFieldOptions = []
      this.filteredOperatorOptions = []
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeStartTime = []
      this.daterangeEndTime = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      // 生成作业单号
      this.form.workOrderId = this.generateWorkOrderId()
      this.open = true
      this.title = "添加农机作业记录"
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()

      // 直接使用行数据进行回显（因为目前使用模拟数据）
      this.form = { ...row }

      // 确保所有字段都正确回显
      this.form.workOrderId = row.workOrderId || row.id
      this.form.machineCode = row.machineCode
      this.form.machineName = row.machineName
      this.form.machineType = row.machineType
      this.form.farmName = row.farmName
      this.form.fieldName = row.fieldName
      this.form.taskName = row.taskName
      this.form.taskType = row.taskType
      this.form.status = row.status
      this.form.startTime = row.startTime
      this.form.endTime = row.endTime
      this.form.operatorName = row.operatorName
      this.form.remark = row.remark

      // 编辑时根据农场初始化过滤选项（传递初始化标志，保持原有值）
      if (this.form.farmName) {
        this.handleFarmChange(this.form.farmName, true)
      }

      this.open = true
      this.title = "修改农机作业记录"

      // 如果将来需要使用API，可以使用以下代码
      /*
      const id = row.id || this.ids
      getMachineWorkRecords(id).then(response => {
        this.form = response.data
        // 确保保留原始作业单号
        if (!this.form.workOrderId) {
          this.form.workOrderId = row.workOrderId
        }
        // 编辑时根据农场初始化过滤选项
        if (this.form.farmName) {
          this.handleFarmChange(this.form.farmName)
        }
        this.open = true
        this.title = "修改农机作业记录"
      }).catch(error => {
        console.warn('API调用失败，使用当前行数据:', error)
        // 回退到使用行数据的逻辑
      })
      */
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 确保有作业单号，无论是新增还是修改
          if (!this.form.workOrderId || this.form.workOrderId === 'null' || this.form.workOrderId === '') {
            this.form.workOrderId = this.generateWorkOrderId()
          }

          if (this.title.indexOf("修改") !== -1) {
            updateMachineWorkRecords(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            }).catch(error => {
              this.$modal.msgError("修改失败: " + (error.message || '未知错误'))
            })
          } else {
            addMachineWorkRecords(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            }).catch(error => {
              this.$modal.msgError("新增失败: " + (error.message || '未知错误'))
            })
          }
        }
      })
    },


    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      const workOrderId = row.workOrderId || '未知'
      this.$modal.confirm('是否确认删除作业单号为"' + workOrderId + '"的数据项？').then(function () {
        return delMachineWorkRecords(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('base/machineWorkRecords/export', {
        ...this.queryParams
      }, `machineWorkRecords_${new Date().getTime()}.xlsx`)
    },
    // 获取状态标签的类名
    getStatusClass(status) {
      const statusMap = {
        '0': 'pending',     // 待开始（灰）
        '1': 'in-progress', // 进行中（蓝）
        '2': 'completed',   // 已完成（绿）
        '3': 'cancelled'    // 已取消（红）
      }
      return statusMap[status] || ''
    },
    // 获取农机类型标签
    getMachineTypeLabel(value) {
      const dict = this.machineTypeOptions.find(item => item.value === value)
      return dict ? dict.label : value
    },
    // 获取作业类型标签
    getTaskTypeLabel(value) {
      const dict = this.taskTypeOptions.find(item => item.value === value)
      return dict ? dict.label : value
    },
    // 获取作业状态标签
    getStatusLabel(value) {
      const dict = this.statusOptions.find(item => item.value === value)
      return dict ? dict.label : value
    },
    /** 农场变更处理 */
    handleFarmChange(farmValue, isInitialLoad = false) {
      if (farmValue) {
        // 根据选择的农场过滤相关选项
        this.filteredMachineOptions = this.machineOptions.filter(machine => machine.farmId === farmValue)
        this.filteredFieldOptions = this.fieldOptions.filter(field => field.farmId === farmValue)
        this.filteredOperatorOptions = this.operatorOptions.filter(operator => operator.farmId === farmValue)

        // 只有在用户主动变更农场时才清空依赖字段，初始化加载时不清空
        if (!isInitialLoad) {
          this.form.machineName = null
          this.form.fieldName = null
          this.form.operatorName = null
        }
      } else {
        // 清空过滤选项
        this.filteredMachineOptions = []
        this.filteredFieldOptions = []
        this.filteredOperatorOptions = []

        // 清空依赖字段
        this.form.machineName = null
        this.form.fieldName = null
        this.form.operatorName = null
      }
    },

    /** 农机名称变更处理 */
    handleMachineNameChange(machineValue) {
      const selectedMachine = this.machineOptions.find(m => m.value === machineValue)
      if (selectedMachine) {
        // 自动填充农机编号和类型（编辑时使用）
        this.form.machineCode = selectedMachine.machineCode
        this.form.machineType = selectedMachine.machineType
      }
    },




  }
}
</script>

<style scoped>
/* 作业状态标签样式 */
.work-status-tag {
  display: inline-block !important;
  padding: 4px 12px !important;
  border-radius: 12px !important;
  font-size: 12px !important;
  font-weight: 500 !important;
  text-align: center !important;
  min-width: 60px !important;
  line-height: 1.2 !important;
  white-space: nowrap !important;
  border: 1px solid !important;
  overflow: visible !important;
  text-overflow: clip !important;
}

/* 确保表格单元格不显示省略号 */
.el-table td .cell {
  overflow: visible !important;
  text-overflow: clip !important;
}

/* 专门针对作业状态列的单元格样式 */
.el-table .el-table__body-wrapper .el-table__body td .cell {
  overflow: visible !important;
  text-overflow: clip !important;
  white-space: nowrap !important;
}

/* 更强的选择器覆盖Element UI默认样式 */
.el-table__body tr td .cell {
  overflow: visible !important;
  text-overflow: clip !important;
}

/* 全局移除表格省略号，使用最高优先级 */
.el-table .cell {
  overflow: visible !important;
  text-overflow: clip !important;
  white-space: nowrap !important;
}

/* 专门针对包含work-status-tag的单元格 */
.el-table .cell:has(.work-status-tag),
.el-table td:has(.work-status-tag) .cell {
  overflow: visible !important;
  text-overflow: clip !important;
  white-space: nowrap !important;
}

/* 待开始状态 - 灰色 */
.work-status-tag.pending {
  background-color: #f9fafb !important;
  color: #6b7280 !important;
  border-color: #d1d5db !important;
}

/* 进行中状态 - 蓝色 */
.work-status-tag.in-progress {
  background-color: #eff6ff !important;
  color: #2563eb !important;
  border-color: #bfdbfe !important;
}

/* 已完成状态 - 绿色 */
.work-status-tag.completed {
  background-color: #f0fdf4 !important;
  color: #16a34a !important;
  border-color: #bbf7d0 !important;
}

/* 已取消状态 - 红色 */
.work-status-tag.cancelled {
  background-color: #fef2f2 !important;
  color: #dc2626 !important;
  border-color: #fecaca !important;
}

/* 备注文本样式 */
.remark-text {
  display: inline-block;
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 表单样式优化 */
.el-form-item {
  margin-bottom: 18px;
}

/* 表单对话框样式优化 */
.el-dialog__body {
  padding: 20px 25px;
}

.el-form-item__label {
  font-weight: 500;
  color: #606266;
}

.el-row {
  margin-bottom: 0;
}
</style>
