<template>
  <view class="example">
    <uni-forms ref="formRef" :modelValue="reportFormData" :rules="rules" validateTrigger="submit" label-position="top">
      <uni-forms-item label="时间" required label-width="120px">
        <view class="custom-select-class" style="background: #f7f6f6;cursor: not-allowed; color: #d5d5d5">
          <view class="custom-select-content">
            <text>{{ detail.week_report?.begin_from + '~' + detail.week_report?.end_to + '，第' + detail.week_report?.week
              + '周' }}</text>
          </view>
        </view>
      </uni-forms-item>
      <uni-forms-item label="填写人" required label-width="120px" name="name">
        <view class="custom-select-class" style="background: #f7f6f6;cursor: not-allowed; color: #d5d5d5">
          <view class="custom-select-content">
            <text>{{ detail.week_report?.reporter_name }}</text>
          </view>
        </view>
      </uni-forms-item>
      <uni-forms-item label="项目名称" required label-width="120px" name="prj_id">
        <view class="custom-select-class form-item-disabled">
          <view class="custom-select-content">
            <text>{{ reportFormData.prj_name }}</text>
          </view>
          <uni-icons :size="14" color="#d5d5d5" type="down" style=" padding: 0 5px;"></uni-icons>
        </view>
      </uni-forms-item>
      <uni-forms-item label="本周工作总结" label-width="120px" name="summary" required>
        <uni-easyinput type="textarea" v-model="reportFormData.summary" placeholder="请输入本周工作总结" />
      </uni-forms-item>
      <uni-forms-item label="下周工作计划" label-width="120px" name="plan" required>
        <uni-easyinput type="textarea" v-model="reportFormData.plan" placeholder="请输入下周工作计划" />
      </uni-forms-item>
      <uni-forms-item label="建议或需协助事宜" label-width="120px" name="issues">
        <uni-easyinput type="textarea" v-model="reportFormData.issues" placeholder="请输入建议或需协助事宜" />
      </uni-forms-item>
      <uni-forms-item label="周报附件" label-width="120px" name="attachments">
        <uni-file-picker v-if="!showProgress" file-mediatype="all" :auto-upload="false" mode="list"
          @select="(e: any) => handlerSelectFileUpload(e)">
          <button size="mini" class="upload-btn" hover-class="is-hover">上传文件</button>
        </uni-file-picker>
        <view style="display: flex;flex-direction: column;">
          <template v-for="(item, index) in fileList" :key="item.id">
            <div class="upload-container">
              <div class="file-container">
                <div class="filename">
                  {{ item.name }}
                </div>
              </div>
              <div style="margin-left: 10px">
                <uni-icons :size="25" color="#007aff" type="download" style=" padding: 0 5px;"
                  @click="startDownloadFileItem(item)"></uni-icons>
                <uni-icons :size="25" color="#dd524d" type="trash" style=" padding: 0 5px;"
                  @click="removeFileItem(index)"></uni-icons>
              </div>
            </div>
          </template>
        </view>
        <custom-progress v-if="showProgress" :value="currentProgress" style="min-width: 250px"
          :stroke-width="16"></custom-progress>
      </uni-forms-item>
      <uni-group>
        <view style="margin-bottom: 10px;">
          <custom-button width="100%" type="filled" color="#007aff"
            @click="handlerModifyWeekReport()">保存</custom-button>
        </view>
        <view>
          <custom-button width="100%" type="filled" color="#dd524d" @click="restForm()">重置</custom-button>
        </view>
      </uni-group>
    </uni-forms>
  </view>

</template>

<script lang="ts" setup>
import { downloadFile, getSelfInfo, saveFile, uploadFile } from '@/api/base/client';
import { endOfWeek, format, getWeek, startOfWeek } from 'date-fns';
import { getDownloadWeekReportFileUrl, getUploadWeekReportFileUrl, getWeekReportDetail, modifyWeekReport } from '@/api/project-center/week-report';
import { useEmitt } from '@/logics/mitt/useEmitt';
import { WeekReportDetailResParams } from '@/types/week-report';
import customProgress from '@/components/cu-progress/index.vue'

const formRef = ref()
const fileList = ref<{ id: string, name: string }[]>([])
const rules = {
  prj_id: {
    rules: [
      {
        required: true,
        errorMessage: '不能为空'
      }
    ]
  },
  summary: {
    rules: [
      {
        required: true,
        errorMessage: '不能为空'
      }
    ]
  },
  plan: {
    rules: [
      {
        required: true,
        errorMessage: '不能为空'
      }
    ]
  }
}

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

const reportFormData = ref<{
  id?: string
  name?: string
  prj_id?: string
  prj_name?: string
  weeks?: number
  summary?: string
  plan?: string
  issues?: string
  attachments?: string[]
}>({})

const { emitter } = useEmitt()
const startOfWeekDate = format(startOfWeek(new Date()), 'yyyy-MM-dd')
const endOfWeekDate = format(endOfWeek(new Date()), 'yyyy-MM-dd')
const showProgress = ref(false)
const currentProgress = ref(0)





// 获取上传进度信息
const onProgressResult = (e: UniApp.OnProgressUpdateResult | UniApp.OnProgressDownloadResult) => {
  showProgress.value = true
  currentProgress.value = e.progress

}

