<template>
  <div class="container">
    <a-card class="general-card" style="margin: 0 auto">
      <template #title>
        <div style="padding: 12px 20px">
          <a-tooltip content="返回周报列表">
            <a-button
              class="nav-btn"
              type="outline"
              :shape="'circle'"
              @click="redirectReportListPage"
            >
              <template #icon>
                <icon-left />
              </template>
            </a-button>
          </a-tooltip>
        </div>
      </template>

      <template #extra>
        <div style="padding: 12px 20px">
          <a-button type="primary" @click="handleAddReport()">新建</a-button>
        </div>
      </template>
      <a-divider style="margin-top: 0" />
      <a-scrollbar
        :style="{
          height: `${containerHeight}`,
          overflow: 'auto'
        }"
      >
        <div
          :heading="4"
          style="
            text-align: center;
            padding: 0px 0 10px 0;
            color: var(--color-text-1);
            font-weight: 500;
            font-size: 24px;
          "
        >
          项目周报
        </div>
        <a-row style="width: 1100px; margin: 0 auto">
          <a-col :span="24">
            <a-form
              ref="reportFormRef"
              :model="reportForm"
              :rules="reportFormRules"
              :auto-label-width="true"
              label-align="right"
            >
              <div
                class="arco-descriptions arco-descriptions-layout-horizontal arco-descriptions-size-large arco-descriptions-border report-desc"
              >
                <div class="arco-descriptions-body">
                  <table class="arco-descriptions-table">
                    <tbody>
                      <tr class="arco-descriptions-row">
                        <td
                          class="arco-descriptions-item-label arco-descriptions-item-label-block"
                        >
                          姓名
                        </td>
                        <td
                          class="arco-descriptions-item-value arco-descriptions-item-value-block"
                          colspan="1"
                        >
                          <a-input
                            :model-value="reportForm.name"
                            class="editor-input"
                            readonly
                          />
                        </td>
                        <!-- <td
                      class="arco-descriptions-item-label arco-descriptions-item-label-block"
                    >
                      部门
                    </td>
                    <td
                      class="arco-descriptions-item-value arco-descriptions-item-value-block"
                      colspan="1"
                    >
                      <a-input auto-size class="editor-input" />
                    </td> -->
                        <td
                          class="arco-descriptions-item-label arco-descriptions-item-label-block desc-value"
                        >
                          项目名称
                        </td>
                        <td
                          ref="dropDownRef"
                          class="arco-descriptions-item-value arco-descriptions-item-value-block"
                          colspan="1"
                        >
                          <a-form-item no-style field="prjId">
                            <!-- <a-select
                        class="editor-input"
                        readonly
                        style="width: 100%"
                      > -->
                            <a-dropdown
                              trigger="click"
                              :disabled="props.prjId !== undefined"
                              position="bl"
                              :popup-container="dropDownRef"
                              :style="{ width: '100%' }"
                            >
                              <a-input
                                :model-value="reportForm.prjName"
                                readonly
                                class="editor-input"
                              />

                              <template #content>
                                <a-doption
                                  v-for="item in prjList"
                                  :key="item.id"
                                  :value="item.id"
                                  @click="handleSelectPrj(item.id, item.name)"
                                  >{{ item.name }}</a-doption
                                >
                              </template>
                            </a-dropdown>
                          </a-form-item>
                          <!-- <a-trigger trigger="focus">
                        <a-input
                          :model-value="reportForm.prjId"
                          class="editor-input"
                        />
                        <template #content>
                          <div class="arco-dropdown">
                            <div
                              class="arco-scrollbar arco-scrollbar-type-embed"
                            >
                              <div
                                class="arco-scrollbar-container arco-dropdown-list-wrapper"
                                style="max-height: none; overflow-y: hidden"
                              >
                                <ul class="arco-dropdown-list">
                                  <li class="arco-dropdown-option">
                                    <span class="arco-dropdown-option-content"
                                      >Option 1</span
                                    >
                                  </li>
                                  <li
                                    class="arco-dropdown-option arco-dropdown-option-disabled"
                                  >
                                    <span class="arco-dropdown-option-content"
                                      >Option 2</span
                                    >
                                  </li>
                                </ul>
                              </div>
                            </div>
                          </div>
                        </template>
                      </a-trigger> -->

                          <!-- </a-select> -->
                        </td>
                        <td
                          class="arco-descriptions-item-label arco-descriptions-item-label-block desc-value"
                        >
                          时间
                        </td>
                        <td
                          class="arco-descriptions-item-value arco-descriptions-item-value-block"
                          colspan="1"
                        >
                          <a-input
                            auto-size
                            class="editor-input"
                            readonly
                            :model-value="
                              startOfWeekDate +
                              '~' +
                              endOfWeekDate +
                              '，第' +
                              reportForm.weeks +
                              '周'
                            "
                          />
                        </td>
                      </tr>
                      <!-- <tr class="arco-descriptions-row">
                    <td
                      class="arco-descriptions-item-label arco-descriptions-item-label-block"
                    >
                      项目<br /><br />名称
                    </td>
                    <td
                      class="arco-descriptions-item-value arco-descriptions-item-value-block"
                      colspan="3"
                    >
                      <a-textarea
                        auto-size
                        class="editor-textarea"
                        allow-clear
                      />
                    </td> -->
                      <!-- <td
                      class="arco-descriptions-item-label arco-descriptions-item-label-block"
                    >
                      部门
                    </td>
                    <td
                      class="arco-descriptions-item-value arco-descriptions-item-value-block"
                      colspan="1"
                    >
                      <a-input auto-size class="editor-input" />
                    </td> -->
                      <!-- <td
                      class="arco-descriptions-item-label arco-descriptions-item-label-block desc-value"
                    >
                      时间
                    </td>
                    <td
                      class="arco-descriptions-item-value arco-descriptions-item-value-block"
                      colspan="2"
                    >
                      <a-input auto-size class="editor-input" />
                    </td> -->
                      <!-- </tr> -->
                      <!-- <tr class="arco-descriptions-row">
                    <td
                      class="arco-descriptions-item-label arco-descriptions-item-label-block desc-value"
                    >
                      项目<br /><br />描述
                    </td>
                    <td
                      class="arco-descriptions-item-value arco-descriptions-item-value-block"
                      colspan="6"
                    >
                      <a-textarea
                        auto-size
                        class="editor-textarea-1"
                        allow-clear
                      />
                    </td>
                  </tr> -->
                      <tr class="arco-descriptions-row">
                        <td
                          class="arco-descriptions-item-label arco-descriptions-item-label-block desc-value"
                        >
                          <br />本周<br /><br />工作<br /><br />小结<br />
                        </td>
                        <td
                          class="arco-descriptions-item-value arco-descriptions-item-value-block"
                          colspan="6"
                        >
                          <a-form-item no-style field="summary">
                            <a-textarea
                              v-model="reportForm.summary"
                              auto-size
                              class="editor-textarea"
                            />
                          </a-form-item>
                        </td>
                      </tr>
                      <tr class="arco-descriptions-row">
                        <td
                          class="arco-descriptions-item-label arco-descriptions-item-label-block desc-value"
                        >
                          <br />下周<br /><br />工作<br /><br />计划<br />
                        </td>
                        <td
                          class="arco-descriptions-item-value arco-descriptions-item-value-block"
                          colspan="6"
                        >
                          <a-form-item no-style field="plan">
                            <a-textarea
                              v-model="reportForm.plan"
                              auto-size
                              class="editor-textarea"
                            />
                          </a-form-item>
                        </td>
                      </tr>
                      <tr class="arco-descriptions-row">
                        <td
                          class="arco-descriptions-item-label arco-descriptions-item-label-block desc-value"
                        >
                          <br />建议<br /><br />或需<br /><br />协助<br /><br />事宜<br />
                        </td>
                        <td
                          class="arco-descriptions-item-value arco-descriptions-item-value-block"
                          colspan="6"
                        >
                          <a-textarea
                            v-model="reportForm.issue"
                            auto-size
                            class="editor-textarea"
                          />
                        </td>
                      </tr>
                      <tr class="arco-descriptions-row">
                        <td
                          class="arco-descriptions-item-label arco-descriptions-item-label-block"
                        >
                          <br /><br />附件<br /><br />上传<br /><br />
                        </td>
                        <td
                          class="arco-descriptions-item-value arco-descriptions-item-value-block"
                          colspan="6"
                        >
                          <a-upload
                            v-if="!showUploadProgress"
                            v-model:fileList="reportForm.fileItem"
                            style="padding: 10px"
                            :auto-upload="false"
                            :show-file-list="true"
                            :show-upload-button="{
                              showOnExceedLimit: false
                            }"
                            :custom-icon="getCustomIcon()"
                          >
                            <template #upload-button>
                              <a-button type="dashed"
                                ><template #icon><icon-upload /></template
                                >附件</a-button
                              >
                            </template>
                          </a-upload>
                          <div v-else>
                            <div
                              v-for="item in fileUploadProgress"
                              :key="item.uid"
                              class="file-container"
                            >
                              <div class="filename">
                                &nbsp; {{ item.filename }}
                              </div>
                              <div class="file-extra">
                                <a-progress
                                  type="circle"
                                  :percent="item.progress / 100"
                                />
                              </div>
                            </div>

                            <!-- <a-space
                          v-for="item in fileUploadProgress"
                          :key="item.uid"
                        >
                          <span>{{ item.filename }}</span>
                          <a-progress type="circle" :percent="item.progress" />
                        </a-space> -->
                          </div>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </a-form>
            <!-- <a-descriptions
            bordered
            class="report-desc"
            :column="3"
            style="width: 100%"
            size="large"
            :label-style="{ textAlign: 'center', padding: '50px 30px' }"
          >
            <a-descriptions-item label="姓名"> </a-descriptions-item>
            <a-descriptions-item label="部门"> </a-descriptions-item>
            <a-descriptions-item label="岗位"> </a-descriptions-item>
            <a-descriptions-item label="项目" :span="3"> </a-descriptions-item>
            <a-descriptions-item :span="3">
              <template #label> 本周<br /><br />工作<br /><br />小结 </template>
              <template #data>
                <a-textarea class="editor-textarea" auto-size
              /></template>
            </a-descriptions-item>
            <a-descriptions-item :span="3">
              <template #label> 下周<br /><br />工作<br /><br />计划 </template>
            </a-descriptions-item>
            <a-descriptions-item :span="3">
              <template #label>
                建议<br /><br />或需<br /><br />协助<br /><br />事宜
              </template>
            </a-descriptions-item>
            <a-descriptions-item :span="3">
              <template #label> 附件<br /><br />上传 </template>
            </a-descriptions-item>
          </a-descriptions> -->
            <br />
            <a-typography-text
              style="
                color: var(--color-text-3);
                font-size: 12px;
                text-align: right;
              "
            >
              备注：工作小结做到简洁明了，列明事项即可；{{
                props.prjId
              }}</a-typography-text
            >
          </a-col>
        </a-row>
      </a-scrollbar>
      <!-- <a-space
          style="width: 100%; justify-content: center; padding-top: 10px"
          :size="20"
        >
          <a-button type="primary" size="large">新建</a-button>
          <a-button size="large">返回</a-button>
        </a-space> -->
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import { getSelfInfo, uploadFile } from '@/api/client'
import { useEmitt } from '@/logics/mitt/useEmitt'
import { getWeek, startOfWeek, endOfWeek, format } from 'date-fns'
import { ModifyProjectReqParams, Project } from '@/types/project'
import { FileItem } from '@arco-design/web-vue/es/upload/interfaces'
import { h, onMounted, reactive, ref } from 'vue'
import { IconDelete } from '@arco-design/web-vue/es/icon'
import { getProjectList } from '@/api/project/info'
import {
  getUploadWeekReportFileUrl,
  addWeekReport
} from '@/api/project/week-report'
import { WeekReportUploadFileUrlResParams } from '@/types/week-report'
import { FormInstance } from '@arco-design/web-vue/es/form'
import { Message } from '@arco-design/web-vue'

