<template>
  <div class="gl-page-content-full" v-if="!showProjectDetailVisible && !projectsDetailWindow">
    <div class="project-table-list">
      <BaseTable
        listTitle="项目数据"
        v-model:viewType="viewType"
        showIndex
        showCheckbox
        ref="baseTableRef"
        tableName="NODE_LIST_LEVEL1"
        :api="nodeListApi"
        :searchLimitNum="3"
        :actionList="actionList"
        :exportApi="exportProjectApi"
        exportFileName="项目列表"
        fullHeight
      >
        <template #cardTemplate="{ tableData }">
          <div class="project-card-box">
            <div class="projects-grid">
              <div v-for="(project, index) in tableData" :key="project.id" class="project-card">
                <el-dropdown class="options-dropdown" :teleported="false">
                  <div class="options-btn">
                    <el-icon :size="18"><MoreFilled /></el-icon>
                  </div>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item v-for="(action, aIndex) in actionList" :key="aIndex">
                        <el-link :type="action.type" @click="actionClickFun(project, action)">
                          {{ action.title }}
                        </el-link>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>

                <div class="img-box">
                  <template v-if="enableConfigByTenant([TENANT_ENUM.LYRIC])">
                    <div
                      class="gl-pointer-class pure-bg"
                      @click="goProjectDetailFun(project.uuid, project.nodeName)"
                    >
                      <span
                        class="node-code"
                        @click="goProjectDetailFun(project.uuid, project.nodeName)"
                      >
                        {{ project.nodeCode }}
                      </span>
                    </div>
                  </template>
                  <template v-else>
                    <img
                      class="gl-pointer-class"
                      v-if="project.detailImgUrl"
                      @click="goProjectDetailFun(project.uuid, project.nodeName)"
                      :src="getImgPathFun(project.detailImgUrl)"
                      alt=""
                    />
                    <img
                      class="gl-pointer-class"
                      v-else-if="(index as number) % 2 !== 0"
                      @click="goProjectDetailFun(project.uuid, project.nodeName)"
                      src="@/assets/imgs/projectList/project-blue.png"
                      alt=""
                    />
                    <img
                      class="gl-pointer-class"
                      v-else
                      @click="goProjectDetailFun(project.uuid, project.nodeName)"
                      src="@/assets/imgs/projectList/project-green.png"
                      alt=""
                    />
                  </template>
                </div>

                <div class="bottom-box">
                  <span
                    :title="project.nodeName"
                    @click="goProjectDetailFun(project.uuid, project.nodeName)"
                    class="gl-text-ellipsis gl-pointer-class"
                    >{{ project.nodeName }}</span
                  >
                  <!-- <OverflowTooltip
                    class="gl-pointer-class"
                    @click="goProjectDetailFun(project.uuid, project.nodeName)"
                    :content="project.nodeName"
                  /> -->
                  <span
                    :class="
                      project.exeStatus === PROJECT_EXE_STATUS_CODE.COMPLETED
                        ? 'status car-completed'
                        : project.exeStatus === PROJECT_EXE_STATUS_CODE.IN_PROGRESS
                          ? 'status car-ing'
                          : project.exeStatus === PROJECT_EXE_STATUS_CODE.PAUSED
                            ? 'status car-paused'
                            : project.exeStatus === PROJECT_EXE_STATUS_CODE.POSTPONED
                              ? 'status car-postponed'
                              : 'status car-info-status'
                    "
                    >{{ PROJECT_EXE_STATUS.O[project.exeStatus] }}</span
                  >
                </div>
              </div>
            </div>
          </div>
        </template>
        <template #leftOptions>
          <el-button icon="plus" @click="openProjectInfoDiaFun('create')" type="primary">
            {{ $t('项目列表.新增') }}
          </el-button>
          <el-button type="primary" v-if="viewType === 'list'" @click="shwoProjectsFun"
            >查看</el-button
          >
          <!-- <el-button
            title="手动同步EP项目"
            v-if="enableConfigByTenant([TENANT_ENUM.LYRIC])"
            icon="Refresh"
            @click="syncProjectList"
            type="primary"
          >
            同步
          </el-button> -->
        </template>
        <template #nodeCode="{ row }">
          <span class="gl-pointer-class" @click="goProjectDetailFun(row.uuid, row.nodeName)">
            {{ row.nodeCode }}
          </span>
        </template>
        <template #nodeName="{ row }">
          <span class="gl-pointer-class" @click="goProjectDetailFun(row.uuid, row.nodeName)">
            {{ row.nodeName }}
          </span>
        </template>
        <template #nodeSubType="{ row }">
          {{ PROJECT_TYPE.O[row.nodeSubType] }}
        </template>
        <template #creator="{ row }">
          {{ row?.creatorObj?.nickname }}
        </template>
        <template #exeStatus="{ row }">
          <StatusDot
            :status="projectStatus(row.exeStatus)"
            :title="PROJECT_EXE_STATUS.O[row.exeStatus]"
          />
        </template>
        <template #memberList="{ row }">
          {{ disposeMemberList(row) }}
        </template>
      </BaseTable>
    </div>
  </div>
  <projectInfoDialog
    ref="basePageRef"
    v-model="showProjectInfoDialog"
    :projectId="currentProjectBaseInfo.uuid"
    :nodeLevel1List="baseTableRef?.tableData || []"
    @update:currentProjectBaseInfo="updateCurrentProjectBaseInfoFun"
    @nextPageFun="nextPageFun"
    @completeFun="completeFun"
  />
  <ProjectDetail
    v-if="showProjectDetailVisible"
    :projectName="currentProject.nodeName"
    :projectUuid="currentProject.uuid"
    @goBack="showProjectDetailVisible = false"
  ></ProjectDetail>

  <projectOverview
    v-if="projectsDetailWindow"
    :projectUuid="projectUuids"
    @close="projectsDetailWindow = false"
  ></projectOverview>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import BaseTable from '@/components/common/table/baseTable.vue';
