<template>
  <div class="facilities-dialog-container">
    <van-cell-group>
      <van-cell
        title="申请人姓名"
        :value="state.form.userName"
      />
      <van-cell
        title="课题名称"
        :value="state.form.projectGroupName"
      />
      <van-cell
        title="申请时间"
        :value="state.form.createdTime"
      />
      <van-cell
        title="申请状态"
        :value="state.form.approveStatus"
      />
      <van-cell
        title="申请笼位(个)"
        :value="state.form.number"
      />
      <van-cell
        title="动物类别"
        :value="state.form.categoryName"
      />
      <van-cell
        title="品种品系"
        :value="state.form.variety"
      />
      <van-cell
        title="采购渠道"
        :value="checkProcurementChannels"
      />
      <van-cell
        title="雄性数量(只)"
        :value="state.form.maleNumber"
      />
      <van-cell
        title="雌性数量(只)"
        :value="state.form.famaleNumber"
      />
      <van-cell
        title="动物体重"
        :value="state.form.weight.min === state.form.weight.max ? state.form.weight.max : `${state.form.weight.min} - ${state.form.weight.max}`"
      />
      <van-cell
        title="动物周龄"
        :value="state.form.age.min === state.form.age.max ? state.form.age.max : `${state.form.age.min} - ${state.form.age.max}`"
      />
      <van-cell
        title="饲养总天数"
        :value="state.form.feedingDay"
      />
      <van-cell
        title="动物到达时间"
        :value="state.form.comeTime"
      />
      <van-cell
        title="是否有特殊饲养要求"
        :value="checkSpecialFeedingRequirements"
      />
      <van-cell
        v-if="state.form.hasFeedingSpecial === FeedingSpecial.HAVE_FEEDING_SPECIAL"
        title="饲养要求描述"
        :value="state.form.feedingSpecialDesc"
      />
      <van-cell
        v-if="state.form.buyFrom==='20'"
        title="外购来源单位"
        :value="state.form.comeFromUnit"
      />
      <van-cell
        v-if="state.form.licenseNumberFile && state.form.buyFrom==='20'"
        title="生产许可证"
      >
        <template #value>
          <a
            :href="parseFileInfo(state.form.licenseNumberFile).url"
            target="_blank"
            class="file-link"
          >
            {{ parseFileInfo(state.form.licenseNumberFile).name }}
          </a>
        </template>
      </van-cell>
      <van-cell
        v-if="state.form.animalTestDateFile && state.form.buyFrom==='20'"
        title="近三月动物质量检测"
      >
        <template #value>
          <a
            :href="parseFileInfo(state.form.animalTestDateFile).url"
            target="_blank"
            class="file-link"
          >
            {{ parseFileInfo(state.form.animalTestDateFile).name }}
          </a>
        </template>
      </van-cell>
      <van-cell
        v-if="state.form.geneIdentificationFile && state.form.buyFrom==='20'"
        title="基因鉴定报告"
      >
        <template #value>
          <a
            :href="parseFileInfo(state.form.geneIdentificationFile).url"
            target="_blank"
            class="file-link"
          >
            {{ parseFileInfo(state.form.geneIdentificationFile).name }}
          </a>
        </template>
      </van-cell>
      <van-cell
        v-if="state.form.ethicsCheckFile"
        title="伦理审查表"
      >
        <template #value>
          <a
            :href="parseFileInfo(state.form.ethicsCheckFile).url"
            target="_blank"
            class="file-link"
          >
            {{ parseFileInfo(state.form.ethicsCheckFile).name }}
          </a>
        </template>
      </van-cell>
      <van-cell
        v-if="state.form.ethicsAdviceFile"
        title="伦理意见表"
      >
        <template #value>
          <a
            :href="parseFileInfo(state.form.ethicsAdviceFile).url"
            target="_blank"
            class="file-link"
          >
            {{ parseFileInfo(state.form.ethicsAdviceFile).name }}
          </a>
        </template>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script setup lang="ts" name="systemProDialog">
  import to from 'await-to-js'
  import { nextTick, reactive, watch, computed } from 'vue'
  import dayjs from 'dayjs'

  import { usePlatAnimalCageApplicationApi } from '/@/api/platform/animal'
  import { ProcurementChannels, FeedingSpecial } from '/@/constants/pageConstants'

  const checkProcurementChannels = computed(() => {
    return state.form.buyFrom === ProcurementChannels.PURCHASED_BY_OTHERS ? '动物房代购' : '自行购买'
  })

  const checkSpecialFeedingRequirements = computed(() => {
    return state.form.hasFeedingSpecial === FeedingSpecial.HAVE_FEEDING_SPECIAL ? '有' : '无'
  })

  // 定义子组件向父组件传值/事件
  const props = defineProps({
    code: { type: String, default: '' },
  })

  const approveStatusList = [
    {
      name: '待提交',
      id: 10,
    },
    {
      name: '审批中',
      id: 20,
    },
    {
      name: '通过',
      id: 30,
    },
    {
      name: '撤回',
      id: 35,
    },
    {
      name: '拒绝',
      id: 40,
    },
  ]
  // 解析范围字段
  const parseRangeField = (str: string) => {
    try {
      if (!str) return { min: 0, max: 0 };
      // 处理双重转义的情况
      const cleanStr = str.replace(/\\"/g, '"').replace(/^"|"$/g, '');
      const parsed = JSON.parse(cleanStr);
      return {
        min: parsed.min || 0,
        max: parsed.max || 0
      };
    } catch (e) {
      console.warn('解析范围字段失败:', str, e);
      return { min: 0, max: 0 };
    }
  };
  const platAnimalCageApplicationApi = usePlatAnimalCageApplicationApi()

  const state = reactive({
    form: {
      userName: '',
      number: 0,
      approveStatus: '',
      categoryName: '',
      variety: '',
      projectGroupName: '',
      createdTime: '',
      maleNumber: 0,
      famaleNumber: 0,
      weight: { min: null, max: null },
      age: { min: null, max: null },
      feedingDay: 0,
      buyFrom: '',
      comeTime: '',
      comeFromUnit: '',
      hasFeedingSpecial: '',
      feedingSpecialDesc: '',
      licenseNumberFile: '',
      animalTestDateFile: '',
      envTestDateFile: '',
      cageAppointFile: '',
      ethicsCheckFile: '',
      ethicsAdviceFile: '',
      geneIdentificationFile: '',
    },
    disabled: false,
  })

  // 解析附件字段，返回 { name, url }
  const parseFileInfo = (file: any): { name: string; url: string } => {
    const info = { name: '', url: '' }
    if (!file) return info
    try {
      if (typeof file === 'string') {
        const trimmed = file.trim()
        if ((trimmed.startsWith('{') && trimmed.endsWith('}')) || (trimmed.startsWith('[') && trimmed.endsWith(']'))) {
          const data = JSON.parse(trimmed)
          const pick = (d: any) => ({
            name: d?.name || d?.fileName || d?.originalName || d?.filename || '',
            url: d?.url || d?.fileUrl || d?.path || d?.filePath || '',
          })
          if (Array.isArray(data)) {
            const first = data[0] || {}
            return pick(first)
          }
          return pick(data)
        }
        // 普通字符串：可能是 URL 或文件名
        if (/^https?:\/\//.test(trimmed) || trimmed.includes('/') || trimmed.includes('\\')) {
          const segs = trimmed.split(/[\\\/]/)
          info.name = segs[segs.length - 1] || trimmed
          info.url = trimmed
        } else {
          info.name = trimmed
        }
        return info
      }
      if (typeof file === 'object') {
        info.name = file?.name || file?.fileName || file?.originalName || file?.filename || ''
        info.url = file?.url || file?.fileUrl || file?.path || file?.filePath || ''
        return info
      }
    } catch (e) {
      const s = String(file)
      const segs = s.split(/[\\\/]/)
      info.name = segs[segs.length - 1] || s
      info.url = s
    }
    return info
  }

  // 打开弹窗
  const initForm = async (code: string) => {
    const [err, res]: ToResponse = await to(platAnimalCageApplicationApi.getEntityById({ id: parseInt(code) }))
    if (err) return
    await nextTick()
    // 处理范围字段的JSON字符串
    const processedRow = {
      ...res?.data,
      age: parseRangeField(res?.data?.age),
      weight: parseRangeField(res?.data?.weight)
    };
    state.form = {
      ...processedRow,
      approveStatus: approveStatusList.find((item) => item.id == res?.data?.approveStatus)?.name,
      createdTime: dayjs(res?.data?.createdTime).format('YYYY-MM-DD'),
    }
  }

  watch(
    () => props.code,
    (val) => {
      initForm(val)
    },
    {
      deep: true,
      immediate: true,
    },
  )
  // 暴露变量
  defineExpose({
    initForm,
  })
</script>
<style lang="scss" scoped>
  .file-link {
    color: #1989fa;
    text-decoration: underline;
  }
</style>
