<template>
  <el-form ref="formRef" :model="form" :rules="rules" label-width="160px" >
    <el-row :gutter="24">
<!--      <el-col :span="12" class="mb20">-->
<!--        <el-form-item label="验收日期" prop="acceptDate">-->
<!--          <el-date-picker-->
<!--            v-model="form.acceptDate"-->
<!--            type="date"-->
<!--            placeholder="请选择"-->
<!--            format="YYYY-MM-DD"-->
<!--            value-format="YYYY-MM-DD"-->
<!--            style="width: 100%"-->
<!--            :disabled="readonly"-->
<!--          />-->
<!--        </el-form-item>-->
<!--      </el-col>-->

      <!-- 上传履约验收模版 -->
      <el-col :span="12" class="mb20">
        <el-form-item label="履约验收文件" prop="templateFileIds" :required="true">
          <upload-file v-model="templateFiles" :limit="1" :file-type="['pdf']" :data="{ purchaseId: purchaseId || '', fileType: '110' }" upload-file-url="/purchase/purchasingfiles/upload" :disabled="readonly" />
          <el-link v-if="!readonly" type="primary" @click="handleDownloadTemplate" style="margin-top: 8px; display: inline-flex; align-items: center;">
            <el-icon><Download /></el-icon>
            <span style="margin-left: 4px;">下载{{ lyysTemplateLabel }}</span>
          </el-link>
        </el-form-item>
      </el-col>

      <el-col :span="24">
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="请输入" :disabled="readonly" />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { Download } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import UploadFile from "/@/components/Upload/index.vue";
import { downloadTemplate } from "/@/api/purchase/purchasingAccept";

/** 项目类型 A:货物 B:工程 C:服务 */
const LYYS_TEMPLATE_MAP: Record<string, { label: string }> = {
  A: { label: '履约验收表模板（货物）' },
  B: { label: '履约验收表模板（工程）' },
  C: { label: '履约验收表模板（服务）' },
}

const props = defineProps<{
  modelValue: Record<string, any>
  readonly?: boolean
  purchaseId?: string
  /** 项目类型 A:货物 B:工程 C:服务，用于模版下载 */
  projectType?: string
  /** 预算金额，用于判断模板目录 */
  budget?: number
  batchNum?: number
}>()

const emit = defineEmits(['update:modelValue'])

const formRef = ref<FormInstance>()
// 文件对象数组，用于上传组件显示（包含id和fileTitle）
const templateFiles = ref<any[]>([])

const projectTypeKey = computed(() => (props.projectType === 'A' || props.projectType === 'B' || props.projectType === 'C' ? props.projectType : 'A'))
const lyysTemplateLabel = computed(() => {
  const amountLabel = (props.budget && props.budget >= 50000) ? '(≥5万)' : '(<5万)'
  return LYYS_TEMPLATE_MAP[projectTypeKey.value]?.label + amountLabel || LYYS_TEMPLATE_MAP.A.label + amountLabel
})
const lyysTemplateDownloadName = computed(() => `${lyysTemplateLabel.value}.docx`)

/** 下载模板 - 调用后台接口 */
const handleDownloadTemplate = async () => {
  if (!props.purchaseId) {
    ElMessage.warning('采购ID不存在')
    return
  }
  try {
    const res = await downloadTemplate(props.purchaseId)
    const blob = res as unknown as Blob
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = lyysTemplateDownloadName.value
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
  } catch (e: any) {
    ElMessage.error(e?.message || '下载模板失败')
  }
}

const form = reactive({
  acceptType: '2', // 固定为上传模式
  acceptDate: '',
  templateFileIds: [] as string[],
  remark: '',
})

// 从外部数据初始化（仅在挂载和 modelValue 引用变化时执行）
const initData = () => {
  const val = props.modelValue
  if (!val) return

  form.acceptType = '2'
  form.acceptDate = val.acceptDate || ''
  form.remark = val.remark || ''

  // 处理文件数据：支持 _templateFiles 数组或 templateFileIds
  if (val._templateFiles && Array.isArray(val._templateFiles)) {
    templateFiles.value = val._templateFiles.map((f: any) => ({
      id: f.id,
      fileTitle: f.fileTitle,
      name: f.fileTitle || '',
      url: '',
    }))
    form.templateFileIds = val._templateFiles.map((f: any) => f.id)
  } else if (val.templateFileIds) {
    if (typeof val.templateFileIds === 'string') {
      const ids = val.templateFileIds.split(',').filter(Boolean)
      templateFiles.value = ids.map((id: string) => ({ id: id.trim(), name: '', url: '' }))
      form.templateFileIds = ids
    } else if (Array.isArray(val.templateFileIds)) {
      templateFiles.value = val.templateFileIds.map((item: any) => {
        if (typeof item === 'string') return { id: item, name: '', url: '' }
        return { id: item.id, fileTitle: item.fileTitle, name: item.fileTitle || '', url: '' }
      })
      form.templateFileIds = val.templateFileIds.map((item: any) => typeof item === 'string' ? item : item.id).filter(Boolean)
    }
  } else {
    templateFiles.value = []
    form.templateFileIds = []
  }
}

// 挂载时初始化
onMounted(() => {
  initData()
})

// 监听文件变化，更新 form.templateFileIds
watch(templateFiles, (files) => {
  if (Array.isArray(files)) {
    form.templateFileIds = files.map((f: any) => f.id).filter(Boolean)
  } else {
    form.templateFileIds = []
  }
}, { deep: true })

const rules: FormRules = {
  templateFileIds: [
    { 
      validator: (_rule: any, value: any, callback: (e?: Error) => void) => {
        if (!value || (Array.isArray(value) && value.length === 0) || (typeof value === 'string' && !value.trim())) {
          callback(new Error('请上传履约验收文件'))
          return
        }
        callback()
      }, 
      trigger: 'change' 
    },
  ],
}

const validate = () => formRef.value?.validate()

// 获取当前表单数据（供父组件调用）
const getFormData = () => ({
  acceptType: form.acceptType,
  acceptDate: form.acceptDate,
  templateFileIds: [...form.templateFileIds],
  remark: form.remark,
})

defineExpose({ validate, form, getFormData, initData })
</script>

<style scoped>
.mb20 {
  margin-bottom: 20px;
}
</style>