const props = defineProps({
  prjId: {
    type: String
  },
  containerHeight: {
    type: String,
    default: () => {
      return 'calc(100vh - 200px)'
    }
  }
})
const reportFormRef = ref<FormInstance>()
const { emitter } = useEmitt()
const redirectReportListPage = () => {
  emitter.emit('redirectReportListPage')
}

const showUploadProgress = ref(false)
const fileUploadProgress = ref<
  { uid: string; filename: string; progress: number }[]
>([])
const prjList = ref<Project[]>([])
const dropDownRef = ref()
const reportForm = reactive<{
  id?: string
  name?: string
  prjId?: string
  prjName?: string
  weeks?: number
  summary?: string
  plan?: string
  issue?: string
  fileItem: FileItem[]
  attachments?: string[]
}>({
  fileItem: [],
  attachments: []
})

const reportFormRules = {
  prjId: [{ required: true, message: '项目信息不能为空', trigger: 'blur' }],
  summary: [
    { required: true, message: '本周工作总结不能为空', trigger: 'blur' }
  ],
  plan: [{ required: true, message: '下周工作计划不能为空', trigger: 'blur' }]
}

const modifyParams = ref<ModifyProjectReqParams>({
  id: 'd'
})

const handleSelectPrj = (id: string, name: string) => {
  reportForm.prjId = id
  reportForm.prjName = name
}
const getCustomIcon = () => {
  return {
    removeIcon: () => h(IconDelete, { size: 16, style: { color: 'red' } }),
    fileName: (file: any) => {
      return `${file.name}`
    }
  }
}

