<template>
  <div class="container">
    <a-card class="general-card" style="margin: 0 auto" title="">
      <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" status="success" @click="handleEditReport()"
            >保存</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-dropdown
                              trigger="click"
                              disabled
                              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="
                              reportForm.begin +
                              '~' +
                              reportForm.end +
                              '，第' +
                              reportForm.week +
                              '周'
                            "
                          />
                        </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.issues"
                            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"
                        >
                          <!-- :on-before-remove="
                            (file: FileItem) => handleRemoveReportFile(file)
                          " -->
                          <a-upload
                            v-if="!showProgress"
                            v-model:fileList="reportForm.fileItem"
                            style="padding: 10px"
                            :auto-upload="false"
                            :show-file-list="true"
                            :show-preview-button="true"
                            :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 fileProgress"
                              :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 fileProgress"
                          :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>
            <br />
            <a-typography-text
              style="
                color: var(--color-text-3);
                font-size: 12px;
                text-align: right;
              "
            >
              备注：工作小结做到简洁明了，列明事项即可；{{
                props.reportId
              }}</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"
            status="success"
            @click="handleEditReport()"
            >修改</a-button
          >
          <a-button size="large" @click="redirectReportListPage">返回</a-button>
        </a-space> -->
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import { uploadFile, downloadFile } from '@/api/client'
import { useEmitt } from '@/logics/mitt/useEmitt'
import { ModifyProjectReqParams, Project } from '@/types/project'
import { Modal, Message, Space, Button } from '@arco-design/web-vue'
import { FileItem } from '@arco-design/web-vue/es/upload/interfaces'
import { h, onMounted, reactive, ref, Component, toRaw, markRaw } from 'vue'
import { IconDelete, IconDownload } from '@arco-design/web-vue/es/icon'
import {
  getUploadWeekReportFileUrl,
  getDownloadWeekReportFileUrl,
  getWeekReportDetail,
  removeReportFile,
  modifyWeekReport
} from '@/api/project/week-report'
import {
  WeekReportDetailResParams,
  WeekReportUploadFileUrlResParams
} from '@/types/week-report'
import { FormInstance } from '@arco-design/web-vue/es/form'
import { areObjectsEqual } from '@/utils'

const props = defineProps({
  reportId: {
    type: String
  },
  prjId: {
    type: String
  },
  containerHeight: {
    type: String,
    default: () => {
      return 'calc(100vh - 200px)'
    }
  }
})

const reportFormRef = ref<FormInstance>()
const { emitter } = useEmitt()
const redirectReportListPage = () => {
  const oldAttachments = reportDetail.detail?.attachments
  const newAttachments = reportForm.fileItem.map((item: any) => {
    return {
      obj_id: item.uid,
      filename: item.name,
      uploaded_at: item.uploaded_at || '',
      size: item.size || 0
    }
  })

  const oldObj = {
    summary: reportDetail.detail?.summary,
    plan: reportDetail.detail?.plan,
    issues: reportDetail.detail?.issues,
    attachments: toRaw(oldAttachments)
  }
  const newObj = {
    summary: reportForm.summary,
    plan: reportForm.plan,
    issues: reportForm.issues,
    attachments: newAttachments
  }
  if (areObjectsEqual(oldObj, newObj)) {
    emitter.emit('redirectReportListPage')
    return
  }
  const title = {
    setup() {
      return () => h('strong', '警告')
    }
  }
  const ModalContent = {
    setup() {
      return () =>
        h('span', { style: 'margin-left: 10px;' }, [
          h('strong', `您还未保存您的编辑内容，确定要退出吗`),
          h('span', ` 吗？`)
        ])
    }
  }

  const modal = Modal.warning({
    title: () => h(title),
    content: () => h(ModalContent),
    alignCenter: true,
    titleAlign: 'start',
    draggable: true,
    escToClose: true,
    width: 350,
    simple: true,
    footer: () => h(ModalFooter),
    hideCancel: false,
    okText: '保存',
    onOk: async () => {
      Message.success('删除成功')
    }
  })
  const ModalFooter = {
    setup() {
      const m = modal
      return () =>
        h('div', {}, [
          h(
            Button,
            {
              type: 'primary',
              status: 'danger',
              onClick: () => {
                modal.close()
                return emitter.emit('redirectReportListPage')
              }
            },
            { default: () => '退出' }
          ),
          h(
            Button,
            {
              onClick: () => {
                return modal.close()
              }
            },
            {
              default: () => '取消'
            }
          ),
          h(
            Button,
            {
              type: 'primary',
              onClick: () => {
                modal.close()
                return handleEditReport()
              }
            },
            { default: () => '保存' }
          )
        ])
    }
  }
  // emitter.emit('redirectReportListPage')
}