import projectInfoDialog from '@/components/project/projectInfoDialog.vue';
// import { useRouter } from 'vue-router';
import {
  deleteNodeApi,
  exportProjectApi,
  queryNodeListApi,
  // syncProjectListApi,
} from '@/api/project/node';
import { ElMessage } from 'element-plus';
import { NODE_TYPE } from '@/utils/enum/node';
import { disposeMemberList } from '../projectDetail/components/project';
import { useDict } from '@/utils/useDict';
import dayjs from 'dayjs';
import ProjectDetail from '../projectDetail/index.vue';
// import OverflowTooltip from '@/components/common/text/overflowTooltip.vue';
import StatusDot from '@/components/common/statusDot/index.vue';
import { projectStatus } from '@/components/common/statusDot/statusMap';
import { MoreFilled } from '@element-plus/icons-vue';
import { ElMessageBox } from 'element-plus';
import { PROJECT_EXE_STATUS_CODE } from '@/utils/enum/project';
import { enableConfigByTenant, TENANT_ENUM } from '@/tenants/tenant';
// import { getUserId, getUserTenantId } from '@/utils/user';
import projectOverview from '@/views/task/projectOverview/index.vue';

export interface IUserInfo {
  id: number;
  company: string | null;
  creator: string;
  createTime: string;
  updater: string | null;
  updateTime: string | null;
  tenantId: string | null;
  nodeId: string;
  identity: string;
  name: string;
}

interface IProjectInfo {
  [key: string]: string;
  id: string;
  uuid: string;
  nodeName: string;
  nodeCode: string;
  nodeType: string;
  nodeSubType: string;
  memberList: any;
  progressStatus: string;
  currentNode: string;
  beginTime: string;
  endTime: string;
  actualStartTime: string;
  actualEndTime: string;
  description: string;
}
const env = import.meta.env;

const actionList = ref<any>([
  {
    title: '查看',
    type: 'primary',
    click: (row: any) => {
      goProjectDetailFun(row.uuid, row.nodeName);
    },
  },
  {
    title: '编辑',
    type: 'primary',
    click: (row: any) => {
      openProjectInfoDiaFun('edit', row);
    },
  },
  {
    title: '删除',
    type: 'danger',
    needConfirm: true,
    confirmTip: '确认删除吗？',
    click: (row: any) => {
      deleteNodeFun(row);
    },
  },
]);

// const router = useRouter();
const basePageRef = ref();
const nodePageRef = ref();

const { PROJECT_TYPE, PROJECT_EXE_STATUS } = useDict('PROJECT_TYPE', 'PROJECT_EXE_STATUS');

const showProjectInfoDialog = ref(false);
const showNodeInfoDialog = ref(false);
const showTaskDialog = ref(false);

const showProjectDetailVisible = ref(false);

const dialogType = ref('create'); // create 编辑 edit
const currentProjectBaseInfo = reactive<any>({
  id: '',
  exeStatus: '',
  uuid: '',
  nodeName: '',
  nodeCode: '',
  nodeType: '',
  nodeSubType: '',
  progressStatus: '',
  currentNode: '',
  beginTime: '',
  endTime: '',
  actualStartTime: '',
  actualEndTime: '',
  description: '',
  memberList: [],
});

const viewType = ref('car');

const currentRow = ref();

