<template>
  <div class="file-item-group">
    <!-- 搜索区域 -->
    <div class="search-area">
      <a-form-model ref="searchForm" :model="formData" layout="inline">
        <a-form-model-item prop="dateRange">
          <a-range-picker
            v-model="formData.dateRange"
            :ranges="dateRanges"
            :show-time="{ format: 'HH:mm' }"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
            :placeholder="['开始时间', '结束时间']"
            @change="handleDateChange"
          />
        </a-form-model-item>
        <a-form-model-item>
          <a-button type="primary" :loading="loading" @click="handleSearch">
            <a-icon type="search" />查询
          </a-button>
        </a-form-model-item>
        <a-form-model-item v-if="currUser.rolestr.includes('补录附件') && workflowId">
          <a-button type="primary" :loading="loading" @click="showfiles">
            <a-icon type="upload" />上传附件
          </a-button>
        </a-form-model-item>
      </a-form-model>
    </div>

    <!-- 文件列表区域 -->
    <template v-if="Object.keys(groupedFiles).length > 0">
      <div class="file-list-container">
        <a-spin :spinning="loading">
          <template v-for="(group, date) in groupedFiles">
            <div :key="date" class="file-group">
              <div class="group-header">
                <a-icon type="calendar" />
                <span class="date-label">{{ formatDate(date) }}</span>
                <span class="file-count">({{ group.length }}个文件)</span>
              </div>
              <file-item
                :files="group"
                :downloadable="downloadable"
              />
            </div>
          </template>
        </a-spin>
      </div>
    </template>
    <template v-else>
      <a-empty></a-empty>
    </template>
    <a-modal
      v-model="applyAddFiles"
      :footer="null"
      :dialog-style="{ top: '5rem' }"
      :z-index="1001"
      title="附件补录"
      :destroyOnClose="true">
      <x-add-native-form ref="xForm" @onSubmit="applySubmit"/>
    </a-modal>
  </div>
</template>

<script>
import FileItem from './FileItem.vue'
import XAddNativeForm from '@vue2-client/base-client/components/common/XAddNativeForm/XAddNativeForm.vue'
import { getConfigByName, runLogic } from '@vue2-client/services/api/common'
import { postByServiceName } from '@vue2-client/services/api/restTools'
import { mapState } from 'vuex'

