<!--
 * @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, getMaterial, deleteResource } from '@/api/material'
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 { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getMaterial({
      page: unref(currentPage),
      pageSize: unref(pageSize),
      name: unref(text)
    })
    res.data.content.map((item) => {
      item.materialIcon = PATH_URL + item.materialIcon
      item.icon = item.materialIcon
    })
    console.log('kankan2232', res.data.content)

    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: 'materialName',
    label: '材质名称'
  },
  {
    field: 'icon',
    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 = {
        materialIds: data.row.materialId
      }
      const res = await deleteResource(arr)
      refresh()
      refresh()
      if (res.code == 200) {
        ElMessage.success('删除成功')
      }
      refresh()
    })
    .catch(() => {
      // catch error
    })
}

const dialogVisible = ref(false)

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

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

const schema = reactive<FormSchema[]>([
  {
    field: 'materialName',
    label: '材质名称',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      style: {
        width: '100%'
      },
      placeholder: '请输入材质名称'
    },
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'materialIcon',
    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.materialIcon = _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: 'jsonPath',
    component: 'Upload',
    label: '材质内容',
    colProps: {
      span: 24
    },
    componentProps: {
      limit: 1,
      action: PATH_URL + '/resource/v1/addJsonFile',
      headers: headers,
      fileList: [],
      multiple: true,
      onPreview: (uploadFile) => {
        console.log(uploadFile)
      },
      onRemove: async (file) => {
        const formData = await getFormData()
        formData.jsonPath = ''
        formData.compressFileName = ''
        formData.uploadCompress = false
      },
      onSuccess: async (_response, uploadFile) => {
        console.log('kankan_response', uploadFile)
        const formData = await getFormData()
        formData.jsonPath = _response.data
        formData.compressFileName = uploadFile.name
      },
      beforeRemove: (uploadFile) => {},
      onExceed: (files, uploadFiles) => {
        ElMessage.warning('只能上传一个资源，请移除后重新上传')
      },
      beforeUpload: (rawFile) => {
        console.log('kokokoko', rawFile)
        // if (rawFile.type !== 'application/x-zip-compressed' && 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.materialName = data.row.materialName
  formData.compressFileName = data.row.compressFileName
  formData.jsonPath = data.row.jsonPath

  formData.materialIcon = data.row.materialIcon.replace(PATH_URL, '')
  imageUrl.value = data.row.materialIcon
  formData.materialId = data.row.materialId
  schema[2].componentProps.fileList = [
    {
      name: data.row.compressFileName,
      url: data.row.jsonPath
    }
  ]
}
// 添加编辑模板管理
const signIn = async () => {
  const formRef = await getElFormExpose()
  const formData = await getFormData()

  //如果是编辑去掉icon的拼接
  console.log('kakkkkak', formData)
  await formRef?.validate(async (isValid) => {
    if (isValid) {
      const res = await saveResource(formData)
      if (res) {
        dialogVisible.value = false
        refresh()
      }
    }
  })
}

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

  let arr = {
    materialIds: []
  }
  if (selections) {
    arr.materialIds = selections.map((item) => {
      return item.materialId
    })
  }
  if (arr.materialIds.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
}
</script>

<template>
  <ContentWrap>
    <div style="margin-bottom: 10px">
      <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>
