<script setup lang="ts">
import AddTextbookListDialog from '../stepTwoComponents/AddTextbookListDialog.vue'
const emit = defineEmits<Emits>()

const dataList: any = ref([])
const isShowAddDialog = ref(false)
interface Emits {
  (e: 'information', dataList: any): void
}
const props = defineProps({
  data: {
    type: Array,
    required: true
  },
  id: {
    type: String
  }
})

watch(
  () => props.data,
  value => {
    if (value?.length > 0) {
      dataList.value = [...props.data]
    } else {
      dataList.value = []
    }
  },
  { immediate: true }
)
watch(
  () => dataList.value,
  value => {
    if (value?.length > 0) {
      emit('information', dataList.value)
    }
  }
)

const handleAddData = () => {
  isShowAddDialog.value = true
}
const handleAdd = (val: any) => {
  dataList.value = [val]
  emit('information', dataList.value)
}
const listOptions = $computed(() => {
  return {
    columns: [
      { label: '数字教材名称', prop: 'name' },
      {
        label: '封面',
        prop: 'img',
        computed(row: any) {
          return `<img src="${row.row.img}" style="height:100px;display:block">`
        }
      },
      { label: '作者', prop: 'authors' },
      // { label: '发布者', prop: 'user.real_name' },
      // { label: '版号', prop: 'name' },
      { label: '操作', slots: 'table-operate', align: 'center', width: 200, fixed: 'right' }
    ],
    data: dataList.value.length > 0 ? dataList.value : []
  }
})

const handleDel = (row: any) => {
  const index = dataList.value.findIndex((item: any) => item.id === row.id)
  dataList.value.splice(index, 1)
  emit('information', dataList.value)
}

const handleView = function (row: any) {
  window.open(`https://zijingebook.ezijing.com/student/book?book_id=${row.id}`)
}
</script>

<template>
  <div>
    <el-button type="primary" @click="handleAddData">添加数字教材</el-button>
    <AppList v-bind="listOptions" ref="appList">
      <template #table-operate="{ row }">
        <el-button plain @click="handleView(row)">查阅</el-button>
        <el-button type="primary" plain @click="handleDel(row)">删除</el-button>
      </template>
    </AppList>
    <!-- 添加资源 -->
    <AddTextbookListDialog
      v-if="isShowAddDialog === true"
      v-model:isShowAddDialog="isShowAddDialog"
      @create="handleAdd"
    />
  </div>
</template>
<style>
.node_type {
  background: #bf9d6b;
  border-radius: 20px;
  line-height: 1;
  font-size: 12px;
  font-weight: 400;
  color: #ffffff;
  text-align: center;
  padding: 4px 8px;
  margin-right: 14px;
}
</style>
