<template>
  <div class="detail-drawer-container">
    <van-popup v-model:show="props.showDialog" position="right"
      :style="{ width: '100vw', maxWidth: '460px', height: '100vh' }" :closeable="true" @close="closeDialog"
      :close-on-click-overlay="false">
      <div class="drawer-wrapper">
        <header class="drawer-header">
          <h3>详情</h3>
        </header>
        <div class="drawer-body">
          <van-cell-group inset>
            <van-field v-model="state.form.projectGroupName" label="课题名称" readonly placeholder="请输入课题名称" />
            <van-field v-model="state.form.userName" label="姓名" readonly placeholder="请输入姓名" />
            <van-field v-model="state.form.deptName" label="部门" readonly />
            <van-field v-model="state.form.phone" label="联系方式" readonly />
          </van-cell-group>

          <h4 class="section-title">实验动物笼位预约信息</h4>
          <van-cell-group inset>
            <van-field v-model="state.form.number" label="笼位数量" readonly type="digit" />
            <van-field v-model="state.form.startDate" label="开始使用时间" readonly placeholder="请开始使用时间" />
            <van-field v-model="state.form.categoryName" label="动物类别" readonly placeholder="请选择" />
            <van-field v-model="state.form.variety" label="品种品系" readonly placeholder="请选择" />
            <van-field v-model="levelName" label="饲养区域" readonly placeholder="请选择" />
            <van-field :modelValue="state.form.age.min === state.form.age.max ? state.form.age.min : `${state.form.age.min} - ${state.form.age.max}`" label="周龄" readonly />
            <van-field :modelValue="state.form.age.min === state.form.age.max ? state.form.age.min : `${state.form.age.min} - ${state.form.age.max}`" label="体重" readonly />
            <van-field v-model="state.form.maleNumber" label="雄性" readonly type="digit" />
            <van-field v-model="state.form.famaleNumber" label="雌性" readonly type="digit" />
            <van-field v-model="state.form.totalNumber" label="合计" readonly type="digit" />
            <van-field v-model="state.form.feedingDay" label="饲养总天数" readonly type="digit" />
          </van-cell-group>

          <h4 class="section-title">采购渠道</h4>
          <van-cell-group inset>
            <van-cell title="采购渠道">
              <template #value>
                <van-radio-group v-model="state.form.buyFrom" direction="horizontal" disabled>
                  <van-radio :name="ProcurementChannels.PURCHASED_BY_OTHERS">动物房代购</van-radio>
                  <van-radio :name="ProcurementChannels.PURCHASED_BY_MYSELF">自行购买</van-radio>
                </van-radio-group>
              </template>
            </van-cell>
            <van-field v-if="state.form.buyFrom === ProcurementChannels.PURCHASED_BY_MYSELF"
              v-model="state.form.comeFromUnit" label="外购来源单位" readonly />
            <van-field v-model="state.form.comeTime" label="动物到达时间" readonly placeholder="请选择到达时间" />
          </van-cell-group>

          <h4 class="section-title">特殊要求和附件</h4>
          <van-cell-group inset>
            <van-cell title="是否有特殊饲养要求">
              <template #value>
                <van-radio-group v-model="state.form.hasFeedingSpecial" direction="horizontal" disabled>
                  <van-radio :name="FeedingSpecial.HAVE_FEEDING_SPECIAL">有</van-radio>
                  <van-radio :name="FeedingSpecial.NO_FEEDING_SPECIAL">无</van-radio>
                </van-radio-group>
              </template>
            </van-cell>
            <van-field v-model="state.form.feedingSpecialDesc" label="特殊饲养要求" readonly type="textarea" rows="3"
              placeholder="请输入特殊饲养要求" />
          </van-cell-group>

          <!-- 附件列表 -->
          <van-cell-group v-if="state.form.licenseNumberFile && JSON.stringify(state.form.licenseNumberFile) !== '[]'"
            inset class="mt10">
            <van-cell title="生产许可证">
              <template #value>
                <div class="file-links">
                  <a v-for="item in state.form.licenseNumberFile" :key="item.url" :href="item.url" target="_blank"
                    class="file-link">
                {{ item.name }}
                  </a>
                </div>
              </template>
            </van-cell>
          </van-cell-group>

          <van-cell-group v-if="state.form.animalTestDateFile && JSON.stringify(state.form.animalTestDateFile) !== '[]'"
            inset class="mt10">
            <van-cell title="近三个月动物质量检测证明">
              <template #value>
                <div class="file-links">
                  <a v-for="item in state.form.animalTestDateFile" :key="item.url" :href="item.url" target="_blank"
                    class="file-link">
                {{ item.name }}
                  </a>
                </div>
              </template>
            </van-cell>
          </van-cell-group>

          <van-cell-group
            v-if="state.form.geneIdentificationFile && JSON.stringify(state.form.geneIdentificationFile) !== '[]'" inset
            class="mt10">
            <van-cell title="基因鉴定报告">
              <template #value>
                <div class="file-links">
                  <a v-for="item in state.form.geneIdentificationFile" :key="item.url" :href="item.url" target="_blank"
                    class="file-link">
                {{ item.name }}
                  </a>
                </div>
              </template>
            </van-cell>
          </van-cell-group>

          <van-cell-group v-if="state.form.envTestDateFile && JSON.stringify(state.form.envTestDateFile) !== '[]'" inset
            class="mt10">
            <van-cell title="近三个月饲养环境检测证明">
              <template #value>
                <div class="file-links">
                  <a v-for="item in state.form.envTestDateFile" :key="item.url" :href="item.url" target="_blank"
                    class="file-link">
                {{ item.name }}
                  </a>
                </div>
              </template>
            </van-cell>
          </van-cell-group>

          <van-cell-group v-if="state.form.cageAppointFile && JSON.stringify(state.form.cageAppointFile) !== '[]'" inset
            class="mt10">
            <van-cell title="笼位预约表">
              <template #value>
                <div class="file-links">
                  <a v-for="item in state.form.cageAppointFile" :key="item.url" :href="item.url" target="_blank"
                    class="file-link">
                {{ item.name }}
                  </a>
                </div>
              </template>
            </van-cell>
          </van-cell-group>

          <van-cell-group v-if="state.form.ethicsCheckFile && JSON.stringify(state.form.ethicsCheckFile) !== '[]'" inset
            class="mt10">
            <van-cell title="实验动物福利伦理审查申请表">
              <template #value>
                <div class="file-links">
                  <a v-for="item in state.form.ethicsCheckFile" :key="item.url" :href="item.url" target="_blank"
                    class="file-link">
                {{ item.name }}
                  </a>
                </div>
              </template>
            </van-cell>
          </van-cell-group>

          <van-cell-group v-if="state.form.ethicsAdviceFile && JSON.stringify(state.form.ethicsAdviceFile) !== '[]'"
            inset class="mt10">
            <van-cell title="实验动物福利伦理审查意见表">
              <template #value>
                <div class="file-links">
                  <a v-for="item in state.form.ethicsAdviceFile" :key="item.url" :href="item.url" target="_blank"
                    class="file-link">
                {{ item.name }}
                  </a>
                </div>
              </template>
            </van-cell>
          </van-cell-group>

          <div class="card mt10">
            <h4 class="section-title">审批记录</h4>
            <FlowTable :id="state.form.id" :businessCode="`${state.form.id}`" defCode="plat_cage_applications" />
          </div>
        </div>
        </div>
    </van-popup>
  </div>
