<!--
 * @Author: 半生瓜 1515706227@qq.com
 * @Date: 2024-05-06 19:31:40
 * @LastEditors: 半生瓜 1515706227@qq.com
 * @LastEditTime: 2024-05-28 00:03:36
 * @FilePath: \vue-element-plus-admin-mini\src\views\zy\Menu12.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script setup lang="tsx">
import { ElInput } from 'element-plus'
import { ref } from 'vue'
import { Dialog } from '@/components/Dialog'
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn, TableSlotDefault } from '@/components/Table'
import { upTemplate, saveTemplate } from '@/api/table'
import { saveResource, getResource, deleteResource } from '@/api/resource'
import { reactive, unref } from 'vue'
import { ElButton, ElMessageBox, ElMessage, ElIcon } from 'element-plus'
import { useTable } from '@/hooks/web/useTable'
import { Search, Edit, Delete } from '@element-plus/icons-vue'
import { useValidator } from '@/hooks/web/useValidator'
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { BaseButton } from '@/components/Button'
import { useUserStore } from '@/store/modules/user'
import { log } from 'console'
const PATH_URL = window.VITE_API_BASE_PATH

const { required } = useValidator()
const text = ref('')
const userStore = useUserStore()
defineOptions({
  name: 'TemplateManage'
})

const compare = ref('')

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getResource({
      page: unref(currentPage),
      pageSize: unref(pageSize),
      name: unref(text)
    })
    res.data.content.map((item) => {
      console.log('opopopop', item)
      item.icon = PATH_URL + item.icon
    })
    return {
      list: res.data.content,
      total: res.data.totalElements
    }
  }
})

const { loading, dataList, total, currentPage, pageSize } = tableState

const { refresh, getElTableExpose } = tableMethods

const { t } = useI18n()

const columns = reactive<TableColumn[]>([
  {
    field: 'selection',
    type: 'selection'
  },
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index'
  },
  {
    field: 'categoryName',
    label: '资源库分类'
  },
  {
    field: 'icon',
    label: '图标'
  },
  {
    field: 'modelCount',
    label: '对象数量'
  },

  {
    field: 'action',
    label: t('tableDemo.action'),
    slots: {
      default: (data) => {
        return (
          <>
            <ElButton type="primary" onClick={() => edittab(data)}>
              {t('tableDemo.edit')}
            </ElButton>
            <ElButton type="danger" onClick={() => deletetab(data)}>
              {t('tableDemo.delete')}
            </ElButton>
          </>
        )
      }
    }
  }
])
const imageUrl = ref('')
const isedit = ref('添加')
//删除
const deletetab = async (data: TableSlotDefault) => {
  ElMessageBox.confirm('确定删除该数据?')
    .then(async () => {
      let arr = {
        categoryId: [data.row.categoryId]
      }
      const res = await deleteResource(arr)
      refresh()
      refresh()
      if (res.code == 200) {
        ElMessage.success('删除成功')
      }
      refresh()
    })
    .catch(() => {
      // catch error
    })
}

const dialogVisible = ref(false)

const Authorization = ref(`Bearer ${userStore.getToken}`)
const headers = ref({ Authorization: Authorization.value })

setInterval(() => {
  Authorization.value = `Bearer ${userStore.getToken}`
  console.log('Authorization', Authorization.value)
  headers.value = { Authorization: Authorization.value }
}, 6000) // 每60秒更新一次token

const { formRegister, formMethods } = useForm()
const { getElFormExpose, getFormData } = formMethods

const schema = reactive<FormSchema[]>([
  {
    field: 'categoryName',
    label: '资源分类',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      style: {
        width: '100%'
      },
      placeholder: '请输入资源名称'
    },
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'icon',
    component: 'Upload',
    colProps: {
      span: 24
    },
    label: '图标',
    formItemProps: {
      rules: [required()]
    },
    componentProps: {
      action: PATH_URL + '/resource/manage/uploadImg',
      headers: headers,
      showFileList: false,
      onSuccess: async (_response, uploadFile) => {
        imageUrl.value = URL.createObjectURL(uploadFile.raw!)
        const formData = await getFormData()
        formData.icon = _response.data
      },
      beforeUpload: (rawFile) => {
        console.log('kankangeshi', rawFile)
        if (rawFile.type !== 'image/png' && rawFile.type !== 'image/jpeg') {
          ElMessage.error('上传格式：png、jpg!')
          return false
        }
        return true
      },
      slots: {
        default: () => (
          <>
            {imageUrl.value ? <img src={imageUrl.value} class="avatar" /> : null}
            {!imageUrl.value ? (
              <ElIcon class="avatar-uploader-icon" size="large" style="font-size: 50px">
                +
              </ElIcon>
            ) : null}
          </>
        ),
        tip: () => <div class="el-upload__tip">上传格式：png、jpg，大小：56x56px；</div>
      }
    }
  },
  {
    field: 'compressFilePath',
    component: 'Upload',
    label: '资源内容',
    colProps: {
      span: 24
    },
    componentProps: {
      limit: 1,
      action: PATH_URL + '/resource/manage/addModelCompress',
      headers: headers,
      fileList: [],
      multiple: true,
      onPreview: (uploadFile) => {
        console.log(uploadFile)
      },
      onRemove: async (file) => {
        const formData = await getFormData()
        formData.compressFilePath = ''
        formData.compressFileName = ''
        formData.uploadCompress = false
      },
      onSuccess: async (_response, uploadFile) => {
        console.log('kankan_response', uploadFile)
        const formData = await getFormData()
        formData.compressFilePath = _response.data
        formData.compressFileName = uploadFile.name
      },
      beforeRemove: (uploadFile) => {},
      onExceed: (files, uploadFiles) => {
        ElMessage.warning('只能上传一个资源，请移除后重新上传')
      },
      beforeUpload: (rawFile) => {
        console.log('kokokoko', rawFile)
        if (rawFile.name.indexOf('.zip') == -1 && rawFile.name.indexOf('.rar') == -1) {
          ElMessage.error('只能上传RAR、ZIP文件')
          return false
        }
        return true
      },
      slots: {
        default: () => <BaseButton type="primary">点击上传</BaseButton>,
        tip: () => <div class="el-upload__tip">文件类型：RAR\ZIP</div>
      }
    }
  }
])

