<template>
  <div class="p-2 wcs-plc-address-page">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px] plc-address-search-wrap">
        <el-card class="plc-address-search-card" shadow="hover">
          <el-form ref="queryFormRef" class="plc-address-query-form" :model="queryParams" :inline="true">
            <el-form-item label="楼编号" prop="workshopId">
              <el-input v-model="queryParams.workshopId" placeholder="请输入楼编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="层数" prop="workshopLevel">
              <el-input v-model="queryParams.workshopLevel" placeholder="请输入层数" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="PLC IP地址" prop="plcIp" label-width="100px">
              <el-input v-model="queryParams.plcIp" placeholder="请输入PLC IP地址" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item class="plc-address-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:plcAddress:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['wcs:plcAddress:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['wcs:plcAddress:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['wcs:plcAddress: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="plcAddressList" @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="workshopId" width="100" />
        <el-table-column v-if="columns[2].visible" label="层数" align="center" prop="workshopLevel" width="90" />
        <el-table-column v-if="columns[3].visible" label="PLC IP地址" align="center" prop="plcIp" min-width="150" :show-overflow-tooltip="true" />
        <el-table-column v-if="columns[4].visible" label="创建时间" align="center" prop="createTime" width="170">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[5].visible" label="更新时间" align="center" prop="updateTime" width="170">
          <template #default="scope">
            <span>{{ parseTime(scope.row.updateTime, '{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:plcAddress:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['wcs:plcAddress: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>
    <!-- 添加或修改PLC地址配置对话框 -->
    <el-dialog class="plc-address-edit-dialog" :title="dialog.title" v-model="dialog.visible" width="560px" append-to-body>
      <el-form ref="plcAddressFormRef" class="plc-address-dialog-form" :model="form" :rules="rules" label-width="94px">
        <el-form-item label="楼编号" prop="workshopId">
          <el-input v-model="form.workshopId" placeholder="请输入楼编号" />
        </el-form-item>
        <el-form-item label="层数" prop="workshopLevel">
          <el-input v-model="form.workshopLevel" placeholder="请输入层数" />
        </el-form-item>
        <el-form-item label="PLC IP地址" prop="plcIp">
          <el-input v-model="form.plcIp" placeholder="请输入PLC IP地址" />
        </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="PlcAddress" lang="ts">
import { listPlcAddress, getPlcAddress, delPlcAddress, addPlcAddress, updatePlcAddress } from '@/api/wcs/plcAddress';
import { PlcAddressVO, PlcAddressQuery, PlcAddressForm } from '@/api/wcs/plcAddress/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const plcAddressList = ref<PlcAddressVO[]>([]);
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 plcAddressFormRef = ref<ElFormInstance>();

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

// PLC地址主键只用于修改和删除定位，列表按楼层/IP呈现，更贴近现场接线和调试视角。
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: 'PLC IP地址', visible: true, children: [] },
  { key: 4, label: '创建时间', visible: true, children: [] },
  { key: 5, label: '更新时间', visible: true, children: [] }
]);

const initFormData: PlcAddressForm = {
  id: undefined,
  workshopId: undefined,
  workshopLevel: undefined,
  plcIp: undefined,
}
const data = reactive<PageData<PlcAddressForm, PlcAddressQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    workshopId: undefined,
    workshopLevel: undefined,
    plcIp: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "主键不能为空", trigger: "blur" }
    ],
    workshopId: [
      { required: true, message: "楼编号不能为空", trigger: "blur" }
    ],
    workshopLevel: [
      { required: true, message: "层数不能为空", trigger: "blur" }
    ],
    plcIp: [
      { required: true, message: "PLC IP地址不能为空", trigger: "blur" }
    ],
  }
});

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

/** 查询PLC地址配置列表 */
const getList = async () => {
  loading.value = true;
  const res = await listPlcAddress(queryParams.value);
  plcAddressList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

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

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

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

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加PLC地址配置";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: PlcAddressVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getPlcAddress(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改PLC地址配置";
}

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

/** 删除按钮操作 */
const handleDelete = async (row?: PlcAddressVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除PLC地址配置编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delPlcAddress(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

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

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

<style scoped lang="scss">
.wcs-plc-address-page {
  /* PLC 地址是设备通讯配置，筛选项少但必须规整，方便现场按楼层/IP 快速定位。 */
  :deep(.plc-address-search-card) {
    border: 1px solid var(--el-border-color-lighter);
    border-radius: 8px;
    box-shadow: 0 8px 22px rgb(15 23 42 / 6%);
  }

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

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

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

  :deep(.plc-address-query-form .el-form-item__label) {
    justify-content: flex-start;
    width: 82px;
    color: var(--el-text-color-regular);
  }

  :deep(.plc-address-query-form .el-input) {
    width: 100%;
  }

  :deep(.plc-address-query-actions) {
    grid-column: 1 / -1;
  }

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

:global(.plc-address-edit-dialog) {
  width: min(560px, calc(100vw - 32px)) !important;
}

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

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

:global(.plc-address-edit-dialog .plc-address-dialog-form) {
  padding-right: 4px;
}

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

:global(.plc-address-edit-dialog .el-input) {
  width: 100%;
}

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

@media (max-width: 768px) {
  .wcs-plc-address-page {
    :deep(.plc-address-query-form) {
      grid-template-columns: 1fr;
    }
  }
}
</style>
