<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="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="machineType">
        <el-select v-model="queryParams.machineType" placeholder="请选择农机类型" clearable>
          <el-option v-for="dict in dict.type.agricultural_machine_type" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="厂家" prop="manufacturer">
        <el-input v-model="queryParams.manufacturer" placeholder="请输入厂家" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="型号" prop="model">
        <el-input v-model="queryParams.model" 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="managerName">
        <el-input v-model="queryParams.managerName" placeholder="请输入负责人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="启用时间" prop="purchaseDate">
        <el-date-picker v-model="daterangePurchaseDate" 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="manufactureDate">
        <el-date-picker v-model="daterangeManufactureDate" 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="onlineStatus">
        <el-select v-model="queryParams.onlineStatus" placeholder="请选择当前状态" clearable>
          <el-option v-for="dict in dict.type.agricultural_online_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>


      <el-form-item label="保养状态" prop="maintenanceStatus">
        <el-select v-model="queryParams.maintenanceStatus" placeholder="请选择保养状态" clearable>
          <el-option v-for="dict in dict.type.agricultural_maintenance_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="定位状态" prop="locationStatus">
        <el-select v-model="queryParams.locationStatus" placeholder="请选择定位状态" clearable>
          <el-option v-for="dict in dict.type.agricultural_location_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </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:machines: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:machines: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:machines: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:machines:export']">导出</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="machinesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <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" key="deptName" prop="deptName" />
      <!-- <el-table-column label="所属地块" align="center" prop="fieldArea" /> -->
      <el-table-column label="负责人" align="center" prop="managerName" />
      <el-table-column label="厂家" align="center" prop="manufacturer" />
      <el-table-column label="型号" align="center" prop="model" />
      <el-table-column label="生产日期" align="center" prop="manufactureDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.manufactureDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="启用时间" align="center" prop="purchaseDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.purchaseDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="当前状态" align="center" prop="onlineStatus" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.agricultural_online_status" :value="scope.row.onlineStatus"
            :class="['online-status-tag', getOnlineStatusClass(scope.row.onlineStatus)]" />
        </template>
      </el-table-column>
      <el-table-column label="当前任务" align="center" prop="currentTask" />
      <el-table-column label="保养状态" align="center" prop="maintenanceStatus" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.agricultural_maintenance_status" :value="scope.row.maintenanceStatus"
            :class="['maintenance-status-tag', getMaintenanceStatusClass(scope.row.maintenanceStatus)]" />
        </template>
      </el-table-column>
      <el-table-column label="定位状态" align="center" prop="locationStatus" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.agricultural_location_status" :value="scope.row.locationStatus"
            :class="['location-status-tag', getLocationStatusClass(scope.row.locationStatus)]" />
        </template>
      </el-table-column>
      <el-table-column label="报警次数" align="center" prop="alarmCount" />
      <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-view"
            @click="handleView(scope.row)"
            v-hasPermi="['base:machines:view']"
          >查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['base:machines:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['base:machines: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">
          <el-col :span="12">
            <el-form-item label="农机编号" prop="machineCode">
              <el-input v-model="form.machineCode" placeholder="请输入农机编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="农机名称" prop="machineName">
              <el-input v-model="form.machineName" placeholder="请输入农机名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="农机类型" prop="machineType">
              <el-select v-model="form.machineType" placeholder="请选择农机类型" style="width: 100%">
                <el-option v-for="dict in dict.type.agricultural_machine_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属农场" prop="farmId">
              <treeselect v-model="form.farmId" :options="enabledDeptOptions" :show-count="true" placeholder="请先选择所属农场" />
            </el-form-item>

          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="负责人" prop="managerName">
              <el-input v-model="form.managerName" placeholder="请输入负责人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="厂家" prop="manufacturer">
              <el-input v-model="form.manufacturer" placeholder="请输入厂家" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">

          <el-col :span="12">
            <el-form-item label="型号" prop="model">
              <el-input v-model="form.model" placeholder="请输入型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产日期" prop="manufactureDate">
              <el-date-picker clearable v-model="form.manufactureDate" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择生产日期" style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="20">

          <el-col :span="12">
            <el-form-item label="启用时间" prop="purchaseDate">
              <el-date-picker clearable v-model="form.purchaseDate" type="date" value-format="yyyy-MM-dd"
                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="imageUrl">
              <image-upload v-model="form.imageUrl" :limit="1" />
            </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 { listMachines, getMachines, delMachines, addMachines, updateMachines } from "@/api/base/machines"
import ImageUpload from "@/components/ImageUpload"
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: "Machines",
  components: {
    ImageUpload,
    Treeselect
  },
  dicts: ['agricultural_machine_type', 'agricultural_maintenance_status', 'agricultural_online_status', 'agricultural_location_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      machineCodes: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 农机管理列表表格数据
      machinesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 启用时间范围
      daterangePurchaseDate: [],
      // 生产日期范围
      daterangeManufactureDate: [],
      // 农场选项列表
      farmOptions: [],
      // 地块选项列表
      fieldOptions: [],

      // 部门树选项
      deptOptions: undefined,
      // 过滤掉已禁用部门树选项
      enabledDeptOptions: undefined,

      // 所属地块
      fieldIdList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        machineCode: null,
        machineName: null,
        machineType: null,
        manufacturer: null,
        model: null,
        farmId: null,
        fieldId: null,
        managerId: null,
        onlineStatus: null,
        maintenanceStatus: null,
        locationStatus: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        machineCode: [
          { required: true, message: "农机编号不能为空", trigger: "blur" }
        ],
        machineName: [
          { required: true, message: "农机名称不能为空", trigger: "blur" }
        ],
        machineType: [
          { required: true, message: "农机类型不能为空", trigger: "change" }
        ],
        farmId: [
          { required: true, message: "所属农场不能为空", trigger: "change" }
        ],
        fieldArea: [
          { required: true, message: "所属地块不能为空", trigger: "change" }
        ],
        managerName: [
          { required: true, message: "负责人不能为空", trigger: "blur" }
        ],
        manufacturer: [
          { required: true, message: "厂家不能为空", trigger: "blur" }
        ],
        model: [
          { required: true, message: "型号不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getDeptTree()
    this.getFieldNameList()
  },
  methods: {

    /** 查询地块名称 **/
    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
      })
    },
    /** 获取农场选项 */
    getFarmOptions() {
      // 暂时没有数据，可以在后续添加API调用
      // 示例: getFarmList().then(response => { this.farmOptions = response.data })
      this.farmOptions = []
    },
    /** 查询农机管理列表列表 */
    getList() {
      this.loading = true
      this.queryParams.params = {}
      if (null != this.daterangePurchaseDate && '' != this.daterangePurchaseDate) {
        this.queryParams.params["beginPurchaseDate"] = this.daterangePurchaseDate[0]
        this.queryParams.params["endPurchaseDate"] = this.daterangePurchaseDate[1]
      }
      if (null != this.daterangeManufactureDate && '' != this.daterangeManufactureDate) {
        this.queryParams.params["beginManufactureDate"] = this.daterangeManufactureDate[0]
        this.queryParams.params["endManufactureDate"] = this.daterangeManufactureDate[1]
      }
      listMachines(this.queryParams).then(response => {
        this.machinesList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 获取字典标签
    getDictLabel(options, value) {
      if (!options || (value === null || value === undefined || value === '')) return ''
      // 尝试字符串和数字匹配
      const item = options.find(option =>
        option.value === value ||
        option.value === String(value) ||
        String(option.value) === String(value)
      )
      return item ? item.label : value
    },
    // 获取在线状态样式类
    getOnlineStatusClass(status) {
      const statusMap = {
        '0': 'offline',     // 离线
        '1': 'online',      // 在线
        '2': 'busy',        // 忙碌
        '3': 'error',       // 故障
        0: 'offline',
        1: 'online',
        2: 'busy',
        3: 'error'
      }
      return statusMap[status] || 'offline'
    },
    // 获取保养状态样式类
    getMaintenanceStatusClass(status) {
      const statusMap = {
        '0': 'normal',      // 正常
        '1': 'warning',     // 需要保养
        '2': 'urgent',      // 过期
        '3': 'maintaining', // 保养中
        0: 'normal',
        1: 'warning',
        2: 'urgent',
        3: 'maintaining'
      }
      return statusMap[status] || 'normal'
    },
    // 获取定位状态样式类
    getLocationStatusClass(status) {
      const statusMap = {
        '0': 'disconnected', // 未定位
        '1': 'connected',    // 已定位
        '2': 'weak',         // 信号弱
        '3': 'error',        // 定位异常
        0: 'disconnected',
        1: 'connected',
        2: 'weak',
        3: 'error'
      }
      return statusMap[status] || 'disconnected'
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        machineCode: null,
        machineName: null,
        machineType: null,
        farmId: null,
        fieldArea: null,
        managerId: null,
        manufacturer: null,
        model: null,
        manufactureDate: null,
        purchaseDate: null,
        imageUrl: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangePurchaseDate = []
      this.daterangeManufactureDate = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.machineCodes = selection.map(item => item.machineCode)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加农机管理列表"
    },
    /** 查看按钮操作 */
    handleView(row) {
      const machineId = row.id
      this.$router.push({
        path: '/base/machines/monitor',
        query: { id: machineId }
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getMachines(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改农机管理列表"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateMachines(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addMachines(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      const machineCodes = row.machineCode || this.machineCodes
      this.$modal.confirm('确认删除农机管理列表编号为"' + machineCodes + '"的数据项？').then(function () {
        return delMachines(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('base/machines/export', {
        ...this.queryParams
      }, `machines_${new Date().getTime()}.xlsx`)
    },

  }
}
</script>

<style scoped>
/* dict-tag组件的基础样式重置 */
.el-table .online-status-tag,
.el-table .maintenance-status-tag,
.el-table .location-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;
  background: none !important;
  box-shadow: none !important;
  color: inherit !important;
}

/* 在线状态标签 */
.el-table .online-status-tag.online {
  background-color: #f0fdf4 !important;
  color: #16a34a !important;
  border-color: #bbf7d0 !important;
}

.el-table .online-status-tag.offline {
  background-color: #f9fafb !important;
  color: #6b7280 !important;
  border-color: #d1d5db !important;
}

.el-table .online-status-tag.busy {
  background-color: #fffbeb !important;
  color: #d97706 !important;
  border-color: #fed7aa !important;
}

.el-table .online-status-tag.error {
  background-color: #fef2f2 !important;
  color: #dc2626 !important;
  border-color: #fecaca !important;
}

/* 保养状态标签 */
.el-table .maintenance-status-tag.normal {
  background-color: #f0fdf4 !important;
  color: #16a34a !important;
  border-color: #bbf7d0 !important;
}

.el-table .maintenance-status-tag.warning {
  background-color: #fffbeb !important;
  color: #d97706 !important;
  border-color: #fed7aa !important;
}

.el-table .maintenance-status-tag.urgent {
  background-color: #fef2f2 !important;
  color: #dc2626 !important;
  border-color: #fecaca !important;
}

.el-table .maintenance-status-tag.maintaining {
  background-color: #eff6ff !important;
  color: #2563eb !important;
  border-color: #bfdbfe !important;
}

/* 定位状态标签 */
.el-table .location-status-tag.connected {
  background-color: #f0fdf4 !important;
  color: #16a34a !important;
  border-color: #bbf7d0 !important;
}

.el-table .location-status-tag.disconnected {
  background-color: #f9fafb !important;
  color: #6b7280 !important;
  border-color: #d1d5db !important;
}

.el-table .location-status-tag.weak {
  background-color: #fffbeb !important;
  color: #d97706 !important;
  border-color: #fed7aa !important;
}

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

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

.el-row {
  margin-bottom: 0;
}

.el-form-item {
  margin-bottom: 20px;
}

/* 图片上传区域样式 */
.el-form-item:has([role="group"]) {
  margin-bottom: 25px;
}

/* 备注区域样式 */
.el-form-item:last-of-type {
  margin-bottom: 15px;
}
</style>