//编辑
const edittab = async (data: TableSlotDefault) => {
  console.log('shanchu', data)
  isedit.value = '编辑'
  dialogVisible.value = true
  const formRef = await getElFormExpose()
  const formData = await getFormData()
  formData.categoryName = data.row.categoryName
  formData.compressFileName = data.row.compressFileName
  formData.compressFilePath = data.row.compressFilePath
  compare.value = data.row.compressFilePath
  formData.icon = data.row.icon.replace(PATH_URL, '')
  imageUrl.value = data.row.icon
  formData.categoryId = data.row.categoryId
  schema[2].componentProps.fileList = [
    {
      name: data.row.compressFileName,
      url: data.row.compressFilePath
    }
  ]
}
// 添加编辑模板管理
const signIn = async () => {
  const formRef = await getElFormExpose()
  const formData = await getFormData()
  console.log('lplplp', formData.compressFilePath)
  if (
    formData.compressFilePath !== compare.value &&
    formData.compressFilePath !== '' &&
    formData.compressFilePath
  ) {
    formData.uploadCompress = true
  } else {
    formData.uploadCompress = false
  }
  //如果是编辑去掉icon的拼接
  console.log('kakkkkak', formData)
  await formRef?.validate(async (isValid) => {
    if (isValid) {
      const res = await saveResource(formData)
      if (res) {
        dialogVisible.value = false
        refresh()
      }
    }
  })
}

//搜索
const handersearch = function () {
  tableState.currentPage.value = 1
  refresh()
}

//多选删除
const getSelections = async () => {
  const elTableRef = await getElTableExpose()
  const selections = elTableRef?.getSelectionRows()

  let arr = {
    categoryId: []
  }
  if (selections) {
    arr.categoryId = selections.map((item) => {
      return item.categoryId
    })
  }
  if (arr.categoryId.length !== 0) {
    ElMessageBox.confirm('确定删除所选数据?')
      .then(async () => {
        console.log('kankan', arr)
        const res = await deleteResource(arr)
        console.log('kkkkkkss', res)
        if (res.code == 200) {
          ElMessage.success('删除成功')
        }
        refresh()
      })
      .catch(() => {
        // catch error
      })
  } else {
    ElMessage.warning('请选择数据')
  }
}
const tianjia = async () => {
  imageUrl.value = ''
  isedit.value = '添加'
  schema[2].componentProps.fileList = []
  dialogVisible.value = true
  compare.value = ''
}
</script>

<template>
  <ContentWrap>
    <div style="margin-bottom: 10px">
      <span style="color: #606266"> 资源分类：</span>
      <el-input
        v-model="text"
        style="width: 200px; height: 43px; margin: 7px"
        placeholder="请输入资源分类名称"
      />
      <ElButton type="primary" size="large" @click="handersearch" :icon="Search">搜索</ElButton>
      <ElButton type="success" size="large" @click="tianjia" :icon="Edit">添加</ElButton>
      <ElButton type="danger" size="large" @click="getSelections" :icon="Delete">删除</ElButton>
    </div>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="columns"
      :image-preview="['icon']"
      :data="dataList"
      row-key="id"
      headerAlign="center"
      align="center"
      :loading="loading"
      sortable
      :pagination="{
        total: total
      }"
      @register="tableRegister"
      @refresh="refresh"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" maxHeight="390px" width="35rem" :title="isedit">
    <Form :schema="schema" @register="formRegister" />
    <template #footer>
      <div style="width: 100%; display: flex; justify-content: center">
        <BaseButton
          style="font-size: 1rem; height: 2.2rem; margin: auto"
          type="primary"
          class="w-[15%]"
          @click="signIn"
        >
          确定
        </BaseButton>
      </div>
    </template>
  </Dialog>
</template>

<style>
.el-image__preview {
  width: 56px !important;
  height: 56px !important;
}
</style>

<style lang="less">
.el-upload {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  transition: var(--el-transition-duration-fast);
}

.el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
  width: 120px;
  height: 120px;
  font-size: 28px;
  color: #8c939d;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
}
</style>
