<template>
  <div class="todo-list">
    <Header />

    <div class="content-wrapper mt-15 max-w-[1200px] mx-auto">
      <div class="flex gap-5 items-center mb-4 bg-[#fff] py-2 pl-4 rounded-sm">
        <p class="flex items-center">
          <Icon
            icon="mynaui:arrow-up-down"
            class="icon pr-1 h-6 w-6"
            color="#014099"
          />CRM待办任务列表
        </p>

        <el-button
          type="primary"
          round
          size="small"
          color="#02409b"
          @click="router.back()"
          ><Icon
            icon="mynaui:corner-up-left"
            class="icon pr-1"
            width="20"
            height="20"
          />返回</el-button
        >
      </div>
      <div v-loading="loading" class="table-wrapper">
        <el-table
          v-loading="loading"
          :data="oaTasks"
          style="width: 100%"
          height="70vh"
          stripe
          element-loading-text="加载中..."
          :empty-text="loading ? '' : '暂无数据'"
          :header-cell-style="{
            backgroundColor: '#e9f7ff',
            color: 'black',
            fontWeight: '400',
          }"
          :cell-style="{
            color: 'black',
          }"
        >
          <el-table-column
            type="index"
            label="序号"
            width="80"
            fixed="left"
            align="center"
          />
          <el-table-column
            prop="instTitle"
            label="流程标题"
            min-width="220"
            fixed="left"
            align="center"
          />
          <el-table-column
            prop="entityTypeId"
            label="业务类型"
            width="140"
            align="center"
          />
          <el-table-column
            prop="priority"
            label="优先级别"
            width="100"
            align="center"
          >
            <template #default="scope">
              <el-tag v-if="scope.row.priority == 50" type="warning" size="mini"
                >一般</el-tag
              >
              <el-tag
                v-else-if="scope.row.priority === 90"
                type="danger"
                size="mini"
              >
                紧急
              </el-tag>

              <span v-else></span>
            </template>
          </el-table-column>

          <el-table-column
            prop="createAt"
            label="任务提交时间"
            width="180"
            align="center"
          >
            <template #default="scope">
              {{ timestampToDateTime(scope.row.submitAt) }}
            </template>
          </el-table-column>

          <el-table-column
            prop="createAt"
            label="任务创建时间"
            width="180"
            align="center"
          >
            <template #default="scope">
              {{ timestampToDateTime(scope.row.createdAt) }}
            </template>
          </el-table-column>

          <el-table-column
            prop="endAt"
            label="任务完成时间"
            width="180"
            align="center"
          >
            <template #default="scope">
              {{ timestampToDateTime(scope.row.endAt) }}
            </template>
          </el-table-column>

          <el-table-column
            prop="userName"
            label="任务提交人"
            width="120"
            align="center"
          />

          <el-table-column
            prop="status"
            label="任务状态"
            width="100"
            align="center"
          >
            <template #default="scope">
              <el-tag v-if="scope.row.status === 1" type="info" size="mini"
                >待提交</el-tag
              >
              <el-tag
                v-else-if="scope.row.status === 2"
                type="info"
                size="mini"
              >
                待重新提交
              </el-tag>

              <el-tag
                v-else-if="scope.row.status === 3"
                type="info"
                size="mini"
              >
                待提交到退回节点
              </el-tag>

              <el-tag
                v-else-if="scope.row.status === 4"
                type="primary"
                size="mini"
              >
                已提交
              </el-tag>

              <el-tag
                v-else-if="scope.row.status === 5"
                type="info"
                size="mini"
              >
                待办理
              </el-tag>

              <el-tag
                v-else-if="scope.row.status === 6"
                type="success"
                size="mini"
              >
                已同意
              </el-tag>

              <el-tag
                v-else-if="scope.row.status === 7"
                type="danger"
                size="mini"
              >
                已拒绝
              </el-tag>

              <el-tag
                v-else-if="scope.row.status === 8"
                type="danger"
                size="mini"
              >
                已转办
              </el-tag>

              <el-tag
                v-else-if="scope.row.status === 9"
                type="primary"
                size="mini"
              >
                已抄送
              </el-tag>

              <el-tag
                v-else-if="scope.row.status === 10"
                type="warning"
                size="mini"
              >
                加签挂起
              </el-tag>

              <el-tag
                v-else-if="scope.row.status === 11"
                type="warning"
                size="mini"
              >
                任务挂起
              </el-tag>

              <el-tag
                v-else-if="scope.row.status === 12"
                type="warning"
                size="mini"
              >
                已收回
              </el-tag>

              <el-tag
                v-else-if="scope.row.status === 13"
                type="warning"
                size="mini"
              >
                已移交
              </el-tag>

              <el-tag
                v-else-if="scope.row.status === 14"
                type="warning"
                size="mini"
              >
                已委托
              </el-tag>

              <el-tag
                v-else-if="scope.row.status === 99"
                type="success"
                size="mini"
              >
                无需办理
              </el-tag>
              <span v-else></span>
            </template>
          </el-table-column>

          <el-table-column
            label="操作"
            width="120"
            fixed="right"
            align="center"
          >
            <template #default="scope">
              <span
                class="text-[#02409b] cursor-pointer"
                @click="goBackPage(scope.row)"
                >处理</span
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          background
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>

    <Footer />
  </div>
