<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>{{ startOfWeekDate + '~' + endOfWeekDate + '，第' + reportFormData.weeks + '周' }}</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>{{ reportFormData.name }}</text>
          </view>
        </view>
      </uni-forms-item>
      <uni-forms-item label="项目名称" required label-width="120px" name="prj_id">
        <view class="custom-select-class" :class="isProject ? 'form-item-disabled' : ''"
          @click="showProjectModal([reportFormData.prj_id])">
          <view class="custom-select-content">
            <text v-if="reportFormData.prj_id">{{ reportFormData.prj_name }}</text>
            <text v-else style="color:#909399;font-size: 12px;">请选择周报项目</text>
          </view>
          <uni-icons :size="14" :color="isProject ? '#d5d5d5' : '#909399'" 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" :disabled="!reportFormData.prj_id" :class="reportFormData.prj_id ? 'upload-btn' : ''"
            hover-class="is-hover">{{
              reportFormData.prj_id ? '上传文件' : '需选择项目' }}</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="#dd524d" type="trash" style=" padding: 0 5px;"
                  @click="removeFileItem(index)"></uni-icons>
              </div>
            </div>
          </template>
        </view>
        <custom-progress v-show="showProgress" :value="currentProgress" style="min-width: 250px"
          :stroke-width="16"></custom-progress>
      </uni-forms-item>
    </uni-forms>
    <view style="margin-bottom: 10px;display: flex;">
      <custom-button width="100%" type="filled" color="#dd524d" @click="restForm()"
        style="margin-right: 5px;flex:1">重置</custom-button>
      <custom-button width="100%" type="filled" color="#007aff" style="flex:1;"
        @click="handlerCreateWeekReport()">新建</custom-button>
    </view>
    <next-tree :ifSearch="true" :border="true" labelKey="name" ref="selectRef" :checkStrictly="true" :funcMode="'radio'"
      :treeData="projectList" @confirm="confirmSelect" @cancel="cancelSelect"></next-tree>
  </view>

</template>

<script lang="ts" setup>
import { getSelfInfo, uploadFile } from '@/api/base/client';
import { endOfWeek, format, getWeek, startOfWeek } from 'date-fns';
import nextTree from '@/components/next-tree/next-tree.vue'
import { getProjectList } from '@/api/project-center/info';
import { addWeekReport, getUploadWeekReportFileUrl } from '@/api/project-center/week-report';
import { useEmitt } from '@/logics/mitt/useEmitt';
import customProgress from '@/components/cu-progress/index.vue'

const formRef = ref()
const selectRef = ref()
const isProject = ref(false)
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 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 projectList = ref<{ id: string, name: string }[]>([])
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 getProjects = async () => {
  try {
    const { list } = await getProjectList({ page_no: 1, page_size: 9999 })
    projectList.value = list
  } catch (e) {
    console.error(e)
  }
}

function checkedTreeData(treeData: any, selectIds?: any) {
  treeData.map((item: any) => {
    if (selectIds.indexOf(item.id) !== -1) {
      item.checked = true
    } else {
      item.checked = false
    }
    if (item.children && item.children.length) {
      checkedTreeData(item.children, selectIds)
    }
  })
}


// 显示项目选择下拉框
const showProjectModal = async (selectId?: any) => {
  if (isProject.value) {
    return;
  }
  checkedTreeData(projectList.value, selectId)
  unref(selectRef).showTree = true
}


const getSelf = async () => {
  const { name } = await getSelfInfo()
  reportFormData.value.name = name
}

function confirmSelect(list: { id: string, name: string }[]) {
  if (list.length > 0) {
    reportFormData.value.prj_id = list[0].id
    reportFormData.value.prj_name = list[0].name
  } else {
    reportFormData.value.prj_id = undefined
    reportFormData.value.prj_name = undefined
  }
}

const cancelSelect = () => {
  // checkedTreeData(unref(tr), []) 
}

// 获取上传进度信息
const onProgressResult = (e: UniApp.OnProgressUpdateResult) => {
  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 handlerCreateWeekReport = async () => {
  const isValid = await formRef.value?.validate()
  if (!isValid) {
    return
  }
  await addWeekReport({
    prj_id: reportFormData.value.prj_id!,
    summary: reportFormData.value.summary!,
    issues: reportFormData.value.issues,
    plan: reportFormData.value.plan!,
    attachments: fileList.value.map(item => item.id)
  })
  emitter.emit('get_week_report_list')
  uni.showModal({
    title: '创建成功，是否返回？',
    success: (res: { confirm: boolean }) => {
      const { confirm } = res;
      if (confirm) {
        return uni.navigateBack()
      }
    }
  })
}

onLoad((option) => {
  reportFormData.value.prj_id = option?.prj_id
  reportFormData.value.prj_name = option?.prj_name
  isProject.value = option?.prj_id !== undefined
  if (!isProject.value) {
    getProjects()
  }
});



const restForm = async () => {
  if (!isProject.value) {
    reportFormData.value.prj_id = undefined
    reportFormData.value.prj_name = undefined
    fileList.value = []
    reportFormData.value.issues = undefined;
    reportFormData.value.summary = undefined;
    reportFormData.value.plan = undefined;
  } else {
    fileList.value = []
    reportFormData.value.issues = undefined;
    reportFormData.value.summary = undefined;
    reportFormData.value.plan = undefined;
  }
}




onMounted(() => {

  getSelf()
  reportFormData.value.weeks = getWeek(new Date())
})

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