<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { ref, unref, nextTick, watch, reactive, onMounted } from 'vue'
import {
  ElTree,
  ElInput,
  ElDivider,
  ElButton,
  ElPagination,
  ElCard,
  ElImage,
  ElTooltip,
  ElEmpty,
  ElMessageBox,
  ElMessage,
  ElTabs,
  ElTabPane
} from 'element-plus'
import { Search } from '@/components/Search'
import { BaseButton } from '@/components/Button'
import {
  getFileType,
  getFileList,
  setFileType,
  delFileType,
  delFile,
  updateFile
} from '@/api/system/file'
import { FormSchema } from '@/components/Form'
import type Node from 'element-plus/es/components/tree/src/model/node'
import upFile from './components/upFile.vue'
import { useIcon } from '@/hooks/web/useIcon'
import { createVideoViewer } from '@/components/VideoPlayer'
const icon = useIcon({ icon: 'vi-ep:upload-filled' })
const successicon = useIcon({ icon: 'vi-ep:select' })
interface Tree {
  label?: string
  id: string | number
  children?: Tree[]
}
const { t } = useI18n()
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const fileType = ref(1)
const dataList = ref<any[]>([])
const searchParams = ref({ name: '' })
const searchSchema = reactive<FormSchema[]>([
  {
    field: 'name',
    label: '文件名',
    component: 'Input',
    colProps: { span: 8 }
  }
])
const modelValue = defineModel<any[]>({
  default: () => []
})
// 初始化数据
onMounted(() => {
  fetchDepartment()
})

const setSearchParams = (params: any) => {
  currentPage.value = 1
  searchParams.value = params
  getList()
}

const getList = async () => {
  const res = await getFileList({
    pid: unref(currentNodeKey),
    page: unref(currentPage),
    limit: unref(pageSize),
    file_type: unref(fileType),
    ...unref(searchParams)
  })
  dataList.value = res.data.list.map((ree) => {
    ree.checked = false
    return ree
  })
  total.value = res.data.count
}
const treeEl = ref<typeof ElTree>()
const currentNodeKey = ref('')
const departmentList = ref<any[]>([])
const fetchDepartment = async () => {
  getList()
  const res = await getFileType({
    file_type: unref(fileType)
  })
  departmentList.value = res.data.list
  departmentList.value.unshift({
    children: [],
    id: '',
    name: unref(fileType) == 1 ? '全部图片' : '全部视频'
  })
  currentNodeKey.value = ''
  await nextTick()
  unref(treeEl)?.setCurrentKey(currentNodeKey.value)
}

const currentDepartment = ref('')
watch(
  () => currentDepartment.value,
  (val) => {
    unref(treeEl)!.filter(val)
  }
)

const currentChange = (data) => {
  currentNodeKey.value = data.id
  currentPage.value = 1
  getList()
}
const tabChange = async (data) => {
  console.log('tabChange', data)
  fileType.value = data
  currentPage.value = 1
  dataList.value = []
  fetchDepartment()
}

const filterNode = (value: string, data) => {
  if (!value) return true
  return data.title.includes(value)
}

const showDrawer = ref(false)

const AddAction = () => {
  showDrawer.value = true
}

const delLoading = ref(false)
watch(currentPage, (val) => {
  if (val) {
    // console.log(val)
    currentPage.value = val
    getList()
  }
})
const append = async (data: Tree) => {
  const { value } = await ElMessageBox.prompt('请输入名称', '添加文件分类', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^.{1}(.*)$/,
    inputErrorMessage: '请填写内容'
  })
  const res = await setFileType({
    pid: data.id,
    name: value,
    file_type: unref(fileType)
  })

  if (res) {
    ElMessage({
      type: 'success',
      message: `添加成功`
    })
    fetchDepartment()
  }
}
const editorTitle = async (item) => {
  ElMessageBox.prompt('请输入名称', '编辑文件名称', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputValue: item.name,
    inputPattern: /^(.*).{1}[\.png,\.jpg,\.jpeg]{1}$/,
    inputErrorMessage: '请填写正确的文件名'
  }).then(async ({ value }) => {
    const res = await updateFile({
      id: item.att_id,
      real_name: value
    })
    if (res) {
      ElMessage({
        type: 'success',
        message: `编辑成功`
      })
      getList()
    }
  })
}
const remove = async (node: Node, data: Tree) => {
  await ElMessageBox.confirm('删除分类后无法恢复，是否删除？', '删除提示', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  })
  await delFileType(data.id)
  ElMessage({
    type: 'success',
    message: `删除成功`
  })
  const parent = node.parent
  const children: Tree[] = parent.data.children || parent.data
  const index = children.findIndex((d) => d.id === data.id)
  children.splice(index, 1)
}

