<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="位置编号" prop="locationCode">
              <el-input v-model="queryParams.locationCode" placeholder="请输入位置编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="位置别名" prop="locationAlias">
              <el-input v-model="queryParams.locationAlias" placeholder="请输入位置别名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="位置类型" prop="locationType">
              <el-select v-model="queryParams.locationType" placeholder="请选择位置类型" clearable>
                <el-option v-for="dict in location_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="父级编号，对应本表id" prop="parentId">
              <el-input v-model="queryParams.parentId" placeholder="请输入父级编号，对应本表id" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->
            <el-form-item label="是否标识" prop="isMarked">
              <el-select v-model="queryParams.isMarked" placeholder="请选择是否标识" clearable>
                <el-option v-for="dict in is_marked" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <!-- 以下为审计字段搜索条件，按规范默认不暴露，如需启用请与业务确认后再放开 -->
            <!--
            <el-form-item label="创建人" prop="createdBy">
              <el-input v-model="queryParams.createdBy" placeholder="请输入创建人" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="创建时间" prop="createdAt">
              <el-date-picker clearable
                v-model="queryParams.createdAt"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="选择创建时间"
              />
            </el-form-item>
            <el-form-item label="更新人" prop="updatedBy">
              <el-input v-model="queryParams.updatedBy" placeholder="请输入更新人" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="更新时间" prop="updatedAt">
              <el-date-picker clearable
                v-model="queryParams.updatedAt"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="选择更新时间"
              />
            </el-form-item>
            -->
            <el-form-item>
              <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="['rfid:rfidLocation:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" :search="true" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table
        ref="rfidLocationTableRef"
        v-loading="loading"
        :data="rfidLocationList"
        row-key="id"
        border
        :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <!-- 树形结构页面不使用序号列，仅展示业务字段 -->
        <el-table-column label="位置编号" prop="locationCode" v-if="columns[0].visible" />
        <el-table-column label="位置别名" align="center" prop="locationAlias" v-if="columns[1].visible" />
        <el-table-column label="位置类型" align="center" prop="locationType" v-if="columns[2].visible">
          <template #default="scope">
            <dict-tag :options="location_type" :value="scope.row.locationType"/>
          </template>
        </el-table-column>
        <el-table-column label="是否标识" align="center" prop="isMarked" v-if="columns[3].visible">
          <template #default="scope">
            <dict-tag :options="is_marked" :value="scope.row.isMarked"/>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" v-if="columns[4].visible" />
        <el-table-column label="创建人" align="center" prop="createdBy" v-if="columns[5].visible" />
        <el-table-column label="创建时间" align="center" prop="createdAt" width="180" v-if="columns[6].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="更新人" align="center" prop="updatedBy" v-if="columns[7].visible" />
        <el-table-column label="更新时间" align="center" prop="updatedAt" width="180" v-if="columns[8].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</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="['rfid:rfidLocation:edit']" />
            </el-tooltip>
            <el-tooltip content="新增" placement="top">
              <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['rfid:rfidLocation:add']" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['rfid:rfidLocation:remove']" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加或修改位置信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="rfidLocationFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="父级位置" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="rfidLocationOptions"
            :props="{ value: 'id', label: 'locationAlias', children: 'children' }"
            value-key="id"
            placeholder="请选择父级位置"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="位置编号" prop="locationCode">
          <el-input v-model="form.locationCode" placeholder="请输入位置编号" />
        </el-form-item>
        <el-form-item label="位置别名" prop="locationAlias">
          <el-input v-model="form.locationAlias" placeholder="请输入位置别名" />
        </el-form-item>
        <el-form-item label="位置类型" prop="locationType">
          <el-select v-model="form.locationType" placeholder="请选择位置类型">
            <el-option
              v-for="dict in location_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否标识" prop="isMarked">
          <el-radio-group v-model="form.isMarked">
            <el-radio
              v-for="dict in is_marked"
              :key="dict.value"
              :value="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <!-- 以下为审计字段输入，按规范由后端自动维护，前端默认不提供编辑入口，如需启用请与业务确认后再放开 -->
        <!--
        <el-form-item label="创建人" prop="createdBy">
          <el-input v-model="form.createdBy" placeholder="请输入创建人" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createdAt">
          <el-date-picker clearable
            v-model="form.createdAt"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择创建时间"
          />
        </el-form-item>
        <el-form-item label="更新人" prop="updatedBy">
          <el-input v-model="form.updatedBy" placeholder="请输入更新人" />
        </el-form-item>
        <el-form-item label="更新时间" prop="updatedAt"">
          <el-date-picker clearable
            v-model="form.updatedAt"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择更新时间"
          />
        </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="RfidLocation" lang="ts">
