<template>
  <div class="p-2">
    <div class="head-card">
      <el-card shadow="hover">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <el-form-item label="页面名称">
            <el-input v-model="queryParams.title" 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>

    <el-card shadow="hover">
      <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-row>
      </template>

      <el-table v-loading="loading" border :data="dataList">
        <el-table-column label="页面名称" align="center" prop="title" :show-overflow-tooltip="true" />
        <el-table-column label="页面类型" align="center" :show-overflow-tooltip="true">
          <template #default="scope">
            {{
              scope.row.type == 1
                ? '首页'
                : scope.row.type == 2
                  ? '个人中心'
                  : scope.row.type == 3
                    ? '商品详情'
                    : scope.row.type == 4
                      ? '分类'
                      : scope.row.type == 5
                        ? '自定义'
                        : ''
            }}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" :show-overflow-tooltip="true">
          <template #default="scope">
            {{ scope.row.dictType }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="160" 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)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </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="dialogVisible" title="创建新页面" width="1122px">
      <div class="card-container">
        <div
          v-for="(item, index) in dialogList"
          @click="onDialog(item)"
          :key="index"
          class="card-item"
          :class="{ active: dialogType === item.diyType }"
        >
          <div class="card-image">
            <img :src="item.img" alt="图片" />
          </div>
          <div class="card-text">{{ item.title }}</div>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addEvent()">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { diyList, delDiy, template, miniList } from '@/api/diy/index';
import { FormInstance } from 'element-plus';
import diy1 from '@/assets/images/diy/diy1.jpg';
import diy2 from '@/assets/images/diy/diy2.jpg';
import diy3 from '@/assets/images/diy/diy3.jpg';
import diy4 from '@/assets/images/diy/diy4.png';
import diy5 from '@/assets/images/diy/diy5.jpg';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const dataList = ref<any[]>([]);
const loading = ref(true);
const total = ref(0);
const dialogType = ref();
const dialogList = ref<any>([
  // { title: '首页', diyType: 1, img: diy1 },
  // { title: '个人中心', diyType: 3, img: diy3 },
  // { title: '商品详情', diyType: 4, img: diy4 },
  // { title: '分类', diyType: 4, img: diy2 },
  { title: '自定义页面', diyType: 5, img: diy5 }
]);

const pageType: any = reactive({}); // 页面类型
const dialogVisible = ref(false);
const formRef = ref<FormInstance>();

miniList({ pageNum: 1, pageSize: 10 }).then((res) => {
  if (res.code == 200) {
    res.rows.forEach((item: any) => {
      const obj = {
        title: item.name,
        diyType: item.type,
        img: item.type == 1 ? diy1 : item.type == 2 ? diy3 : diy4,
        templateId: item.id
      };
      // dialogList.value.unshift(obj);
      dialogList.value.push(obj);
    });
  }
});

// 添加自定义页面
const formData = reactive({
  title: '',
  type: ''
});
// 表单验证规则
const formRules = computed(() => {
  return {
    title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
    type: [{ required: true, message: '请选择页面类型', trigger: 'blur' }]
  };
});

const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  title: '',
  addon_name: '',
  type: ''
});

/** 查询字典类型列表 */
const getList = () => {
  loading.value = true;
  diyList(queryParams.value).then((res) => {
    if (res.code == 200) {
      dataList.value = res.rows;
      total.value = res.total;
      loading.value = false;
    }
  });
};
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  handleQuery();
};
/** 新增按钮操作 */
const router = useRouter();
const handleAdd = () => {
  dialogVisible.value = true;
  // const url = router.resolve({
  //   path: '/diy/edit',
  //   query: {}
  // });
  // window.open(url.href);
};
/** 修改按钮操作 */
const handleUpdate = async (row?: any) => {
  const query = { id: row.id };
  const url = router.resolve({
    path: '/diy/edit',
    query
  });
  window.open(url.href);
};
/** 删除按钮操作 */
const handleDelete = async (row?: any) => {
  await proxy?.$modal.confirm('是否确认删除"' + row.name + '"的diy数据项？').finally(() => (loading.value = false));
  await delDiy(row.id);
  proxy?.$modal.msgSuccess('删除成功');
  getList();
};

const getTemplate = () => {
  template({ mode: '', addon: '' }).then((res) => {
    if (res.code == 200) {
      for (const key in pageType) {
        delete pageType[key];
      }

      for (const key in res.data) {
        pageType[key] = res.data[key];
      }
    }
  });
};

const addEvent = () => {
  const obj = dialogList.value.find((item: any) => item.diyType == dialogType.value);
  const query = { type: obj.diyType, title: obj.title, templateId: obj.templateId ? obj.templateId : '' };
  const url = router.resolve({
    path: '/diy/edit',
    query
  });
  window.open(url.href);
  dialogVisible.value = false;
};

// const addEvent = async (formEl: FormInstance | undefined) => {
//   if (!formEl) return;

//   await formEl.validate(async (valid) => {
//     if (valid) {
//       const query = { type: formData.type, title: formData.title };
//       const url = router.resolve({
//         path: '/diy/edit',
//         query
//       });
//       window.open(url.href);
//       dialogVisible.value = false;
//       formData.title = '';
//       formData.type = '';
//     }
//   });
// };

const onDialog = (item: any) => {
  dialogType.value = item.diyType;
};

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

<style lang="scss" scoped>
.head-card {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 0px !important;
  }
}

.card-container {
  display: flex;
  flex-wrap: wrap;
  gap: 0 15px;
  width: 1060px;
  .card-item {
    width: 200px;
    height: 390px;
    padding: 5px;
    border-radius: 8px;
    border: 1px solid #e5e7eb;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;

    &:hover {
      border-color: #b0b0b0;
    }

    &.active {
      border-color: #409eff;
      background-color: #ecf5ff;
    }
    .card-image {
      width: 190px;
      height: 340px;
      overflow: hidden;
      border-radius: 4px;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
    .card-text {
      width: 190px;
      bottom: 0;
      left: 0;
      font-size: 14px;
      color: #333;
      text-align: center;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      text-align: center;
      margin-top: 20px;
    }
  }
}
</style>