export default {
  name: 'FileItemGroup',
  components: {
    FileItem,
    XAddNativeForm
  },
  props: {
    downloadable: {
      type: Boolean,
      default: true
    },
    workflowId: {
      type: String,
      default: ''
    }
  },
  data () {
    const now = new Date()
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
    const yesterday = new Date(today)
    yesterday.setDate(yesterday.getDate() - 1)
    const last7Days = new Date(today)
    last7Days.setDate(last7Days.getDate() - 6)
    const last30Days = new Date(today)
    last30Days.setDate(last30Days.getDate() - 29)

    return {
      loading: false,
      formData: {
        dateRange: []
      },
      files: [],
      applyAddFiles: false,
      dateRanges: {
        今天: [today, new Date(today.getTime() + 24 * 60 * 60 * 1000 - 1)],
        昨天: [yesterday, new Date(yesterday.getTime() + 24 * 60 * 60 * 1000 - 1)],
        最近7天: [last7Days, new Date(today.getTime() + 24 * 60 * 60 * 1000 - 1)],
        最近30天: [last30Days, new Date(today.getTime() + 24 * 60 * 60 * 1000 - 1)]
      }
    }
  },
  mounted () {
    this.handleSearch()
  },
  computed: {
    ...mapState('account', { currUser: 'user' }),
    groupedFiles () {
      const groups = {}
      this.files.forEach(file => {
        const originalDate = file.upload_time?.split(' ')[0]

        let displayDate
        if (!originalDate || !/^\d{4}-\d{2}-\d{2}$/.test(originalDate)) {
          displayDate = '无日期'
        } else {
          displayDate = originalDate
        }

        groups[displayDate] = groups[displayDate] || []
        groups[displayDate].push(file)
      })

      // 自定义排序：有日期的按日期降序，无日期在最后
      return Object.fromEntries(
        Object.entries(groups).sort(([dateA], [dateB]) => {
          if (dateA === '无日期') return 1
          if (dateB === '无日期') return -1
          return dateB.localeCompare(dateA)
        })
      )
    }
  },
  methods: {
    handleDateChange (dates) {
      this.formData.dateRange = dates
    },
    handleSearch () {
      this.$refs.searchForm.validate(async valid => {
        if (valid) {
          this.loading = true
          let queryDate
          if (this.formData.dateRange && this.formData.dateRange.length > 0) {
            queryDate = this.formData.dateRange
          } else {
            queryDate = undefined
          }
          const callback = (res) => {
            console.warn('>>>callback', res)
            this.files = res.files
            this.loading = false
          }
          const errorCallback = (e) => {
            console.warn('>>>errorCallback', e)
            this.$message.error('获取文件列表失败:' + e.getMessage())
            this.loading = false
          }
          this.$emit('search', queryDate, callback, errorCallback)
        } else {
          this.$message.error('请检查日期选择是否正确')
        }
      })
    },
    formatDate (date) {
      if (date === '无日期') {
        return '无日期'
      }
      const today = new Date().toISOString().split('T')[0]
      const yesterday = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString().split('T')[0]

      if (date === today) {
        return '今天'
      } else if (date === yesterday) {
        return '昨天'
      }

      const [year, month, day] = date.split('-')
      return `${year}年${month}月${day}日`
    },
    showfiles () {
      this.applyAddFiles = true
      // 获取所有步骤
      postByServiceName('/logic/getWorkFlowDefine', {
        id: this.workflowId
      }).then(res => {
        const steps = res.steps
        runLogic('getWorkFlowStepState', { workflowId: this.workflowId }, 'af-system').then(
          work => {
           const stepState = work
            console.log('stepState', stepState)
            const options = []
            stepState.forEach(state => {
              steps.forEach(step => {
                if (step.name === state.f_name) {
                  step.properties.form.formJson.forEach(item => {
                    if (item.type === 'file') {
                      options.push({
                        label: step.name,
                        value: step.name
                      })
                    }
                  })
                }
              })
            })
            // 去重操作
            const keys = options.filter((option, index, self) =>
              index === self.findIndex(opt => opt.value === option.value)
            )
            this.$nextTick(
              () => {
                getConfigByName('addApplyFilesForm', 'af-system', (res) => {
                  res.formJson[0].keys = keys
                  this.$refs.xForm.init({
                    businessType: '新增',
                    title: '附件补录',
                    ...res
                  })
                })
              }
            )
          }
        )
      })
    },
    applySubmit (formData) {
      console.log('formData', formData)
      formData.workflowId = this.workflowId
      runLogic('addApplyFiles', formData, 'af-system').then(
        res => {
          this.$message.success('附件补录成功')
          this.handleSearch()
          this.applyAddFiles = false
        }
      ).catch(() => {
        this.applyAddFiles = false
      })
    }
  }
}
</script>

<style lang="less" scoped>
.file-item-group {
  .search-area {
    display: flex;
    gap: 16px;
    margin-bottom: 24px;
    padding: 16px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
  }

  .file-list-container {
    .file-group {
      margin-bottom: 24px;

      .group-header {
        display: flex;
        align-items: center;
        margin-bottom: 16px;
        padding: 8px 16px;
        background: #fafafa;
        border-radius: 6px;

        .anticon {
          margin-right: 8px;
          color: @primary-color;
        }

        .date-label {
          font-size: 15px;
          font-weight: 500;
          color: rgba(0, 0, 0, 0.85);
        }

        .file-count {
          margin-left: 8px;
          color: rgba(0, 0, 0, 0.45);
          font-size: 13px;
        }
      }
    }
  }
}
</style>