import { listRfidLocation, getRfidLocation, delRfidLocation, addRfidLocation, updateRfidLocation, getRfidLocationList } from "@/api/rfid/rfidLocation";
import { RfidLocationVO, RfidLocationQuery, RfidLocationForm } from '@/api/rfid/rfidLocation/types';

type RfidLocationOption = {
  id: number;
  locationAlias: string;
  children?: RfidLocationOption[];
}

const { proxy } = getCurrentInstance() as ComponentInternalInstance;;

const { location_type, is_marked } = toRefs<any>(proxy?.useDict('location_type', 'is_marked'));

const rfidLocationList = ref<RfidLocationVO[]>([]);
const rfidLocationOptions = ref<RfidLocationOption[]>([]);
const buttonLoading = ref(false);
const showSearch = ref(true);

// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: '位置编号', visible: true },
  { key: 1, label: '位置别名', visible: true },
  { key: 2, label: '位置类型', visible: true },
  { key: 3, label: '是否标识', visible: false },
  { key: 4, label: '备注', visible: false },
  { key: 5, label: '创建人', visible: false },
  { key: 6, label: '创建时间', visible: false },
  { key: 7, label: '更新人', visible: false },
  { key: 8, label: '更新时间', visible: false }
]);
const isExpandAll = ref(true);
const loading = ref(false);

const queryFormRef = ref<ElFormInstance>();
const rfidLocationFormRef = ref<ElFormInstance>();
const rfidLocationTableRef = ref<ElTableInstance>()

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


const initFormData: RfidLocationForm = {
    id: undefined,
    locationCode: undefined,
    locationAlias: undefined,
    locationType: undefined,
    parentId: undefined,
    isMarked: '1',
    remark: undefined,
    createdBy: undefined,
    createdAt: undefined,
    updatedBy: undefined,
    updatedAt: undefined
}

const data = reactive<PageData<RfidLocationForm, RfidLocationQuery>>({
  form: {...initFormData},
  queryParams: {
    locationCode: undefined,
    locationAlias: undefined,
    locationType: undefined,
    parentId: undefined,
    isMarked: undefined,
    createdBy: undefined,
    createdAt: undefined,
    updatedBy: undefined,
    updatedAt: undefined,
    params: {
    }
  },
  rules: {
    locationCode: [
      { required: true, message: "位置编号不能为空", trigger: "blur" }
    ],
    isMarked: [
      { required: true, message: "是否标识不能为空", trigger: "change" }
    ],
  }
});

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

/** 查询位置信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listRfidLocation(queryParams.value);
  const data = proxy?.handleTree<RfidLocationVO>(res.data, "id", "parentId");
  if (data) {
    rfidLocationList.value = data;
    loading.value = false;
  }
}

/** 查询位置信息下拉树结构，使用 getRfidLocationList 获取全量数据 */
const getTreeselect = async () => {
	const res = await getRfidLocationList();
	rfidLocationOptions.value = [];
	const data: RfidLocationOption = { id: 0, locationAlias: '顶级节点', children: [] };
	data.children = proxy?.handleTree<RfidLocationOption>(res.data, "id", "parentId");
	rfidLocationOptions.value.push(data);
}

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

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

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
}

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

/** 新增按钮操作 */
const handleAdd = (row?: RfidLocationVO) => {
  reset();
  getTreeselect();
  if (row != null && row.id) {
    form.value.parentId = row.id;
  } else {
    form.value.parentId = 0;
  }
  dialog.visible = true;
  dialog.title = "添加位置信息";
}

/** 展开/折叠操作 */
const handleToggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value;
  toggleExpandAll(rfidLocationList.value, isExpandAll.value)
}

/** 展开/折叠操作 */
const toggleExpandAll = (data: RfidLocationVO[], status: boolean) => {
  data.forEach((item) => {
    rfidLocationTableRef.value?.toggleRowExpansion(item, status)
    if (item.children && item.children.length > 0) toggleExpandAll(item.children, status)
  })
}

/** 修改按钮操作 */
const handleUpdate = async (row: RfidLocationVO) => {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentId = row.parentId;
  }
  const res = await getRfidLocation(row.id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改位置信息";
}

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

/** 删除按钮操作 */
const handleDelete = async (row: RfidLocationVO) => {
  try {
    await proxy?.$modal.confirm('是否确认删除位置信息编号为"' + row.id + '"的数据项？');
    loading.value = true;
    await delRfidLocation(row.id);
    proxy?.$modal.msgSuccess("删除成功");
    await getList();
  } finally {
    loading.value = false;
  }
}

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