</template>

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

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

  const FlowTable = defineAsyncComponent(() => import('/@/components/FlowTable.vue'))

  // 定义子组件向父组件传值/事件
  const props = defineProps({
    code: { type: String, default: '' },
    showDialog: { type: Boolean, default: false },
    isReturnCageList: { type: Boolean, default: false },
  })
  const emit = defineEmits(['close'])

  const platAnimalCageApplicationApi = usePlatAnimalCageApplicationApi()

  const expertDialogFormRef = ref()
  const animalTypeList = ref<any[]>([])

  // 解析范围字段
  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 categoryName = computed(() => {
  if (state.form.categoryId) {
    const category = animalTypeList.value.find((item) => item.id === state.form.categoryId)
    return category ? category.name : ''
  }
  return ''
})

const levelName = computed(() => {
  if (state.form.level) {
    const level = LeavelList.find((item) => item.id === state.form.level)
    return level ? level.name : ''
  }
  return ''
})

  const state = reactive({
    form: {
      id: 0,
      userName: '',
      number: 0,
      approveStatus: '',
      categoryName: '',
    variety: '',
      projectGroupName: '',
      createdTime: '',
      returnNumber: 0,
      maleNumber: 0,
      famaleNumber: 0,
      weight: { min: null, max: null },
      age: { min: null, max: null },
      feedingDay: 0,
      buyFrom: ProcurementChannels.PURCHASED_BY_OTHERS,
      comeTime: '',
      comeFromUnit: '',
      licenseNumberFile: [],
      animalTestDateFile: [],
      envTestDateFile: [],
      hasFeedingSpecial: FeedingSpecial.HAVE_FEEDING_SPECIAL,
      feedingSpecialDesc: '',
      cageAppointFile: [],
      ethicsCheckFile: [],
      ethicsAdviceFile: [],
      geneIdentificationFile: [],
      deptName: '',
      phone: '',
      categoryId: null,
      level: null,
      startDate: '',
      totalNumber: 0,
    },
    disabled: false,
  })

  const getDicts = () => {
    Promise.all([platAnimalCageApplicationApi.getAnimalTypeList({})]).then(([animalType]) => {
      animalTypeList.value = animalType.data
    })
  }

  // 打开弹窗
  const initForm = async (code: string) => {
    await getDicts()
    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'),
      licenseNumberFile: res?.data?.licenseNumberFile ? JSON.parse(res?.data?.licenseNumberFile) : [],
      animalTestDateFile: res?.data?.animalTestDateFile ? JSON.parse(res?.data?.animalTestDateFile) : [],
      envTestDateFile: res?.data?.envTestDateFile ? JSON.parse(res?.data?.envTestDateFile) : [],
      cageAppointFile: res?.data?.cageAppointFile ? JSON.parse(res?.data?.cageAppointFile) : [],
      ethicsCheckFile: res?.data?.ethicsCheckFile ? JSON.parse(res?.data?.ethicsCheckFile) : [],
      ethicsAdviceFile: res?.data?.ethicsAdviceFile ? JSON.parse(res?.data?.ethicsAdviceFile) : [],
      geneIdentificationFile: res?.data?.geneIdentificationFile ? JSON.parse(res?.data?.geneIdentificationFile) : [],
    }

  }

  const closeDialog = () => {
    emit('close')
  if (expertDialogFormRef.value && expertDialogFormRef.value.resetFields) {
    expertDialogFormRef.value.resetFields()
  }
  }

  // 暴露变量
  defineExpose({
    initForm,
  })

  watch(
    () => [state.form.maleNumber, state.form.famaleNumber],
    ([maleNumber, famaleNumber]) => {
      state.form.totalNumber = (maleNumber || 0) + (famaleNumber || 0)
    },
    { immediate: true },
  )
</script>
<style lang="scss" scoped>
.detail-drawer-container {
  .drawer-wrapper {
    display: flex;
    flex-direction: column;
    height: 100vh;
  }

  .drawer-header {
    padding: 16px;
    border-bottom: 1px solid #f0f0f0;

    h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      text-align: center;
    }
  }

  .drawer-body {
    flex: 1;
    overflow-y: auto;
    padding: 16px 12px 80px;
    -webkit-overflow-scrolling: touch;
  }

  .section-title {
    font-size: 16px;
    font-weight: 600;
    margin: 20px 0 8px;
    padding-left: 8px;
    position: relative;

    &::before {
      content: '';
    position: absolute;
    left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 3px;
      height: 16px;
      background-color: #1c9bfd;
    }
  }

  .file-links {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }

  .file-link {
    color: #1989fa;
    text-decoration: none;
    word-break: break-all;

    &:hover {
      text-decoration: underline;
    }
  }

  .card {
    background-color: #fff;
    border-radius: 8px;
    margin-top: 16px;
  }

  .mt10 {
    margin-top: 10px;
  }
}

:deep(.van-field__label) {
  width: 120px;
}

:deep(.van-cell__title) {
  flex: 0 0 120px;
  }
</style>