<template>
  <div class="container">
    <a-space direction="vertical" :size="16" fill>
      <a-card class="general-card">
        <template #title> 总进度 &nbsp;{{ milestones.progress }}%</template>
        <a-scrollbar style="overflow: auto; padding-top: 30px">
          <a-timeline
            :pending="props.phaseId != 'done'"
            mode="alternate"
            label-position="relative"
            style="padding: 0 20px; min-height: 170px"
            direction="horizontal"
          >
            <a-timeline-item label="" position="bottom">
              <template #dot>
                <icon-font type="my-start" :size="22" />
              </template>
            </a-timeline-item>

            <a-timeline-item
              v-for="item in milestones.tasks"
              :key="item.task_id"
              position="bottom"
            >
              <template #dot>
                <icon-font
                  :type="milestoneStatus(item.status)?.icon"
                  :size="milestoneStatus(item.status)?.iconSize ? 26 : 22"
                />
              </template>
              <div
                :style="{
                  border:
                    selectedTaskId === item.task_id
                      ? `1px dashed ${milestoneStatus(item.status)?.color}`
                      : 'none'
                }"
                class="m-container"
              >
                <a-button
                  :status="milestoneStatus(item.status)?.theme"
                  :type="
                    milestoneStatus(item.status)?.theme ? 'outline' : undefined
                  "
                  shape="round"
                  size="large"
                  @click="selectedTask(item.task_id, item.name)"
                  >{{ item.name }}</a-button
                >
              </div>
              <template #label>
                <a-row
                  :style="{ display: 'inline-flex', alignItems: 'center' }"
                >
                  <div
                    :style="{
                      marginBottom: '10px',
                      color: milestoneStatus(item.status)?.color,
                      fontSize: '14px'
                    }"
                  >
                    状态：{{ milestoneStatus(item.status)?.label }}
                    <div :style="{}">{{ item.end_at }}</div>
                  </div>
                </a-row>
              </template>
            </a-timeline-item>
          </a-timeline>
        </a-scrollbar>
      </a-card>
      <a-row style="flex-flow: nowrap" :gutter="10">
        <a-col flex="auto">
          <a-scrollbar
            style="
              height: calc(100vh - 430px);
              overflow: auto;
              background: var(--color-bg-2);
            "
          >
            <a-card
              class="general-card"
              :title="selectedTaskName ? selectedTaskName : '交付物清单'"
            >
              <a-table
                style="padding-top: 20px"
                :pagination="false"
                :columns="tableColumns"
                :data="outcomeList"
                :bordered="{
                  cell: false,
                  headerCell: true,
                  wrapper: false
                }"
                :hoverable="false"
                table-layout-fixed
              >
                <template #index="{ rowIndex }">
                  {{ rowIndex + 1 }}
                </template>
                <template #status="{ record }">
                  <a-tag :color="outcomeStatus(record.status)?.color">{{
                    outcomeStatus(record.status)?.label
                  }}</a-tag>
                </template>
                <template #operate="{ record }">
                  <a-button
                    v-if="record.status === 5"
                    type="text"
                    @click="
                      showDownloadModal(
                        record.id,
                        record.name,
                        record.object_name,
                        record.filename
                      )
                    "
                    >下载附件</a-button
                  >
                </template>
              </a-table>
            </a-card>
          </a-scrollbar>
        </a-col>
        <a-col flex="400px">
          <a-card class="general-card log-card" title="项目动态">
            <a-scrollbar style="height: calc(100vh - 547px); overflow: auto">
              <a-list :bordered="false">
                <a-list-item
                  v-for="(item, index) in prjLogs"
                  :key="index"
                  action-layout="vertical"
                >
                  <template #actions> {{ item.ts }} </template>
                  <a-list-item-meta :title="item.creator_name">
                    <template #avatar>
                      <a-avatar
                        shape="square"
                        :style="{ backgroundColor: '#14C9C9' }"
                      >
                        <icon-font type="my-log-bell" />
                      </a-avatar>
                    </template>
                    <template #description>
                      <!-- <a-typography-paragraph> -->
                      <!-- <div v-html="content"></div> -->
                      <!-- eslint-disable-next-line vue/no-v-html -->
                      <div style="font-size: 12px" v-html="item.content"></div>
                      <!-- </a-typography-paragraph> -->
                    </template>
                  </a-list-item-meta>
                </a-list-item>
              </a-list>
            </a-scrollbar>
            <template #actions>
              <Page
                :page="page"
                :simple="true"
                @change="logsPageChangehandle"
              />
            </template>
          </a-card>
        </a-col>
      </a-row>
    </a-space>
    <DownloadModal ref="downloadModalRef" />
  </div>
</template>

