<template>
  <el-skeleton :rows="10" v-if="!isLoaded" :throttle="500" />
  <div class="page-manage" v-else>
    <div class="top-buttons">
      <el-button
        type="primary"
        class="ant-btn-success"
        @click="addPage(pageForm)"
        >新增页面</el-button
      >
    </div>
    <el-tree
      :data="pages"
      ref="pageTree"
      class="main-tree"
      :expand-on-click-node="false"
    >
      <template #default="{ data }">
        <div class="custom-tree-node">
          <div class="node-title">
            <el-icon :size="14">
              <my-icon :type="data.icon" v-if="data.icon"></my-icon>
            </el-icon>
            <span class="title-text">{{ data.title }}</span>
          </div>
          <div class="node-buttons">
            <span
              class="icon-wrap"
              v-if="data.type == 0"
              @click.stop="() => setPageCon(data)"
              >设置页面内容</span
            >
            <span class="icon-wrap" @click.stop="() => editPage(data)"
              >修改</span
            >
            <span class="icon-wrap" @click="addPage(pageForm, data)">添加</span>
            <el-popconfirm
              title="Are you sure delete this task?"
              confirmButtonText="Yes"
              cancelButtonText="No"
              @confirm.stop="remove(data)"
            >
              <template #reference>
                <span class="icon-wrap">删除</span>
              </template>
            </el-popconfirm>
          </div>
        </div>
      </template>
    </el-tree>
    <el-dialog
      :title="dialogTitle"
      v-model="dialogAddPage"
      draggable
      lock-scroll
    >
      <el-form
        :model="form"
        :rules="formRule"
        label-width="80px"
        ref="pageForm"
      >
        <el-form-item label="名称" prop="title">
          <el-input v-model="form.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="路径" prop="path">
          <el-input v-model="form.path" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-input v-model="form.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择页面类型">
            <el-option label="模板" :value="0">模板</el-option>
            <el-option label="特型页" :value="1">特型页</el-option>
            <el-option label="菜单" :value="2">菜单</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="菜单展示" prop="type">
          <el-select v-model="form.isTableShow">
            <el-option label="隐藏" :value="0">隐藏</el-option>
            <el-option label="显示" :value="1">显示</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="orderBy">
          <el-input v-model="form.orderBy" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description" placeholder></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogAddPage = false">Cancel</el-button>
          <el-button type="primary" @click="onOk(pageForm)">Confirm</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { getCurrentInstance, onMounted, reactive, ref } from "vue";
import { onBeforeRouteUpdate, useRouter } from "vue-router";
import { ElMessage as $message, ElLoading as $loading } from "element-plus";
import { pageService } from "@/ApiService/pageService";
let pages = ref([]),
  dialogAddPage = ref(false),
  dialogTitle = ref("新增页面"),
  form = reactive({
    id: "",
    title: "",
    path: "",
    icon: "",
    type: "",
    parentId: "",
    orderBy: "",
    description: "",
    isTableShow: "",
  }),
  formRule = reactive({
    title: [{ required: true, message: "请输入页面名称", trigger: "change" }],
  });
const isLoaded = ref(false);
const pageForm = ref();
const vm = getCurrentInstance();
const $router = useRouter();

onMounted(() => {
  fetchBaseData().then((res) => {
    pages.value.push(...res);
    isLoaded.value = true;
  });
});

