<!--
 * @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, ElSelect, ElOption } 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, batchsavecz } 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'
import { json } from 'stream/consumers'
const PATH_URL = window.VITE_API_BASE_PATH
const tietu = ref('')
const { required } = useValidator()
const text = ref('')
const materialType = 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),
      materialType: unref(materialType)
    })
    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: 'materialType',
    label: '材质类型',
    formatter: (_: Recordable, __: TableColumn, cellValue: number) => {
      return cellValue === 1 ? '贴图' : cellValue === 2 ? '颜色' : ''
    }
  },
  {
    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 imageUrl2 = 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 dialogVisible2 = 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) //

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

const schema = reactive<FormSchema[]>([
  {
    field: 'materialType',
    label: '材质类型',
    component: 'Select',
    colProps: {
      span: 24
    },
    componentProps: {
      options: [
        { label: '贴图', value: 1 },
        { label: '颜色', value: 2 }
      ],
      placeholder: '请选择材质类型',
      onChange: (value) => {
        if (value === 2) {
          schema.find((item) => item.field === 'TIETU').colProps.span = 0
        } else {
          schema.find((item) => item.field === 'TIETU').colProps.span = 24
        }
      }
    },
    formItemProps: {
      rules: [required()]
    }
  },
  {
    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('sadghasgdaj', rawFile.name.includes('jpeg'))
        console.log('kankangeshi', rawFile)
        if (rawFile.name.includes('jpeg')) {
          ElMessage.error('上传格式：png、jpg!')
          return false
        }
        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: 'TIETU',
    component: 'Upload',
    colProps: {
      span: 24
    },
    label: '贴图图片',
    formItemProps: {},
    componentProps: {
      action: PATH_URL + '/resource/manage/uploadImg',
      headers: headers,
      showFileList: false,
      onSuccess: async (_response, uploadFile) => {
        imageUrl2.value = URL.createObjectURL(uploadFile.raw!)
        const formData = await getFormData()
        formData.TIETU = _response.data
        console.log('asdhjasdkj', formData)
      },
      beforeUpload: (rawFile) => {
        console.log('sadghasgdaj', rawFile.name.includes('jpeg'))
        console.log('kankangeshi', rawFile)
        if (rawFile.name.includes('jpeg')) {
          ElMessage.error('上传格式：png、jpg!')
          return false
        }
        if (rawFile.type !== 'image/png' && rawFile.type !== 'image/jpeg') {
          ElMessage.error('上传格式：png、jpg!')
          return false
        }

        return true
      },
      slots: {
        default: () => (
          <>
            {imageUrl2.value ? <img src={imageUrl2.value} class="avatar" /> : null}
            {!imageUrl2.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: 'jsonValue',
    label: '材质内容',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      type: 'textarea',
      rows: 4,
      placeholder: '请输入材质内容'
    },

    formItemProps: {
      rules: [required()]
    }
  }
])
const schema2 = reactive<FormSchema[]>([
  {
    field: 'jsonPath',
    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.jsonPath = ''
        formData.compressFileName = ''
        formData.uploadCompress = false
      },
      onSuccess: async (_response, uploadFile) => {
        console.log('kankan_response', uploadFile)
        const formData = await getFormData()
        formData.compressFilePath = _response.data
      },
      beforeRemove: (uploadFile) => {},
      onExceed: (files, uploadFiles) => {
        ElMessage.warning('只能上传一个资源，请移除后重新上传')
      },
      beforeUpload: (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.compressFileName = data.row.compressFileName
  formData.jsonPath = data.row.jsonPath
  formData.TIETU = data.row.jsonValue.texture

  formData.materialName = data.row.materialName

  let a = JSON.parse(JSON.stringify(data.row.jsonValue))
  tietu.value = a.texture
  imageUrl2.value = PATH_URL + data.row.jsonValue.texture
  delete a.texture
  formData.jsonValue = JSON.stringify(a)

  formData.materialType = data.row.materialType

  formData.materialIcon = data.row.materialIcon.replace(PATH_URL, '')
  imageUrl.value = data.row.materialIcon

  formData.materialId = data.row.materialId
  schema[1].componentProps.fileList = [
    {
      name: data.row.compressFileName,
      url: data.row.jsonPath
    }
  ]

  // 如果材质类型是颜色，不显示贴图图标
  if (formData.materialType === 2) {
    schema.find((item) => item.field === 'TIETU').colProps.span = 0
  } else {
    schema.find((item) => item.field === 'TIETU').colProps.span = 24
  }
}
// 添加编辑模板管理
const signIn = async () => {
  const formRef = await getElFormExpose()
  const formData = await getFormData()
  console.log('asdhajgsh', formData.jsonValue)

  if (!formData.TIETU && formData.materialType == 1) {
    ElMessage.warning('请上传贴图图标')
    return
  }

  try {
    formData.jsonValue = JSON.parse(formData.jsonValue)
  } catch (error) {
    ElMessage.error('材质内容格式错误')
    return
  }

  console.log('shdjasd1', formData.TIETU)
  if (formData.TIETU) {
    formData.jsonValue.texture = formData.TIETU
  } else {
    formData.jsonValue.texture = tietu.value
  }
  //如果是编辑去掉icon的拼接
  console.log('kakkkkak', formData)
  await formRef?.validate(async (isValid) => {
    if (isValid) {
      const res = await saveResource(formData)
      console.log('shdjasd22', res)
      if (res) {
        dialogVisible.value = false
        ElMessage.success('保存成功')
        refresh()
      } else {
        console.log('asdhjasd')
        delete formData.jsonValue.texture
        formData.jsonValue = JSON.stringify(formData.jsonValue)
      }
    }
  })
}
// 批量添加材质
const signIn2 = async () => {
  const formRef = await getElFormExpose()
  const formData = await getFormData()

  //如果是编辑去掉icon的拼接
  console.log('kakkkkak', formData)
  await formRef?.validate(async (isValid) => {
    if (isValid) {
      const res = await batchsavecz(formData)
      if (res) {
        dialogVisible2.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 options = [
  {
    value: 1,
    label: '贴图'
  },
  {
    value: 2,
    label: '颜色'
  }
]

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

const tianjia = async () => {
  imageUrl.value = ''
  imageUrl2.value = ''
  isedit.value = '添加'
  schema[1].componentProps.fileList = []
  dialogVisible.value = true
}
</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="请输入材质名称"
      />
      <span style="color: #606266"> 材质状态：</span>
      <el-select
        v-model="materialType"
        clearable
        placeholder="全部"
        size="large"
        style="width: 240px"
      >
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>

      <ElButton
        style="margin-left: 20px"
        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="580px" 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>

  <Dialog v-model="dialogVisible2" maxHeight="390px" width="35rem" :title="isedit">
    <Form :schema="schema2" @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="signIn2"
        >
          确定
        </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>
