<script setup lang="ts">
import { useStorage } from '@vueuse/core'
import { getVideoList, createCharacter, getCourseListSearch, getLessonList, getOtherList } from '../../api'
import CardListItem from './CardListItem.vue'
import { useGetCategoryList } from '@/composables/useGetCategoryList'
import { ElMessage } from 'element-plus'
import { PictureFilled } from '@element-plus/icons-vue'
const appList = ref()
// 资源出处 tab触发
const tabValue = ref('1')
const path = ref('')
const tableData = ref<any>({
  list: [],
  title: '',
  total: '',
})
const emit = defineEmits<Emits>()
const props = defineProps({
  isShowAddDialog: {
    type: Boolean,
    required: true,
  },
  course_id: {
    type: String,
    required: true,
  },
  chapterName: {
    type: String,
    required: true,
  },
  chapterID: {
    type: String,
    required: true,
  },
  btnInfo: {
    type: Object,
    required: true,
  },
})
interface Emits {
  (e: 'update:isShowAddDialog', isShowVideoDialog: boolean): void
  (e: 'create', val: any): void
}
// 筛选下拉选择tree 视频分类
let { list: selectTree }: any = useGetCategoryList()
const defaultProps = {
  children: 'children',
  label: 'category_name',
  value: 'id',
}
const typeFilter = () => {
  appList.value.refetch()
}

const listOptions = computed(() => {
  let getHttpRequest = null
  if (props.btnInfo.resource_type === '2') {
    getHttpRequest = getVideoList
  } else if (props.btnInfo.resource_type === '10') {
    getHttpRequest = getCourseListSearch
  } else if (props.btnInfo.resource_type === '11') {
    getHttpRequest = getLessonList
  } else if (props.btnInfo.resource_type === '4') {
    getHttpRequest = getOtherList
  }

  return {
    remote: {
      httpRequest: getHttpRequest,
      beforeRequest(params: any) {
        if (params.course_id === '0') {
          params.course_id === ''
        }
        return params
      },
      callback(data: any) {
        data.list.forEach((item: any) => (item.check_status = false))
        tableData.value = data
        return { list: data.list, total: data.total }
      },
      params: { tab: tabValue, status: '1', authorized: '', name: '', course_id: props.course_id || '' },
    },
    filters: [
      { prop: 'classification', label: '类别：', slots: 'filter-type' },
      { type: 'input', prop: 'name', label: '标题：' },
    ],
    columns: [
      { type: 'selection' },
      {
        label: '视频标题',
        prop: 'name',
        align: 'center',
        computed({ row }: any) {
          return row.name?.length > 10 ? `${row.name.slice(0, 10)}...` : row.name
        },
      },
      { label: '视频分类', prop: 'classification_name', align: 'center' },
      { label: '知识点', prop: 'knowledge_points', align: 'center' },
      { label: '封面', slots: 'table-cover', width: 150, align: 'center' },
      { label: '资源状态', prop: 'status_name', align: 'center' },
      { label: '审核状态', prop: 'audit_status_name', align: 'center' },
      { label: '更新人', prop: 'updated_operator_name', align: 'center' },
      { label: '更新人部门', prop: 'organ_id_name', align: 'center' },
      { label: '更新日期', prop: 'updated_time', align: 'center' },
    ],
    data: tableData.value.list,
  }
})
// tab切换
const tabChange = () => {
  appList.value?.refetch()
}
// 取消
const handleCancel = () => {
  emit('update:isShowAddDialog', false)
}
// 保存 添加
const handleAdd = (val: any) => {
  if (props.course_id === '0') {
    emit('update:isShowAddDialog', false)
    emit('create', val)
  } else {
    const params: any = {
      name: val.name,
      course_id: props.course_id,
      resource_type: props.btnInfo.resource_type,
      parent_id: props.chapterID,
      resource_id: val.id,
    }
    createCharacter(params).then(() => {
      emit('update:isShowAddDialog', false)
      emit('create', val)
    })
  }
}
if (props.btnInfo.resource_type === '2') {
  path.value = '/resource/video/view'
} else if (props.btnInfo.resource_type === '10') {
  path.value = '/resource/courseware/view'
} else if (props.btnInfo.resource_type === '11') {
  path.value = '/resource/lessonplan/view'
} else if (props.btnInfo.resource_type === '4') {
  path.value = '/resource/other/view'
}

const checkName = ref('全选')
// 写到这了
const checkboxAll = function () {
  const data = tableData.value.list.reduce((a: any, b: any) => {
    if (b.check_status) a.push(b)
    return a
  }, [])
  if (data.length === tableData.value.list.length) {
    tableData.value.list.map((item: any) => {
      item.check_status = false
      return item
    })
    checkName.value = '全选'
  } else {
    tableData.value.list.map((item: any) => {
      item.check_status = true
      return item
    })
    checkName.value = '取消全选'
  }
}

