<template>
  <div class="p-2 wcs-agv-status-page">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px] agv-status-search-wrap">
        <el-card class="agv-status-search-card" shadow="hover">
          <el-form ref="queryFormRef" class="agv-status-query-form" :model="queryParams" :inline="true">
            <el-form-item label="设备编号" prop="equipNo">
              <el-input v-model="queryParams.equipNo" placeholder="请输入设备编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="小车名称" prop="agvname">
              <el-input v-model="queryParams.agvname" placeholder="请输入小车名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="电量" prop="battery">
              <el-input v-model="queryParams.battery" placeholder="请输入电量" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="地图编号" prop="mapcode">
              <el-input v-model="queryParams.mapcode" placeholder="请输入地图编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="是否在线" prop="online">
              <el-select v-model="queryParams.online" placeholder="请选择是否在线" clearable>
                <el-option v-for="dict in online_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="路线" prop="path">
              <el-input v-model="queryParams.path" placeholder="请输入路线" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="背货架的编号" prop="podcode">
              <el-input v-model="queryParams.podcode" placeholder="请输入背货架的编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="背货架的方向" prop="poddir">
              <el-input v-model="queryParams.poddir" placeholder="请输入背货架的方向" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="X" prop="posx">
              <el-input v-model="queryParams.posx" placeholder="请输入X" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="Y" prop="posy">
              <el-input v-model="queryParams.posy" placeholder="请输入Y" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="机器人方向" prop="robotdir">
              <el-input v-model="queryParams.robotdir" placeholder="请输入机器人方向" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="机器人IP" prop="robotip">
              <el-input v-model="queryParams.robotip" placeholder="请输入机器人IP" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="机器人速度" prop="speed">
              <el-input v-model="queryParams.speed" placeholder="请输入机器人速度" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="状态详情" prop="statusDetail">
              <el-input v-model="queryParams.statusDetail" placeholder="请输入状态详情" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="是否暂停" prop="stop">
              <el-select v-model="queryParams.stop" placeholder="请选择是否暂停" clearable>
                <el-option v-for="dict in yes_no_int" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="时间" prop="timestamp">
              <el-date-picker clearable
                v-model="queryParams.timestamp"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择时间"
              />
            </el-form-item>
            <el-form-item class="agv-status-query-actions">
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['wcs:agvStatus:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['wcs:agvStatus:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['wcs:agvStatus:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['wcs:agvStatus:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" :columns="columns" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="agvStatusList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="columns[0].visible" type="index" label="序号" width="60" align="center" />
        <el-table-column v-if="columns[1].visible" label="机器人编号" align="center" prop="robotcode" min-width="120" />
        <el-table-column v-if="columns[2].visible" label="设备编号" align="center" prop="equipNo" min-width="110" />
        <el-table-column v-if="columns[3].visible" label="小车名称" align="center" prop="agvname" min-width="110" />
        <el-table-column v-if="columns[4].visible" label="电量" align="center" prop="battery" width="80" />
        <el-table-column v-if="columns[5].visible" label="排除状态" align="center" prop="excltype" width="100">
          <template #default="scope">
            <dict-tag :options="excl_type" :value="scope.row.excltype" />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[6].visible" label="地图编号" align="center" prop="mapcode" width="100" />
        <el-table-column v-if="columns[7].visible" label="在线状态" align="center" prop="online" width="100">
          <template #default="scope">
            <dict-tag :options="online_status" :value="scope.row.online" />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[8].visible" label="路线" align="center" prop="path" min-width="160" :show-overflow-tooltip="true" />
        <el-table-column v-if="columns[9].visible" label="背货架编号" align="center" prop="podcode" min-width="120" />
        <el-table-column v-if="columns[10].visible" label="背货架方向" align="center" prop="poddir" width="110" />
        <el-table-column v-if="columns[11].visible" label="X坐标" align="center" prop="posx" width="90" />
        <el-table-column v-if="columns[12].visible" label="Y坐标" align="center" prop="posy" width="90" />
        <el-table-column v-if="columns[13].visible" label="机器人方向" align="center" prop="robotdir" width="110" />
        <el-table-column v-if="columns[14].visible" label="机器人IP" align="center" prop="robotip" min-width="130" />
        <el-table-column v-if="columns[15].visible" label="速度" align="center" prop="speed" width="80" />
        <el-table-column v-if="columns[16].visible" label="机器人状态" align="center" prop="status" width="110" />
        <el-table-column v-if="columns[17].visible" label="状态详情" align="center" prop="statusDetail" min-width="150" :show-overflow-tooltip="true" />
        <el-table-column v-if="columns[18].visible" label="暂停状态" align="center" prop="stop" width="100">
          <template #default="scope">
            <dict-tag :options="yes_no_int" :value="scope.row.stop" />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[19].visible" label="状态时间" align="center" prop="timestamp" width="170">
          <template #default="scope">
            <span>{{ parseTime(scope.row.timestamp, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right"  class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['wcs:agvStatus:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['wcs:agvStatus:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改AGV状态对话框 -->
    <el-dialog class="agv-status-edit-dialog" :title="dialog.title" v-model="dialog.visible" width="860px" append-to-body>
      <el-form ref="agvStatusFormRef" class="agv-status-dialog-form" :model="form" :rules="rules" label-width="118px">
        <el-form-item label="设备编号" prop="equipNo">
          <el-input v-model="form.equipNo" placeholder="请输入设备编号" />
        </el-form-item>
        <el-form-item label="小车名称" prop="agvname">
          <el-input v-model="form.agvname" placeholder="请输入小车名称" />
        </el-form-item>
        <el-form-item label="电量" prop="battery">
          <el-input v-model="form.battery" placeholder="请输入电量" />
        </el-form-item>
        <el-form-item label="地图编号" prop="mapcode">
          <el-input v-model="form.mapcode" placeholder="请输入地图编号" />
        </el-form-item>
        <el-form-item label="是否在线" prop="online">
          <el-select v-model="form.online" placeholder="请选择是否在线">
            <el-option v-for="dict in online_status" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item class="agv-status-dialog-span" label="路线" prop="path">
            <el-input v-model="form.path" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="背货架的编号" prop="podcode">
          <el-input v-model="form.podcode" placeholder="请输入背货架的编号" />
        </el-form-item>
        <el-form-item label="背货架的方向" prop="poddir">
          <el-input v-model="form.poddir" placeholder="请输入背货架的方向" />
        </el-form-item>
        <el-form-item label="X" prop="posx">
          <el-input v-model="form.posx" placeholder="请输入X" />
        </el-form-item>
        <el-form-item label="Y" prop="posy">
          <el-input v-model="form.posy" placeholder="请输入Y" />
        </el-form-item>
        <el-form-item label="机器人方向" prop="robotdir">
          <el-input v-model="form.robotdir" placeholder="请输入机器人方向" />
        </el-form-item>
        <el-form-item label="机器人IP" prop="robotip">
          <el-input v-model="form.robotip" placeholder="请输入机器人IP" />
        </el-form-item>
        <el-form-item label="机器人速度" prop="speed">
          <el-input v-model="form.speed" placeholder="请输入机器人速度" />
        </el-form-item>
        <el-form-item label="状态详情" prop="statusDetail">
          <el-input v-model="form.statusDetail" placeholder="请输入状态详情" />
        </el-form-item>
        <el-form-item label="是否暂停" prop="stop">
          <el-radio-group v-model="form.stop">
            <el-radio v-for="dict in yes_no_int" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="时间" prop="timestamp">
          <el-date-picker clearable
            v-model="form.timestamp"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AgvStatus" lang="ts">
import { listAgvStatus, getAgvStatus, delAgvStatus, addAgvStatus, updateAgvStatus } from '@/api/wcs/agvStatus';
import { AgvStatusVO, AgvStatusQuery, AgvStatusForm } from '@/api/wcs/agvStatus/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { excl_type, online_status, yes_no_int } = toRefs<any>(proxy?.useDict('excl_type', 'online_status', 'yes_no_int'));

const agvStatusList = ref<AgvStatusVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const agvStatusFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// AGV状态看板字段较多，用columns控制可见性；机器人编号是现场识别码，因此保留为业务列。
const columns = ref<FieldOption[]>([
  { key: 0, label: '序号', visible: true, children: [] },
  { key: 1, label: '机器人编号', visible: true, children: [] },
  { key: 2, label: '设备编号', visible: true, children: [] },
  { key: 3, label: '小车名称', visible: true, children: [] },
  { key: 4, label: '电量', visible: true, children: [] },
  { key: 5, label: '排除状态', visible: true, children: [] },
  { key: 6, label: '地图编号', visible: true, children: [] },
  { key: 7, label: '在线状态', visible: true, children: [] },
  { key: 8, label: '路线', visible: true, children: [] },
  { key: 9, label: '背货架编号', visible: true, children: [] },
  { key: 10, label: '背货架方向', visible: true, children: [] },
  { key: 11, label: 'X坐标', visible: true, children: [] },
  { key: 12, label: 'Y坐标', visible: true, children: [] },
  { key: 13, label: '机器人方向', visible: true, children: [] },
  { key: 14, label: '机器人IP', visible: true, children: [] },
  { key: 15, label: '速度', visible: true, children: [] },
  { key: 16, label: '机器人状态', visible: true, children: [] },
  { key: 17, label: '状态详情', visible: true, children: [] },
  { key: 18, label: '暂停状态', visible: true, children: [] },
  { key: 19, label: '状态时间', visible: true, children: [] }
]);

const initFormData: AgvStatusForm = {
  robotcode: undefined,
  equipNo: undefined,
  agvname: undefined,
  battery: undefined,
  excltype: undefined,
  mapcode: undefined,
  online: undefined,
  path: undefined,
  podcode: undefined,
  poddir: undefined,
  posx: undefined,
  posy: undefined,
  robotdir: undefined,
  robotip: undefined,
  speed: undefined,
  status: undefined,
  statusDetail: undefined,
  stop: undefined,
  timestamp: undefined,
}
const data = reactive<PageData<AgvStatusForm, AgvStatusQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    equipNo: undefined,
    agvname: undefined,
    battery: undefined,
    excltype: undefined,
    mapcode: undefined,
    online: undefined,
    path: undefined,
    podcode: undefined,
    poddir: undefined,
    posx: undefined,
    posy: undefined,
    robotdir: undefined,
    robotip: undefined,
    speed: undefined,
    status: undefined,
    statusDetail: undefined,
    stop: undefined,
    timestamp: undefined,
    params: {
    }
  },
  rules: {
    robotcode: [
      { required: true, message: "机器人海康编号不能为空", trigger: "blur" }
    ],
    equipNo: [
      { required: true, message: "设备编号不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询AGV状态列表 */
const getList = async () => {
  loading.value = true;
  const res = await listAgvStatus(queryParams.value);
  agvStatusList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  agvStatusFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: AgvStatusVO[]) => {
  ids.value = selection.map(item => item.robotcode);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加AGV状态";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: AgvStatusVO) => {
  reset();
  const _robotcode = row?.robotcode || ids.value[0]
  const res = await getAgvStatus(_robotcode);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改AGV状态";
}

/** 提交按钮 */
const submitForm = () => {
  agvStatusFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.robotcode) {
        await updateAgvStatus(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addAgvStatus(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: AgvStatusVO) => {
  const _robotcodes = row?.robotcode || ids.value;
  await proxy?.$modal.confirm('是否确认删除AGV状态编号为"' + _robotcodes + '"的数据项？').finally(() => loading.value = false);
  await delAgvStatus(_robotcodes);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('wcs/agvStatus/export', {
    ...queryParams.value
  }, `agvStatus_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>

<style scoped lang="scss">
.wcs-agv-status-page {
  /* AGV 状态字段偏监控排障，查询区按设备、位置、状态信息分散排布，减少横向拥挤。 */
  :deep(.agv-status-search-card) {
    border: 1px solid var(--el-border-color-lighter);
    border-radius: 8px;
    box-shadow: 0 8px 22px rgb(15 23 42 / 6%);
  }

  :deep(.agv-status-search-card .el-card__body) {
    padding: 16px 18px 6px;
  }

  :deep(.agv-status-query-form) {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(230px, 1fr));
    column-gap: 16px;
    align-items: start;
  }

  :deep(.agv-status-query-form .el-form-item) {
    margin-right: 0;
    margin-bottom: 12px;
  }

  :deep(.agv-status-query-form .el-form-item__label) {
    justify-content: flex-start;
    width: 104px;
    color: var(--el-text-color-regular);
  }

  :deep(.agv-status-query-form .el-input),
  :deep(.agv-status-query-form .el-select),
  :deep(.agv-status-query-form .el-date-editor) {
    width: 100%;
  }

  :deep(.agv-status-query-actions) {
    grid-column: 1 / -1;
  }

  :deep(.agv-status-query-actions .el-form-item__content) {
    justify-content: flex-end;
    gap: 8px;
  }
}

:global(.agv-status-edit-dialog) {
  width: min(860px, calc(100vw - 32px)) !important;
}

:global(.agv-status-edit-dialog .el-dialog__header) {
  padding: 18px 22px 14px;
  background: linear-gradient(90deg, rgb(37 99 235 / 8%), rgb(20 184 166 / 6%));
}

:global(.agv-status-edit-dialog .el-dialog__body) {
  padding: 20px 24px 8px !important;
}

:global(.agv-status-edit-dialog .agv-status-dialog-form) {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  column-gap: 18px;
}

:global(.agv-status-edit-dialog .el-form-item) {
  margin-bottom: 18px;
}

:global(.agv-status-edit-dialog .agv-status-dialog-span) {
  grid-column: 1 / -1;
}

:global(.agv-status-edit-dialog .el-input),
:global(.agv-status-edit-dialog .el-select),
:global(.agv-status-edit-dialog .el-date-editor) {
  width: 100%;
}

:global(.agv-status-edit-dialog .el-textarea__inner) {
  min-height: 72px !important;
}

:global(.agv-status-edit-dialog .el-dialog__footer) {
  padding: 12px 24px 18px;
  border-top: 1px solid var(--el-border-color-lighter);
}

@media (max-width: 768px) {
  .wcs-agv-status-page {
    :deep(.agv-status-query-form) {
      grid-template-columns: 1fr;
    }
  }

  :global(.agv-status-edit-dialog .agv-status-dialog-form) {
    grid-template-columns: 1fr;
  }
}
</style>
