<template>
  <div>
    <div class="tw-bg-white tw-p-5 tw-rounded-xl tw-mb-5">
      <a-input
        v-model:value="name"
        class="tw-mr-4"
        style="width: 178px"
        placeholder="项目名称"
        allowClear
      ></a-input>

      <span class="tw-mr-4"></span>
      <ProjectStatusSelect v-model:value="projectStatus" />
      <span class="tw-mr-4"></span>
      <a-button class="query-btn" @click="clickSearch">查询</a-button>
    </div>

    <div
      v-if="store.isGreaterThanEqualRootOrgAdmin"
      class="tw-flex tw-gap-2 tw-my-4"
    >
      <a-button type="primary" @click="newProject">新增</a-button>
      <a-button @click="handleDeleteProjects(selectIds)">批量删除</a-button>
    </div>

    <div class="tw-bg-white tw-p-5 tw-rounded-xl">
      <a-table
        rowKey="id"
        :columns="columns"
        :scroll="{ x: 1400 }"
        :data-source="data"
        :rowSelection="{
          selectedRowKeys: selectIds,
          onChange: handleRowSelect,
        }"
        :pagination="{
          pageSize: pageSize,
          current: pageNo,
          total: totalElements,
          showTotal: () => ``,
          onChange: (pageNoChanged, pageSizeChanged) => {
            selectIds = [];
            pageNo = pageNoChanged;
            pageSize = pageSizeChanged;
          },
        }"
      >
        <template #name="{ record }">
          <a-tooltip placement="topLeft">
            <template #title>{{ record.name }}</template>
            {{ record.name }}
          </a-tooltip>
        </template>
        <template #status="{ text }">
          <a>{{ $filters.projectStatusFilter(text) }}</a>
        </template>
        <template #compute="{ text }">
          <a>{{ $filters.booleanYesNoFilter(text) }}</a>
        </template>
        <template #action="{ record }">
          <span>
            <a-button
              v-if="store.isGreaterThanEqualRootOrgAdmin"
              @click="showModal(record)"
              >编辑</a-button
            >
            <a-button
              v-if="store.isGreaterThanEqualRootOrgAdmin"
              @click="handleDeleteProjects([record.id])"
            >
              删除
            </a-button>
            <a-button
              v-if="
                record.status === 'PROCESSING' &&
                store.isGreaterThanEqualRootOrgAdmin
              "
              @click="handleCancelProject(record.id)"
            >
              取消计算
            </a-button>
            <a-button
              v-if="
                record.status === 'FINISH' &&
                store.isGreaterThanEqualRootOrgAdmin
              "
              :class="[record.needCompute && 'need-compute']"
              @click="selectRestartProject(record)"
            >
              重新计算
            </a-button>
            <a-popover placement="bottom" trigger="click">
              <template #content>
                <div class="tw-flex tw-flex-col">
                  <a-button
                    v-if="!store.isCourseAdmin"
                    type="text"
                    style="color: white"
                    @click="handleLogsOfProject(record.id)"
                  >
                    错误报告
                  </a-button>
                  <a-button
                    v-if="
                      record.status !== 'PROCESSING' &&
                      store.isGreaterThanEqualRootOrgAdmin
                    "
                    type="text"
                    style="color: white"
                    @click="goProjectDataSource(record.id)"
                  >
                    数据管理
                  </a-button>
                  <a-button
                    v-if="
                      record.status !== 'PROCESSING' && !store.isCourseAdmin
                    "
                    type="text"
                    style="color: white"
                    @click="goProjectParams(record.id)"
                  >
                    参数配置
                  </a-button>
                  <!-- <a-button
                    type="text"
                    style="color: white"
                    @click="goProjectPapers(record.id)"
                  >
                    试卷列表
                  </a-button> -->
                  <a-button
                    type="text"
                    style="color: white"
                    @click="goAllAnalysis(record.id)"
                  >
                    结果查询
                  </a-button>
                </div>
              </template>
              <a-button>更多</a-button>
            </a-popover>
          </span>
        </template>
      </a-table>
    </div>

    <a-modal
      v-model:visible="visible"
      title="项目信息页"
      okText="确定"
      cancelText="取消"
      @ok="handleOk"
    >
      <a-form :labelCol="{ span: 4 }">
        <a-form-item v-show="projectObj.id" label="项目id">
          <a-input
            v-model:value="projectObj.id"
            :disabled="!!projectObj.id"
          ></a-input>
        </a-form-item>
        <a-form-item label="项目名称">
          <a-input v-model:value="projectObj.name" :maxlength="50"></a-input>
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal
      v-model:visible="showRestartModalVisible"
      title="重新计算"
      okText="确定"
      cancelText="取消"
      @ok="handleRestartProject"
    >
      <ul class="tw-ml-4 tw-list-disc">
        <li v-if="selectedProject.changeInfo?.ITEM1">单科线</li>
        <li v-if="selectedProject.changeInfo?.ITEM2">题型分布</li>
        <li v-if="selectedProject.changeInfo?.ITEM3">试题难度分组分段分布</li>
        <li v-if="selectedProject.changeInfo?.ITEM4">客观题高低分组</li>
        <li v-if="selectedProject.changeInfo?.ITEM5">科目分数线分组分段</li>
        <li v-if="selectedProject.changeInfo?.ITEM6">
          本科目成绩占初试总分权重分段
        </li>
      </ul>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import {
  cancelProject,
  deleteProjects,
  getProjectList,
  logsOfProject,
  restartProject,
  updateProject,
} from "@/api/projectManagementPage";
import router from "@/router";
import { useMainStore } from "@/store";
import { Project } from "@/types";
import { message, Modal } from "ant-design-vue";
import { watch, onMounted, ref, reactive, toRaw } from "vue";

