<template>
  <div class="gen-container">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="search-wrapper">
        <el-card shadow="hover" class="search-card">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="类型名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入类型名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-input v-model="queryParams.sort" placeholder="请输入排序" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">搜索</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover" class="table-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span class="header-title">服务分类列表</span>
          </div>
          <div class="header-right">
            <el-button type="primary" size="small" @click="handleAdd"
              v-hasPermi="['service:classification:add']">新增</el-button>
            <el-button type="danger" size="small" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['service:classification:remove']">删除</el-button>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
          </div>
        </div>
      </template>

      <el-table v-loading="loading" stripe :data="classificationList" @selection-change="handleSelectionChange"
        class="gen-table">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" prop="id" v-if="false" />
        <el-table-column label="类型名称" align="center" prop="name" />
        <el-table-column label="排序" align="center" prop="sort" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="160" fixed="right">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handleUpdate(scope.row)"
              v-hasPermi="['service:classification:edit']">编辑</el-button>
            <el-button link type="danger" size="small" @click="handleDelete(scope.row)"
              v-hasPermi="['service:classification:remove']">删除</el-button>
          </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>
    <!-- 添加或修改服务分类对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="classificationFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="类型名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入类型名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" 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="Classification" lang="ts">
import { listClassification, getClassification, delClassification, addClassification, updateClassification } from '@/api/service/classification';
import { ClassificationVO, ClassificationQuery, ClassificationForm } from '@/api/service/classification/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const classificationList = ref<ClassificationVO[]>([]);
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 classificationFormRef = ref<ElFormInstance>();

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

const initFormData: ClassificationForm = {
  id: undefined,
  name: undefined,
  sort: undefined,
  remark: undefined,
}
const data = reactive<PageData<ClassificationForm, ClassificationQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    sort: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "序号不能为空", trigger: "blur" }
    ],
    name: [
      { required: true, message: "类型名称不能为空", trigger: "blur" }
    ],
    sort: [
      { required: true, message: "排序不能为空", trigger: "blur" }
    ],
  }
});

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

/** 查询服务分类列表 */
const getList = async () => {
  loading.value = true;
  const res = await listClassification(queryParams.value);
  classificationList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

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

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

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

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加服务分类";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: ClassificationVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getClassification(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改服务分类";
}

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

/** 删除按钮操作 */
const handleDelete = async (row?: ClassificationVO) => {
  const _ids = row?.id || ids.value;
  let confirmMsg = '';

  if (row) {
    confirmMsg = `
      <div style="text-align: left;">
        <p style="margin-bottom: 12px;">是否确认删除以下服务分类？</p>
        <div style="padding: 8px 0; line-height: 1.8;">
          <div>名称：${row.name || '-'}</div>
          <div>排序：${row.sort ?? '-'}</div>
          <div>备注：${row.remark || '-'}</div>
        </div>
      </div>
    `;
  } else {
    const selectedItems = classificationList.value.filter(item => ids.value.includes(item.id));
    if (selectedItems.length === 1) {
      const item = selectedItems[0];
      confirmMsg = `
        <div style="text-align: left;">
          <p style="margin-bottom: 12px;">是否确认删除以下服务分类？</p>
          <div style="padding: 8px 0; line-height: 1.8;">
            <div>名称：${item.name || '-'}</div>
            <div>排序：${item.sort ?? '-'}</div>
            <div>备注：${item.remark || '-'}</div>
          </div>
        </div>
      `;
    } else {
      confirmMsg = `是否确认删除选中的 ${selectedItems.length} 条服务分类数据？`;
    }
  }

  await ElMessageBox.confirm(confirmMsg, '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    dangerouslyUseHTMLString: true
  }).finally(() => loading.value = false);
  await delClassification(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

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

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

<style lang="scss" scoped>
.gen-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.search-wrapper {
  margin-bottom: 20px;
}

.search-card {
  :deep(.el-card__body) {
    padding: 20px;
  }
}

.table-card {
  :deep(.el-card__header) {
    padding: 16px 20px;
    border-bottom: 1px solid #f0f0f0;
  }

  :deep(.el-card__body) {
    padding: 20px;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .header-left {
    .header-title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }
  }

  .header-right {
    display: flex;
    gap: 8px;
    align-items: center;
    flex-wrap: nowrap;
  }
}

.gen-table {
  :deep(.el-table__header) {
    th {
      background-color: #f5f7fa;
      color: #606266;
      font-weight: 600;
      border-bottom: 1px solid #ebeef5;
    }
  }

  :deep(.el-table__body) {
    td {
      border-bottom: 1px solid #ebeef5;
    }
  }

  :deep(.el-table__row) {
    &:last-child td {
      border-bottom: none;
    }
  }
}
</style>