</template>

<script setup>
import Header from "@components/home/header.vue";
import { ref, onMounted } from "vue";
import { getCRMTasks, ssoLogin } from "@/api/user";
import { useUserStore } from "@/stores/useUserStore";
import { Icon } from "@iconify/vue";
import router from "@/router";
const userStore = useUserStore();

const oaTasks = ref([]);
const loading = ref(false);

const pagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});

const handleCurrentChange = async (page) => {
  pagination.value.pageNum = page;
  loading.value = true;
  try {
    const res = await getCRMTasks({
      id: userStore.getUser.username,
      type: "pending",
      pageNum: pagination.value.pageNum,
      pageSize: pagination.value.pageSize,
    });
    oaTasks.value = res.todoList;
    pagination.value.total = res.todoCount;
  } finally {
    loading.value = false;
  }
};

const handleSizeChange = async (size) => {
  pagination.value.pageSize = size;
  pagination.value.pageNum = 1;
  loading.value = true;
  try {
    const res = await getCRMTasks({
      id: userStore.getUser.username,
      type: "pending",
      pageNum: pagination.value.pageNum,
      pageSize: pagination.value.pageSize,
    });
    oaTasks.value = res.todoList;
    pagination.value.total = res.todoCount;
  } finally {
    loading.value = false;
  }
};

const goBackPage = async (row) => {
  // const res = await ssoLogin({
  //   username: userStore.getUser.username,
  // });
  // if (res) {
  //   const newTab = window.open("", "_blank");
  //   newTab.location.href =
  //     "https://yfoa.keruioil.com/wui/index.html" +
  //     "?ssoToken=" +
  //     res +
  //     "#/main";
  //   setTimeout(function () {
  //     newTab.location.href = `https://yfoa.keruioil.com/spa/workflow/static4form/index.html?_rdm=1776063595284#/main/workflow/req?requestid=${row.requestId}`;
  //   }, 50);
  // }
};

function timestampToDateTime(timestamp) {
  // 兼容 10位(秒) / 13位(毫秒)
  const len = String(timestamp).length;
  const date = new Date(Number(timestamp) * (len === 10 ? 1000 : 1));

  // 年
  const year = date.getFullYear();
  // 月（0~11 → +1）
  const month = String(date.getMonth() + 1).padStart(2, "0");
  // 日
  const day = String(date.getDate()).padStart(2, "0");
  // 时
  const hours = String(date.getHours()).padStart(2, "0");
  // 分
  const minutes = String(date.getMinutes()).padStart(2, "0");
  // 秒
  const seconds = String(date.getSeconds()).padStart(2, "0");

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
onMounted(async () => {
  if (userStore.getUser.username) {
    loading.value = true;
    try {
      const res = await getCRMTasks({
        id: userStore.getUser.username,
        type: "pending",
        pageNum: pagination.value.pageNum,
        pageSize: pagination.value.pageSize,
      });
      oaTasks.value = res.todoList;
      pagination.value.total = res.todoCount;
    } finally {
      loading.value = false;
    }
  }
});
</script>

<style scoped>
.todo-list {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.content {
  padding: 16px 20px;
  margin-top: 100px;
}

.pagination-wrap {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.news-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.content-wrapper {
  flex: 1;
  max-width: 1200px;
  /* margin: 0 auto; */
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
}

.page-title {
  margin-bottom: 20px;
  color: #303133;
  border-left: 5px solid #409eff;
  padding-left: 10px;
}

.table-wrapper {
  min-height: 400px;
  background: #fff;
  padding: 20px;
  border-radius: 4px;
}

.table-title {
  font-weight: 500;
  color: #303133;
}

.table-summary {
  color: #606266;
  font-size: 13px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 0px;
  padding: 20px 0;
}
</style>