const store = useMainStore();
store.currentLocation = "项目管理 / 项目列表";

let rootOrgId = $ref(undefined as unknown as number);
let name = $ref("");
let projectStatus = $ref(undefined as undefined | string);

let data = $ref<Project[]>([]);
let pageSize = $ref(10);
let pageNo = $ref(1);
let totalElements = $ref(0);

async function search() {
  await fetchData();
}

async function clickSearch() {
  pageNo = 1;
  await fetchData();
}

watch(() => [pageNo, pageSize], fetchData);

async function fetchData() {
  const res = await getProjectList({
    name,
    status: projectStatus,
    rootOrgId,
    pageSize,
    pageNo,
  });
  // console.log(res);
  res.data.content = res.data.content.map((p) => {
    p.changeInfo = JSON.parse(<string>(<unknown>p.changeInfo) || "{}");
    return p;
  });
  data = res.data.content;
  pageNo = res.data.pageNo;
  pageSize = res.data.pageSize;
  totalElements = res.data.totalElements;
}

const columns = [
  {
    title: "项目id",
    dataIndex: "id",
    width: 80,
  },
  {
    title: "项目名称",
    dataIndex: "name",
    width: 180,
    slots: { customRender: "name" },
    ellipsis: true,
  },
  {
    title: "分析状态",
    dataIndex: "status",
    slots: { customRender: "status" },
    width: 90,
  },
  {
    title: "需重新计算",
    dataIndex: "needCompute",
    slots: { customRender: "compute" },
    width: 110,
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
    width: 180,
  },
  {
    title: "创建人",
    dataIndex: "creator",
    width: 80,
  },
  {
    title: "更新时间",
    dataIndex: "updateTime",
    width: 180,
  },
  {
    title: "更新人",
    dataIndex: "updater",
    width: 80,
  },
  {
    title: "操作",
    key: "action",
    slots: { customRender: "action" },
    width: 360,
    fixed: "right",
  },
];

onMounted(async () => {
  rootOrgId = store.userInfo.rootOrgId;
  await search();
});

const visible = ref<boolean>(false);

const showModal = (record: Project) => {
  Object.assign(projectObj, record);
  visible.value = true;
};

const handleOk = async () => {
  await updateProject(toRaw(projectObj));
  visible.value = false;
  await search();
  void message.success({ content: "操作成功" });
};

const initProject = <Project>(<unknown>{
  id: undefined,
  code: "",
  name: "",
  enable: true,
  type: undefined,
  rootOrgId: store.userInfo.rootOrgId,
});
const projectObj = reactive({ ...initProject });

const newProject = () => {
  Object.assign(projectObj, initProject);
  showModal(projectObj);
};

function checkEmpty(selectIds: number[]): boolean {
  if (selectIds && selectIds.length > 0) {
    return false;
  } else {
    void message.warn({ content: "请先选择行" });
    return true;
  }
}
function handleDeleteProjects(ids: number[]) {
  if (checkEmpty(ids)) return;
  Modal.confirm({
    title: "提示",
    content: "确认删除？",
    cancelText: "取消",
    okText: "确定",
    onOk: async () => {
      await deleteProjects(ids);
      selectIds = [];
      await search();
      void message.success({ content: "操作成功" });
    },
  });
}

let selectIds = $ref<number[]>([]);

function handleCancelProject(id: number) {
  Modal.confirm({
    title: "提示",
    content: "确认取消计算？",
    cancelText: "取消",
    okText: "确定",
    onOk: async () => {
      await cancelProject(id);
      await search();
      void message.success({ content: "操作成功" });
    },
  });
}

let showRestartModalVisible = $ref(false);
let selectedProject = reactive<Project>({ id: 0 } as Project);
function selectRestartProject(p: Project) {
  Object.assign(selectedProject, p);
  showRestartModalVisible = true;
}
function handleRestartProject() {
  Modal.confirm({
    title: "提示",
    content: "确认重新计算？",
    cancelText: "取消",
    okText: "确定",
    onOk: async () => {
      await restartProject(selectedProject.id);
      await search();
      showRestartModalVisible = false;
      void message.success({ content: "操作成功" });
    },
  });
}

async function handleLogsOfProject(id: number) {
  await logsOfProject(id);
  void message.success({ content: "操作成功" });
}

async function goProjectDataSource(id: number) {
  await router.push("datasource/" + id);
}

async function goProjectParams(id: number) {
  await router.push("params/" + id);
}

// async function goProjectPapers(id: number) {
//   await router.push("papers/" + id);
// }

async function goAllAnalysis(projectId: number) {
  await router.push(`/project/allAnalysis/${projectId}`);
}
const handleRowSelect = (selectedRowKeys: (string | number)[]) => {
  selectIds = selectedRowKeys as number[];
};
</script>

<style>
.need-compute span {
  color: red;
  animation: 1s ease-in-out 1s infinite alternate scale_text;
}

@keyframes scale_text {
  from {
    transform: scale(1);
  }
  to {
    transform: scale(1.1);
  }
}
</style>
