<script setup>
import { getExperimentRecord } from '../api'
import { useNow, useDateFormat } from '@vueuse/core'

const props = defineProps({ experiment: Object, data: Object })

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

let pictures = $ref([])
const currentPictures = $computed(() => {
  return pictures.map(item => {
    const is_bind = !!props.data.files.find(file => file.url === item.url)
    return { ...item, is_bind }
  })
})
function fetchRecord() {
  getExperimentRecord({ experiment_id: props.experiment.id }).then(res => {
    pictures = res.data.data.pictures || []
  })
}
onMounted(() => {
  fetchRecord()
})

function handleBind(row) {
  const files = props.data.files
  const formatted = useDateFormat(useNow(), 'YYYY-MM-DD HH:mm:ss')
  emit('update', [
    ...files,
    {
      id: Date.now().toString(),
      url: row.url,
      name: row.name,
      type: '2',
      file_type: 'png',
      updated_time: formatted.value,
      upload_time: row.upload_time
    }
  ])
}

function handleRemove(row) {
  const files = props.data.files
  emit(
    'update',
    files.filter(file => file.url !== row.url)
  )
}
</script>

<template>
  <el-dialog append-to-body title="关联截图" width="800px" @update:modelValue="value => $emit('update:modelValue', value)">
    <el-table :data="currentPictures" stripe>
      <el-table-column prop="name">
        <template #default="{ row }">
          <el-link type="primary" :href="row.url" target="_blank"> {{ row.name }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="upload_time"></el-table-column>
      <el-table-column width="100">
        <template #default="{ row }">
          <el-button text type="danger" @click="handleRemove(row)" v-if="row.is_bind">取消关联</el-button>
          <el-button text type="primary" @click="handleBind(row)" v-else>关联截图</el-button>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <el-row justify="center">
        <el-button round auto-insert-space @click="$emit('update:modelValue', false)">关闭</el-button>
      </el-row>
    </template>
  </el-dialog>
</template>