const openProjectInfoDiaFun = (tag: string, row?: IProjectInfo) => {
  dialogType.value = tag;
  showProjectInfoDialog.value = true;
  currentRow.value = row;
  if (tag === 'edit' && row) {
    Object.keys(currentProjectBaseInfo).forEach((key) => {
      (currentProjectBaseInfo as any)[key] = (row as any)[key];
    });
    currentProject.nodeName = row.nodeName;
    currentProject.uuid = row.uuid;
  } else {
    Object.keys(currentProjectBaseInfo).forEach((key) => {
      (currentProjectBaseInfo as any)[key] = '';
    });
    currentProject.nodeName = '';
    currentProject.uuid = '';
  }
};

const currentProject = reactive({
  nodeName: '',
  uuid: '',
});
const goProjectDetailFun = (uuid: string, nodeName: string) => {
  showProjectDetailVisible.value = true;
  currentProject.nodeName = nodeName;
  currentProject.uuid = uuid;

  // router.push({ path: '/task/projectDetail', query: { nodeId: uuid, nodeName } });
};

const nodeListApi = async (params: any) => {
  const res: any = await queryNodeListApi({ ...params, nodeType: NODE_TYPE.PROJECT });
  if (res && res.code === 200) {
    res.data.data = res.data.data.map((item: any) => {
      if (item.beginTime && item.endTime) {
        const now = new Date();
        if (dayjs(now).isBefore(item.beginTime)) {
          item.progress = 0;
        } else if (dayjs(item.endTime).isBefore(now)) {
          item.progress = 100;
        } else {
          const progress =
            dayjs(now).diff(item.beginTime) / dayjs(item.endTime).diff(item.beginTime);
          item.progress = Number(progress.toFixed(4)) * 100;
        }
      } else {
        item.progress = 0;
      }
      return item;
    });
    return res;
  }
};

const updateCurrentProjectBaseInfoFun = (info: any) => {
  for (const key in currentProjectBaseInfo) {
    currentProjectBaseInfo[key] = info[key];
  }
};

const nextPageFun = (step: string) => {
  if (step === 'basePage') {
    showProjectInfoDialog.value = false;
    showNodeInfoDialog.value = true;
  }
  if (step === 'nodePage') {
    showNodeInfoDialog.value = false;
    showTaskDialog.value = true;
  }
};

// const prePageFun = (step:string) => {
//   if (step === 'nodePage') {
//     showNodeInfoDialog.value = false;
//     showProjectInfoDialog.value = true;
//   }
//   if (step === 'taskPage') {
//     showTaskDialog.value = false;
//     showNodeInfoDialog.value = true;
//   }
// };

const baseTableRef = ref();

const completeFun = async (page: string) => {
  if (page === 'nodePage') {
    await basePageRef.value.createProject();
    nodePageRef.value.addNodeDisposeFun(nodePageRef.value.nodeTableList, currentProjectBaseInfo.id);
  }
  baseTableRef.value.resetFun({});
};

const deleteNodeFun = async (row: IProjectInfo) => {
  // 调用删除接口
  const res: any = await deleteNodeApi({ deleteNodeIdList: [row.uuid] });
  if (res && res.code === 200) {
    ElMessage.success('删除项目成功');
  } else {
    ElMessage.error(res.message || '删除项目失败');
  }
  baseTableRef.value.resetFun({});
};

const actionClickFun = (row: any, action: any) => {
  const { click, needConfirm, confirmTip } = action;
  if (click) {
    if (needConfirm) {
      ElMessageBox.confirm(confirmTip || '确定操作吗？', '提示', {
        type: 'warning',
      })
        .then(() => {
          click(row);
        })
        .catch(() => {});
    } else {
      click(row);
    }
  }
};
// const syncProjectList = async () => {
//   const res: any = await syncProjectListApi({
//     jobnumber: getUserId(),
//     tenantid: getUserTenantId(),
//     userId: getUserId(),
//   });
//   if (res && res.code === 200) {
//     ElMessage.success('同步成功');
//   } else {
//     ElMessage.error(res.message || '同步失败');
//   }
// };

const getImgPathFun = (fileId: any) => {
  let url: any = '';
  if (fileId) {
    url = `${env.VITE_API_IMAGE_PREVIEW_URL}/data/previewImage?fileId=${fileId}`;
  }
  return url;
};

const projectUuids = ref<any>([]);
const projectsDetailWindow = ref(false);
const shwoProjectsFun = () => {
  const projects: any = baseTableRef.value.tableRef.getCheckboxRecords(true) || [];
  projectUuids.value = [];
  if (projects.length) {
    projectUuids.value = projects.map((item: any) => {
      return item.uuid;
    });
    projectsDetailWindow.value = true;
  } else {
    ElMessage.warning('请选择一个或多个项目查看项目内容');
  }
};
</script>