const reportDetail = reactive<{ detail?: WeekReportDetailResParams }>({
  detail: undefined
}) // 客户详情

const showProgress = ref(false)
const fileProgress = 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
  begin?: string
  end?: string
  week?: number
  summary?: string
  plan?: string
  issues?: 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: FileItem) =>
      h('div', { style: 'display: flex; justify-content: space-between;' }, [
        h('span', file.name),
        h('span', {}, [
          h(IconDownload, {
            size: 16,
            style: {
              display: file.status === 'init' ? 'none' : '',
              color: 'rgb(var(--primary-6))'
            },
            onClick: (event: MouseEvent) => {
              fileProgress.value = []
              fileProgress.value.push({
                uid: file.uid,
                filename: `${file.name}~下载中`,
                progress: 0
              })
              downloadDoc(file)
            }
          })
          // h(IconDownload, {
          //   size: 16,
          //   style: {
          //     display: file.status === 'init' ? 'none' : '',
          //     color: 'rgb(var(--primary-6))'
          //   },
          //   onClick: (event: MouseEvent) => {
          //     fileProgress.value = []
          //     fileProgress.value.push({
          //       uid: file.uid,
          //       filename: `${file.name}~下载中`,
          //       progress: 0
          //     })
          //     downloadDoc(file)
          //   }
          // })
        ])
      ])
  }
}

const handleRemoveReportFile = async (fileItem: FileItem): Promise<boolean> => {
  if (fileItem.status === 'init') {
    return true
  }
  const { uid, name } = fileItem
  const title = {
    setup() {
      return () => h('strong', '警告')
    }
  }
  const ModalContent = {
    setup() {
      return () =>
        h('span', { style: 'margin-left: 10px;' }, [
          h('span', `确认删除 `),
          h('strong', `${name}`),
          h('span', ` 附件吗？`)
        ])
    }
  }
  const b = await createRemoveModal(title, ModalContent, uid)
  return b
}

const createRemoveModal = (
  title: Component,
  ModalContent: Component,
  id: string
): Promise<boolean> => {
  return new Promise((resolve, reject) => {
    Modal.warning({
      title: () => h(title),
      content: () => h(ModalContent),
      alignCenter: true,
      titleAlign: 'start',
      draggable: true,
      escToClose: true,
      width: 300,
      simple: true,
      hideCancel: false,
      onOk: async () => {
        await removeReportFile(id)
        Message.success('删除成功')
        return resolve(true)
      },
      onCancel: async () => {
        return resolve(false)
      }
    })
  })
}

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

/**
 * 下载文档
 * @param item
 */
const downloadDoc = async (file: FileItem) => {
  try {
    const { url } = await getDownloadWeekReportFileUrl({ id: file.uid })
    // const downloadUrl = url.replace(/https:\/\/pmr\.surkw\.com:29000\//, '')
    Message.info('开始下载')
    await downloadFile(file.name!, url, getDownloadProgress, file)
    showProgress.value = false
    // item.downloadProgress = 0
    Message.success('下载成功')
  } catch (e) {
    showProgress.value = false
    // item.downloadProgress = 0
  }
}

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

/**
 * 上传
 * @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[] = []
  fileProgress.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)
      fileProgress.value.push({
        uid: item.uid,
        filename: `${item.name || item.uid}~上传中`,
        progress: 0
      })
    } else {
      attachments.push(item.uid)
      fileProgress.value.push({
        uid: item.uid,
        filename: item.name || item.uid,
        progress: 100
      })
    }
  })
  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)
  showProgress.value = false
  return attachments.concat(ids)
}

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

const getDetail = async () => {
  const detail = await getWeekReportDetail(props.reportId!)
  reportDetail.detail = detail
  reportForm.prjId = detail.prj_id
  reportForm.prjName = detail.prj_name
  reportForm.begin = detail.begin_from
  reportForm.end = detail.end_to
  reportForm.week = detail.week
  reportForm.name = detail.reporter_name
  reportForm.issues = detail.issues
  reportForm.plan = detail.plan
  reportForm.summary = detail.summary
  reportForm.fileItem = detail.attachments.map(p => {
    return {
      uid: p.obj_id,
      name: p.filename,
      size: p.size,
      uploaded_at: p.uploaded_at
    }
  })
}

onMounted(async () => {
  await getDetail()
})
</script>

<script lang="ts">
export default {
  name: 'ReportDetail'
}
</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;

    .arco-progress-type-circle {
      display: none;
    }

    .arco-upload-icon-success {
      color: rgb(var(--primary-6));
    }
  }

  .arco-upload-list-item-name-text {
    width: 100%;
  }
}

.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>
