<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="vehicleName">
        <el-input
          v-model="queryParams.vehicleName"
          placeholder="请输入车辆名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车牌号" prop="plateNo">
        <vehicle-no-input
          v-model="queryParams.plateNo"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="车辆类型" prop="vehicleType">
        <el-select v-model="queryParams.vehicleType" placeholder="车辆类型" clearable style="width: 240px">
          <el-option
            v-for="dict in dict.type.vehicle_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 style="width: 240px">
          <el-option
            v-for="dict in dict.type.vehicle_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: 240px"
        >
          <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="创建时间">
        <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:vehicle: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:vehicle: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:vehicle:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="vehicleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="车辆名称" align="center" prop="vehicleName" :show-overflow-tooltip="true" />
      <el-table-column label="车牌号" align="center" prop="plateNo" :show-overflow-tooltip="true" />
      <el-table-column label="车辆类型" align="center" prop="vehicleType" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ vehicleTypeLabel(scope.row.vehicleType) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="能力标签" align="center" min-width="200">
        <template slot-scope="scope">
          <template v-if="parseCapabilities(scope.row.capabilities).length">
            <el-tag
              v-for="tag in parseCapabilities(scope.row.capabilities)"
              :key="tag"
              size="mini"
              class="capability-tag"
            >
              {{ tag }}
            </el-tag>
          </template>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="所属队伍" align="center" min-width="140">
        <template slot-scope="scope">
          <span>{{ resolveTeamName(scope.row.teamId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-tag :type="statusTagType(scope.row.status)">
            {{ statusLabel(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="GPS位置" align="center" width="150">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.gpsLat && scope.row.gpsLng"
            type="text"
            size="mini"
            icon="el-icon-location"
            @click="showMap(scope.row)"
          >
            查看位置
          </el-button>
          <span v-else style="color: #909399;">未定位</span>
        </template>
      </el-table-column>
      <el-table-column label="最后定位时间" align="center" prop="lastSeenAt" width="160">
        <template slot-scope="scope">
          <span v-if="scope.row.lastSeenAt">{{ parseTime(scope.row.lastSeenAt) }}</span>
          <span v-else style="color: #909399;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-dropdown trigger="click" @command="(cmd) => handleAction(cmd, scope.row)">
            <el-button size="mini" type="text">
              更多操作<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item 
                command="edit"
                v-hasPermi="['resource:vehicle:edit']"
              >
                <i class="el-icon-edit"></i> 修改
              </el-dropdown-item>
              <el-dropdown-item 
                command="delete"
                v-hasPermi="['resource:vehicle:remove']"
              >
                <i class="el-icon-delete"></i> 删除
              </el-dropdown-item>
              <el-dropdown-item 
                command="location"
                v-hasPermi="['resource:vehicle:query']"
              >
                <i class="el-icon-location"></i> 位置
              </el-dropdown-item>
              <el-dropdown-item 
                command="updateLocation"
                v-hasPermi="['resource:vehicle:edit']"
              >
                <i class="el-icon-coordinate"></i> 更新位置
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </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 :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="车辆名称" prop="vehicleName">
              <el-input v-model="form.vehicleName" placeholder="请输入车辆名称" maxlength="100" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="车牌号" prop="plateNo">
              <vehicle-no-input v-model="form.plateNo" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="车辆类型" prop="vehicleType">
              <el-select v-model="form.vehicleType" placeholder="请选择车辆类型" clearable style="width: 100%">
                <el-option
                  v-for="dict in dict.type.vehicle_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="status">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                <el-option
                  v-for="dict in dict.type.vehicle_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <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-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备提供商" prop="deviceProvider">
              <el-select v-model="form.deviceProvider" placeholder="请选择定位协议" clearable style="width: 100%">
                <el-option
                  v-for="dict in dict.type.device_provider"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="定位设备ID" prop="deviceId">
              <el-input v-model="form.deviceId" placeholder="请输入定位设备ID" maxlength="64" />
            </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>

    <!-- 地图弹窗 -->
    <el-dialog title="车辆位置" :visible.sync="mapVisible" width="800px" append-to-body :close-on-click-modal="false" @close="closeMap">
      <div style="position: relative;">
        <amap
          v-if="mapVisible"
          :center="mapCenter"
          :markers="mapMarkers"
          height="500px"
        />
        <!-- 无定位信息提示层 -->
        <div 
          v-if="mapMarkers.length === 0 && showNoLocationMessage" 
          style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: rgba(255, 255, 255, 0.95); padding: 20px 40px; border-radius: 8px; box-shadow: 0 2px 12px rgba(0,0,0,0.15); z-index: 1000; text-align: center; min-width: 280px;"
        >
          <i 
            class="el-icon-close" 
            style="position: absolute; top: 8px; right: 8px; font-size: 18px; color: #909399; cursor: pointer;"
            @click="showNoLocationMessage = false"
            title="关闭"
          ></i>
          <i class="el-icon-warning" style="font-size: 32px; color: #E6A23C; display: block; margin-bottom: 10px;"></i>
          <span style="font-size: 16px; color: #606266; font-weight: 500;">该车辆暂无定位信息</span>
        </div>
      </div>
    </el-dialog>

    <LocationPickerDialog
      :visible.sync="locationPickerVisible"
      :initial-location="{
        longitude: locationPickerTarget ? locationPickerTarget.gpsLng : undefined,
        latitude: locationPickerTarget ? locationPickerTarget.gpsLat : undefined,
        locationName: locationPickerTarget ? (locationPickerTarget.vehicleName || locationPickerTarget.plateNo || '') : ''
      }"
      @confirm="handleLocationConfirm"
    />
  </div>
</template>

<script>
import { listVehicle, getVehicle, delVehicle, addVehicle, updateVehicle, updateVehicleLocation } from "@/api/resource/vehicle"
import { listTeam } from "@/api/resource/team"
import Amap from "@/components/Amap"
import VehicleNoInput from "@/components/VehicleNoInput"
import LocationPickerDialog from "@/components/location/LocationPickerDialog.vue"

export default {
  name: "ResourceVehicle",
  components: {
    Amap,
    VehicleNoInput,
    LocationPickerDialog
  },
  dicts: ['vehicle_status', 'vehicle_type', 'device_provider'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      plateNos: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 车辆表格数据
      vehicleList: [],
      // 队伍选项（用于下拉选择）
      teamOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 地图弹窗
      mapVisible: false,
      mapCenter: [116.397428, 39.90923], // 默认北京天安门
      mapMarkers: [],
      showNoLocationMessage: true, // 是否显示"暂无定位信息"提示
      locationPickerVisible: false,
      locationPickerTarget: null,
      // 能力标签选项（可选，用于预定义标签）
      capabilityOptions: [],
      locationPickerSubmitting: false,
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        vehicleName: undefined,
        plateNo: undefined,
        vehicleType: undefined,
        status: undefined,
        teamId: undefined
      },
      // 表单校验
      rules: {
        vehicleName: [
          { required: true, message: "车辆名称不能为空", trigger: "blur" },
          { max: 100, message: "车辆名称长度不能超过100个字符", trigger: "blur" }
        ],
        plateNo: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback()
                return
              }
              // 去除空格
              const cleaned = value.replace(/\s/g, '').toUpperCase()
              
              // 普通车牌：省份(1汉字) + 字母(1位) + 5位字母数字
              const normalPattern = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{5}$/
              // 新能源车牌：省份(1汉字) + 字母(1位) + 6位字母数字（所有字母都支持新能源车牌）
              const newEnergyPattern = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{6}$/
              
              if (normalPattern.test(cleaned) || newEnergyPattern.test(cleaned)) {
                callback()
              } else {
                callback(new Error("请输入正确的车牌号格式，如：京A12345（普通） 或 京A123456（新能源）"))
              }
            },
            trigger: "blur"
          }
        ],
        vehicleType: [
          { max: 32, message: '车辆类型长度不能超过32个字符', trigger: 'blur' }
        ],
        deviceProvider: [
          { max: 32, message: '设备提供商长度不能超过32个字符', trigger: 'blur' }
        ],
        capabilities: [
          {
            validator: (rule, value, callback) => {
              if (!value || !Array.isArray(value) || value.length === 0) {
                callback()
                return
              }
              // 检查JSON字符串长度（模拟保存时的格式）
              const jsonString = JSON.stringify(value)
              if (jsonString.length > 500) {
                callback(new Error('能力标签总长度不能超过500个字符'))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getTeamOptions()
  },
  methods: {
    /** 查询车辆列表 */
    getList() {
      this.loading = true
      listVehicle(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.vehicleList = response.rows
        this.total = response.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 获取队伍选项（用于下拉选择） */
    getTeamOptions() {
      listTeam({ pageNum: 1, pageSize: 1000 }).then(response => {
        this.teamOptions = response.rows || []
      }).catch(() => {
        this.teamOptions = []
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        vehicleName: undefined,
        plateNo: undefined,
        vehicleType: undefined,
        teamId: undefined,
        status: 'available',
        capabilities: [],
        deviceId: undefined,
        deviceProvider: 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.plateNos = selection.map(item => item.plateNo || item.vehicleName)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 操作下拉菜单处理 */
    handleAction(command, row) {
      switch (command) {
        case 'edit':
          this.handleUpdate(row)
          break
        case 'delete':
          this.handleDelete(row)
          break
        case 'location':
          this.showMap(row)
          break
        case 'updateLocation':
          this.openLocationPicker(row)
          break
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加车辆"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids[0]
      getVehicle(id).then(response => {
        this.form = response.data
        // 确保状态有默认值
        if (!this.form.status) {
          this.form.status = 'available'
        }
        // 解析能力标签JSON字符串为数组
        this.form.capabilities = this.safeJsonArray(this.form.capabilities)
        this.open = true
        this.title = "修改车辆"
      }).catch(() => {})
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 转换能力标签数组为JSON字符串
          const payload = {
            ...this.form,
            capabilities: Array.isArray(this.form.capabilities) && this.form.capabilities.length > 0
              ? JSON.stringify(this.form.capabilities)
              : null
          }
          if (this.form.id != undefined) {
            updateVehicle(payload).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addVehicle(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.plateNo || row.vehicleName)
      } else if (this.plateNos.length > 0) {
        curNames.push(...this.plateNos)
      }
      const quotedNames = curNames.map(item => `“${item}”`);
      const resNames = quotedNames.join('、');
      this.$modal.confirm(`是否确认删除车辆 ${resNames || ''}？`).then(function() {
        return delVehicle(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 显示地图 */
    showMap(row) {
      // 始终打开地图弹窗
      this.mapVisible = true
      
      if (row.gpsLat && row.gpsLng) {
        // 有坐标：设置车辆位置
        this.mapCenter = [row.gpsLng, row.gpsLat]
        this.mapMarkers = [{
          lat: row.gpsLat,
          lng: row.gpsLng,
          title: row.vehicleName || row.plateNo || '车辆',
          content: `
            <div style="padding: 10px;">
              <p style="margin: 5px 0;"><strong>车辆名称：</strong>${row.vehicleName || '-'}</p>
              <p style="margin: 5px 0;"><strong>车牌号：</strong>${row.plateNo || '-'}</p>
              <p style="margin: 5px 0;"><strong>车辆类型：</strong>${this.vehicleTypeLabel(row.vehicleType) || '-'}</p>
              <p style="margin: 5px 0;"><strong>能力标签：</strong>${this.parseCapabilities(row.capabilities).join('、') || '-'}</p>
              <p style="margin: 5px 0;"><strong>最后定位：</strong>${this.parseTime(row.lastSeenAt) || '-'}</p>
            </div>
          `
        }]
        this.showNoLocationMessage = false // 有定位信息，不显示提示
      } else {
        // 无坐标：使用默认中心点（北京），不设置标记点
        this.mapCenter = [116.397428, 39.90923] // 北京天安门
        this.mapMarkers = []
        this.showNoLocationMessage = true // 无定位信息，显示提示
      }
    },
    /** 关闭地图弹窗 */
    closeMap() {
      // 重置为默认中心点
      this.mapCenter = [116.397428, 39.90923]
      this.mapMarkers = []
      this.showNoLocationMessage = true // 重置提示显示状态
    },
    openLocationPicker(row) {
      this.locationPickerTarget = row
      this.locationPickerVisible = true
    },
    handleLocationConfirm({ lng, lat }) {
      if (!this.locationPickerTarget) {
        this.locationPickerVisible = false
        return
      }
      this.locationPickerSubmitting = true
      updateVehicleLocation(this.locationPickerTarget.id, {
        gpsLat: lat,
        gpsLng: lng
      }).then(() => {
        this.$modal.msgSuccess("车辆位置更新成功")
        this.locationPickerVisible = false
        this.locationPickerTarget = null
        this.getList()
      }).catch(() => {
        this.$modal.msgError("车辆位置更新失败")
      }).finally(() => {
        this.locationPickerSubmitting = false
      })
    },
    /** 状态标签类型 */
    statusTagType(status) {
      const map = {
        'available': 'success',
        'busy': 'warning',
        'maintenance': 'info',
        'offline': 'danger',
        'scrap': 'info'
      }
      return map[status] || 'info'
    },
    /** 状态标签文本 */
    statusLabel(status) {
      const dict = this.dict.type.vehicle_status.find(item => item.value === status)
      return dict ? dict.label : status
    },
    /** 车辆类型标签文本 */
    vehicleTypeLabel(vehicleType) {
      if (!vehicleType) return ''
      const dict = this.dict.type.vehicle_type.find(item => item.value === vehicleType)
      return dict ? dict.label : vehicleType
    },
    resolveTeamName(teamId) {
      if (!teamId) {
        return '-'
      }
      const team = this.teamOptions.find(item => item.id === teamId)
      return team ? team.teamName : '-'
    },
    parseCapabilities(value) {
      if (!value) {
        return []
      }
      try {
        const parsed = JSON.parse(value)
        if (Array.isArray(parsed)) {
          return parsed
        }
      } catch (e) {
        // ignore JSON parse error
      }
      return value.split(/[,;；、\s]+/).filter(Boolean)
    },
    /** 安全解析JSON数组 */
    safeJsonArray(val) {
      if (!val) return []
      try {
        const arr = JSON.parse(val)
        return Array.isArray(arr) ? arr : []
      } catch (e) {
        return []
      }
    }
  }
}
</script>

<style scoped>
.capability-tag {
  margin: 2px;
}
</style>