<style lang="scss" scoped>
.gl-page-content-full {
  .project-table-list {
    height: 100%;
  }
  .project-car-list {
    width: 100%;
    // // overflow-y: auto;
    // // height: calc(100% - 16px);
    // // margin-top: 16px;
    // display: flex;
    // flex-wrap: wrap;
    // gap: @DEFAULT_PADDING;
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 12px;
    // padding-right: 5px;
    .filter-btn {
      text-align: right;
      margin: 10px 0;
    }
    .project {
      // width: calc(25% - 9px);
      height: 156px;
      display: flex;
      justify-content: space-between;
      padding: 12px;
      border-radius: 6px;
      position: relative;

      overflow: hidden;
      border: 1px solid red;
      .progress {
        width: 40px;
        display: flex;
        flex-direction: column;
        align-items: center;
      }
    }

    .activeProject {
      // background-color: @DEFAULT_THEME_BACKGROUND_COLOR;
      border: 2px solid red;
      // color: #fff;
      box-shadow: 0 0 5px 2px #d3d0f0;

      .projectCenter {
        .projectName {
          font-size: 14px;
          // color: #fff;
        }
      }

      .name {
        font-weight: 700;
      }
    }

    .circle {
      display: inline-block;
      width: 10px;
      height: 10px;
      position: absolute;
      top: 6px;
      right: 6px;
      margin-right: 0;
    }
  }
}

.projects-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

.project-card {
  height: 160px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
  // padding: 18px;
  transition: all 0.3s ease;
  border: 1px solid var(--el-border-color);
  overflow: hidden;
  position: relative;
  &:hover {
    .options-dropdown {
      opacity: 1;
    }
  }
  .options-dropdown {
    opacity: 0;
    position: absolute;
    top: var(--margin-tiny);
    right: var(--margin-tiny);
    transition: all 0.3s ease-in-out;
    .options-btn {
      position: absolute;
      top: var(--margin-tiny);
      right: var(--margin-tiny);
      width: 32px;
      height: 32px;
      background-color: var(--el-bg-color);
      font-weight: bold;
      font-size: 18px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: var(--border-radius-normal);
      cursor: pointer;
    }
  }
  .img-box {
    width: 100%;
    height: 100%;
    position: relative;
    img {
      width: 100%;
      height: 100%;
    }
    .pure-bg {
      width: 100%;
      height: 100%;
      background: rgba(216, 210, 210, 0.2);
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .node-code {
      position: absolute;
      top: 40%;
      left: 50%;
      transform: translate(-50%, -50%);
      color: var(--el-color-primary);
      font-size: 20px;
      cursor: pointer;
      width: 100%;
      text-align: center;
      padding: 0 15px;
    }
  }
  .bottom-box {
    position: absolute;
    left: 0;
    bottom: 0;
    height: 40px;
    width: 100%;
    border-radius: 8px;
    background-color: var(--el-bg-color);
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 20px;
    .status {
      display: flex;
      align-items: center;
      justify-content: center;
      // background-color: var(--el-bg-color-page);
      border: 1px solid var(--el-border-color);
      font-size: 12px;
      border-radius: 4px;
      width: 75px;
      height: 25px;
    }
  }
}

.project-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.1);
  border-color: var(--el-border-color);
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.project-icon {
  width: 36px;
  height: 36px;
  background-color: #ef4444;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 14px;
  font-weight: bold;
  margin-right: 12px;
  flex-shrink: 0;
}

.title-section {
  flex-grow: 1;
}

.project-title {
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.project-manager {
  font-size: 12px;
  color: #64748b;
}

.project-info {
  margin-bottom: 16px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 13px;
}

.info-label {
  color: #64748b;
  font-weight: 500;
}

.info-value {
  color: #1e293b;
  font-weight: 500;
}

.status-badge {
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  display: inline-block;
}

.status-planning {
  background-color: #eff6ff;
  color: #3b82f6;
}

.status-progress {
  background-color: #ecfdf5;
  color: #10b981;
}

.status-delayed {
  background-color: #fef2f2;
  color: #ef4444;
}

.status-no-start {
  background-color: #f8fafc;
  color: #64748b;
}

.progress-section {
  margin-top: 18px;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 6px;
  font-size: 13px;
}

.progress-label {
  color: #64748b;
}

.progress-value {
  color: #3b82f6;
  font-weight: 600;
}

.progress-bar {
  height: 6px;
  background-color: #e2e8f0;
  border-radius: 3px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #3b82f6, #60a5fa);
  border-radius: 3px;
  transition: width 0.5s ease;
}

.date-row {
  display: flex;
  justify-content: space-between;
  margin-top: 4px;
  font-size: 12px;
  color: #64748b;
}
.car-ing {
  background-color: #e7f1ff;
  color: #2580fe;
}
.car-paused {
  background-color: #f7ffc8;
  color: #b7c03e;
}
.car-completed {
  background-color: #e0f6eb;
  color: #1eaa39;
}
.car-postponed {
  background-color: #fae4e5;
  color: #d8232a;
}
</style>
