<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">
              <template v-if="enableConfigByTenant([TENANT_ENUM.LYRIC])">
                <LyricProjectCard
                  v-for="(project, index) in tableData"
                  :key="project.id"
                  :project="project"
                  :index="Number(index)"
                  :actionList="cardActionList"
                  @cardClick="cardClickFun"
                  @actionClick="actionClickFun"
                />
              </template>
              <template v-else>
                <DefaultProjectCard
                  v-for="(project, index) in tableData"
                  :key="project.id"
                  :project="project"
                  :index="Number(index)"
                  :actionList="cardActionList"
                  @cardClick="cardClickFun"
                  @actionClick="actionClickFun"
                />
              </template>
            </div>
          </div>
        </template>
        <template #leftOptions>
          <el-button
            icon="plus"
            v-permission="'project_list_add_project'"
            @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 { computed, reactive, ref } from 'vue';
import BaseTable from '@/components/common/table/baseTable.vue';
import projectInfoDialog from '@/components/project/projectInfoDialog.vue';
import { deleteNodeApi, exportProjectApi, queryNodeListApi } from '@/api/project/node';
import { ElMessage } from 'element-plus';
import { NODE_TYPE } from '@/utils/enum/node';
import { disposeMemberList } from '@/views/task/projectDetail/components/project';
import { useDict } from '@/utils/useDict';
import dayjs from 'dayjs';
import ProjectDetail from '@/views/task/projectDetail/index.vue';
import StatusDot from '@/components/common/statusDot/index.vue';
import { projectStatus } from '@/components/common/statusDot/statusMap';
import { ElMessageBox } from 'element-plus';
import { enableConfigByTenant, TENANT_ENUM } from '@/tenants/tenant';
import projectOverview from '@/views/task/projectOverview/index.vue';
import { hasPermission } from '@/utils/permission';
import DefaultProjectCard from '@/views/task/projectList/components/projectCard.vue';
import LyricProjectCard from '@/tenants/lyric/views/project/projectCard.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 actionList = ref<any>([
  {
    title: '查看',
    type: 'primary',
    click: (row: any) => {
      goProjectDetailFun(row.uuid, row.nodeName);
    },
  },
  {
    title: '编辑',
    type: 'primary',
    code: 'project_list_edit_project',
    click: (row: any) => {
      openProjectInfoDiaFun('edit', row);
    },
    hide: () => {
      return !hasPermission('project_list_edit_project');
    },
  },
  {
    title: '删除',
    type: 'danger',
    needConfirm: true,
    confirmTip: '确认删除吗？',
    code: 'project_list_delete_project',
    click: (row: any) => {
      deleteNodeFun(row);
    },
    hide: () => {
      return !hasPermission('project_list_delete_project');
    },
  },
]);
// 卡片布局
const cardActionList = computed(() => {
  const list = actionList.value.filter((item: any) => {
    return hasPermission(item.code) || !item.code;
  });
  return list;
});

// 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;
};

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, confirmTipFun } = action;
  if (click) {
    if (needConfirm) {
      ElMessageBox.confirm(
        (confirmTipFun && confirmTipFun(row)) || confirmTip || '确定操作吗？',
        '提示',
        {
          type: 'warning',
        }
      )
        .then(() => {
          click(row);
        })
        .catch(() => {});
    } else {
      click(row);
    }
  }
};

const cardClickFun = (project: any) => {
  goProjectDetailFun(project.uuid, project.nodeName);
};
// 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 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%;
  }
}

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