const checkboxSelect = function () {
  const data = tableData.value.list.reduce((a: any, b: any) => {
    if (b.check_status) a.push(b)
    return a
  }, [])
  data.length !== tableData.value.list.length ? (checkName.value = '全选') : (checkName.value = '取消全选')
}

const addVideo = function () {
  const data = tableData.value.list.filter((item: any) => item.check_status === true)
  data.forEach((item: any, index: number) => {
    addRequest(item, index, data)
  })
}

const addRequest = function (item: any, index: number, data: any) {
  if (props.course_id === '0') {
    emit('update:isShowAddDialog', false)
    emit('create', item)
  } else {
    const params: any = {
      name: item.name,
      course_id: props.course_id,
      resource_type: props.btnInfo.resource_type,
      parent_id: props.chapterID,
      resource_id: item.id,
    }
    createCharacter(params).then(() => {
      if (index === data.length - 1) {
        emit('update:isShowAddDialog', false)
        emit('create', item)
        ElMessage.success('添加成功')
      }
    })
  }
}

// 列表切换
const isCard = useStorage('isCard', true)
const changeCard = () => {
  isCard.value = !isCard.value
}

const checkBox = ref<any[]>([])
const select = function (row: any) {
  checkBox.value = row
}

const addVideoList = function () {
  checkBox.value.forEach((item: any, index: number) => {
    addRequest(item, index, checkBox.value)
  })
}
</script>

<template>
  <el-drawer
    :model-value="isShowAddDialog"
    draggable
    :before-close="handleCancel"
    size="60%"
    :title="`添加${props.btnInfo.btn_name}`">
    <div class="video-head">
      <el-tabs @tab-change="tabChange" v-model="tabValue">
        <el-tab-pane label="我的资源" name="1"></el-tab-pane>
        <el-tab-pane label="部门资源" name="2"></el-tab-pane>
        <el-tab-pane label="公开资源" name="3"></el-tab-pane>
      </el-tabs>
      <div class="video-head-icon" @click="changeCard">
        <img v-if="!isCard" src="/center_resource/change_card.png" alt="" />
        <img v-else src="/center_resource/change_list.png" alt="" />
      </div>
    </div>
    <AppList @selection-change="select" v-bind="listOptions" ref="appList">
      <template #header-aside></template>
      <template #table-cover="{ row }">
        <div style="background: #ccc">
          <el-icon :size="50" color="#fff" v-if="row.cover == ''">
            <PictureFilled></PictureFilled>
          </el-icon>
          <div
            v-else
            :style="`width: 150px;
              display: block;
              height: 83px;
              background-size: cover;
              background-image: url(${row.cover});`"></div>
        </div>
      </template>
      <template #filter-type="{ params }">
        <el-tree-select
          filterable
          @change="typeFilter"
          clearable
          :props="defaultProps"
          v-model="params.classification"
          :data="selectTree"
          :default-expanded-keys="selectTree.length ? [selectTree[0]?.id] : []" />
      </template>
      <template #body="{ data }" v-if="isCard">
        <div class="card-list" v-if="data.length">
          <div style="display: flex; margin-bottom: 20px">
            <el-button type="primary" @click="checkboxAll">{{ checkName }}</el-button>
            <el-button type="primary" @click="addVideo">添加</el-button>
          </div>
          <div class="card-list-con">
            <CardListItem
              v-for="(item, index) in data"
              :key="index"
              :tabIndex="tabValue"
              :data="item"
              :path="path"
              @add="handleAdd">
              <el-checkbox @change="checkboxSelect" v-model="item.check_status"></el-checkbox>
            </CardListItem>
          </div>
        </div>
      </template>
      <el-button style="margin-bottom: 20px" type="primary" @click="addVideoList" v-if="!isCard">添加</el-button>
    </AppList>
  </el-drawer>
</template>
<style lang="scss" scoped>
.card-list {
  display: flex;
  flex-direction: column;
}
.card-list-con {
  background: #fafafa;
  padding: 20px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
}
.video-head {
  position: relative;
  .video-head-icon {
    position: absolute;
    top: 0;
    right: 0;
    font-size: 30px;
    color: #666;
    cursor: pointer;
  }
}
.video-tool-btn {
  padding: 10px 0 30px 0;
}

.video-head-icon {
  position: absolute;
  top: 0;
  right: 0;
  font-size: 30px;
  color: #666;
  cursor: pointer;
}
</style>
