<script setup lang="ts">
import Card from "./components/Card.vue";
import { getCardList } from "@/api/list";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import { ref, onMounted, nextTick, markRaw } from "vue";
import dialogForm from "./components/DialogForm.vue";
import { useRouter } from "vue-router";
import { isString } from "@pureadmin/utils";
import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
// import { useRenderIcon } from "@/components/ReIcon/src/hooks";
// import Search from "@iconify-icons/ep/search";
// import AddFill from "@iconify-icons/ri/add-circle-line";
import emptyPic from "@/assets/static/project_empty.png";
import { QuestionFilled } from "@element-plus/icons-vue";

defineOptions({
  name: "MyAlgorithm"
});

const svg = `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `;

const INITIAL_DATA = {
  name: "",
  status: "",
  description: "",
  type: "",
  mark: "",
  leader: "",
  phone: ""
};

const pagination = ref({ current: 1, pageSize: 12, total: 0 });

const productList = ref([]);
const dataLoading = ref(true);

const getCardListData = async () => {
  try {
    const { data } = await getCardList();
    productList.value = data.list;
    pagination.value = {
      ...pagination.value,
      total: data.list.length
    };
  } catch (e) {
    console.log(e);
  } finally {
    setTimeout(() => {
      dataLoading.value = false;
    }, 500);
  }
};

onMounted(() => {
  getCardListData();
});

const formDialogVisible = ref(false);
const formData = ref({ ...INITIAL_DATA });
const searchValue = ref("");

const onPageSizeChange = (size: number) => {
  pagination.value.pageSize = size;
  pagination.value.current = 1;
};
const onCurrentChange = (current: number) => {
  pagination.value.current = current;
};
const handleDeleteItem = product => {
  ElMessageBox.confirm(
    product ? `确定删除这个项目吗，删除后将无法找回，请谨慎操作` : "",
    "确定删除这个项目吗？",
    {
      showClose: false,
      type: "warning",
      icon: markRaw(QuestionFilled),
      customClass: "msg-box-style",
      confirmButtonClass: "btn-custom-confirm",
      cancelButtonClass: "btn-custom-cancel"
    }
  )
    .then(() => {
      productList.value.forEach((item, index) => {
        console.log(item.type);
        if (item.type == product.type) {
          productList.value.splice(index, 1);
        }
      });
      pagination.value.total = productList.value.length;
      message("删除成功", { type: "success" });
    })
    .catch(() => {});
};
const handleManageProduct = product => {
  formDialogVisible.value = true;
  nextTick(() => {
    formData.value = { ...product, status: product?.isSetup ? "1" : "0" };
  });
};
const router = useRouter();
const handleProductDetail = product => {
  Object.keys(product).forEach(param => {
    if (!isString(product[param])) {
      product[param] = product[param].toString();
    }
  });
  // 保存信息到标签页
  useMultiTagsStoreHook().handleTags("push", {
    path: `/project/details`,
    name: "ProjectDetails",
    query: product,
    meta: {
      title: `项目详情`,
      showLink: false
    }
  });
  router.push({ name: "ProjectDetails", query: product });
};
const addProject = product => {
  console.log(product.value);

  if (!product.value.type) {
    const data = product.value;
    data.type = 1;
    productList.value.unshift(data);
  } else {
    productList.value.forEach((item, index) => {
      if (item.type == product.value.type) {
        Object.assign(productList.value[index], product.value);
      }
    });
    // Object.assign(productList.value, product.value);
  }
  pagination.value.total = productList.value.length;
};
</script>

<template>
  <div class="main">
    <div class="w-full flex justify-between mb-4">
      <h2>我的算法库</h2>
    </div>
    <div
      v-loading="dataLoading"
      :element-loading-svg="svg"
      element-loading-svg-view-box="-10, -10, 50, 50"
    >
      <el-card
        class="box-card"
        :body-style="{
          height: '462px',
          display: 'flex',
          'justify-content': 'center',
          'align-items': 'center'
        }"
        v-show="
          productList
            .slice(
              pagination.pageSize * (pagination.current - 1),
              pagination.pageSize * pagination.current
            )
            .filter(v =>
              v.name.toLowerCase().includes(searchValue.toLowerCase())
            ).length === 0
        "
      >
        <el-empty description="暂未添加任何项目" :image="emptyPic">
          <el-button
            type="primary"
            color="#1C0D82"
            @click="formDialogVisible = true"
          >
            新建项目
          </el-button>
        </el-empty>
      </el-card>
      <template v-if="pagination.total > 0">
        <el-card shadow="never">
          <el-row :gutter="16">
            <el-col
              v-for="(product, index) in productList
                .slice(
                  pagination.pageSize * (pagination.current - 1),
                  pagination.pageSize * pagination.current
                )
                .filter(v =>
                  v.name.toLowerCase().includes(searchValue.toLowerCase())
                )"
              :key="index"
              :xs="24"
              :sm="12"
              :md="8"
              :lg="6"
              :xl="6"
            >
              <Card
                :product="product"
                @delete-item="handleDeleteItem"
                @manage-product="handleManageProduct"
                @product-detail="handleProductDetail"
              />
            </el-col>
          </el-row>
          <el-pagination
            v-if="false"
            class="justify-end"
            v-model:currentPage="pagination.current"
            :page-size="pagination.pageSize"
            :total="pagination.total"
            :page-sizes="[12, 24, 36]"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="onPageSizeChange"
            @current-change="onCurrentChange"
          />
        </el-card>
      </template>
    </div>
    <dialogForm
      v-model:visible="formDialogVisible"
      :data="formData"
      @submit-form="addProject"
    />
  </div>
</template>
<style lang="scss">
// :deep(.el-dialog, .is-draggable, .el-dialog__header) {
//   border-bottom: 1px solid #eee !important;
// }
.msg-box-style {
  // --el-messagebox-width: 580px;
  // height: 184px;
  .btn-custom-cancel:hover {
    color: #fff;
    // color: skyblue;
    background-color: #1c0d82;
    opacity: 0.5;
  }

  .btn-custom-confirm {
    color: #fff;
    background-color: #1c0d82;
    border: #1c0d82;

    &:hover {
      color: #fff;
      // color: skyblue;
      background-color: #1c0d82;
      opacity: 0.5;
    }
  }
}
</style>