<script lang="ts" setup>
import { Icon, TableColumnData } from '@arco-design/web-vue'
import {
  IconFontUrl,
  MilestoneStatusList,
  OutcomeStatusList
} from '@/enums/api'
import { ref, reactive, onMounted } from 'vue'
import { getProjectLogs, getProjectMilestone } from '@/api/project/info'
import Page from '@/components/page/index.vue'
import usePage, { IPage } from '@/components/page/index'
import { Task } from '@/types/plan-task'
import { Outcome } from '@/types/outcome'
import { getOutcomeList } from '@/api/project/outcome'
import { ProjectLog } from '@/types/project'
import { useEmitt } from '@/logics/mitt/useEmitt'
import DownloadModal from './task/outcome/download.vue'

const { page } = usePage()
const IconFont = Icon.addFromIconFontCn({
  src: IconFontUrl.URL
})

// 项目详情父级传过来的项目编号
const props = defineProps({
  prjId: {
    type: String
  },
  phaseId: {
    type: String
  }
})

const prjLogs = ref<ProjectLog[]>([])
const outcomeList = ref<Outcome[]>([]) // 交付物列表
const selectedTaskId = ref() // 选中的任务编号
const selectedTaskName = ref() // 选中的任务名称
const downloadModalRef = ref()

// 根据里程碑状态筛选获取对应的样式
const milestoneStatus = (status: number) => {
  return MilestoneStatusList.find(item => item.status === status)
}

// 根据交付物状态获取对应样式标签
const outcomeStatus = (status: number) => {
  return OutcomeStatusList.find(item => item.status === status)
}

// 里程碑
const milestones = reactive<{ progress: number; tasks: Task[] }>({
  progress: 0, // 总进度
  tasks: [] // 第一级任务信息
})

/**
 * 选中计划任务时获取交付物信息
 * @param id 任务编号
 * @param name 任务名称
 */
const selectedTask = async (id: string, name: string) => {
  selectedTaskId.value = id
  selectedTaskName.value = `${name}-交付物清单`
  const { list } = await getOutcomeList({ task_id: id, draft: false })
  outcomeList.value = list
}

// 交付物th列表
const tableColumns: TableColumnData[] = [
  {
    title: '序号',
    align: 'left',
    slotName: 'index'
  },
  {
    title: '名称',
    dataIndex: 'name',
    align: 'left'
  },
  {
    title: '状态',
    dataIndex: 'status',
    align: 'left',
    slotName: 'status'
  },
  {
    title: '计划交付时间',
    dataIndex: 'plan_time',
    align: 'left'
  },
  {
    title: '实际交付时间',
    dataIndex: 'completed_at',
    align: 'left'
  },
  {
    title: '操作',
    slotName: 'operate',
    width: 150
  }
]

/**
 * 获取里程碑信息（第一级任务）
 * @param prjId 项目编号
 */
const getMilestone = async (prjId: string) => {
  const { tasks, progress } = await getProjectMilestone({ prj_id: prjId })
  milestones.tasks = tasks
  milestones.progress = progress
  if (tasks.length > 0) {
    selectedTask(tasks[0].task_id, tasks[0].name)
  }
}

// 获取项目动态日志
const getLogs = async (prjId: string) => {
  const { list, total } = await getProjectLogs({
    page_no: page.pageIndex,
    page_size: page.pageSize,
    id: prjId
  })
  page.total = total
  prjLogs.value = list
}

/**
 * 分页变化事件
 * @param argPage
 */
const logsPageChangehandle = (argPage: IPage): void => {
  page.pageIndex = argPage.pageIndex
  page.pageSize = argPage.pageSize
  getLogs(props.prjId!).then(() => console.log('获取日志列表'))
}

// 显示下载交付物
const showDownloadModal = (
  id: string,
  name: string,
  objectName: string,
  filename: string
) => {
  downloadModalRef.value?.showDownloadModal(id, name, objectName, filename)
}

// 监听子组件增加，修改，删除事件，更新列表
useEmitt({
  name: 'get_project_log',
  callback: () => {
    getLogs(props.prjId!)
  }
})

// 页面加载时获取里程碑信息
onMounted(() => {
  getMilestone(props.prjId!)
  getLogs(props.prjId!)
})
</script>

<style scoped lang="less">
.container {
  padding: 20px 20px 20px 20px;
  .general-card {
    :deep(.arco-card-header) {
      padding: 20px 20px 0 20px;
    }
    :deep(
        .arco-timeline-item-horizontal-bottom
          > .arco-timeline-item-content-wrapper
      ) {
      margin: 0 0 16px 0px;
      .m-container {
        display: inline-flex;
        position: relative;
        transform: translateX(-48%);
        padding: 20px;
        &:hover {
          border: 1px dashed rgb(var(--primary-4));
        }
      }
    }
    :deep(
        .arco-timeline-item-horizontal-bottom.arco-timeline-item-label-relative
          > .arco-timeline-item-label
      ) {
      transform: translate(-50%, 100%);
    }
  }

  .log-card {
    :deep(.arco-card-body) {
      padding-right: 0;
    }
    :deep(.arco-card-actions) {
      justify-content: center;
      margin-top: 0;
    }
  }
}
:deep(.arco-list-item-action) {
  margin-left: 56px;
  color: var(--color-text-3);
  font-size: 12px;
}
div.arco-typography,
p.arco-typography {
  margin-bottom: 0;
}
</style>