const fetchUpdateData = () => {
  const loading = $loading.service({
    lock: true,
    text: "Loading",
    background: "rgba(0, 0, 0, 0.1)",
  });
  fetchBaseData().then((res) => {
    pages.value = [];
    pages.value = res;
    loading.close();
  });
};
const addPage = (page, data) => {
  dialogTitle.value = "新增页面";
  page ? page.resetFields() : "";
  for (let i in form) {
    form[i] = "";
  }
  form.parentId = data ? data.id : 0;
  dialogAddPage.value = true;
};
const fetchBaseData = () => {
  return new Promise((resolve) => {
    pageService.queryWebPageOutput().then(async (res) => {
      if (res.code == 0) {
        if (res.data.children && res.data.children.length != 0) {
          const pages = await chargedata(res.data.children);
          resolve(pages);
        }
      }
    });
  });
};
const chargedata = (pages) => {
  return new Promise((resolve) => {
    if (pages == undefined || pages.length == 0) {
      resolve([]);
    }
    pages.map((item, index) => {
      item.level = 1;
      if (item.children && item.children.length != 0) {
        let children = item.children;
        children.map((item2) => {
          item2.level = 2;
          if (item2.children && item2.children.length != 0) {
            item2.children.map((item3) => {
              item3.level = 3;
              item3.noAppend = true;
              return item3;
            });
          }
          return item2;
        });
      }
      return item;
    });
    resolve(pages);
  });
};
const setPageCon = (data) => {
  $router.push({
    name: "pageConManage",
    query: { webId: data.id, title: data.title },
  });
};
const editPage = (data) => {
  dialogTitle.value = "修改页面";
  let {
    title,
    icon,
    path,
    type,
    id,
    orderBy,
    description,
    parentId,
    isTableShow,
  } = data;

  Object.assign(form, {
    title,
    icon,
    path,
    type,
    id,
    orderBy,
    description,
    parentId,
    isTableShow,
  });
  dialogAddPage.value = true;
};
const remove = (data) => {
  pageService.deleteWebpage(data.id).then((res) => {
    if (res.code == 0) {
      setTimeout(() => {
        fetchUpdateData();
      }, 500);
      $message.success("删除成功");
    } else {
      $message.error(res.err);
    }
  });
};
function removeNode(item, treeData) {
  let key = -1;
  console.log(treeData);
  treeData.map((treeItem, treeIndex) => {
    if (treeItem.id == item.id) {
      key = treeIndex;
    }
  });
  if (key == -1) {
    treeData.map((treeItem) => {
      removeNode(item, treeItem.children);
    });
  } else {
    console.log("找到了", key, treeData[key]);
    treeData.splice(key, 1);
  }
  return treeData;
}
const onOk = () => {
  pageForm.value.validate().then(
    (res) => {
      if (form.id) {
        editPageAction();
      } else {
        addPageAction();
      }
    },
    (error) => {
      console.log(error);
    }
  );
};
const editPageAction = () => {
  pageService.updateWebpage(form).then((res) => {
    if (res.code == 0) {
      $message.success("修改成功");
      dialogAddPage.value = false;
      setTimeout(() => {
        fetchUpdateData();
      }, 500);
    } else {
      $message.error(res.err);
    }
  });
};
const addPageAction = () => {
  pageService.addWebpage(form).then((res) => {
    if (res.code == 0) {
      $message.success("添加成功");
      dialogAddPage.value = false;
      setTimeout(() => {
        fetchUpdateData();
      }, 500);
    } else {
      $message.error(res.err);
    }
  });
};
</script>
<style lang="scss" scoped>
.page-manage {
  .top-buttons {
    width: 100%;
    display: flex;
    justify-content: flex-end;
  }
  .main-tree {
    font-size: var(--font-size-base);

    :deep(.el-tree-node) {
      .el-tree-node__content {
        height: 40px;
      }
    }
  }
  :deep(.ant-tree-node-content-wrapper) {
    display: inline-block;
    width: 100%;
  }
  .custom-tree-node {
    width: 100%;
    padding-right: 20px;
    height: 40px;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    align-content: center;
    border-bottom: 1px solid #f2f2f2;
    .node-title,
    .node-buttons {
      display: flex;
      align-items: center;
    }
    .title-text {
      padding: 0 10px;
    }
    .font-strong {
      font-weight: bold;
    }
  }
  .node-buttons {
    display: flex;
    justify-content: space-around;
    span.icon-wrap {
      padding: 0 10px;
    }
  }
}
</style>
