<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="remark">
              <el-input v-model="queryParams.remark" placeholder="请输入备注" clearable @keyup.enter="handleQuery" />
            </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">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">删除</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="emsBaseLocationJsonList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" width="70">
          <template #default="scope">
            <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="ID" align="center" prop="id" width="100" />
        <el-table-column label="备注" align="center" prop="remark" min-width="180" show-overflow-tooltip />
        <el-table-column label="部门ID" align="center" prop="deptId" min-width="120" />
        <el-table-column label="操作" align="center" fixed="right" width="100">
          <template #default="scope">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>

    <el-dialog v-model="dialog.visible" :title="dialog.title" width="680px" append-to-body>
      <el-form ref="emsBaseLocationJsonFormRef" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" 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 lang="ts" name="VisualEditorList">
import { addEmsBaseLocationJson, delEmsBaseLocationJson, listEmsBaseLocationJson } from '@/api/ems/base/emsBaseLocationJson';
import type { EmsBaseLocationJsonForm, EmsBaseLocationJsonQuery, EmsBaseLocationJsonVO } from '@/api/ems/base/emsBaseLocationJson/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

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

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

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

const initFormData: EmsBaseLocationJsonForm = {
  id: undefined,
  json: '{}',
  remark: undefined,
  deptId: undefined
};

const data = reactive<PageData<EmsBaseLocationJsonForm, EmsBaseLocationJsonQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    json: undefined,
    deptId: undefined,
    params: {}
  },
  rules: {
    json: [{ required: true, message: '请输入JSON内容', trigger: 'blur' }]
  }
});

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

const getList = async () => {
  loading.value = true;
  try {
    const res = await listEmsBaseLocationJson(queryParams.value);
    emsBaseLocationJsonList.value = res.rows || [];
    total.value = res.total || 0;
  } finally {
    loading.value = false;
  }
};

const reset = () => {
  form.value = { ...initFormData };
  emsBaseLocationJsonFormRef.value?.resetFields();
};

const cancel = () => {
  dialog.visible = false;
  reset();
};

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

const handleSelectionChange = (selection: EmsBaseLocationJsonVO[]) => {
  ids.value = selection.map((item) => item.id);
  multiple.value = selection.length === 0;
};

const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '新增前端电路图配置';
};

const submitForm = () => {
  emsBaseLocationJsonFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) return;
    buttonLoading.value = true;
    try {
      await addEmsBaseLocationJson(form.value);
      proxy?.$modal.msgSuccess('新增成功');
      dialog.visible = false;
      await getList();
    } finally {
      buttonLoading.value = false;
    }
  });
};

const handleDelete = async (row?: EmsBaseLocationJsonVO) => {
  const deleteIds = row?.id || ids.value;
  if (!deleteIds || (Array.isArray(deleteIds) && deleteIds.length === 0)) {
    return;
  }
  await proxy?.$modal.confirm(`是否确认删除前端电路图配置编号为"${deleteIds}"的数据项？`);
  await delEmsBaseLocationJson(deleteIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

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