// 选择合同上传文件，并上传
const handlerSelectFileUpload = async (e: {
  tempFilePaths: string[], tempFiles: {
    name: string
    extname: string
    url: string
  }[]
}) => {
  try {
    const { tempFiles, tempFilePaths } = e
    if (tempFilePaths.length > 0) {
      const {
        url,
        form_data,
        object_name,
        headers
      } = await getUploadWeekReportFileUrl({
        prj_id: reportFormData.value.prj_id!,
        filename: tempFiles[0].name
      })

      await uploadFile({ url, object_name, headers, formData: form_data, filePath: tempFilePaths[0], uploadProgress: onProgressResult })
      uni.showToast({ title: '上传成功' })
      fileList.value.push({
        id: object_name,
        name: tempFiles[0].name
      })
      showProgress.value = false
      currentProgress.value = 0
    }

  } catch (_e) {
    showProgress.value = false
    currentProgress.value = 0

  }

}

/**
 * 删除
 * @param index 
 */
const removeFileItem = (index: number) => {
  fileList.value.splice(index, 1)
}

const startDownloadFileItem = async (item: { id: string, name: string }) => {
  uni.showActionSheet({
    itemList: ['分享到好友', '添加到收藏'],
    success: async (res: UniApp.ShowActionSheetRes) => {
      await downloadFileItem(item, res.tapIndex)
    }
  });

}

// 下载文件
const downloadFileItem = async (item: { id: string, name: string }, sheetIndex: number) => {
  try {
    const { url } = await getDownloadWeekReportFileUrl({
      id: item.id,
    })
    const { savedFilePath } = await downloadFile({ url, downloadProgress: onProgressResult })
    await saveFile(savedFilePath, item.name, sheetIndex)
    showProgress.value = false
    currentProgress.value = 0
  } catch (_e) {
    showProgress.value = false
    currentProgress.value = 0
  }
}


// 确认创建周报
const handlerModifyWeekReport = async () => {
  const isValid = await formRef.value?.validate()
  if (!isValid) {
    return
  }
  try {
    await modifyWeekReport({
      id: reportFormData.value.id!,
      summary: reportFormData.value.summary,
      plan: reportFormData.value.plan,
      issues: reportFormData.value.issues,
      attachments: fileList.value.map(item => item.id)
    })
    uni.showModal({
      title: '保存成功，是否返回？',
      success: (res: { confirm: boolean }) => {
        const { confirm } = res;
        if (confirm) {
          return uni.navigateBack()
        }
      }
    })
  } catch (e) {
    getDetail(reportFormData.value.id!)
  }

}

// 获取周报详情
const getDetail = async (id: string) => {
  const details = await getWeekReportDetail(id)
  detail.week_report = details
  reportFormData.value.prj_id = details.prj_id
  reportFormData.value.prj_name = details.prj_name
  reportFormData.value.name = details.reporter_name
  reportFormData.value.issues = details.issues
  reportFormData.value.plan = details.plan
  reportFormData.value.summary = details.summary
  fileList.value = details.attachments.map(item => {
    return {
      id: item.obj_id,
      name: item.filename
    }
  })
  uni.setNavigationBarTitle({
    title: `${details.reporter_name}~第${details.week}周`,
  })
}

onLoad((option) => {
  reportFormData.value.id = option?.id
  getDetail(option?.id!)
});



const restForm = async () => {
  fileList.value = []
  reportFormData.value.issues = undefined;
  reportFormData.value.summary = undefined;
  reportFormData.value.plan = undefined;
}

</script>
<script lang="ts">
export default {
  options: {
    styleIsolation: 'apply-shared', //解除样式隔离
  }

}
</script>
<style scoped lang="scss">
.example {
  padding: 15px;
  background-color: #fff;
}

:deep(.is-disabled) {
  color: #333;

}

.custom-select-class {
  border-color: #e5e5e5;
  background-color: transparent;
  display: flex;
  box-sizing: border-box;
  flex-direction: row;
  align-items: center;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.upload-btn {
  color: #ffffff !important;
  background-color: #007aff !important;
  border-color: #007aff !important;
}

.form-item-disabled {
  background: #f7f6f6;
  cursor: not-allowed;
  color: #d5d5d5
}

.custom-select-content {
  width: auto;
  position: relative;
  overflow: hidden;
  flex: 1;
  line-height: 1;
  font-size: 14px;
  line-height: 35px;
  padding-left: 10px;
  height: 35px;

}

.tag-container {
  &__item {
    padding: 0 6px 0 0;
  }
}

.upload-container {
  position: relative;
  display: flex;
  align-items: center;
  box-sizing: border-box;
  margin-top: 10rpx;

}

.file-container {
  display: flex;
  align-items: center;
  overflow: hidden;
  font-size: 14px;
  border-radius: 3px;
  transition: background-color 0.1s cubic-bezier(0, 0, 1, 1);
}

.filename {
  padding: 8px 0px 8px 10px;
  flex: 1;
  width: 300px;
  background-color: #f7f8fa;
  align-items: center;
  font-size: 13px;
  overflow: hidden;
  color: #606266;
  font-size: 14px;
  line-height: 1.4286;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.file-extra {
  margin-left: 20px;
  color: #606266;
}

:deep(.is-text-box) {
  display: none;
}
</style>