<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="cateId">
              <el-input v-model="queryParams.cateId" placeholder="请输入分类id" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->
            <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="pageType">
              <el-select v-model="queryParams.pageType" placeholder="页面类型" clearable>
                <el-option label="pc端" :value="'1'" />
                <el-option label="小程序端" :value="'2'" />
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="添加时间" prop="createTime">
              <el-date-picker clearable v-model="queryParams.createTime" 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">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="pageLinkList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="ID" align="center" prop="id" v-if="true" />
        <el-table-column label="所属分类" align="center" prop="cateId">
          <template #default="scope">
            {{ cateIdToName.get(scope.row.cateId) || '-' }}
          </template>
        </el-table-column>
        <!-- <el-table-column label="分组" align="center" prop="type" /> -->
        <el-table-column label="页面名称" align="center" prop="name" />
        <el-table-column label="标识key" align="center" prop="linkKey" />
        <el-table-column label="链接" align="center" prop="url" />
        <el-table-column label="来源" align="center" prop="isCustom">
          <template #default="scope">
            <el-tag v-if="scope.row.isCustom === 1" type="success">自定义</el-tag>
            <el-tag v-else>系统预设</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 0" type="success">启用</el-tag>
            <el-tag v-else>禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" prop="sort" />
        <el-table-column prop="pageType" align="center" label="页面类型" width="120">
          <template #default="scope">
            <el-tag> {{ scope.row.pageType == '1' ? 'pc端' : '小程序' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="添加时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="商户类型" align="center" prop="isMer">
          <template #default="scope">
            <el-tag v-if="scope.row.isMer === 1" type="success">商户</el-tag>
            <el-tag v-else>平台</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</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="pageLinkFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属分类" prop="cateId">
          <el-tree-select
            v-model="form.cateId"
            :data="categoryOptions"
            :props="{ value: 'id', label: 'name', children: 'children' } as any"
            value-key="id"
            placeholder="选择分类"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="页面名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入页面名称" />
        </el-form-item>
        <el-form-item label="标识key" prop="key">
          <el-input v-model="form.linkKey" placeholder="请输入标识key" />
        </el-form-item>
        <el-form-item label="链接" prop="url">
          <el-input v-model="form.url" placeholder="请输入链接" />
        </el-form-item>
        <el-form-item label="来源" prop="isCustom">
          <el-radio-group v-model="form.isCustom">
            <el-radio :label="1">自定义</el-radio>
            <el-radio :label="0">系统预设</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商户类型" prop="isMer">
          <el-radio-group v-model="form.isMer">
            <el-radio :label="0">平台</el-radio>
            <el-radio :label="1">商户</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="页面类型" prop="pageType">
          <el-radio-group v-model="form.pageType">
            <el-radio :label="'1'">pc端</el-radio>
            <el-radio :label="'2'">小程序</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" placeholder="请输入排序" :min="1" />
        </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="PageLink" lang="ts">
import { listPageLink, getPageLink, delPageLink, addPageLink, updatePageLink } from '@/api/mall/pageLink/api';
import { PageLinkVO, PageLinkQuery, PageLinkForm } from '@/api/mall/pageLink/types';
import { getCategoryTree } from '@/api/mall/pageCategory/api';
interface CategoryOptionsType {
  id: number | string;
  name: string;
  children: CategoryOptionsType[];
}

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const pageLinkList = ref<PageLinkVO[]>([]);
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 categoryOptions = ref<CategoryOptionsType[]>([]);

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

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

const cateIdToName = computed(() => {
  const map = new Map<number, string>();
  const buildMap = (items: CategoryOptionsType[]) => {
    items.forEach((item) => {
      map.set(Number(item.id), item.name);
      if (item.children && item.children.length > 0) {
        buildMap(item.children);
      }
    });
  };
  buildMap(categoryOptions.value);
  return map;
});

const initFormData: PageLinkForm = {
  id: undefined,
  cateId: undefined,
  type: undefined,
  name: undefined,
  linkKey: undefined,
  url: undefined,
  isCustom: 1,
  status: 1,
  sort: 100,
  createTime: undefined,
  isMer: 0
};
const data = reactive<PageData<PageLinkForm, PageLinkQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    cateId: undefined,
    name: undefined,
    createTime: undefined,
    pageType: '1',
    params: {}
  },
  rules: {}
});

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

/** 获取页面分类数据 */
const getCategorys = async () => {
  try {
    // 获取分类树形结构用于选择器
    const res = await getCategoryTree(queryParams.value.pageType);
    if (res.data) {
      categoryOptions.value = res.data as CategoryOptionsType[];
    }
  } catch (error) {
    console.error('获取分类树失败:', error);
    proxy?.$modal.msgError('获取分类树失败');
  }
};

/** 查询页面链接列表 */
const getList = async () => {
  loading.value = true;
  const res = await listPageLink(queryParams.value);
  pageLinkList.value = res.rows;
  total.value = res.total;
  loading.value = false;
  getCategorys();
};

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

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

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: PageLinkVO[]) => {
  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?: PageLinkVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getPageLink(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改页面链接';
};

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

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

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'mall/pageLink/export',
    {
      ...queryParams.value
    },
    `组件页面链接_${new Date().getTime()}.xlsx`
  );
};

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