const actionFileList = ref<any[]>([])
const checkedFile = (item) => {
  if (!checkedFileIs(item)) {
    actionFileList.value.push(item.att_id)
    modelValue.value.push(item)
  } else {
    const index = actionFileList.value.indexOf(item.att_id)
    actionFileList.value.splice(index, 1)
    modelValue.value.splice(index, 1)
  }
  // console.log(actionFileList.value, 'actionFileList.value')
}
const checkedFileIs = (item) => {
  // console.log(item, 'item')
  if (actionFileList.value.indexOf(item.att_id) == -1) {
    return false
  } else {
    return true
  }
}
const delData = async (id?: string) => {
  await ElMessageBox.confirm('删除图片后无法恢复，是否删除？', '删除提示', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  })
  let ids = ''
  if (id) {
    ids = id
  } else {
    ids = actionFileList.value.join(',')
  }
  const re = await delFile({ ids })
  actionFileList.value = []
  modelValue.value = []
  if (re) {
    ElMessage({
      type: 'success',
      message: `删除成功`
    })
    getList()
  }
}
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="w-250px">
      <div class="flex justify-center items-center">
        <ElInput
          v-model="currentDepartment"
          class="flex-[2] mr-3"
          placeholder="搜索分类"
          clearable
        />
        <BaseButton type="primary" @click="append({ id: '' })"> 新增 </BaseButton>
      </div>
      <ElDivider />
      <ElTree
        ref="treeEl"
        :data="departmentList"
        default-expand-all
        :expand-on-click-node="false"
        node-key="id"
        :current-node-key="currentNodeKey"
        :props="{
          label: 'name'
        }"
        :filter-node-method="filterNode"
        @current-change="currentChange"
      >
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <span>{{ node.label }}</span>
            <span @click.stop>
              <BaseButton link size="small" type="primary" @click="append(data)"> 添加 </BaseButton>
              <BaseButton link size="small" type="primary" @click="remove(node, data)">
                删除
              </BaseButton>
            </span>
          </span>
        </template>
      </ElTree>
    </ContentWrap>
    <ContentWrap class="flex-[3] ml-20px">
      <ElTabs class="tabs" v-model="fileType" @tab-change="tabChange">
        <ElTabPane label="图片" :name="1" />
        <ElTabPane label="视频" :name="2" />
      </ElTabs>
      <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />
      <div class="mb-10px">
        <BaseButton type="primary" :icon="icon" @click="AddAction">{{
          fileType == 1 ? '上传图片' : '上传视频'
        }}</BaseButton>
        <BaseButton
          :loading="delLoading"
          type="danger"
          :disabled="actionFileList.length == 0"
          @click="delData()"
        >
          {{ t('exampleDemo.del') }}
        </BaseButton>
      </div>
      <div class="flex flex-wrap justify-start">
        <ElCard class="card-list mr-3 mb-3" v-for="(item, index) in dataList" :key="index">
          <template #header>
            <ElTooltip effect="dark" :content="item.name" placement="top">
              <div class="flex align-center">
                <div class="white-nowrap">{{ item.name }}</div>
                <!-- <BaseButton link size="small" type="primary" @click="editorTitle(item)">
                  修改
                </BaseButton> -->
              </div>
            </ElTooltip>
          </template>
          <ElImage
            v-if="fileType == 1"
            class="card-list-img"
            fit="contain"
            :key="index"
            :src="item.satt_dir"
            hide-on-click-modal
            :alt="item.name"
            :preview-src-list="[item.att_dir]"
          >
            <template #error>
              <div class="h-100% flex items-center justify-center">
                <Icon icon="vi-ep:picture" :size="30" />
              </div>
            </template>
          </ElImage>
          <div
            v-if="fileType == 2"
            class="card-list-img"
            @click="
              createVideoViewer({
                url: item.satt_dir
              })
            "
          >
            <div class="payBackground flex items-center justify-center">
              <Icon icon="vi-ep:caret-right" :size="80" />
            </div>
          </div>
          <template #footer>
            <BaseButton
              class="buttom-checked"
              link
              :loading="delLoading"
              type="danger"
              @click="delData(item.att_id)"
            >
              {{ t('exampleDemo.del') }}
            </BaseButton>
            <ElButton
              class="buttom-checked"
              :type="!checkedFileIs(item) ? 'info' : 'success'"
              :icon="successicon"
              size="small"
              @click="checkedFile(item)"
            />
          </template>
        </ElCard>
        <ElEmpty class="flex-1" v-if="dataList.length == 0" description="暂无数据" />
      </div>
      <ElPagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        layout="sizes, prev, pager, next, jumper, ->, total"
        :page-sizes="[10, 20, 30, 40, 50, 100]"
        class="mt-10px"
        :total="total"
      />
    </ContentWrap>
    <upFile :fileType="fileType" v-model="showDrawer" @confirm="getList" />
  </div>
</template>
<style lang="less" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.card-list {
  font-size: 10px;
  width: 150px;
  :deep(&.el-card) {
    line-height: 1;
    .el-card__header {
      padding: 5px 10px !important;
      .white-nowrap {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        align-self: center;
      }
    }

    .el-card__body {
      padding: 0 !important;
      height: 150px;
    }
    .el-card__footer {
      padding: 0 !important;
      text-align: center;
    }
  }
  .card-list-img {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    .payBackground {
      color: #fff;
      width: 90px;
      height: 90px;
      background-color: rgba(0, 0, 0, 0.2);
      border-radius: 100%;
    }
  }
  .buttom-checked {
    width: 74px;
    height: 30px;
    margin-left: 0;
  }
}
</style>