const startOfWeekDate = format(startOfWeek(new Date()), 'yyyy-MM-dd')
const endOfWeekDate = format(endOfWeek(new Date()), 'yyyy-MM-dd')

const getProjects = async () => {
  const { list } = await getProjectList({ page_no: 1, page_size: 99999 })
  prjList.value = list
  if (props.prjId !== undefined) {
    reportForm.prjId = props.prjId
    reportForm.prjName = list.find(item => item.id === props.prjId)?.name
  }
}

// 获取上传进度信息
const uploadProgress = (e: ProgressEvent, fileItem: FileItem) => {
  showUploadProgress.value = true
  const progress = Number(((e.loaded / e.total) * 100).toFixed(0))
  const fileUpload = fileUploadProgress.value.find(
    item => item.uid === fileItem.uid
  )
  if (fileUpload) {
    fileUpload.progress = progress
  }
  // currentProgress.value = Number(((e.loaded / e.total) * 100).toFixed(0))
}

/**
 * 上传
 * @param fileList
 * @param prjId 项目编号
 * @param reportId 周报编号
 */
const uploadWeekReportFiles = async (
  fileList: FileItem[],
  prjId: string,
  reportId?: string
) => {
  const list: Promise<WeekReportUploadFileUrlResParams>[] = []
  const attachments: string[] = []
  const uploadPromiseList: any[] = []
  fileUploadProgress.value = []
  if (fileList.length === 0) {
    return []
  }
  fileList.forEach((item: FileItem) => {
    if (item.file) {
      const result = getUploadWeekReportFileUrl({
        filename: item.name!,
        prj_id: prjId!,
        report_id: reportId
      })
      list.push(result)
    } else {
      attachments.push(item.uid)
    }
    fileUploadProgress.value.push({
      uid: item.uid,
      filename: item.name || item.uid,
      progress: 0
    })
  })
  const reportResult = await Promise.all(list)
  const ids = fileList
    .filter(item => item.file)
    .map((item: any, index: number) => {
      if (item.file) {
        const result = uploadFile(
          reportResult[index].url,
          {
            data: reportResult[index].form_data,
            file: item.file!
          },
          (e: ProgressEvent) => uploadProgress(e, item),
          1000 * 60 * 60
        )
        uploadPromiseList.push(result)
        return `${reportResult[index].object_name}`
      }
      return `${item.url}`
    })
  await Promise.all(uploadPromiseList)
  showUploadProgress.value = false
  return attachments.concat(ids)
}

