<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="equipmentCode">
        <el-input
          v-model="queryParams.equipmentCode"
          placeholder="请输入装备编码"
          clearable
          style="width: 220px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="装备名称" prop="equipmentName">
        <el-input
          v-model="queryParams.equipmentName"
          placeholder="请输入装备名称"
          clearable
          style="width: 220px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="装备类型" prop="equipmentType">
        <el-select v-model="queryParams.equipmentType" placeholder="请选择装备类型" clearable style="width: 220px">
          <el-option
            v-for="dict in dict.type.equipment_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="品牌" prop="brand">
        <el-input
          v-model="queryParams.brand"
          placeholder="请输入品牌"
          clearable
          style="width: 220px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 220px">
          <el-option
            v-for="dict in dict.type.equipment_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属队伍" prop="teamId">
        <el-select
          v-model="queryParams.teamId"
          placeholder="请选择所属队伍"
          clearable
          filterable
          style="width: 220px"
        >
          <el-option
            v-for="team in teamOptions"
            :key="team.id"
            :label="team.teamName"
            :value="team.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属仓库" prop="warehouseId">
        <el-select
          v-model="queryParams.warehouseId"
          placeholder="请选择所属仓库"
          clearable
          filterable
          style="width: 220px"
        >
          <el-option
            v-for="warehouse in warehouseList"
            :key="warehouse.id"
            :label="warehouse.warehouseName"
            :value="warehouse.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          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>
        <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="['resource:equipment: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="['resource:equipment: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="['resource:equipment:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="equipmentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="装备编码" align="center" prop="equipmentCode" :show-overflow-tooltip="true" min-width="120" />
      <el-table-column label="装备名称" align="center" prop="equipmentName" :show-overflow-tooltip="true" min-width="150" />
      <el-table-column label="装备类型" align="center" prop="equipmentType" :show-overflow-tooltip="true" width="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.equipment_type" :value="scope.row.equipmentType" />
        </template>
      </el-table-column>
      <el-table-column label="品牌/型号" align="center" width="150">
        <template slot-scope="scope">
          <span>{{ scope.row.brand || '-' }} / {{ scope.row.model || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属队伍" align="center" prop="teamName" :show-overflow-tooltip="true" width="120" />
      <el-table-column label="所属仓库" align="center" prop="warehouseName" :show-overflow-tooltip="true" width="120" />
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.equipment_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="能力标签" min-width="200">
        <template slot-scope="scope">
          <span v-if="!scope.row.capabilitiesArray || !scope.row.capabilitiesArray.length" class="text-placeholder">-</span>
          <el-tag
            v-for="(item, index) in scope.row.capabilitiesArray"
            :key="index"
            size="mini"
            type="success"
            class="mr4"
          >{{ item }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="采购日期" align="center" prop="purchaseDate" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.purchaseDate">{{ parseTime(scope.row.purchaseDate, '{y}-{m}-{d}') }}</span>
          <span v-else style="color: #909399;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="保修到期" align="center" prop="warrantyDate" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.warrantyDate" :class="getWarrantyDateClass(scope.row.warrantyDate)">
            {{ parseTime(scope.row.warrantyDate, '{y}-{m}-{d}') }}
          </span>
          <span v-else style="color: #909399;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="280" fixed="right" 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="['resource:equipment:edit']"
          >编辑</el-button>
          <el-dropdown v-if="scope.row.status !== 'scrap'">
            <span class="el-dropdown-link">
              状态<i class="el-icon-arrow-down el-icon--right" />
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-if="scope.row.status === 'busy'"
                v-hasPermi="['resource:equipment:release']"
                @click.native="handleStatusAction(scope.row, 'release')"
              >解除占用</el-dropdown-item>
              <el-dropdown-item
                v-if="scope.row.status === 'available' || scope.row.status === 'busy'"
                v-hasPermi="['resource:equipment:edit']"
                @click.native="handleStatusAction(scope.row, 'send-repair')"
              >送修</el-dropdown-item>
              <el-dropdown-item
                v-if="scope.row.status === 'repair'"
                v-hasPermi="['resource:equipment:edit']"
                @click.native="handleStatusAction(scope.row, 'finish-repair')"
              >修复完成</el-dropdown-item>
              <el-dropdown-item
                v-if="scope.row.status !== 'scrap'"
                v-hasPermi="['resource:equipment:edit']"
                @click.native="handleStatusAction(scope.row, 'scrap')"
              >报废</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleViewLogs(scope.row)"
            v-hasPermi="['resource:equipment:query']"
          >日志</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['resource:equipment: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="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="装备编码" prop="equipmentCode">
              <el-input v-model="form.equipmentCode" placeholder="请输入装备编码" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="装备名称" prop="equipmentName">
              <el-input v-model="form.equipmentName" placeholder="请输入装备名称" maxlength="200" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="装备类型" prop="equipmentType">
              <el-select v-model="form.equipmentType" placeholder="请选择装备类型" clearable style="width: 100%">
                <el-option
                  v-for="dict in dict.type.equipment_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="form.brand" placeholder="请输入品牌" maxlength="100" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="型号" prop="model">
              <el-input v-model="form.model" placeholder="请输入型号" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属队伍" prop="teamId">
              <el-select
                v-model="form.teamId"
                placeholder="请选择所属队伍"
                clearable
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="team in teamOptions"
                  :key="team.id"
                  :label="team.teamName"
                  :value="team.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属仓库" prop="warehouseId">
              <el-select
                v-model="form.warehouseId"
                placeholder="请选择所属仓库（可选）"
                clearable
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="warehouse in warehouseList"
                  :key="warehouse.id"
                  :label="warehouse.warehouseName"
                  :value="warehouse.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态">
              <template v-if="form.id">
                <!-- 编辑时：只读显示，提示通过状态流转修改 -->
                <div>
                  <dict-tag :options="dict.type.equipment_status" :value="form.status" />
                  <el-tooltip content="状态需要通过状态流转功能修改" placement="top">
                    <i class="el-icon-info" style="margin-left: 5px; color: #909399; cursor: help;" />
                  </el-tooltip>
                </div>
              </template>
              <el-select v-else v-model="form.status" placeholder="请选择状态" style="width: 100%">
                <!-- 新增时：可以选择初始状态 -->
                <el-option
                  v-for="dict in dict.type.equipment_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购日期" prop="purchaseDate">
              <el-date-picker
                v-model="form.purchaseDate"
                type="date"
                placeholder="选择采购日期"
                value-format="yyyy-MM-dd"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="保修到期日期" prop="warrantyDate">
              <el-date-picker
                v-model="form.warrantyDate"
                type="date"
                placeholder="选择保修到期日期"
                value-format="yyyy-MM-dd"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="能力标签" prop="capabilities">
              <el-select
                v-model="form.capabilities"
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请输入能力标签"
                style="width: 100%"
              >
                <el-option
                  v-for="item in capabilityOptions"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </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" placeholder="请输入备注" maxlength="500" :rows="3" />
            </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>

    <!-- 状态流转弹窗 -->
    <equipment-status-dialog
      :visible.sync="statusDialogVisible"
      :equipment="currentEquipment"
      @success="handleStatusSuccess"
    />

    <!-- 操作日志弹窗 -->
    <el-dialog title="操作日志" :visible.sync="logDialogVisible" width="900px" append-to-body :close-on-click-modal="false">
      <el-table v-loading="logLoading" :data="logList" border>
        <el-table-column label="操作时间" align="center" prop="createdAt" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createdAt) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作类型" align="center" prop="action" width="120">
          <template slot-scope="scope">
            <span>{{ getActionLabel(scope.row.action) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="原状态" align="center" prop="fromStatus" width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.equipment_status" :value="scope.row.fromStatus" />
          </template>
        </el-table-column>
        <el-table-column label="新状态" align="center" prop="toStatus" width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.equipment_status" :value="scope.row.toStatus" />
          </template>
        </el-table-column>
        <el-table-column label="操作人" align="center" prop="operatorName" width="120" />
        <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      </el-table>
      <pagination
        v-show="logTotal > 0"
        :total="logTotal"
        :page.sync="logQueryParams.pageNum"
        :limit.sync="logQueryParams.pageSize"
        @pagination="getLogList"
      />
    </el-dialog>
  </div>
</template>

<script>
import {
  listEquipment,
  getEquipment,
  addEquipment,
  updateEquipment,
  delEquipment,
  assignEquipment,
  releaseEquipment,
  sendRepair,
  finishRepair,
  scrapEquipment,
  listEquipmentLogs
} from '@/api/resource/equipment'
import { listTeam } from '@/api/resource/team'
import { listWarehouse } from '@/api/resource/warehouse'
import EquipmentStatusDialog from './components/EquipmentStatusDialog'

export default {
  name: 'ResourceEquipment',
  components: {
    EquipmentStatusDialog
  },
  dicts: ['equipment_status', 'equipment_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      equipmentCodes: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 装备表格数据
      equipmentList: [],
      // 队伍选项（用于下拉选择）
      teamOptions: [],
      // 仓库选项（用于下拉选择）
      warehouseList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 状态流转弹窗
      statusDialogVisible: false,
      currentEquipment: null,
      // 日志弹窗
      logDialogVisible: false,
      logLoading: false,
      logList: [],
      logTotal: 0,
      logQueryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 日期范围
      dateRange: [],
      // 能力标签选项
      capabilityOptions: ['通信保障', '定位追踪', '数据传输', '视频监控', '环境监测'],
      // 表单参数
      form: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        equipmentCode: undefined,
        equipmentName: undefined,
        equipmentType: undefined,
        brand: undefined,
        status: undefined,
        teamId: undefined,
        warehouseId: undefined
      },
      // 表单校验
      rules: {
        equipmentCode: [
          { required: true, message: '装备编码不能为空', trigger: 'blur' },
          { max: 50, message: '装备编码长度不能超过50个字符', trigger: 'blur' }
        ],
        equipmentName: [
          { required: true, message: '装备名称不能为空', trigger: 'blur' },
          { max: 200, message: '装备名称长度不能超过200个字符', trigger: 'blur' }
        ],
        equipmentType: [
          { max: 64, message: '装备类型长度不能超过64个字符', trigger: 'blur' }
        ],
        brand: [
          { max: 100, message: '品牌长度不能超过100个字符', trigger: 'blur' }
        ],
        model: [
          { max: 100, message: '型号长度不能超过100个字符', trigger: 'blur' }
        ],
        remark: [
          { max: 500, message: '备注长度不能超过500个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getTeamOptions()
    this.loadWarehouses()
  },
  methods: {
    /** 查询装备列表 */
    getList() {
      this.loading = true
      listEquipment(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        const rows = response.rows || []
        this.equipmentList = rows.map(item => this.decorateEquipment(item))
        this.total = response.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 装饰装备数据 */
    decorateEquipment(data) {
      const clone = { ...data }
      clone.capabilitiesArray = this.safeJsonArray(clone.capabilities)
      return clone
    },
    /** 安全解析 JSON 数组 */
    safeJsonArray(val) {
      if (!val) return []
      try {
        const arr = JSON.parse(val)
        return Array.isArray(arr) ? arr : []
      } catch (e) {
        return []
      }
    },
    /** 获取队伍选项（用于下拉选择） */
    getTeamOptions() {
      listTeam({ pageNum: 1, pageSize: 1000 }).then(response => {
        this.teamOptions = response.rows || []
      }).catch(() => {
        this.teamOptions = []
      })
    },
    /** 加载仓库列表 */
    async loadWarehouses() {
      try {
        const res = await listWarehouse({ pageNum: 1, pageSize: 1000 })
        this.warehouseList = res.rows || res.data || []
      } catch (error) {
        console.error('Failed to load warehouses:', error)
        this.warehouseList = []
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        equipmentCode: undefined,
        equipmentName: undefined,
        equipmentType: undefined,
        brand: undefined,
        model: undefined,
        teamId: undefined,
        warehouseId: undefined,
        status: 'available',
        capabilities: [],
        purchaseDate: undefined,
        warrantyDate: undefined,
        remark: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.equipmentCodes = selection.map(item => item.equipmentCode)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加装备'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids[0]
      getEquipment(id).then(response => {
        const data = response.data || {}
        this.form = {
          id: data.id,
          equipmentCode: data.equipmentCode,
          equipmentName: data.equipmentName,
          equipmentType: data.equipmentType,
          brand: data.brand,
          model: data.model,
          teamId: data.teamId,
          warehouseId: data.warehouseId,
          status: data.status || 'available',
          capabilities: this.safeJsonArray(data.capabilities),
          purchaseDate: data.purchaseDate,
          warrantyDate: data.warrantyDate,
          remark: data.remark
        }
        this.open = true
        this.title = '编辑装备'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const payload = {
            ...this.form,
            capabilities: this.form.capabilities || []
          }
          if (this.form.id != undefined) {
            // 编辑时，不传递状态字段（状态通过状态流转功能管理）
            delete payload.status
            updateEquipment(payload).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            // 新增时，可以设置初始状态
            addEquipment(payload).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let ids = this.ids
      let curNames = [];
      if (row) {
        ids = row.id || this.ids;
        curNames.push(row.equipmentCode)
      } else if (this.equipmentCodes.length > 0) {
        curNames.push(...this.equipmentCodes)
      }
      const quotedNames = curNames.map(item => `“${item}”`);
      const resNames = quotedNames.join('、');
      this.$modal.confirm('是否确认删除装备编码为"' + resNames + '"的数据项？').then(() => {
        return delEquipment(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 状态流转操作 */
    handleStatusAction(row, action) {
      this.currentEquipment = { ...row, action }
      this.statusDialogVisible = true
    },
    /** 状态流转成功回调 */
    handleStatusSuccess() {
      this.getList()
    },
    /** 查看操作日志 */
    handleViewLogs(row) {
      this.logDialogVisible = true
      this.logQueryParams.pageNum = 1
      this.getLogList(row.id)
    },
    /** 查询操作日志 */
    getLogList(equipmentId) {
      this.logLoading = true
      listEquipmentLogs(equipmentId, this.logQueryParams).then(response => {
        this.logList = response.rows || []
        this.logTotal = response.total || 0
        this.logLoading = false
      }).catch(() => {
        this.logLoading = false
      })
    },
    /** 获取操作类型中文标签 */
    getActionLabel(action) {
      const actionMap = {
        'assign': '分配占用',
        'release': '解除占用',
        'send_repair': '送修',
        'send-repair': '送修',
        'finish_repair': '修复完成',
        'finish-repair': '修复完成',
        'scrap': '报废'
      }
      return actionMap[action] || action || '-'
    },
    /** 获取保修日期样式类 */
    getWarrantyDateClass(warrantyDate) {
      if (!warrantyDate) return ''
      const date = new Date(warrantyDate)
      const today = new Date()
      const diffDays = Math.ceil((date - today) / (1000 * 60 * 60 * 24))
      if (diffDays < 0) {
        return 'warranty-expired' // 已过期
      } else if (diffDays <= 30) {
        return 'warranty-warning' // 30天内到期
      }
      return ''
    }
  }
}
</script>

<style scoped>
.mr4 {
  margin-right: 4px;
  margin-bottom: 2px;
}

.text-placeholder {
  color: #c0c4cc;
}

.warranty-expired {
  color: #f56c6c;
  font-weight: bold;
}

.warranty-warning {
  color: #e6a23c;
  font-weight: bold;
}

.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
  margin: 0 6px;
}
</style>