/**
 * 创建周报
 */
const handleAddReport = async () => {
  const isValid = await reportFormRef.value?.validate()
  if (isValid) {
    Message.warning('项目信息、本周总结、下周计划、建议协作事宜不能为空！')
    return
  }
  const attachments = await uploadWeekReportFiles(
    reportForm.fileItem,
    reportForm.prjId!,
    reportForm.id
  )
  await addWeekReport({
    prj_id: reportForm.prjId,
    summary: reportForm.summary!,
    issues: reportForm.issue,
    plan: reportForm.plan!,
    attachments
  })

  Message.warning('新建成功！')
  reportForm.summary = undefined
  reportForm.issue = undefined
  reportForm.plan = undefined
  reportForm.fileItem = []
}

onMounted(async () => {
  const { name } = await getSelfInfo()
  reportForm.name = name
  reportForm.weeks = getWeek(new Date())
  getProjects()
})
</script>

<script lang="ts">
export default {
  name: 'ReportAdd'
}
</script>

<style lang="less" scoped>
.container {
  padding: 20px;
  .general-card {
    :deep(.arco-card-header) {
      padding: 0;
      .nav-btn {
        border-color: transparent;
        color: var(--text-2);
        background-color: var(--color-fill-2);
        font-size: 14px;
      }
    }
    :deep(.report-desc) {
      .arco-descriptions-body {
        border-top: 1px solid var(--color-text-4);
        border-left: 1px solid var(--color-text-4);
        border-bottom: 1px solid var(--color-text-4);
        border-right: none;
        .arco-descriptions-row:not(:last-child) {
          border-bottom: 1px solid var(--color-text-4);
        }
        .arco-descriptions-item-label-block {
          background-color: transparent;
          border-right: 1px solid var(--color-text-4);
          font-weight: bold;
          padding: 20px 40px;
          color: var(--color-text-2);
        }
        .arco-descriptions-item-value-block {
          border-right: 1px solid var(--color-text-4);
          padding: 0;
          position: relative;
          height: auto;
          // padding: 10px;
          .editor-textarea {
            background: transparent;
            width: 100%;
            min-height: 260px;
            overflow: auto;
            border: transparent;
          }
          .editor-textarea-1 {
            background: transparent;
            width: 100%;
            min-height: 260px;
            overflow: auto;
            border: transparent;
          }
          .editor-input {
            background: transparent;
            width: 100%;
            min-height: 50px;
            border: transparent;
          }
        }
        .arco-input-wrapper:focus-within,
        .arco-input-wrapper:focus-visible,
        .arco-input-wrapper.arco-input-focus,
        .arco-textarea-wrapper:focus-within,
        .arco-textarea-wrapper:focus-visible,
        .arco-textarea-wrapper.arco-textarea-focus {
          border: transparent;
        }
        // .arco-descriptions-border .arco-descriptions-row:not(:last-child) {
        //   border: 1px solid var(--color-text-4);
        //   .arco-descriptions-item-label-block {
        //     border: 1px solid var(--color-text-4);
        //   }
        // }
      }
    }
  }
}

:deep(.arco-upload-list-item) {
  .arco-upload-progress {
    display: none;
  }
}

.file-container {
  display: flex;
  flex-wrap: nowrap;
  align-items: center;
  box-sizing: border-box;
  padding: 5px 20px;
  overflow: hidden;
  .filename {
    display: flex;
    flex: 1 1 auto;
    width: 80%;
    transition: background-color 0.1s cubic-bezier(0, 0, 1, 1);
    border-radius: var(--border-radius-small);
    padding: 8px 10px 8px 12px;
    background-color: var(--color-fill-1);
    align-items: center;
    margin-right: 10px;
    overflow: hidden;
    color: var(--color-text-1);
    font-size: 14px;
    line-height: 1.4286;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .file-extra {
    display: flex;
    margin-left: 10px;
    flex: 0 0 80px;
    color: var(--color-text-2);
  }
}
</style>
